text
stringlengths
14
6.51M
unit cif8by6; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, ComCtrls, mask, Grids, Menus, Printers, ActnList, DataController, dcEdit, SelectBOD, dcCheckBox, dcMemo, NotesDialog, TTSLNOTTable, TTSTRAKTable, TTSHITMTable, TTSTITMTable, InputDialog, AdvEdit, RxToolEdit, RxCurrEdit, dcCalcEdit, advlistv, TrackedItemFrame, DataBuf, TCWODT, AdvGrid, FFSAdvStringGrid, DocumentListFrame, RXCtrls, dcCalcEditBtn, dcEditbtn, ChangeLoanNumberForm, ttsCifTable, ToolWin, ReportSetupDialog, sBitBtn, sCheckBox, sSkinProvider, AdvUtil, System.Actions, AdvObj, BaseGrid, sPageControl; type TfrmCif8by6 = class(TForm) MainMenu1: TMainMenu; Options1: TMenuItem; DeleteCif1: TMenuItem; Print1: TMenuItem; ActionList1: TActionList; actNotes: TAction; actTrackAdd: TAction; actEditCat: TAction; actDeleteCat: TAction; actCatNotes: TAction; actViewGuaranteed: TAction; actGotoLoan: TAction; actApplychanges: TAction; actCancelChanges: TAction; ChangeCifNumber1: TMenuItem; lblLoan: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label10: TLabel; imgTape: TImage; edtAddress1: TdcEditBtn; edtAddress2: TdcEditBtn; edtCity: TdcEditBtn; edtState: TdcEditBtn; edtPhone: TdcEditBtn; edtLoanNumber: TdcEditBtn; lblOfficer: TLabel; lblBranch: TLabel; lblDivision: TLabel; Label2: TLabel; lblIndirect: TLabel; lblLetterName: TLabel; edtLetterName: TdcEditBtn; edtBranch: TdcEditBtn; edtDivision: TdcEditBtn; edtOfficer: TdcEditBtn; edtHoldNotice: TdcCheckBox; lblCollCodeDesc: TLabel; lblCollCode: TLabel; edtCollCode: TdcEditBtn; Label1: TLabel; edtZip: TdcEditBtn; edtDirectDebt: TdcCalcEditBtn; edtIndirectDebt: TdcCalcEditBtn; edtActiveStatus: TdcEditBtn; lbl1: TLabel; N1: TMenuItem; Close1: TMenuItem; edtActive: TdcEditBtn; ActSelectBranch: TAction; dcLoan: TDataController; dlgCifNotes: TNotesDialog; ExportCIFDatatoLoans1: TMenuItem; actSaveChanges: TAction; Shape1: TShape; PushCifRecord1: TMenuItem; Notebook: TsPageControl; tabTracked: TsTabSheet; tabLoans: TsTabSheet; tabGuaranteed: TsTabSheet; tabNotes: TsTabSheet; tabDocs: TsTabSheet; Panel6: TPanel; btnGoToLoan: TsBitBtn; Panel8: TPanel; btnViewGuaranteed: TsBitBtn; edtNotes: TdcMemo; Panel7: TPanel; btnHasNotes: TSpeedButton; TrackedItemFram1: TTrackedItemFram; BufLoan: TTTSCIFBuffer; grdGuaranteed: TFFSAdvStringGrid; grdLoans: TFFSAdvStringGrid; DocFrame: TFrameDocumentList; dcEditBtn1: TdcEditBtn; dcEditBtn2: TdcEditBtn; Label3: TLabel; Apply1: TMenuItem; Close2: TMenuItem; Cancel1: TMenuItem; Ok1: TMenuItem; ToolBar2: TToolBar; ToolButton2: TToolButton; edtName1: TdcEditBtn; edtName2: TdcEditBtn; Label4: TLabel; edtFirst1: TdcEditBtn; Label8: TLabel; edtFirst2: TdcEditBtn; lblDept: TLabel; edtDept: TdcEditBtn; btnClose: TsBitBtn; BitBtn2: TsBitBtn; BitBtn3: TsBitBtn; BitBtn4: TsBitBtn; rptDlg: TReportSetupDialog; edtemail: TdcEditBtn; Label9: TLabel; edtAddlField: TdcEditBtn; lblAddlField: TLabel; procedure FormCloseQuery(Sender: TObject; var CanClose: boolean); procedure DeleteCif1Click(Sender: TObject); procedure actNotesExecute(Sender: TObject); procedure actViewGuaranteedExecute(Sender: TObject); procedure actGotoLoanExecute(Sender: TObject); procedure actCancelChangesExecute(Sender: TObject); procedure actApplychangesExecute(Sender: TObject); procedure DBMemo1DblClick(Sender: TObject); procedure edtCollCodeExit(Sender: TObject); procedure ChangeCifNumber1Click(Sender: TObject); procedure Print1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Close1Click(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dcLoanStartEdit(Sender: TObject); procedure dcLoanFinishEdit(Sender: TObject); procedure dcLoanCancelEdit(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure edtColl1Change(Sender: TObject); procedure edtColl2Change(Sender: TObject); procedure ExportCIFDatatoLoans1Click(Sender: TObject); procedure edtZipExit(Sender: TObject); procedure actSaveChangesExecute(Sender: TObject); procedure PushCifRecord1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure edtBranchButtonClick(Sender: TObject); procedure edtDivisionButtonClick(Sender: TObject); procedure edtOfficerButtonClick(Sender: TObject); procedure edtCollCodeButtonClick(Sender: TObject); procedure edtCollCodeEnter(Sender: TObject); procedure edtActiveStatusButtonClick(Sender: TObject); procedure edtActiveStatusExit(Sender: TObject); procedure NotebookEnter(Sender: TObject); procedure grdLoansRecordEdit(Sender: TObject); procedure grdLoansDblClick(Sender: TObject); procedure grdLoansGetAlignment(Sender: TObject; ARow, ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment); procedure grdGuaranteedGetAlignment(Sender: TObject; ARow, ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment); procedure edtNotesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure edtLtrName1Enter(Sender: TObject); procedure edtLtrName1Exit(Sender: TObject); procedure edtLtrName2Enter(Sender: TObject); procedure edtLtrName2Exit(Sender: TObject); procedure edtDeptButtonClick(Sender: TObject); procedure edtFirst1ButtonClick(Sender: TObject); procedure edtFirst2ButtonClick(Sender: TObject); procedure TrackedItemFram1btnAddClick(Sender: TObject); procedure TrackedItemFram1btnEditClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure grdLoansMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure grdLoansMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure grdGuaranteedMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure grdGuaranteedMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure DocFrameDocGridMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure DocFrameDocGridMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure edtBranchExit(Sender: TObject); procedure edtOfficerExit(Sender: TObject); procedure edtDivisionExit(Sender: TObject); procedure edtDeptExit(Sender: TObject); procedure edtAddlFieldButtonClick(Sender: TObject); private FLoanNum: string; OldCollCode:string; GuarCount:integer; LoanCount:integer; procedure LoadDataFields; procedure SetLoanNum(const Value: String); procedure RefreshActiveStatus; procedure DoCollateralCodeChange; procedure SaveChanges(DoClose: boolean); procedure GoToLoan; private property LoanNum : String read FLoanNum write SetLoanNum; public constructor Create(AOwner: Tcomponent);override; procedure AppendCif(ACifNumber: String); procedure RefreshData; end; var frmCif8by6: TfrmCif8by6; procedure OpenCIFScreen(cifNumber: String; createoption: boolean); implementation uses ProgramSettings, datamod, TrackedItem, addguar, ActiveState, Loan1, SelectCollateralCode, ffsexception, titmdoc, StrUtils, FFSUtils, TicklerTypes, TicklerGlobals, ffstypes,{LoanView} ReportLoanPrint; //uFreeLocalizer; {$R *.DFM} procedure OpenCIFScreen(cifNumber: String; createoption: boolean); //var Spread : boolean; var msgstr1 : string; begin if not assigned(frmCif8by6) then frmCif8by6 := TfrmCif8by6.Create(Application); cifNumber := cifNumber.Trim.PadLeft(20); frmCif8by6.LoanNum := cifNumber; frmCif8by6.TrackedItemFram1.SetLCIF(FlagCif, CifNumber); frmCif8by6.DocFrame.SetLCif(FlagCif,CifNumber); if daapi.CifExists(CurrentLend.Number, cifNumber) then begin frmCif8by6.bufLoan.Data := daapi.CifGetRecord(CurrentLend.Number, cifNumber); if currentLend.BranchesEnabled and not empty(CurrentUser.PBranch) then begin if (frmCif8by6.bufLoan.Data.PBranch <> CurrentUser.PBranch) then begin msgAsterisk(format('The %s number you tried to open does not exist for branch %s.',[CurrentLend.capCif,CurrentUser.PBranch])); exit; end; end; with frmCif8by6.bufLoan do daapi.CollCheckCodes(CurrentLend.Number, FlagCif,cifNumber, data.PCustCode, '', CurrentUser.PUserName, false); frmCif8by6.LoadDataFields; frmCif8by6.RefreshData; //update all tables if not add frmCif8by6.Show; frmCif8by6.Notebook.ActivePageIndex := 0; frmCif8by6.ActiveControl := frmCif8by6.TrackedItemFram1.titmGrid; if frmCif8by6.WindowState=wsMinimized then frmCif8by6.WindowState := wsNormal end else begin if createoption then begin msgstr1 := format('%s Number not found. Create a new %s?', [CurrentLend.capcif, CurrentLend.capcif + ':' + Trim( cifNumber ) + ' ']); //if TrMsgConfirmation('Cif Number not found. Create a new Cif?' , MB_YESNOCANCEL + MB_ICONQUESTION + MB_DEFBUTTON2) =IDYES then begin if TrMsgConfirmation(msgStr1, MB_YESNOCANCEL + MB_ICONQUESTION + MB_DEFBUTTON2) = IDYES then begin frmCif8by6.Show; frmCif8by6.AppendCif(cifNumber); if frmCif8by6.WindowState=wsMinimized then frmCif8by6.WindowState := wsNormal end end else TrMsgInformation('The CIF number you tried to open does not exist.') end end; procedure TfrmCif8by6.DoCollateralCodeChange; begin lblCollCodeDesc.Caption := daapi.CollGetDesc(CurrentLend.Number, edtCollCode.Text); daapi.CollCheckCodes(CurrentLend.Number, FlagCIF, LoanNum, edtCollCode.Text, '', CurrentUser.PUserName, true); TrackedItemFram1.SetCCC(edtCollCode.Text, 1); RefreshData; end; procedure TfrmCif8by6.FormCloseQuery(Sender: TObject; var CanClose: boolean); begin CanClose := TRUE; //check to see if the user needs to press the apply/cancel button first! if dcLoan.Modified then begin MsgAsterisk('Sorry, press Apply/Cancel to save/cancel changes first.'); CanClose := FALSE; end end; procedure TfrmCif8by6.DeleteCif1Click(Sender: TObject); var rslt : integer; begin if not UsrRights(tpCifDelete) then exit; rslt := -1; if TrMsgConfirmation('Delete this CIF Record?') = IDYES then begin rslt := daapi.CifDelete(CurrentLend.Number, LoanNum, CurrentUser.PUserName); case rslt of 0 : TrMsgInformation('Deleted!'); 1 : TrMsgInformation(Format('Cannot delete this CIF. There are %ss linked to it.',[CurrentLend.capLoan])); 2 : TrMsgInformation(Format('Cannot delete this CIF. It is the Guarantor for one or more %ss.',[CurrentLend.capLoan])); 3 : TrMsgInformation(Format('%s record does not exist anymore.',[CurrentLend.capLoan])); end; end; if rslt = 0 then Close; end; constructor TfrmCif8by6.Create(AOwner: Tcomponent); begin inherited Create(AOwner); TrackedItemFram1.Enabled := TRUE; end; procedure TfrmCif8by6.actNotesExecute(Sender: TObject); var modcount : integer; begin dlgCifNotes.Notes := daapi.CifGetNotes(CurrentLend.Number, LoanNum); dlgCifNotes.NewNote := CurrentUser.PUserName + ' ' + trim(DateTimeStamp) + ' '; dlgCifNotes.NoteOption := nopReadOnly; if UsrRights(tpCifNoteAppend) then dlgCifNotes.NoteOption := nopReadWrite; if UsrRights(tpCifNoteFull) then dlgCifNotes.NoteOption := nopWriteAll; modcount := daapi.CifGetModCount(CurrentLend.Number, LoanNum); if dlgCifNotes.Execute then begin if daapi.CifGetModCount(CurrentLend.Number, LoanNum) = modcount then begin edtNotes.Text := dlgCifNotes.Notes; daapi.CifUpdateNotes(CurrentLend.Number, LoanNum, edtNotes.Text); end else begin TrMsgInformation('Changes have been made to the notes by another user. You will need to re-enter your notes.'); edtNotes.Text := daapi.CifGetNotes(CurrentLend.Number, LoanNum); end; end; RefreshData; end; procedure TfrmCif8by6.RefreshData; var glist : TStringList; llist : TStringList; x : integer; begin trackedItemFram1.RefreshGrid(false,false); // guaranteed GuarCount := 0; glist := TStringList.create; try daapi.GuarGetLoanList(CurrentLend.Number, LoanNum, glist); GuarCount := Glist.count; grdGuaranteed.LoadFromCSVStringList(glist); finally glist.free; end; for x := 1 to GuarCount do grdGuaranteed.Currency[2,x] := grdGuaranteed.Currency[2,x]; actViewGuaranteed.Enabled := GuarCount > 0; // Loans LoanCount := 0; llist := TStringlist.create; try daapi.CifGetLoanList(CurrentLend.Number, LoanNum, llist); LoanCount := llist.count; grdLoans.LoadFromCSVStringlist(llist); finally llist.free; end; for x := 1 to LoanCount do grdLoans.Currency[1,x] := grdLoans.Currency[1,x]; actGotoLoan.Enabled := LoanCount > 0; // others NoteBook.Update; imgTape.visible := bufloan.data.PTapeLoan; end; procedure TfrmCif8by6.actViewGuaranteedExecute(Sender: TObject); begin OpenLoanScreen(grdGuaranteed.cells[0, grdGuaranteed.row],false, 0); end; procedure TfrmCif8by6.actGotoLoanExecute(Sender: TObject); begin GotoLoan; end; procedure TfrmCif8by6.GoToLoan; var lnum : string; begin lnum := grdLoans.cells[0,grdLoans.row]; if trim(lnum) = '' then exit; OpenLoanScreen(lnum, false,0); end; procedure TfrmCif8by6.actCancelChangesExecute(Sender: TObject); begin if TrMsgConfirmation('Are you SURE you wish to Cancel?', MB_YESNO + MB_DEFBUTTON2)=IDYES then begin dcLoan.CancelEdit; LoadDataFields; end end; procedure TfrmCif8by6.actApplychangesExecute(Sender: TObject); begin SaveChanges(true) end; procedure TfrmCif8by6.SaveChanges(DoClose: boolean); var // x: integer; s : string; begin // save edits // ActiveControl := btnApply; if daapi.CifGetModCount(CurrentLend.Number, LoanNum) = BufLoan.Data.PModCount then begin // get the data from the fields to the buffer dcLoan.WriteData; // inc the mod count BufLoan.Data.PModCount := BufLoan.Data.PModCount + 1; daapi.CifUpdateRecord(BufLoan.Data); daapi.InsertNameSearch(CurrentLend.Number, FlagCIF, BufLoan.Data.PCifNumber, BufLoan.Data.PName1+' '+BufLoan.Data.PFirstName1, BufLoan.Data.PName2+' '+BufLoan.Data.PFirstName2, bufLoan.data.PBranch ); if DoClose then Close; end else begin s := 'Changes have been made to this CIF by another user. This screen will be refreshed with the current values and you will need to re-enter your changes.'; TrMsgInformation(s); dcLoan.CancelEdit; BufLoan.Data := daapi.CifGetRecord(CurrentLend.Number, LoanNum); LoadDataFields; RefreshData; end; end; procedure TfrmCif8by6.DBMemo1DblClick(Sender: TObject); begin actNotes.Execute; end; procedure TfrmCif8by6.edtCollCodeExit(Sender: TObject); begin if OldCollCode <> edtCollCode.text then DoCollateralCodeChange; RefreshData; end; procedure TfrmCif8by6.ChangeCifNumber1Click(Sender: TObject); var frmChangeLNum : TfrmChangeLoanNumber; begin if not UsrRights(tpCifChangeNum) then exit; if dcLoan.Modified then begin MsgAsterisk('Sorry, press Apply/Cancel to save/cancel changes first.') end else begin frmChangeLNum := TfrmChangeLoanNumber.Create(self); try frmChangeLNum.OldLoanNumber := LoanNum; if frmChangeLNum.ShowModal = mrOk then begin try daapi.CifChangeNumber(CurrentLend.Number, LoanNum, frmChangeLNum.NewLoanNumber, currentuser.PUserName); OpenCIFScreen(frmChangeLNum.NewLoanNumber, false); except on E : Exception do MsgAsterisk(E.Message); end; end; finally frmChangeLNum.free; end; end; end; procedure TfrmCif8by6.Print1Click(Sender: TObject); var rptLoanPrint: TrptLoanPrint; begin if rptDlg.Execute then begin rptDlg.ViewCaption := ''; rptLoanPrint := TrptLoanPrint.create(self); try rptLoanPrint.RptID := copy(trim(LoanNum),1,3); rptLoanPrint.LoanNumber := LoanNum; rptLoanPrint.LendNumber := CurrentLend.Number; rptLoanPrint.PrintCIF := true; if rptdlg.Destination = rdScreen then begin rptLoanPrint.Execute(rptDlg.TIHist, rptDlg.LoanNotes, rptDlg.TINotes, rptDlg.ExceptionNotice,rptDlg.PrintWaived, rptDlg.PrintHistory,rptDlg.PrintSatisfied,rptDlg.ExceptionOfficer); end else begin rptLoanPrint.PrintExecute(rptDlg.TIHist, rptDlg.LoanNotes, rptDlg.TINotes, rptDlg.ExceptionNotice,rptDlg.PrintWaived, rptDlg.PrintHistory,rptDlg.PrintSatisfied,rptDlg.ExceptionOfficer); end; finally rptLoanPrint.free; end; end; end; procedure TfrmCif8by6.AppendCif(ACifNumber: String); begin fillchar(Bufloan.data, sizeof(Bufloan.data), 0); BufLoan.Data.PLenderNum := CurrentLend.Number; BufLoan.data.PActive := 'A'; BufLoan.data.PCifNumber := ACifNumber.Trim.PadLeft(20); daapi.CifAddRecord(BufLoan.data); LoanNum := ACifNumber; LoadDataFields; RefreshData; ActiveControl := edtName1; dcLoan.StartEdit end; procedure TfrmCif8by6.FormCreate(Sender: TObject); //var // x: integer; begin // tts options // Guarantors if not CurrentLend.GuarantorEnabled then begin tabGuaranteed.TabVisible := false; lblIndirect.visible := false; edtIndirectDebt.visible := false end; // NoCifBal Option if CurrentLend.NoCIFBal then begin edtDirectDebt.ReadOnly := false; edtDirectDebt.Color := clWindow; edtDirectDebt.TabStop := true; end; // Division lblDivision.visible := CurrentLend.DivisionEnabled; edtDivision.visible := CurrentLend.DivisionEnabled; edtDept.Visible := CurrentLend.DeptEnabled; lblDept.Visible := CurrentLend.DeptEnabled; // Documents //tabDocs.TabVisible := False; // ah 07.26.02 for external imaging CurrentLend.DocImagingEnabled; tabDocs.TabVisible := CurrentLend.DocImagingEnabled; // read only for inquiry user dcLoan.ReadOnly := not UsrRights(tpCifModify); DeleteCif1.Visible := UsrRights(tpCifDelete); ChangeCifNumber1.Visible := UsrRights(tpCifChangeNum); ExportCIFDatatoLoans1.Visible := UsrRights(tpCifExptToLoan); // caption Caption := 'CIF Information - ' + CurrentLend.NameAndNumber; tabLoans.caption := Format('&%ss',[CurrentLend.capLoan]); btnGoToLoan.Caption := Format('Go To %s',[CurrentLend.capLoan]); btnViewGuaranteed.caption := Format('View %s',[CurrentLend.capLoan]); if TicklerSetup.CIFAddlField then begin lblAddlField.Visible := True; edtAddlField.Visible := True; end; end; procedure TfrmCif8by6.LoadDataFields; begin dcLoan.ReadData; lblCollCodeDesc.Caption := daapi.CollGetDesc(CurrentLend.Number, edtCollCode.text); // notes TrackedItemFram1.SetCCC(edtCollCode.Text, 1); edtNotes.Text := daapi.CifGetNotes(CurrentLend.Number, LoanNum); RefreshActiveStatus; dcLoan.FinishEdit; end; procedure TfrmCif8by6.SetLoanNum(const Value: String); begin FLoanNum := Value; end; procedure TfrmCif8by6.RefreshActiveStatus; var PaidOut: Boolean; begin PaidOut := daapi.GetCIFPODate(BufLoan.Data.PLenderNum,BufLoan.Data.PCifNumber); if edtActive.Text='Y' then edtActiveStatus.Text := 'Yes - Forced' else if edtActive.Text='N' then edtActiveStatus.Text := 'No - Forced' else if not PaidOut then edtActiveStatus.Text := 'Yes' else edtActiveStatus.Text := 'No' end; procedure TfrmCif8by6.Close1Click(Sender: TObject); begin Close end; procedure TfrmCif8by6.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift=[]) and (Key=VK_Escape) and (not dcLoan.Modified) then begin Key := 0; Close end; end; procedure TfrmCif8by6.dcLoanStartEdit(Sender: TObject); begin actApplychanges.visible := true; actSaveChanges.visible := true; actCancelChanges.visible := true; btnClose.visible := false end; procedure TfrmCif8by6.dcLoanFinishEdit(Sender: TObject); begin actApplychanges.visible := false; actSaveChanges.visible := false; actCancelChanges.visible := false; btnClose.visible := true; end; procedure TfrmCif8by6.dcLoanCancelEdit(Sender: TObject); begin actApplychanges.visible := false; actSaveChanges.visible := false; actCancelChanges.visible := false; btnClose.visible := true end; procedure TfrmCif8by6.btnCloseClick(Sender: TObject); begin Close; end; procedure TfrmCif8by6.edtColl1Change(Sender: TObject); begin dcLoan.StartEdit end; procedure TfrmCif8by6.edtColl2Change(Sender: TObject); begin dcLoan.StartEdit end; procedure TfrmCif8by6.ExportCIFDatatoLoans1Click(Sender: TObject); begin if not UsrRights(tpCifExptToLoan) then exit; // export to loans if dcLoan.Modified then begin TrMsgInformation('Finish editing first'); exit; end; if TrMsgConfirmation('Export CIF data into Loans?')=IDYES then daapi.CifExportCIFToLoans(CurrentLend.Number, LoanNum); end; procedure TfrmCif8by6.edtZipExit(Sender: TObject); begin edtZip.Text := formatZip(edtZip.Text) end; procedure TfrmCif8by6.actSaveChangesExecute(Sender: TObject); begin SaveChanges(false) end; procedure TfrmCif8by6.PushCifRecord1Click(Sender: TObject); var cmdline: AnsiString; begin cmdline := Dir(drExport) + 'IMAGE.BAT'; cmdline := cmdline + ' T ' + CurrentLend.Number + ' ' + BufLoan.data.PCifNumber + ' ' + CurrentUser.PUserName; winExec(PAnsiChar(cmdline), SW_NORMAL) end; procedure TfrmCif8by6.FormShow(Sender: TObject); begin PushCifRecord1.visible := fileexists(Dir(drExport) + 'IMAGE.BAT'); grdLoans.ColumnHeaders[0] := Format('%s Number',[CurrentLend.capLoan]); grdGuaranteed.ColumnHeaders[0] := Format('%s Number',[CurrentLend.capLoan]); // FreeLocalizer.Translate(Self); end; procedure TfrmCif8by6.edtBranchButtonClick(Sender: TObject); var retval : shortstring; begin if dlgSelectBOD(lookBranch,retval) then edtBranch.Text := retval; end; procedure TfrmCif8by6.edtDivisionButtonClick(Sender: TObject); var retval : shortstring; begin if dlgSelectBOD(lookDivision,retval) then edtDivision.Text := retval; end; procedure TfrmCif8by6.edtOfficerButtonClick(Sender: TObject); var retval : shortstring; begin if dlgSelectBOD(lookOfficer, retval) then edtOfficer.Text := retval; end; procedure TfrmCif8by6.edtCollCodeButtonClick(Sender: TObject); var s : shortstring; begin s := ''; if dlgSelectCollateralCode(s) and (OldCollCode <> s) then begin edtCollCode.Text := s; DoCollateralCodeChange; end; end; procedure TfrmCif8by6.edtCollCodeEnter(Sender: TObject); begin OldCollCode := edtCollCode.Text; end; procedure TfrmCif8by6.edtActiveStatusButtonClick(Sender: TObject); begin frmActiveState := TfrmActiveState.Create(Application); frmActiveState.ActiveStatus := edtActive.Text; if frmActiveState.ShowModal=mrOk then edtActive.Text := frmActiveState.ActiveStatus; frmActiveState.Free; RefreshActiveStatus end; procedure TfrmCif8by6.edtActiveStatusExit(Sender: TObject); begin RefreshActiveStatus end; procedure TfrmCif8by6.NotebookEnter(Sender: TObject); begin TrackedItemFram1.SetCCC(edtCollCode.Text, 1); end; procedure TfrmCif8by6.grdLoansRecordEdit(Sender: TObject); begin GoToLoan; end; procedure TfrmCif8by6.grdLoansDblClick(Sender: TObject); begin GoToLoan; end; procedure TfrmCif8by6.grdLoansGetAlignment(Sender: TObject; ARow, ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment); begin if ACol = 1 then HAlign := taRightJustify; end; procedure TfrmCif8by6.grdGuaranteedGetAlignment(Sender: TObject; ARow, ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment); begin if ACol = 2 then HAlign := taRightJustify; end; procedure TfrmCif8by6.edtNotesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (shift = []) and (key = 13) then begin key := 0; btnHasNotes.click; end; end; procedure TfrmCif8by6.FormClose(Sender: TObject; var Action: TCloseAction); begin if assigned(frmLoan1) then frmLoan1.refreshData; end; procedure TfrmCif8by6.edtLtrName1Enter(Sender: TObject); begin edtName1.width := 92; end; procedure TfrmCif8by6.edtLtrName1Exit(Sender: TObject); begin edtName1.width := 173; end; procedure TfrmCif8by6.edtLtrName2Exit(Sender: TObject); begin edtName2.width := 173; end; procedure TfrmCif8by6.edtLtrName2Enter(Sender: TObject); begin edtName2.width := 92; end; procedure TfrmCif8by6.edtDeptButtonClick(Sender: TObject); var retval : shortstring; begin if dlgSelectBOD(lookDept, retval) then edtDept.Text := retval; end; procedure TfrmCif8by6.edtFirst1ButtonClick(Sender: TObject); var AFirst, ALast : string; begin if empty(edtName1.text) then exit; NameBreak(edtName1.Text, AFirst, ALast); edtFirst1.text := AFirst; edtName1.text := ALast; end; procedure TfrmCif8by6.edtFirst2ButtonClick(Sender: TObject); var AFirst, ALast : string; begin if empty(edtName2.text) then exit; NameBreak(edtName2.Text, AFirst, ALast); edtFirst2.text := AFirst; edtName2.text := ALast; end; procedure TfrmCif8by6.TrackedItemFram1btnAddClick(Sender: TObject); begin TrackedItemFram1.actAddItemExecute(Sender); end; procedure TfrmCif8by6.TrackedItemFram1btnEditClick(Sender: TObject); begin TrackedItemFram1.actEditItemExecute(Sender); end; procedure TfrmCif8by6.FormActivate(Sender: TObject); begin if dcLoan.Modified = false then begin BufLoan.Data := daapi.CifGetRecord(BufLoan.Data.PLenderNum,BufLoan.Data.PCifNumber); LoadDataFields; end else RefreshActiveStatus; end; procedure TfrmCif8by6.grdLoansMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin grdLoans.SetFocus; end; procedure TfrmCif8by6.grdLoansMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin grdLoans.SetFocus; end; procedure TfrmCif8by6.grdGuaranteedMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin grdGuaranteed.SetFocus; end; procedure TfrmCif8by6.grdGuaranteedMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin grdGuaranteed.SetFocus; end; procedure TfrmCif8by6.DocFrameDocGridMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin DocFrame.SetFocus; end; procedure TfrmCif8by6.DocFrameDocGridMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin DocFrame.SetFocus; end; procedure TfrmCif8by6.edtBranchExit(Sender: TObject); begin { if not daapi.CodeExists(CurrentLend.Number, tcBranch, edtBranch.Text) then begin TrMsgInformation('Branch: '+edtBranch.Text +' does not exist. Please use the drop down to select correct branch') ; edtBranch.SetFocus; end; } end; procedure TfrmCif8by6.edtOfficerExit(Sender: TObject); begin { if not daapi.CodeExists(CurrentLend.Number, tcOfficer, edtOfficer.Text) then begin TrMsgInformation('Officer: '+ edtOfficer.Text +' does not exist. Please use the drop down to select correct Officer') ; edtBranch.SetFocus; end; } end; procedure TfrmCif8by6.edtDivisionExit(Sender: TObject); begin { if not daapi.CodeExists(CurrentLend.Number, tcDivision, edtDivision.Text) then begin TrMsgInformation('Division: '+ edtDivision.Text +' does not exist. Please use the drop down to select correct Division') ; edtBranch.SetFocus; end; } end; procedure TfrmCif8by6.edtDeptExit(Sender: TObject); begin if not daapi.CodeExists(CurrentLend.Number, tcDept, edtDept.Text) then begin TrMsgInformation('Dept: '+ edtDept.Text +' does not exist. Please use the drop down to select correct Dept') ; edtBranch.SetFocus; end; end; procedure TfrmCif8by6.edtAddlFieldButtonClick(Sender: TObject); var retval : shortstring; begin if dlgSelectBOD(lookCIF, retval) then edtAddlField.Text := retval; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clCertificate; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, Contnrs, Windows, {$ELSE} System.Classes, System.SysUtils, System.Contnrs, Winapi.Windows, {$ENDIF} clCryptAPI, clCryptUtils, clCertificateKey, clWUtils, clTranslator; type TclCertificateVersion = (cvVersion1, cvVersion2, cvVersion3); TclCertificateList = class; TclCertificate = class private FCertContext: PCCERT_CONTEXT; FIssuedTo: string; FEmail: string; FIssuedBy: string; FValidTo: TDateTime; FValidFrom: TDateTime; FSerialNumber: string; FFriendlyName: string; FVersion: TclCertificateVersion; FPrivateKey: string; FPublicKeyAlgorithm: string; FPublicKeyAlgorithmName: string; FSubject: string; FSignatureAlgorithm: string; FSignatureAlgorithmName: string; FUsage: string; FThumbprint: string; FSubjectKeyIdentifier: string; function GetIsServerAuthentication: Boolean; function GetIsClientAuthentication: Boolean; function GetIsCodeSigning: Boolean; function GetIsSecureEmail: Boolean; function CheckUsage(const AOID: string): Boolean; procedure SetFriendlyName(const Value: string); procedure SetUsageFlags(AFlags: TStrings); function GetUsageFlags: string; function GetEMailFromSubject: string; function GetEMailFromAltSubject: string; function GetFriendlyName: string; function GetDecodedName(AType, AFlags: Integer): string; function GetSerialNumber(ABlob: CRYPTOAPI_BLOB): string; function GetOidInfo(const AOID: string): string; function GetSubjectString: string; function GetPrivateKey: string; function GetThumbprint: string; function GetSubjectKeyIdentifier: string; procedure GetCertInfo; procedure SetUsage(const Value: string); public constructor Create(ACertContext: PCCERT_CONTEXT); overload; constructor Create(AEncoded: PByte; ALength: Integer); overload; destructor Destroy; override; procedure SetPrivateKey(const AName, ACSP: string; AProviderType: Integer; AKeyType: TclCertificateKeyType); overload; procedure SetPrivateKey(const AName, ACSP: string; AProviderType, AKeyType: Integer); overload; property Context: PCCERT_CONTEXT read FCertContext; property IssuedTo: string read FIssuedTo; property IssuedBy: string read FIssuedBy; property Email: string read FEmail; property ValidFrom: TDateTime read FValidFrom; property ValidTo: TDateTime read FValidTo; property SerialNumber: string read FSerialNumber; property IsServerAuthentication: Boolean read GetIsServerAuthentication; property IsClientAuthentication: Boolean read GetIsClientAuthentication; property IsCodeSigning: Boolean read GetIsCodeSigning; property IsSecureEmail: Boolean read GetIsSecureEmail; property Version: TclCertificateVersion read FVersion; property SignatureAlgorithm: string read FSignatureAlgorithm; property SignatureAlgorithmName: string read FSignatureAlgorithmName; property PublicKeyAlgorithm: string read FPublicKeyAlgorithm; property PublicKeyAlgorithmName: string read FPublicKeyAlgorithmName; property Subject: string read FSubject; property PrivateKey: string read FPrivateKey; property Thumbprint: string read FThumbprint; property SubjectKeyIdentifier: string read FSubjectKeyIdentifier; property Usage: string read FUsage write SetUsage; property FriendlyName: string read FFriendlyName write SetFriendlyName; end; TclCertificateList = class private FOwnsObjects: Boolean; FList: TList; function GetItem(Index: Integer): TclCertificate; function GetCount: Integer; public constructor Create(AOwnsObjects: Boolean); destructor Destroy; override; procedure Add(ACertificate: TclCertificate); function AddFrom(ACertificate: TclCertificate): TclCertificate; procedure Delete(Index: Integer); procedure Remove(ACertificate: TclCertificate); procedure Clear; property Items[Index: Integer]: TclCertificate read GetItem; default; property Count: Integer read GetCount; property OwnsObjects: Boolean read FOwnsObjects; end; TclCertificateExtension = class private FExtValue: TclCryptData; procedure ClearValue; public destructor Destroy; override; procedure GetExtension(AExtension: PCERT_EXTENSION); virtual; abstract; procedure AssignValue(AValue: PCRYPTOAPI_BLOB; AStructType: PAnsiChar; AStructure: Pointer); end; TclKeyUsageExtension = class(TclCertificateExtension) private FUsage: Integer; public constructor Create(AUsage: Integer); procedure GetExtension(AExtension: PCERT_EXTENSION); override; end; TclEnhancedKeyUsageExtension = class(TclCertificateExtension) private FUsage: TStrings; public constructor Create(AUsage: TStrings); procedure GetExtension(AExtension: PCERT_EXTENSION); override; end; TclCertificateExtensions = class private FList: TObjectList; FrgExtension: TclCryptData; function GetExtension: PCERT_EXTENSION; function GetCount: Integer; procedure Init; function GetItems(Index: Integer): TclCertificateExtension; public constructor Create; destructor Destroy; override; procedure Add(AItem: TclCertificateExtension); procedure Clear; property Items[Index: Integer]: TclCertificateExtension read GetItems; property Count: Integer read GetCount; property Extension: PCERT_EXTENSION read GetExtension; end; {$IFDEF DEMO} {$IFNDEF IDEDEMO} var IsCertDemoDisplayed: Boolean = False; {$ENDIF} {$ENDIF} implementation uses {$IFNDEF DELPHIXE2} {$IFDEF DEMO}Forms,{$ENDIF} {$ELSE} {$IFDEF DEMO}Vcl.Forms,{$ENDIF} {$ENDIF} clEncoder, clUtils{$IFDEF LOGGER}, clLogger{$ENDIF}; { TclCertificate } constructor TclCertificate.Create(ACertContext: PCCERT_CONTEXT); begin inherited Create(); {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Create');{$ENDIF} FCertContext := CertDuplicateCertificateContext(ACertContext); GetCertInfo(); {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Create'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Create', E); raise; end; end;{$ENDIF} end; function TclCertificate.GetSerialNumber(ABlob: CRYPTOAPI_BLOB): string; var i: Integer; p: Pointer; begin Result := ''; for i := ABlob.cbData - 1 downto 0 do begin p := Pointer(TclIntPtr(ABlob.pbData) + i); Result := Result + IntToHex(Byte(p^), 2); end; end; procedure TclCertificate.GetCertInfo(); begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsCertDemoDisplayed) and (not IsEncoderDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsCertDemoDisplayed := True; IsEncoderDemoDisplayed := True; {$ENDIF} end; {$ENDIF} FIssuedTo := GetDecodedName(CERT_NAME_SIMPLE_DISPLAY_TYPE, 0); FIssuedBy := GetDecodedName(CERT_NAME_SIMPLE_DISPLAY_TYPE, CERT_NAME_ISSUER_FLAG); FEmail := GetEMailFromSubject(); if (FEmail = '') then begin FEmail := GetEMailFromAltSubject(); end; FSerialNumber := GetSerialNumber(FCertContext^.pCertInfo.SerialNumber); FValidFrom := ConvertFileTimeToDateTime(FCertContext^.pCertInfo.NotBefore); FValidTo := ConvertFileTimeToDateTime(FCertContext^.pCertInfo.NotAfter); FFriendlyName := GetFriendlyName(); FUsage := GetUsageFlags(); if (FCertContext^.pCertInfo.dwVersion <= DWORD(cvVersion3)) then begin FVersion := TclCertificateVersion(FCertContext^.pCertInfo.dwVersion); end; FSignatureAlgorithm := GetString_(FCertContext^.pCertInfo.SignatureAlgorithm.pszObjId); FSignatureAlgorithmName := GetOidInfo(FSignatureAlgorithm); FPublicKeyAlgorithm := GetString_(FCertContext^.pCertInfo.SubjectPublicKeyInfo.Algorithm.pszObjId); FPublicKeyAlgorithmName := GetOidInfo(FPublicKeyAlgorithm); FSubject := GetSubjectString(); FPrivateKey := GetPrivateKey(); FThumbprint := GetThumbprint(); FSubjectKeyIdentifier := GetSubjectKeyIdentifier(); end; function TclCertificate.GetDecodedName(AType, AFlags: Integer): string; var len: Integer; p: TclCryptData; begin Result := ''; len := CertGetNameString(FCertContext, AType, AFlags, nil, nil, 0); if (len < 1) then Exit; p := TclCryptData.Create(len * 2); try CertGetNameString(FCertContext, AType, AFlags, nil, PWideChar(p.Data), len); Result := string(p.ToWideString()); finally p.Free(); end; end; destructor TclCertificate.Destroy; begin CertFreeCertificateContext(FCertContext); inherited Destroy(); end; function TclCertificate.GetEMailFromAltSubject: string; var i: Integer; pCertExtension: PCERT_EXTENSION; pStruct: Pointer; cbStruct: DWORD; pInfo: PCERT_ALT_NAME_INFO; pEntry: PCERT_ALT_NAME_ENTRY; begin Assert(FCertContext <> nil); Assert(FCertContext.pCertInfo <> nil); Result := ''; if (FCertContext.pCertInfo <> nil) then begin pCertExtension := CertFindExtension(szOID_SUBJECT_ALT_NAME2, FCertContext.pCertInfo.cExtension, FCertContext.pCertInfo.rgExtension); if (pCertExtension <> nil) then begin cbStruct := 0; if (CryptDecodeObject(DefaultEncoding, szOID_SUBJECT_ALT_NAME2, pCertExtension.Value.pbData, pCertExtension.Value.cbData, 0, nil, @cbStruct)) then begin GetMem(pStruct, cbStruct); CryptDecodeObject(DefaultEncoding, szOID_SUBJECT_ALT_NAME2, pCertExtension.Value.pbData, pCertExtension.Value.cbData, 0, pStruct, @cbStruct); pInfo := PCERT_ALT_NAME_INFO(pStruct); for i := 0 to pInfo.cAltEntry - 1 do begin pEntry := PCERT_ALT_NAME_ENTRY(TclIntPtr(pInfo.rgAltEntry) + i * SizeOf(CERT_ALT_NAME_ENTRY)); if (pEntry.dwAltNameChoice = CERT_ALT_NAME_RFC822_NAME) then begin Result := string(WideString(pEntry.pwszRfc822Name)); Break; end; end; FreeMem(pStruct); end; end; end; end; function TclCertificate.GetEMailFromSubject: string; var i, j: Integer; pStruct: Pointer; cbStruct: DWORD; pInfo: PCERT_NAME_INFO; pEntry: PCERT_RDN; pRDNAttr: PCERT_RDN_ATTR; buf: PclChar; begin Assert(FCertContext <> nil); Assert(FCertContext.pCertInfo <> nil); Result := ''; if (FCertContext.pCertInfo <> nil) then begin cbStruct := 0; if (CryptDecodeObject(DefaultEncoding, X509_NAME, FCertContext.pCertInfo.Subject.pbData, FCertContext.pCertInfo.Subject.cbData, 0, nil, @cbStruct)) then begin GetMem(pStruct, cbStruct); CryptDecodeObject(DefaultEncoding, X509_NAME, FCertContext.pCertInfo.Subject.pbData, FCertContext.pCertInfo.Subject.cbData, 0, pStruct, @cbStruct); pInfo := PCERT_NAME_INFO(pStruct); for i := 0 to pInfo.cRDN - 1 do begin pEntry := PCERT_RDN(TclIntPtr(pInfo.rgRDN) + i * SizeOf(CERT_RDN)); for j := 0 to pEntry.cRDNAttr - 1 do begin pRDNAttr := PCERT_RDN_ATTR(TclIntPtr(pEntry.rgRDNAttr) + j * SizeOf(CERT_RDN_ATTR)); if (SameText(GetString_(pRDNAttr.pszObjId), szOID_RSA_emailAddr)) then begin if (pRDNAttr.Value.cbData > 0) then begin GetMem(buf, pRDNAttr.Value.cbData); try System.Move(pRDNAttr.Value.pbData^, Pointer(buf)^, pRDNAttr.Value.cbData); Result := TclTranslator.GetString(buf, pRDNAttr.Value.cbData, 'us-ascii'); finally FreeMem(buf); end; end else begin Result := ''; end; Break; end; end; if (Result <> '') then Break; end; FreeMem(pStruct); end; end; end; function TclCertificate.GetFriendlyName: string; var cbSize: DWORD; buf: TclCryptData; begin Result := ''; cbSize := 0; if not CertGetCertificateContextProperty(FCertContext, CERT_FRIENDLY_NAME_PROP_ID, nil, @cbSize) then Exit; if (cbSize < 1) then Exit; buf := TclCryptData.Create(cbSize); try CertGetCertificateContextProperty(FCertContext, CERT_FRIENDLY_NAME_PROP_ID, buf.Data, @cbSize); Result := string(buf.ToWideString()); finally buf.Free(); end; end; function TclCertificate.GetIsClientAuthentication: Boolean; begin Result := CheckUsage(szOID_PKIX_KP_CLIENT_AUTH); end; function TclCertificate.GetIsCodeSigning: Boolean; begin Result := CheckUsage(szOID_PKIX_KP_CODE_SIGNING); end; function TclCertificate.GetIsSecureEmail: Boolean; begin Result := CheckUsage(szOID_PKIX_KP_EMAIL_PROTECTION); end; function TclCertificate.GetIsServerAuthentication: Boolean; begin Result := CheckUsage(szOID_PKIX_KP_SERVER_AUTH); end; function TclCertificate.GetOidInfo(const AOID: string): string; var pOidInfo: PCCRYPT_OID_INFO; s: string; begin Result := AOID; pOidInfo := CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, PclChar(GetTclString(AOID)), 0); if (pOidInfo <> nil) then begin s := string(WideString(pOidInfo.pwszName)); Result := system.Copy(s, 1, Length(s)); end; end; function TclCertificate.GetPrivateKey: string; var cbSize: DWORD; pInfo: TclCryptData; begin Result := ''; cbSize := 0; if not CertGetCertificateContextProperty(FCertContext, CERT_KEY_PROV_INFO_PROP_ID, nil, @cbSize) then Exit; if (cbSize < 1) then Exit; pInfo := TclCryptData.Create(cbSize); try CertGetCertificateContextProperty(FCertContext, CERT_KEY_PROV_INFO_PROP_ID, pInfo.Data, @cbSize); Result := system.Copy(string(WideString(PCRYPT_KEY_PROV_INFO(pInfo.Data).pwszContainerName)), 1, cbSize); finally pInfo.Free(); end; end; function TclCertificate.GetSubjectKeyIdentifier: string; var pCertExtension: PCERT_EXTENSION; pStruct: Pointer; cbStruct: DWORD; pb: PCRYPT_DATA_BLOB; begin Assert(FCertContext <> nil); Assert(FCertContext.pCertInfo <> nil); Result := ''; if (FCertContext.pCertInfo <> nil) then begin pCertExtension := CertFindExtension(szOID_SUBJECT_KEY_IDENTIFIER, FCertContext.pCertInfo.cExtension, FCertContext.pCertInfo.rgExtension); if (pCertExtension <> nil) then begin cbStruct := 0; if (CryptDecodeObject(DefaultEncoding, szOID_SUBJECT_KEY_IDENTIFIER, pCertExtension.Value.pbData, pCertExtension.Value.cbData, 0, nil, @cbStruct)) then begin GetMem(pStruct, cbStruct); try CryptDecodeObject(DefaultEncoding, szOID_SUBJECT_KEY_IDENTIFIER, pCertExtension.Value.pbData, pCertExtension.Value.cbData, 0, pStruct, @cbStruct); pb := PCRYPT_DATA_BLOB(pStruct); Result := BytesToHex(pb.pbData, pb.cbData); finally FreeMem(pStruct); end; end; end; end; end; function TclCertificate.GetSubjectString: string; var len: Integer; buf: TclCryptData; begin Result := ''; len := CertNameToStr(Context.dwCertEncodingType, @Context.pCertInfo.Subject, CERT_X500_NAME_STR or CERT_NAME_STR_NO_PLUS_FLAG, nil, 0); if (len < 1) then Exit; buf := TclCryptData.Create(len * 2); try CertNameToStr(Context.dwCertEncodingType, @Context.pCertInfo.Subject, CERT_X500_NAME_STR or CERT_NAME_STR_NO_PLUS_FLAG, PWideChar(buf.Data), len); Result := string(buf.ToWideString()); finally buf.Free(); end; end; function TclCertificate.GetThumbprint: string; var cbSize: DWORD; pInfo: TclCryptData; begin Result := ''; cbSize := 0; if not CertGetCertificateContextProperty(FCertContext, CERT_HASH_PROP_ID, nil, @cbSize) then Exit; if (cbSize < 1) then Exit; pInfo := TclCryptData.Create(cbSize); try CertGetCertificateContextProperty(FCertContext, CERT_HASH_PROP_ID, pInfo.Data, @cbSize); Result := BytesToHex(pInfo.Data, cbSize); finally pInfo.Free(); end; end; procedure TclCertificate.SetUsageFlags(AFlags: TStrings); function GetTotalLen(AList: TStrings): Integer; var i: Integer; begin Result := 0; for i := 0 to AList.Count - 1 do begin Result := Result + Length(AList[i]) + 1; end; end; var i: Integer; usageInfo: CERT_ENHKEY_USAGE; pIdentifiers, pFlags: TclCryptData; pi, pf: PclChar; s: TclString; begin usageInfo.cUsageIdentifier := AFlags.Count; pIdentifiers := nil; pFlags := nil; try pIdentifiers := TclCryptData.Create(AFlags.Count * SizeOf(Pointer)); usageInfo.rgpszUsageIdentifier := pIdentifiers.Data; pFlags := TclCryptData.Create(GetTotalLen(AFlags)); pf := PclChar(pFlags.Data); pi := PclChar(usageInfo.rgpszUsageIdentifier); for i := 0 to AFlags.Count - 1 do begin system.Move(pf, pi^, SizeOf(pf)); s := GetTclString(AFlags[i]) + #0; system.Move(Pointer(s)^, pf^, Length(s)); pf := pf + Length(s); pi := pi + SizeOf(Pointer); end; if not CertSetEnhancedKeyUsage(Context, @usageInfo) then begin RaiseCryptError('CertSetEnhancedKeyUsage'); end; finally pFlags.Free(); pIdentifiers.Free(); end; end; function TclCertificate.GetUsageFlags: string; var i: Integer; cbSize: DWORD; pUsage: TclCryptData; usageInfo: PCERT_ENHKEY_USAGE; p: Pointer; pc: PclChar; s: string; begin Result := ''; cbSize := 0; if (not CertGetEnhancedKeyUsage(Context, 0, nil, @cbSize)) or (cbSize = 0) then begin if (GetLastError() = CRYPT_E_NOT_FOUND) then Exit; RaiseCryptError('CertGetEnhancedKeyUsage'); end; pUsage := TclCryptData.Create(cbSize); try CertGetEnhancedKeyUsage(Context, 0, PCERT_ENHKEY_USAGE(pUsage.Data), @cbSize); usageInfo := PCERT_ENHKEY_USAGE(pUsage.Data); for i := 0 to Integer(usageInfo.cUsageIdentifier) - 1 do begin p := Pointer(TclIntPtr(usageInfo.rgpszUsageIdentifier) + i * SizeOf(Pointer)); pc := PclChar(p^); if (Length(pc) > 0) then begin s := TclTranslator.GetString(pc, Length(pc), 'us-ascii'); Result := Result + s + ','; end; end; if (Result <> '') then begin SetLength(Result, Length(Result) - 1); end; finally pUsage.Free(); end; end; procedure TclCertificate.SetFriendlyName(const Value: string); var nameBlob: CRYPT_DATA_BLOB; ws: WideString; begin if (FFriendlyName = Value) then Exit; FFriendlyName := Value; ws := WideString(FFriendlyName); nameBlob.cbData := (Length(ws) + 1) * 2; nameBlob.pbData := Pointer(ws); if not CertSetCertificateContextProperty(Context, CERT_FRIENDLY_NAME_PROP_ID, 0, @nameBlob) then begin RaiseCryptError('CertSetCertificateContextProperty'); end; end; procedure TclCertificate.SetPrivateKey(const AName, ACSP: string; AProviderType: Integer; AKeyType: TclCertificateKeyType); begin SetPrivateKey(AName, ACSP, AProviderType, GetKeyTypeInt(AKeyType)); end; procedure TclCertificate.SetPrivateKey(const AName, ACSP: string; AProviderType, AKeyType: Integer); var info: CRYPT_KEY_PROV_INFO; begin info.pwszContainerName := PWideChar(WideString(AName)); info.pwszProvName := PWideChar(WideString(ACSP)); info.dwProvType := AProviderType; info.dwFlags := 0; info.cProvParam := 0; info.rgProvParam := nil; info.dwKeySpec := AKeyType; if not CertSetCertificateContextProperty(Context, CERT_KEY_PROV_INFO_PROP_ID, 0, @info) then begin RaiseCryptError('CertSetCertificateContextProperty'); end; end; procedure TclCertificate.SetUsage(const Value: string); var s: string; list: TStrings; begin if (FUsage = Value) then Exit; FUsage := Value; s := StringReplace(FUsage, ',', #13#10, [rfReplaceAll]); s := StringReplace(s, ';', #13#10, [rfReplaceAll]); list := TStringList.Create(); try list.Text := s; SetUsageFlags(list); finally list.Free(); end; end; function TclCertificate.CheckUsage(const AOID: string): Boolean; begin Result := (Usage = '') or (system.Pos(AOID, Usage) > 0); end; constructor TclCertificate.Create(AEncoded: PByte; ALength: Integer); begin inherited Create(); {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'CreateFromBinary');{$ENDIF} FCertContext := CertCreateCertificateContext(DefaultEncoding, AEncoded, ALength); FCertContext := CertDuplicateCertificateContext(FCertContext); if (FCertContext = nil) then begin RaiseCryptError('CertDuplicateCertificateContext'); end; GetCertInfo(); {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'CreateFromBinary'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'CreateFromBinary', E); raise; end; end;{$ENDIF} end; { TclCertificateList } procedure TclCertificateList.Add(ACertificate: TclCertificate); begin FList.Add(ACertificate); end; function TclCertificateList.AddFrom(ACertificate: TclCertificate): TclCertificate; begin Result := TclCertificate.Create(ACertificate.Context); Add(Result); end; procedure TclCertificateList.Clear; var i: Integer; begin if FOwnsObjects then begin for i := 0 to Count - 1 do begin Items[i].Free(); end; end; FList.Clear(); end; constructor TclCertificateList.Create(AOwnsObjects: Boolean); begin inherited Create(); FList := TList.Create(); FOwnsObjects := AOwnsObjects; end; procedure TclCertificateList.Delete(Index: Integer); begin if FOwnsObjects then begin Items[Index].Free(); end; FList.Delete(Index); end; destructor TclCertificateList.Destroy; begin Clear(); FList.Free(); inherited Destroy(); end; function TclCertificateList.GetCount: Integer; begin Result := FList.Count; end; function TclCertificateList.GetItem(Index: Integer): TclCertificate; begin Result := TclCertificate(FList[Index]); end; procedure TclCertificateList.Remove(ACertificate: TclCertificate); begin Delete(FList.IndexOf(ACertificate)); end; { TclCertificateExtensions } procedure TclCertificateExtensions.Add(AItem: TclCertificateExtension); begin Init(); FList.Add(AItem); end; procedure TclCertificateExtensions.Clear; begin Init(); FList.Clear(); end; constructor TclCertificateExtensions.Create; begin inherited Create(); FList := TObjectList.Create(True); FrgExtension := nil; end; destructor TclCertificateExtensions.Destroy; begin Clear(); FList.Free(); inherited Destroy(); end; function TclCertificateExtensions.GetCount: Integer; begin Result := FList.Count; end; function TclCertificateExtensions.GetExtension: PCERT_EXTENSION; var i: Integer; begin Init(); Result := nil; if (Count > 0) then begin FrgExtension := TclCryptData.Create(Count * Sizeof(CERT_EXTENSION)); for i := 0 to Count - 1 do begin Items[i].GetExtension(PCERT_EXTENSION(TclIntPtr(FrgExtension.Data) + i * Sizeof(CERT_EXTENSION))); end; Result := PCERT_EXTENSION(FrgExtension.Data); end; end; function TclCertificateExtensions.GetItems(Index: Integer): TclCertificateExtension; begin Result := TclCertificateExtension(FList[Index]); end; procedure TclCertificateExtensions.Init; begin FrgExtension.Free(); FrgExtension := nil; end; { TclKeyUsageExtension } constructor TclKeyUsageExtension.Create(AUsage: Integer); begin inherited Create(); FUsage := AUsage; end; procedure TclKeyUsageExtension.GetExtension(AExtension: PCERT_EXTENSION); var KeyUsage: CRYPT_BIT_BLOB; begin ZeroMemory(@KeyUsage, Sizeof(KeyUsage)); KeyUsage.cbData := 1; GetMem(KeyUsage.pbData, KeyUsage.cbData); try KeyUsage.pbData^ := FUsage; AExtension.pszObjId := szOID_KEY_USAGE; AExtension.fCritical := True; AssignValue(@AExtension.Value, X509_KEY_USAGE, @KeyUsage); finally FreeMem(KeyUsage.pbData); end; end; { TclEnhancedKeyUsageExtension } constructor TclEnhancedKeyUsageExtension.Create(AUsage: TStrings); begin inherited Create(); FUsage := AUsage; end; procedure TclEnhancedKeyUsageExtension.GetExtension(AExtension: PCERT_EXTENSION); var i: Integer; EnhKeyUsage: CERT_ENHKEY_USAGE; p: ^PclChar; oidList: TList; s: TclString; buf: PclChar; begin ZeroMemory(@EnhKeyUsage, Sizeof(EnhKeyUsage)); EnhKeyUsage.cUsageIdentifier := FUsage.Count; GetMem(EnhKeyUsage.rgpszUsageIdentifier, SizeOf(PclChar) * EnhKeyUsage.cUsageIdentifier); try oidList := TList.Create(); try for i := 0 to EnhKeyUsage.cUsageIdentifier - 1 do begin p := Pointer(TclIntPtr(EnhKeyUsage.rgpszUsageIdentifier) + i * SizeOf(PclChar)); s := GetTclString(FUsage[i]); GetMem(buf, Length(s) + 1); oidList.Add(buf); system.Move(Pointer(s)^, buf^, Length(s)); buf[Length(s)] := #0; p^ := buf; end; AExtension.pszObjId := szOID_ENHANCED_KEY_USAGE; AExtension.fCritical := False; AssignValue(@AExtension.Value, X509_ENHANCED_KEY_USAGE, @EnhKeyUsage); finally for i := oidList.Count - 1 downto 0 do begin FreeMem(oidList[i]); end; oidList.Free(); end; finally FreeMem(EnhKeyUsage.rgpszUsageIdentifier); end; end; { TclCertificateExtension } procedure TclCertificateExtension.ClearValue; begin FExtValue.Free(); FExtValue := nil; end; destructor TclCertificateExtension.Destroy; begin ClearValue(); inherited Destroy(); end; procedure TclCertificateExtension.AssignValue(AValue: PCRYPTOAPI_BLOB; AStructType: PAnsiChar; AStructure: Pointer); var size: DWORD; begin ClearValue(); if not CryptEncodeObject(DefaultEncoding, AStructType, AStructure, nil, @size) then begin RaiseCryptError('CryptEncodeObject'); end; FExtValue := TclCryptData.Create(size); AValue.cbData := size; AValue.pbData := FExtValue.Data; ZeroMemory(AValue.pbData, AValue.cbData); if not CryptEncodeObject(DefaultEncoding, AStructType, AStructure, AValue.pbData, @size) then begin RaiseCryptError('CryptEncodeObject'); end; FExtValue.Reduce(size); end; end.
{******************************************************************************} { } { Delphi FB4D Library } { Copyright (c) 2018-2023 Christoph Schneider } { Schneider Infosystems AG, Switzerland } { https://github.com/SchneiderInfosystems/FB4D } { } {******************************************************************************} { } { 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 FB4D.Authentication; interface uses System.Classes, System.SysUtils, System.Types, System.SyncObjs, System.JSON, System.JSON.Types, System.Net.HttpClient, System.Generics.Collections, REST.Types, {$IFDEF TOKENJWT} FB4D.OAuth, {$ENDIF} FB4D.Interfaces, FB4D.Response, FB4D.Request; type TFirebaseAuthentication = class(TInterfacedObject, IFirebaseAuthentication) private const cSafetyMargin = 5 / 3600 / 24; // 5 sec private type TSignType = (stNewUser, stLogin, stAnonymousLogin); private var fApiKey: string; fCSForToken: TCriticalSection; fAuthenticated: boolean; fToken: string; {$IFDEF TOKENJWT} fTokenJWT: ITokenJWT; {$ENDIF} fExpiresAt: TDateTime; fRefreshToken: string; fTokenRefreshCount: cardinal; fOnTokenRefresh: TOnTokenRefresh; fLastUTCServerTime: TDateTime; function SignWithEmailAndPasswordSynchronous(SignType: TSignType; const Email: string = ''; const Password: string = ''): IFirebaseUser; procedure SignWithEmailAndPassword(SignType: TSignType; const Info: string; OnUserResponse: TOnUserResponse; OnError: TOnRequestError; const Email: string = ''; const Password: string = ''); procedure OnUserResp(const RequestID: string; Response: IFirebaseResponse); procedure OnFetchProvidersResp(const RequestID: string; Response: IFirebaseResponse); procedure OnDeleteProvidersResp(const RequestID: string; Response: IFirebaseResponse); procedure OnVerifyPasswordResp(const RequestID: string; Response: IFirebaseResponse); procedure OnUserListResp(const RequestID: string; Response: IFirebaseResponse); procedure CheckAndRefreshTokenResp(const RequestID: string; Response: IFirebaseResponse); procedure AddPairForTokenId(Data: TJSONObject); public constructor Create(const ApiKey: string); destructor Destroy; override; // Create new User with email and password procedure SignUpWithEmailAndPassword(const Email, Password: string; OnUserResponse: TOnUserResponse; OnError: TOnRequestError); function SignUpWithEmailAndPasswordSynchronous(const Email, Password: string): IFirebaseUser; // Login procedure SignInWithEmailAndPassword(const Email, Password: string; OnUserResponse: TOnUserResponse; OnError: TOnRequestError); function SignInWithEmailAndPasswordSynchronous(const Email, Password: string): IFirebaseUser; procedure SignInAnonymously(OnUserResponse: TOnUserResponse; OnError: TOnRequestError); function SignInAnonymouslySynchronous: IFirebaseUser; // Link new email/password access to anonymous user procedure LinkWithEMailAndPassword(const EMail, Password: string; OnUserResponse: TOnUserResponse; OnError: TOnRequestError); function LinkWithEMailAndPasswordSynchronous(const EMail, Password: string): IFirebaseUser; // Login by using OAuth from Facebook, Twitter, Google, etc. procedure LinkOrSignInWithOAuthCredentials(const OAuthTokenName, OAuthToken, ProviderID, RequestUri: string; OnUserResponse: TOnUserResponse; OnError: TOnRequestError); function LinkOrSignInWithOAuthCredentialsSynchronous(const OAuthTokenName, OAuthToken, ProviderID, RequestUri: string): IFirebaseUser; // Logout procedure SignOut; // Send EMail for EMail Verification procedure SendEmailVerification(OnResponse: TOnFirebaseResp; OnError: TOnRequestError); procedure SendEmailVerificationSynchronous; // Providers procedure FetchProvidersForEMail(const EMail: string; OnFetchProviders: TOnFetchProviders; OnError: TOnRequestError); function FetchProvidersForEMailSynchronous(const EMail: string; Providers: TStrings): boolean; // returns true if EMail is registered procedure DeleteProviders(Providers: TStrings; OnProviderDeleted: TOnFirebaseResp; OnError: TOnRequestError); function DeleteProvidersSynchronous(Providers: TStrings): boolean; // Reset Password procedure SendPasswordResetEMail(const Email: string; OnResponse: TOnFirebaseResp; OnError: TOnRequestError); procedure SendPasswordResetEMailSynchronous(const Email: string); procedure VerifyPasswordResetCode(const ResetPasswortCode: string; OnPasswordVerification: TOnPasswordVerification; OnError: TOnRequestError); function VerifyPasswordResetCodeSynchronous(const ResetPasswortCode: string): TPasswordVerificationResult; procedure ConfirmPasswordReset(const ResetPasswortCode, NewPassword: string; OnResponse: TOnFirebaseResp; OnError: TOnRequestError); procedure ConfirmPasswordResetSynchronous(const ResetPasswortCode, NewPassword: string); // Change password, Change email, Update Profile Data // let field empty which shall not be changed procedure ChangeProfile(const EMail, Password, DisplayName, PhotoURL: string; OnResponse: TOnFirebaseResp; OnError: TOnRequestError); procedure ChangeProfileSynchronous(const EMail, Password, DisplayName, PhotoURL: string); // Delete signed in user account procedure DeleteCurrentUser(OnResponse: TOnFirebaseResp; OnError: TOnRequestError); procedure DeleteCurrentUserSynchronous; // Get User Data procedure GetUserData(OnGetUserData: TOnGetUserData; OnError: TOnRequestError); function GetUserDataSynchronous: TFirebaseUserList; // Token refresh procedure RefreshToken(OnTokenRefresh: TOnTokenRefresh; OnError: TOnRequestError); overload; procedure RefreshToken(const LastRefreshToken: string; OnTokenRefresh: TOnTokenRefresh; OnError: TOnRequestError); overload; function CheckAndRefreshTokenSynchronous( IgnoreExpiryCheck: boolean = false): boolean; // register call back in all circumstances when the token will be refreshed procedure InstallTokenRefreshNotification(OnTokenRefresh: TOnTokenRefresh); // Getter methods function Authenticated: boolean; function Token: string; {$IFDEF TOKENJWT} function TokenJWT: ITokenJWT; {$ENDIF} function TokenExpiryDT: TDateTime; function NeedTokenRefresh: boolean; function GetRefreshToken: string; function GetTokenRefreshCount: cardinal; function GetLastServerTime(TimeZone: TTimeZone = tzLocalTime): TDateTime; property ApiKey: string read fApiKey; end; TFirebaseUser = class(TInterfacedObject, IFirebaseUser) private fJSONResp: TJSONObject; fToken: string; {$IFDEF TOKENJWT} fTokenJWT: ITokenJWT; fClaimFields: TDictionary<string,TJSONValue>; {$ENDIF} fExpiresAt: TDateTime; fRefreshToken: string; public constructor Create(JSONResp: TJSONObject; TokenExpected: boolean = true); overload; {$IFDEF TOKENJWT} constructor Create(JSONResp: TJSONObject; TokenJWT: ITokenJWT); overload; {$ENDIF} destructor Destroy; override; // Get User Identification function UID: string; // Get EMail Address function IsEMailAvailable: boolean; function IsEMailRegistered: TThreeStateBoolean; function IsEMailVerified: TThreeStateBoolean; function EMail: string; // Get User Display Name function IsDisplayNameAvailable: boolean; function DisplayName: string; // Get Photo URL for User Avatar or Photo function IsPhotoURLAvailable: boolean; function PhotoURL: string; // Get User Account State and Timestamps function IsDisabled: TThreeStateBoolean; function IsNewSignupUser: boolean; function IsLastLoginAtAvailable: boolean; function LastLoginAt(TimeZone: TTimeZone = tzLocalTime): TDateTime; function IsCreatedAtAvailable: boolean; function CreatedAt(TimeZone: TTimeZone = tzLocalTime): TDateTime; // Provider User Info function ProviderCount: integer; function Provider(ProviderNo: integer): TProviderInfo; // In case of OAuth sign-in function OAuthFederatedId: string; function OAuthProviderId: string; function OAuthIdToken: string; function OAuthAccessToken: string; function OAuthTokenSecret: string; function OAuthRawUserInfo: string; // Get Token Details and Claim Fields function Token: string; {$IFDEF TOKENJWT} function TokenJWT: ITokenJWT; function ClaimFieldNames: TStrings; function ClaimField(const FieldName: string): TJSONValue; {$ENDIF} function ExpiresAt: TDateTime; // local time function RefreshToken: string; end; implementation uses FB4D.Helpers; const GOOGLE_PASSWORD_URL = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty'; GOOGLE_REFRESH_AUTH_URL = 'https://securetoken.googleapis.com/v1/token'; GOOGLE_IDTOOLKIT_URL = 'https://identitytoolkit.googleapis.com/v1'; resourcestring rsSignInAnonymously = 'Sign in anonymously'; rsSignInWithEmail = 'Sign in with email for %s'; rsSignUpWithEmail = 'Sign up with email for %s'; rsSignInWithOAuth = 'Sign in with OAuth for %s'; rsEnableAnonymousLogin = 'In the firebase console under Authentication/' + 'Sign-in method firstly enable anonymous sign-in provider.'; rsSendPasswordResetEMail = 'EMail to reset the password sent to %s'; rsSendVerificationEMail = 'EMail to verify the email sent'; rsVerifyPasswordResetCode = 'Verify password reset code'; rsFetchProviders = 'Fetch providers for %s'; rsDeleteProviders = 'Delete providers %s'; rsConfirmPasswordReset = 'Confirm password reset'; rsChangeProfile = 'Change profile for %s'; rsDeleteCurrentUser = 'Delete signed-in user account'; rsRetriveUserList = 'Get account info'; rsRefreshToken = 'Refresh token'; { TFirebaseAuthentication } constructor TFirebaseAuthentication.Create(const ApiKey: string); begin inherited Create; fApiKey := ApiKey; fCSForToken := TCriticalSection.Create; fTokenRefreshCount := 1; // begin with 1 and use 0 as sentinel fOnTokenRefresh := nil; fLastUTCServerTime := 0; end; destructor TFirebaseAuthentication.Destroy; begin fCSForToken.Free; inherited; end; procedure TFirebaseAuthentication.SignInAnonymously( OnUserResponse: TOnUserResponse; OnError: TOnRequestError); begin SignWithEmailAndPassword(stAnonymousLogin, rsSignInAnonymously, OnUserResponse, OnError); end; function TFirebaseAuthentication.SignInAnonymouslySynchronous: IFirebaseUser; begin result := SignWithEmailAndPasswordSynchronous(stAnonymousLogin); end; procedure TFirebaseAuthentication.SignInWithEmailAndPassword(const Email, Password: string; OnUserResponse: TOnUserResponse; OnError: TOnRequestError); begin SignWithEmailAndPassword(stLogin, Format(rsSignInWithEmail, [EMail]), OnUserResponse, OnError, Email, Password); end; function TFirebaseAuthentication.SignInWithEmailAndPasswordSynchronous( const Email, Password: string): IFirebaseUser; begin result := SignWithEmailAndPasswordSynchronous(stLogin, Email, Password); end; procedure TFirebaseAuthentication.AddPairForTokenId(Data: TJSONObject); begin fCSForToken.Acquire; try if not fToken.IsEmpty then Data.AddPair(TJSONPair.Create('idToken', fToken)); finally fCSForToken.Release; end; end; procedure TFirebaseAuthentication.LinkOrSignInWithOAuthCredentials( const OAuthTokenName, OAuthToken, ProviderID, RequestUri: string; OnUserResponse: TOnUserResponse; OnError: TOnRequestError); var Data: TJSONObject; Params: TQueryParams; Request: IFirebaseRequest; begin fAuthenticated := false; Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_IDTOOLKIT_URL, Format(rsSignInWithOAuth, [ProviderID])); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('postBody', OAuthTokenName + '=' + OAuthToken + '&providerId=' + ProviderID)); Data.AddPair(TJSONPair.Create('requestUri', requestUri)); AddPairForTokenId(Data); Data.AddPair(TJSONPair.Create('returnSecureToken', 'true')); Data.AddPair(TJSONPair.Create('returnIdpCredential', 'true')); Params.Add('key', [ApiKey]); Request.SendRequest(['accounts:signInWithIdp'], rmPost, Data, Params, tmNoToken, OnUserResp, OnError, TOnSuccess.CreateUser(OnUserResponse)); finally Params.Free; Data.Free; end; end; function TFirebaseAuthentication.LinkOrSignInWithOAuthCredentialsSynchronous( const OAuthTokenName, OAuthToken, ProviderID, RequestUri: string): IFirebaseUser; var Data: TJSONObject; Params: TQueryParams; Request: TFirebaseRequest; Response: IFirebaseResponse; User: TFirebaseUser; begin result := nil; fAuthenticated := false; Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_IDTOOLKIT_URL); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('postBody', OAuthTokenName + '=' + OAuthToken + '&providerId=' + ProviderID)); Data.AddPair(TJSONPair.Create('requestUri', requestUri)); AddPairForTokenId(Data); Data.AddPair(TJSONPair.Create('returnSecureToken', 'true')); Data.AddPair(TJSONPair.Create('returnIdpCredential', 'true')); Params.Add('key', [ApiKey]); Response := Request.SendRequestSynchronous(['accounts:signInWithIdp'], rmPost, Data, Params, tmNoToken); Response.CheckForJSONObj; User := TFirebaseUser.Create(Response.GetContentAsJSONObj); fCSForToken.Acquire; try fAuthenticated := true; fToken := User.fToken; {$IFDEF TOKENJWT} fTokenJWT := User.fTokenJWT; {$ENDIF} fExpiresAt := User.fExpiresAt; fRefreshToken := User.fRefreshToken; inc(fTokenRefreshCount); finally fCSForToken.Release; end; if assigned(fOnTokenRefresh) then fOnTokenRefresh(not fRefreshToken.IsEmpty); result := User; finally Response := nil; Params.Free; Request.Free; Data.Free; end; end; procedure TFirebaseAuthentication.SignOut; begin fCSForToken.Acquire; try fToken := ''; {$IFDEF TOKENJWT} fTokenJWT := nil; {$ENDIF} fRefreshToken := ''; fAuthenticated := false; inc(fTokenRefreshCount); finally fCSForToken.Release; end; if assigned(fOnTokenRefresh) then fOnTokenRefresh(false); end; procedure TFirebaseAuthentication.SendEmailVerification(OnResponse: TOnFirebaseResp; OnError: TOnRequestError); var Data: TJSONObject; Params: TQueryParams; Request: IFirebaseRequest; begin Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_PASSWORD_URL, rsSendVerificationEMail); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('requestType', 'VERIFY_EMAIL')); Data.AddPair(TJSONPair.Create('idToken', Token)); Params.Add('key', [ApiKey]); Request.SendRequest(['getOobConfirmationCode'], rmPost, Data, Params, tmNoToken, OnResponse, OnError, TOnSuccess.Create(nil)); finally Params.Free; Data.Free; end; end; procedure TFirebaseAuthentication.SendEmailVerificationSynchronous; var Data: TJSONObject; Params: TQueryParams; Request: TFirebaseRequest; Response: IFirebaseResponse; begin Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_PASSWORD_URL); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('requestType', 'VERIFY_EMAIL')); Data.AddPair(TJSONPair.Create('idToken', Token)); Params.Add('key', [ApiKey]); Response := Request.SendRequestSynchronous(['getOobConfirmationCode'], rmPost, Data, Params, tmNoToken); if not Response.StatusOk then Response.CheckForJSONObj; finally Response := nil; Params.Free; Request.Free; Data.Free; end; end; procedure TFirebaseAuthentication.SignUpWithEmailAndPassword(const Email, Password: string; OnUserResponse: TOnUserResponse; OnError: TOnRequestError); begin SignWithEmailAndPassword(stNewUser, Format(rsSignUpWithEmail, [EMail]), OnUserResponse, OnError, Email, Password); end; function TFirebaseAuthentication.SignUpWithEmailAndPasswordSynchronous( const Email, Password: string): IFirebaseUser; begin result := SignWithEmailAndPasswordSynchronous(stNewUser, Email, Password); end; procedure TFirebaseAuthentication.OnUserResp(const RequestID: string; Response: IFirebaseResponse); var User: IFirebaseUser; ErrMsg: string; begin try Response.CheckForJSONObj; fLastUTCServerTime := Response.GetServerTime(tzUTC); User := TFirebaseUser.Create(Response.GetContentAsJSONObj); fCSForToken.Acquire; try fAuthenticated := true; if fToken <> User.Token then begin fToken := User.Token; {$IFDEF TOKENJWT} fTokenJWT := User.TokenJWT; {$ENDIF} inc(fTokenRefreshCount); end; fExpiresAt := User.ExpiresAt; fRefreshToken := User.RefreshToken; finally fCSForToken.Release; end; if assigned(Response.OnSuccess.OnUserResponse) then Response.OnSuccess.OnUserResponse(RequestID, User); if assigned(fOnTokenRefresh) then fOnTokenRefresh(not fRefreshToken.IsEmpty); except on e: EFirebaseResponse do begin if sameText(e.Message, TFirebaseResponse.ExceptOpNotAllowed) and (RequestID = rsSignInAnonymously) then ErrMsg := rsEnableAnonymousLogin else ErrMsg := e.Message; if assigned(Response.OnError) then Response.OnError(RequestID, ErrMsg) else TFirebaseHelpers.LogFmt(rsFBFailureIn, ['FirebaseAuthentication.OnUserResp', RequestID, ErrMsg]); end; on e: Exception do begin if assigned(Response.OnError) then Response.OnError(RequestID, e.Message) else TFirebaseHelpers.LogFmt(rsFBFailureIn, ['FirebaseAuthentication.OnUserResp', RequestID, e.Message]); end; end; end; procedure TFirebaseAuthentication.SignWithEmailAndPassword(SignType: TSignType; const Info: string; OnUserResponse: TOnUserResponse; OnError: TOnRequestError; const Email, Password: string); const ResourceStr: array [TSignType] of string = ('signupNewUser', 'verifyPassword', 'signupNewUser'); var Data: TJSONObject; Params: TQueryParams; Request: IFirebaseRequest; begin fAuthenticated := false; Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_PASSWORD_URL, Info); Params := TQueryParams.Create; try if SignType < stAnonymousLogin then begin Data.AddPair(TJSONPair.Create('email', Email)); Data.AddPair(TJSONPair.Create('password', Password)); end; Data.AddPair(TJSONPair.Create('returnSecureToken', 'true')); Params.Add('key', [ApiKey]); Request.SendRequest([ResourceStr[SignType]], rmPost, Data, Params, tmNoToken, OnUserResp, OnError, TOnSuccess.CreateUser(OnUserResponse)); finally Params.Free; Data.Free; end; end; function TFirebaseAuthentication.SignWithEmailAndPasswordSynchronous( SignType: TSignType; const Email, Password: string): IFirebaseUser; const ResourceStr: array [TSignType] of string = ('signupNewUser', 'verifyPassword', 'signupNewUser'); var Data: TJSONObject; Params: TQueryParams; Request: TFirebaseRequest; Response: IFirebaseResponse; User: TFirebaseUser; begin result := nil; fAuthenticated := false; Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_PASSWORD_URL); Params := TQueryParams.Create; try if SignType < stAnonymousLogin then begin Data.AddPair(TJSONPair.Create('email', Email)); Data.AddPair(TJSONPair.Create('password', Password)); end; Data.AddPair(TJSONPair.Create('returnSecureToken', 'true')); Params.Add('key', [ApiKey]); Response := Request.SendRequestSynchronous([ResourceStr[SignType]], rmPost, Data, Params, tmNoToken); Response.CheckForJSONObj; fLastUTCServerTime := Response.GetServerTime(tzUTC); User := TFirebaseUser.Create(Response.GetContentAsJSONObj); fCSForToken.Acquire; try fAuthenticated := true; if fToken <> User.fToken then begin fToken := User.fToken; {$IFDEF TOKENJWT} fTokenJWT := User.fTokenJWT; {$ENDIF} inc(fTokenRefreshCount); end; fExpiresAt := User.fExpiresAt; fRefreshToken := User.fRefreshToken; finally fCSForToken.Release; end; if assigned(fOnTokenRefresh) then fOnTokenRefresh(not fRefreshToken.IsEmpty); result := User; finally Response := nil; Params.Free; Request.Free; Data.Free; end; end; procedure TFirebaseAuthentication.FetchProvidersForEMail(const EMail: string; OnFetchProviders: TOnFetchProviders; OnError: TOnRequestError); var Data: TJSONObject; Params: TQueryParams; Request: IFirebaseRequest; begin Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_PASSWORD_URL, Format(rsFetchProviders, [EMail])); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('identifier', Email)); Data.AddPair(TJSONPair.Create('continueUri', 'http://locahost')); Params.Add('key', [ApiKey]); Request.SendRequest(['createAuthUri'], rmPOST, Data, Params, tmNoToken, OnFetchProvidersResp, onError, TOnSuccess.CreateFetchProviders(OnFetchProviders)); finally Params.Free; Data.Free; end; end; procedure TFirebaseAuthentication.OnFetchProvidersResp(const RequestID: string; Response: IFirebaseResponse); var ResObj: TJSONObject; ResArr: TJSONArray; c: integer; Registered: boolean; Providers: TStringList; begin try Response.CheckForJSONObj; fLastUTCServerTime := Response.GetServerTime(tzUTC); ResObj := Response.GetContentAsJSONObj; Providers := TStringList.Create; try if not ResObj.GetValue('registered').TryGetValue(Registered) then raise EFirebaseAuthentication.Create('JSON field registered missing'); if Registered then begin ResArr := ResObj.GetValue('allProviders') as TJSONArray; if not assigned(ResArr) then raise EFirebaseAuthentication.Create( 'JSON field allProviders missing'); for c := 0 to ResArr.Count - 1 do Providers.Add(ResArr.Items[c].ToString); end; if assigned(Response.OnSuccess.OnFetchProviders) then Response.OnSuccess.OnFetchProviders(RequestID, Registered, Providers); finally Providers.Free; ResObj.Free; end; except on e: exception do if assigned(Response.OnError) then Response.OnError(RequestID, e.Message); end; end; function TFirebaseAuthentication.FetchProvidersForEMailSynchronous( const EMail: string; Providers: TStrings): boolean; var Data, ResObj: TJSONObject; Params: TQueryParams; Request: IFirebaseRequest; Response: IFirebaseResponse; ResArr: TJSONArray; c: integer; begin Data := TJSONObject.Create; ResObj := nil; Request := TFirebaseRequest.Create(GOOGLE_PASSWORD_URL); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('identifier', Email)); Data.AddPair(TJSONPair.Create('continueUri', 'http://locahost')); Params.Add('key', [ApiKey]); Response := Request.SendRequestSynchronous(['createAuthUri'], rmPOST, Data, Params, tmNoToken); Response.CheckForJSONObj; fLastUTCServerTime := Response.GetServerTime(tzUTC); ResObj := Response.GetContentAsJSONObj; if not ResObj.GetValue('registered').TryGetValue(result) then raise EFirebaseAuthentication.Create('JSON field registered missing'); if result then begin ResArr := ResObj.GetValue('allProviders') as TJSONArray; if not assigned(ResArr) then raise EFirebaseAuthentication.Create('JSON field allProviders missing'); Providers.Clear; for c := 0 to ResArr.Count - 1 do Providers.Add(ResArr.Items[c].ToString); end; finally ResObj.Free; Params.Free; Data.Free; end; end; procedure TFirebaseAuthentication.DeleteProviders(Providers: TStrings; OnProviderDeleted: TOnFirebaseResp; OnError: TOnRequestError); var Data: TJSONObject; DelArr: TJSONArray; Provider: string; Params: TQueryParams; Request: IFirebaseRequest; begin Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_IDTOOLKIT_URL, Format(rsDeleteProviders, [Providers.CommaText])); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('idToken', Token)); DelArr := TJSONArray.Create; for Provider in Providers do DelArr.Add(Provider); Data.AddPair(TJSONPair.Create('deleteProvider', DelArr)); Params.Add('key', [ApiKey]); Request.SendRequest(['accounts:update'], rmPOST, Data, Params, tmNoToken, OnDeleteProvidersResp, onError, TOnSuccess.Create(OnProviderDeleted)); finally Params.Free; Data.Free; end; end; procedure TFirebaseAuthentication.OnDeleteProvidersResp(const RequestID: string; Response: IFirebaseResponse); begin try if Response.StatusOk then begin Response.CheckForJSONObj; fLastUTCServerTime := Response.GetServerTime(tzUTC); if assigned(Response.OnSuccess.OnResponse) then Response.OnSuccess.OnResponse(RequestID, Response); end; except on e: exception do if assigned(Response.OnError) then Response.OnError(RequestID, e.Message); end; end; function TFirebaseAuthentication.DeleteProvidersSynchronous( Providers: TStrings): boolean; var Data: TJSONObject; DelArr: TJSONArray; Provider: string; Params: TQueryParams; Request: TFirebaseRequest; Response: IFirebaseResponse; begin result := false; Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_IDTOOLKIT_URL); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('idToken', Token)); DelArr := TJSONArray.Create; for Provider in Providers do DelArr.Add(Provider); Data.AddPair(TJSONPair.Create('deleteProvider', DelArr)); Params.Add('key', [ApiKey]); Response := Request.SendRequestSynchronous(['accounts:update'], rmPost, Data, Params, tmNoToken); {$IFDEF DEBUG} TFirebaseHelpers.Log('FirebaseAuthentication.DeleteProvidersSynchronous ' + Response.ContentAsString); {$ENDIF} if Response.StatusOk then begin Response.CheckForJSONObj; fLastUTCServerTime := Response.GetServerTime(tzUTC); result := true; end; finally Response := nil; Params.Free; Request.Free; Data.Free; end; end; procedure TFirebaseAuthentication.SendPasswordResetEMail(const Email: string; OnResponse: TOnFirebaseResp; OnError: TOnRequestError); var Data: TJSONObject; Params: TQueryParams; Request: IFirebaseRequest; begin Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_PASSWORD_URL, Format(rsSendPasswordResetEMail, [EMail])); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('email', Email)); Data.AddPair(TJSONPair.Create('requestType', 'PASSWORD_RESET')); Params.Add('key', [ApiKey]); Request.SendRequest(['getOobConfirmationCode'], rmPost, Data, Params, tmNoToken, OnResponse, OnError, TOnSuccess.Create(nil)); finally Params.Free; Data.Free; end; end; procedure TFirebaseAuthentication.SendPasswordResetEMailSynchronous( const Email: string); var Data: TJSONObject; Params: TQueryParams; Request: TFirebaseRequest; Response: IFirebaseResponse; begin Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_PASSWORD_URL); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('email', Email)); Data.AddPair(TJSONPair.Create('requestType', 'PASSWORD_RESET')); Params.Add('key', [ApiKey]); Response := Request.SendRequestSynchronous(['getOobConfirmationCode'], rmPost, Data, Params, tmNoToken); if not Response.StatusOk then Response.CheckForJSONObj; fLastUTCServerTime := Response.GetServerTime(tzUTC); finally Response := nil; Params.Free; Request.Free; Data.Free; end; end; procedure TFirebaseAuthentication.VerifyPasswordResetCode( const ResetPasswortCode: string; OnPasswordVerification: TOnPasswordVerification; OnError: TOnRequestError); var Data: TJSONObject; Params: TQueryParams; Request: IFirebaseRequest; begin Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_PASSWORD_URL, rsVerifyPasswordResetCode); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('oobCode', ResetPasswortCode)); Params.Add('key', [ApiKey]); Request.SendRequest(['resetPassword'], rmPost, Data, Params, tmNoToken, OnVerifyPasswordResp, OnError, TOnSuccess.CreatePasswordVerification(OnPasswordVerification)); finally Data.Free; end; end; function TFirebaseAuthentication.VerifyPasswordResetCodeSynchronous( const ResetPasswortCode: string): TPasswordVerificationResult; var Data: TJSONObject; Params: TQueryParams; Request: TFirebaseRequest; Response: IFirebaseResponse; begin Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_PASSWORD_URL); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('oobCode', ResetPasswortCode)); Params.Add('key', [ApiKey]); Response := Request.SendRequestSynchronous(['resetPassword'], rmPost, Data, Params, tmNoToken); if Response.StatusOk then result := pvrPassed else if SameText(Response.ErrorMsg, TFirebaseResponse.ExceptOpNotAllowed) then result := pvrOpNotAllowed else if SameText(Response.ErrorMsg, TFirebaseResponse.ExceptExpiredOobCode) then result := pvrpvrExpired else if SameText(Response.ErrorMsg, TFirebaseResponse.ExceptInvalidOobCode) then result := pvrInvalid else raise EFirebaseResponse.Create(Response.ErrorMsg); finally Response := nil; Params.Free; Request.Free; Data.Free; end; end; procedure TFirebaseAuthentication.OnVerifyPasswordResp(const RequestID: string; Response: IFirebaseResponse); begin if assigned(Response.OnSuccess.OnPasswordVerification) then begin if Response.StatusOk then Response.OnSuccess.OnPasswordVerification(RequestID, pvrPassed) else if SameText(Response.ErrorMsg, TFirebaseResponse.ExceptOpNotAllowed) then Response.OnSuccess.OnPasswordVerification(RequestID, pvrOpNotAllowed) else if SameText(Response.ErrorMsg, TFirebaseResponse.ExceptExpiredOobCode) then Response.OnSuccess.OnPasswordVerification(RequestID, pvrpvrExpired) else if SameText(Response.ErrorMsg, TFirebaseResponse.ExceptInvalidOobCode) then Response.OnSuccess.OnPasswordVerification(RequestID, pvrInvalid) else if assigned(Response.OnError) then Response.OnError(RequestID, Response.ErrorMsg) else TFirebaseHelpers.Log('FirebaseAuthentication.OnVerifyPassword failed: ' + Response.ErrorMsg); end; end; procedure TFirebaseAuthentication.ConfirmPasswordReset(const ResetPasswortCode, NewPassword: string; OnResponse: TOnFirebaseResp; OnError: TOnRequestError); var Data: TJSONObject; Params: TQueryParams; Request: IFirebaseRequest; begin Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_PASSWORD_URL, rsConfirmPasswordReset); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('oobCode', ResetPasswortCode)); Data.AddPair(TJSONPair.Create('newPassword', NewPassword)); Params.Add('key', [ApiKey]); Request.SendRequest(['resetPassword'], rmPost, Data, Params, tmNoToken, OnResponse, OnError, TOnSuccess.Create(nil)); finally Params.Free; Data.Free; end; end; procedure TFirebaseAuthentication.ConfirmPasswordResetSynchronous( const ResetPasswortCode, NewPassword: string); var Data: TJSONObject; Params: TQueryParams; Request: TFirebaseRequest; Response: IFirebaseResponse; begin Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_PASSWORD_URL); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('oobCode', ResetPasswortCode)); Data.AddPair(TJSONPair.Create('newPassword', NewPassword)); Params.Add('key', [ApiKey]); Response := Request.SendRequestSynchronous(['resetPassword'], rmPost, Data, Params, tmNoToken); if not Response.StatusOk then Response.CheckForJSONObj; fLastUTCServerTime := Response.GetServerTime(tzUTC); finally Response := nil; Params.Free; Request.Free; Data.Free; end; end; procedure TFirebaseAuthentication.ChangeProfile(const EMail, Password, DisplayName, PhotoURL: string; OnResponse: TOnFirebaseResp; OnError: TOnRequestError); var Data: TJSONObject; Params: TQueryParams; Request: IFirebaseRequest; Info: TStringList; begin Data := TJSONObject.Create; Params := TQueryParams.Create; Info := TStringList.Create; try Data.AddPair(TJSONPair.Create('idToken', Token)); Data.AddPair(TJSONPair.Create('returnSecureToken', 'FALSE')); if not EMail.IsEmpty then begin Data.AddPair(TJSONPair.Create('email', EMail)); Info.Add('EMail'); end; if not Password.IsEmpty then begin Data.AddPair(TJSONPair.Create('password', Password)); Info.Add('Password'); end; if not DisplayName.IsEmpty then begin Data.AddPair(TJSONPair.Create('displayName', DisplayName)); Info.Add('Display name'); end; if not PhotoURL.IsEmpty then begin Data.AddPair(TJSONPair.Create('photoUrl', PhotoURL)); Info.Add('Photo URL'); end; Params.Add('key', [ApiKey]); Request := TFirebaseRequest.Create(GOOGLE_PASSWORD_URL, Format(rsChangeProfile, [Info.CommaText])); Request.SendRequest(['setAccountInfo'], rmPost, Data, Params, tmNoToken, OnResponse, OnError, TOnSuccess.Create(nil)); finally Info.Free; Params.Free; Data.Free; end; end; procedure TFirebaseAuthentication.ChangeProfileSynchronous(const EMail, Password, DisplayName, PhotoURL: string); var Data: TJSONObject; Params: TQueryParams; Request: TFirebaseRequest; Response: IFirebaseResponse; Info: TStringList; begin Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_PASSWORD_URL); Params := TQueryParams.Create; Info := TStringList.Create; try Data.AddPair(TJSONPair.Create('idToken', Token)); Data.AddPair(TJSONPair.Create('returnSecureToken', 'FALSE')); if not EMail.IsEmpty then begin Data.AddPair(TJSONPair.Create('email', EMail)); Info.Add('EMail'); end; if not Password.IsEmpty then begin Data.AddPair(TJSONPair.Create('password', Password)); Info.Add('Password'); end; if not DisplayName.IsEmpty then begin Data.AddPair(TJSONPair.Create('displayName', DisplayName)); Info.Add('Display name'); end; if not PhotoURL.IsEmpty then begin Data.AddPair(TJSONPair.Create('photoUrl', PhotoURL)); Info.Add('Photo URL'); end; Params.Add('key', [ApiKey]); Response := Request.SendRequestSynchronous(['setAccountInfo'], rmPost, Data, Params, tmNoToken); if not Response.StatusOk then Response.CheckForJSONObj; fLastUTCServerTime := Response.GetServerTime(tzUTC); {$IFDEF DEBUG} TFirebaseHelpers.Log('FirebaseAuthentication.ChangeProfileSynchronous ' + Info.CommaText); {$ENDIF} finally Info.Free; Response := nil; Params.Free; Request.Free; Data.Free; end; end; procedure TFirebaseAuthentication.LinkWithEMailAndPassword(const EMail, Password: string; OnUserResponse: TOnUserResponse; OnError: TOnRequestError); var Data: TJSONObject; Params: TQueryParams; Request: TFirebaseRequest; begin Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_IDTOOLKIT_URL); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('idToken', Token)); Data.AddPair(TJSONPair.Create('returnSecureToken', 'TRUE')); Data.AddPair(TJSONPair.Create('email', EMail)); Data.AddPair(TJSONPair.Create('password', Password)); Params.Add('key', [ApiKey]); Request.SendRequest(['accounts:update'], rmPost, Data, Params, tmNoToken, OnUserResp, OnError, TOnSuccess.CreateUser(OnUserResponse)); finally Params.Free; Request.Free; Data.Free; end; end; function TFirebaseAuthentication.LinkWithEMailAndPasswordSynchronous( const EMail, Password: string): IFirebaseUser; var Data: TJSONObject; Params: TQueryParams; Request: TFirebaseRequest; Response: IFirebaseResponse; begin Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_IDTOOLKIT_URL); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('idToken', Token)); Data.AddPair(TJSONPair.Create('returnSecureToken', 'TRUE')); Data.AddPair(TJSONPair.Create('email', EMail)); Data.AddPair(TJSONPair.Create('password', Password)); Params.Add('key', [ApiKey]); Response := Request.SendRequestSynchronous(['accounts:update'], rmPost, Data, Params, tmNoToken); Response.CheckForJSONObj; fLastUTCServerTime := Response.GetServerTime(tzUTC); result := TFirebaseUser.Create(Response.GetContentAsJSONObj); {$IFDEF DEBUG} TFirebaseHelpers.Log( 'FirebaseAuthentication.LinkWithEMailAndPasswordSynchronous' + Response.ContentAsString); {$ENDIF} finally Response := nil; Params.Free; Request.Free; Data.Free; end; end; procedure TFirebaseAuthentication.DeleteCurrentUserSynchronous; var Data: TJSONObject; Params: TQueryParams; Request: TFirebaseRequest; Response: IFirebaseResponse; begin Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_PASSWORD_URL); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('idToken', Token)); Params.Add('key', [ApiKey]); Response := Request.SendRequestSynchronous(['deleteAccount'], rmPost, Data, Params, tmNoToken); if not Response.StatusOk then Response.CheckForJSONObj; fLastUTCServerTime := Response.GetServerTime(tzUTC); {$IFDEF DEBUG} TFirebaseHelpers.Log('FirebaseAuthentication.DeleteCurrentUserSynchronous ' + Response.ContentAsString); {$ENDIF} finally Response := nil; Params.Free; Request.Free; Data.Free; end; end; procedure TFirebaseAuthentication.DeleteCurrentUser(OnResponse: TOnFirebaseResp; OnError: TOnRequestError); var Data: TJSONObject; Params: TQueryParams; Request: IFirebaseRequest; begin Data := TJSONObject.Create; Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('idToken', Token)); Params.Add('key', [ApiKey]); Request := TFirebaseRequest.Create(GOOGLE_PASSWORD_URL, rsDeleteCurrentUser); Request.SendRequest(['deleteAccount'], rmPost, Data, Params, tmNoToken, OnResponse, OnError, TOnSuccess.Create(nil)); finally Params.Free; Data.Free; end; end; procedure TFirebaseAuthentication.GetUserData(OnGetUserData: TOnGetUserData; OnError: TOnRequestError); var Data: TJSONObject; Params: TQueryParams; Request: IFirebaseRequest; begin Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_PASSWORD_URL, rsRetriveUserList); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('idToken', Token)); Params.Add('key', [ApiKey]); Request.SendRequest(['getAccountInfo'], rmPost, Data, Params, tmNoToken, OnUserListResp, OnError, TOnSuccess.CreateGetUserData(OnGetUserData)); finally Params.Free; Data.Free; end; end; function TFirebaseAuthentication.GetUserDataSynchronous: TFirebaseUserList; var Data, UsersObj: TJSONObject; Params: TQueryParams; Request: TFirebaseRequest; Response: IFirebaseResponse; Users: TJSONArray; c: integer; begin result := TFirebaseUserList.Create; Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_PASSWORD_URL); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('idToken', Token)); Params.Add('key', [ApiKey]); Response := Request.SendRequestSynchronous(['getAccountInfo'], rmPost, Data, Params, tmNoToken); fLastUTCServerTime := Response.GetServerTime(tzUTC); if not Response.StatusOk then Response.CheckForJSONObj else begin UsersObj := Response.GetContentAsJSONObj; try if not UsersObj.TryGetValue('users', Users) then raise EFirebaseResponse.Create( 'users field not found in getAccountInfo'); for c := 0 to Users.Count - 1 do {$IFDEF TOKENJWT} if fTokenJWT <> nil then result.Add(TFirebaseUser.Create( Users.Items[c].Clone as TJSONObject, fTokenJWT)) else {$ENDIF} result.Add(TFirebaseUser.Create( Users.Items[c].Clone as TJSONObject, false)); finally UsersObj.Free; end; end; finally Response := nil; Params.Free; Request.Free; Data.Free; end; end; procedure TFirebaseAuthentication.OnUserListResp(const RequestID: string; Response: IFirebaseResponse); var UsersObj: TJSONObject; UserList: TFirebaseUserList; Users: TJSONArray; c: integer; begin try fLastUTCServerTime := Response.GetServerTime(tzUTC); if not Response.StatusOk then Response.CheckForJSONObj else if assigned(Response.OnSuccess.OnGetUserData) then begin UserList := TFirebaseUserList.Create; UsersObj := Response.GetContentAsJSONObj; try if not UsersObj.TryGetValue('users', Users) then raise EFirebaseResponse.Create( 'users field not found in getAccountInfo'); for c := 0 to Users.Count - 1 do {$IFDEF TOKENJWT} if fTokenJWT <> nil then UserList.Add(TFirebaseUser.Create( Users.Items[c].Clone as TJSONObject, fTokenJWT)) else {$ENDIF} UserList.Add(TFirebaseUser.Create( Users.Items[c].Clone as TJSONObject, false)); Response.OnSuccess.OnGetUserData(UserList); finally UsersObj.Free; UserList.Free; end; end; except on e: exception do if assigned(Response.OnError) then Response.OnError(RequestID, e.Message) else TFirebaseHelpers.Log('FirebaseAuthentication.OnUserList failed: ' + e.Message); end; end; procedure TFirebaseAuthentication.RefreshToken(OnTokenRefresh: TOnTokenRefresh; OnError: TOnRequestError); var Data: TJSONObject; Params: TQueryParams; Request: IFirebaseRequest; begin fAuthenticated := false; Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_REFRESH_AUTH_URL, rsRefreshToken); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('grant_type', 'refresh_token')); Data.AddPair(TJSONPair.Create('refresh_token', fRefreshToken)); Params.Add('key', [ApiKey]); Request.SendRequest([], rmPost, Data, Params, tmNoToken, CheckAndRefreshTokenResp, OnError, TOnSuccess.CreateRefreshToken(OnTokenRefresh)); finally Params.Free; Data.Free; end; if assigned(fOnTokenRefresh) then fOnTokenRefresh(not fRefreshToken.IsEmpty); end; procedure TFirebaseAuthentication.RefreshToken(const LastRefreshToken: string; OnTokenRefresh: TOnTokenRefresh; OnError: TOnRequestError); begin fRefreshToken := LastRefreshToken; RefreshToken(OnTokenRefresh, OnError); end; procedure TFirebaseAuthentication.InstallTokenRefreshNotification( OnTokenRefresh: TOnTokenRefresh); begin fOnTokenRefresh := OnTokenRefresh; end; procedure TFirebaseAuthentication.CheckAndRefreshTokenResp(const RequestID: string; Response: IFirebaseResponse); var NewToken: TJSONObject; ExpiresInSec: integer; begin try Response.CheckForJSONObj; fLastUTCServerTime := Response.GetServerTime(tzUTC); NewToken := Response.GetContentAsJSONObj; fCSForToken.Acquire; try fAuthenticated := true; if not NewToken.TryGetValue('access_token', fToken) then raise EFirebaseUser.Create('access_token not found'); {$IFDEF TOKENJWT} fTokenJWT := TTokenJWT.Create(fToken); {$ENDIF} inc(fTokenRefreshCount); if NewToken.TryGetValue('expires_in', ExpiresInSec) then fExpiresAt := now + ExpiresInSec / 24 / 3600 else fExpiresAt := now; if not NewToken.TryGetValue('refresh_token', fRefreshToken) then fRefreshToken := '' else if assigned(Response.OnSuccess.OnRefreshToken) then Response.OnSuccess.OnRefreshToken(true); finally fCSForToken.Release; NewToken.Free; end; if assigned(fOnTokenRefresh) then fOnTokenRefresh(not fRefreshToken.IsEmpty); except on e: exception do if assigned(Response.OnError) then Response.OnError(RequestID, e.Message) else TFirebaseHelpers.Log( 'FirebaseAuthentication.CheckAndRefreshToken failed: ' + e.Message); end; end; function TFirebaseAuthentication.CheckAndRefreshTokenSynchronous( IgnoreExpiryCheck: boolean = false): boolean; var Data: TJSONObject; Params: TQueryParams; Request: TFirebaseRequest; Response: IFirebaseResponse; NewToken: TJSONObject; ExpiresInSec: integer; begin if not NeedTokenRefresh then begin {$IFDEF DEBUG} TFirebaseHelpers.LogFmt( 'FirebaseAuthentication.CheckAndRefreshTokenSynchronous failed because ' + 'token not yet (%s) expired: %s', [TimeToStr(now), TimeToStr(fExpiresAt)]); {$ENDIF} if not IgnoreExpiryCheck then exit(false); end; result := false; fCSForToken.Acquire; try if now + cSafetyMargin < fExpiresAt then exit(false); // Another thread has refreshed the token fAuthenticated := false; Data := TJSONObject.Create; Request := TFirebaseRequest.Create(GOOGLE_REFRESH_AUTH_URL, ''); Params := TQueryParams.Create; try Data.AddPair(TJSONPair.Create('grant_type', 'refresh_token')); Data.AddPair(TJSONPair.Create('refresh_token', fRefreshToken)); Params.Add('key', [ApiKey]); Response := Request.SendRequestSynchronous([], rmPost, Data, Params, tmNoToken); Response.CheckForJSONObj; fLastUTCServerTime := Response.GetServerTime(tzUTC); NewToken := Response.GetContentAsJSONObj; try fAuthenticated := true; if not NewToken.TryGetValue('access_token', fToken) then raise EFirebaseAuthentication.Create('access_token not found'); {$IFDEF TOKENJWT} fTokenJWT := TTokenJWT.Create(fToken); {$ENDIF} inc(fTokenRefreshCount); if NewToken.TryGetValue('expires_in', ExpiresInSec) then fExpiresAt := now + ExpiresInSec / 24 / 3600 else fExpiresAt := now; if not NewToken.TryGetValue('refresh_token', fRefreshToken) then fRefreshToken := '' else result := true; finally NewToken.Free; end; finally Response := nil; Params.Free; Request.Free; Data.Free; end; {$IFDEF DEBUG} if result then TFirebaseHelpers.Log( 'FirebaseAuthentication.CheckAndRefreshTokenSynchronous done') else TFirebaseHelpers.Log( 'FirebaseAuthentication.CheckAndRefreshTokenSynchronous failed ' + 'because no token received'); {$ENDIF} finally fCSForToken.Release; if result and assigned(fOnTokenRefresh) then fOnTokenRefresh(not fRefreshToken.IsEmpty); end; end; function TFirebaseAuthentication.Authenticated: boolean; begin fCSForToken.Acquire; try result := fAuthenticated; finally fCSForToken.Release; end; end; function TFirebaseAuthentication.NeedTokenRefresh: boolean; begin fCSForToken.Acquire; try if fAuthenticated then result := now + cSafetyMargin > fExpiresAt else result := false; finally fCSForToken.Release; end; end; function TFirebaseAuthentication.GetTokenRefreshCount: cardinal; begin result := fTokenRefreshCount; end; function TFirebaseAuthentication.GetRefreshToken: string; begin fCSForToken.Acquire; try result := fRefreshToken; finally fCSForToken.Release; end; end; function TFirebaseAuthentication.GetLastServerTime( TimeZone: TTimeZone): TDateTime; begin result := fLastUTCServerTime; if TimeZone = tzLocalTime then result := TFirebaseHelpers.ConvertToLocalDateTime(result); end; function TFirebaseAuthentication.Token: string; begin fCSForToken.Acquire; try result := fToken; finally fCSForToken.Release; end; end; function TFirebaseAuthentication.TokenExpiryDT: TDateTime; begin fCSForToken.Acquire; try result := fExpiresAt; finally fCSForToken.Release; end; end; {$IFDEF TOKENJWT} function TFirebaseAuthentication.TokenJWT: ITokenJWT; begin fCSForToken.Acquire; try result := fTokenJWT; finally fCSForToken.Release; end; end; {$ENDIF} { TFirebaseUser } constructor TFirebaseUser.Create(JSONResp: TJSONObject; TokenExpected: boolean); var ExpiresInSec: integer; {$IFDEF TOKENJWT} Claims: TJSONObject; c: integer; {$ENDIF} begin inherited Create; {$IFDEF TOKENJWT} fTokenJWT := nil; fClaimFields := TDictionary<string,TJSONValue>.Create; {$ENDIF} fJSONResp := JSONResp; if not fJSONResp.TryGetValue('idToken', fToken) then if TokenExpected then raise EFirebaseUser.Create('idToken not found') else fToken := '' else begin {$IFDEF TOKENJWT} fTokenJWT := TTokenJWT.Create(fToken); Claims := fTokenJWT.Claims.JSON; for c := 0 to Claims.Count - 1 do fClaimFields.Add(Claims.Pairs[c].JsonString.Value, Claims.Pairs[c].JsonValue); {$ENDIF} end; if fJSONResp.TryGetValue('expiresIn', ExpiresInSec) then fExpiresAt := now + ExpiresInSec / 24 / 3600 else fExpiresAt := now; if not fJSONResp.TryGetValue('refreshToken', fRefreshToken) then fRefreshToken := ''; end; {$IFDEF TOKENJWT} constructor TFirebaseUser.Create(JSONResp: TJSONObject; TokenJWT: ITokenJWT); var ExpiresInSec: integer; Claims: TJSONObject; c: integer; begin inherited Create; fTokenJWT := TokenJWT; fClaimFields := TDictionary<string,TJSONValue>.Create; fJSONResp := JSONResp; Claims := fTokenJWT.Claims.JSON; for c := 0 to Claims.Count - 1 do fClaimFields.Add(Claims.Pairs[c].JsonString.Value, Claims.Pairs[c].JsonValue); if fJSONResp.TryGetValue('expiresIn', ExpiresInSec) then fExpiresAt := now + ExpiresInSec / 24 / 3600 else fExpiresAt := now; if not fJSONResp.TryGetValue('refreshToken', fRefreshToken) then fRefreshToken := ''; end; {$ENDIF} destructor TFirebaseUser.Destroy; begin {$IFDEF TOKENJWT} fClaimFields.Free; fTokenJWT := nil; {$ENDIF} fJSONResp.Free; inherited; end; function TFirebaseUser.IsDisabled: TThreeStateBoolean; var bool: boolean; begin if not fJSONResp.TryGetValue('disabled', bool) then result := tsbUnspecified else if bool then result := tsbTrue else result := tsbFalse; end; function TFirebaseUser.IsDisplayNameAvailable: boolean; begin result := fJSONResp.GetValue('displayName') <> nil; end; function TFirebaseUser.DisplayName: string; begin if not fJSONResp.TryGetValue('displayName', result) then raise EFirebaseUser.Create('displayName not found'); end; function TFirebaseUser.IsEMailAvailable: boolean; begin result := fJSONResp.GetValue('email') <> nil; end; function TFirebaseUser.EMail: string; begin if not fJSONResp.TryGetValue('email', result) then raise EFirebaseUser.Create('email not found'); end; function TFirebaseUser.ExpiresAt: TDateTime; begin result := fExpiresAt; end; function TFirebaseUser.UID: string; begin if not fJSONResp.TryGetValue('localId', result) then raise EFirebaseUser.Create('localId not found'); end; function TFirebaseUser.IsEMailRegistered: TThreeStateBoolean; var bool: boolean; begin if not fJSONResp.TryGetValue('registered', bool) then result := tsbUnspecified else if bool then result := tsbTrue else result := tsbFalse; end; function TFirebaseUser.IsEMailVerified: TThreeStateBoolean; var {$IFDEF TOKENJWT} Val: TJSONValue; {$ENDIF} bool: boolean; begin {$IFDEF TOKENJWT} if fClaimFields.TryGetValue('email_verified', Val) then begin if Val.GetValue<boolean> then exit(tsbTrue) else exit(tsbFalse); end; {$ENDIF} if not fJSONResp.TryGetValue('emailVerified', bool) then result := tsbUnspecified else if bool then result := tsbTrue else result := tsbFalse; end; function TFirebaseUser.IsCreatedAtAvailable: boolean; begin result := fJSONResp.GetValue('createdAt') <> nil; end; function TFirebaseUser.CreatedAt(TimeZone: TTimeZone): TDateTime; var dt: Int64; begin if not fJSONResp.TryGetValue('createdAt', dt) then raise EFirebaseUser.Create('createdAt not found'); case TimeZone of tzLocalTime: result := TFirebaseHelpers.ConvertTimeStampToLocalDateTime(dt); tzUTC: result := TFirebaseHelpers.ConvertTimeStampToUTCDateTime(dt); else raise EFirebaseUser.Create('Invalid timezone'); end; end; function TFirebaseUser.IsLastLoginAtAvailable: boolean; begin result := fJSONResp.GetValue('lastLoginAt') <> nil; end; function TFirebaseUser.IsNewSignupUser: boolean; const cSignupNewUser = '#SignupNewUserResponse'; var kind: string; begin result := false; if fJSONResp.TryGetValue('kind', kind) then result := String.EndsText(cSignupNewUser, Kind); end; function TFirebaseUser.LastLoginAt(TimeZone: TTimeZone): TDateTime; var dt: Int64; begin if not fJSONResp.TryGetValue('lastLoginAt', dt) then raise EFirebaseUser.Create('lastLoginAt not found'); case TimeZone of tzLocalTime: result := TFirebaseHelpers.ConvertTimeStampToLocalDateTime(dt); tzUTC: result := TFirebaseHelpers.ConvertTimeStampToUTCDateTime(dt); else raise EFirebaseUser.Create('Invalid timezone'); end; end; function TFirebaseUser.IsPhotoURLAvailable: boolean; begin result := fJSONResp.GetValue('photoUrl') <> nil; end; function TFirebaseUser.PhotoURL: string; begin if not fJSONResp.TryGetValue('photoUrl', result) then raise EFirebaseUser.Create('photoURL not found'); end; function TFirebaseUser.RefreshToken: string; begin result := fRefreshToken; end; function TFirebaseUser.Token: string; begin result := fToken; end; function TFirebaseUser.OAuthProviderId: string; begin if not fJSONResp.TryGetValue('providerId', result) then result := ''; end; function TFirebaseUser.OAuthFederatedId: string; begin if not fJSONResp.TryGetValue('federatedId', result) then result := ''; end; function TFirebaseUser.OAuthIdToken: string; begin if not fJSONResp.TryGetValue('oauthIdToken', result) then result := ''; end; function TFirebaseUser.OAuthAccessToken: string; begin if not fJSONResp.TryGetValue('oauthAccessToken', result) then result := ''; end; function TFirebaseUser.OAuthTokenSecret: string; begin if not fJSONResp.TryGetValue('oauthTokenSecret', result) then result := ''; end; function TFirebaseUser.OAuthRawUserInfo: string; begin if not fJSONResp.TryGetValue('rawUserInfo', result) then result := ''; end; function TFirebaseUser.Provider(ProviderNo: integer): TProviderInfo; var ProvArr: TJSONArray; Provider: TJSONObject; begin result.ProviderId := ''; result.FederatedId := ''; result.RawId := ''; result.DisplayName := ''; result.Email := ''; result.ScreenName := ''; if fJSONResp.TryGetValue('providerUserInfo', ProvArr) then begin Provider := ProvArr.Items[ProviderNo] as TJSONObject; Provider.TryGetValue('providerId', result.ProviderId); Provider.TryGetValue('federatedId', result.FederatedId); Provider.TryGetValue('rawId', result.RawId); Provider.TryGetValue('displayName', result.DisplayName); Provider.TryGetValue('email', result.Email); Provider.TryGetValue('screenName', result.ScreenName); end; end; function TFirebaseUser.ProviderCount: integer; var ProvArr: TJSONArray; begin if not fJSONResp.TryGetValue('providerUserInfo', ProvArr) then result := 0 else result := ProvArr.Count; end; {$IFDEF TOKENJWT} function TFirebaseUser.TokenJWT: ITokenJWT; begin result := fTokenJWT; end; function TFirebaseUser.ClaimField(const FieldName: string): TJSONValue; begin if not fClaimFields.TryGetValue(FieldName, result) then result := nil; end; function TFirebaseUser.ClaimFieldNames: TStrings; var Key: string; begin result := TStringList.Create; for Key in fClaimFields.Keys do result.Add(Key); end; {$ENDIF} end.
unit QThemeSrvLinux; interface uses Qt, Types, SysUtils, Classes, Contnrs, QGraphics, QControls, QForms, QImgList, QStdCtrls, QComCtrls; type // These are all elements which can be themed. TThemedElement = ( teButton, teClock, teComboBox, teEdit, teExplorerBar, teHeader, teListView, teMenu, tePage, teProgress, teRebar, teScrollBar, teSpin, teStartPanel, teStatus, teTab, teTaskBand, teTaskBar, teToolBar, teToolTip, teTrackBar, teTrayNotify, teTreeview, teWindow ); // 'Button' theme data TThemedButton = ( tbButtonDontCare, tbButtonRoot, // The root part of each element is sometimes used for special painting and does not // belong to a certain state. tbPushButtonNormal, tbPushButtonHot, tbPushButtonPressed, tbPushButtonDisabled, tbPushButtonDefaulted, tbRadioButtonUncheckedNormal, tbRadioButtonUncheckedHot, tbRadioButtonUncheckedPressed, tbRadioButtonUncheckedDisabled, tbRadioButtonCheckedNormal, tbRadioButtonCheckedHot, tbRadioButtonCheckedPressed, tbRadioButtonCheckedDisabled, tbCheckBoxUncheckedNormal, tbCheckBoxUncheckedHot, tbCheckBoxUncheckedPressed, tbCheckBoxUncheckedDisabled, tbCheckBoxCheckedNormal, tbCheckBoxCheckedHot, tbCheckBoxCheckedPressed, tbCheckBoxCheckedDisabled, tbCheckBoxMixedNormal, tbCheckBoxMixedHot, tbCheckBoxMixedPressed, tbCheckBoxMixedDisabled, tbGroupBoxNormal, tbGroupBoxDisabled, tbUserButton ); // 'Clock' theme data TThemedClock = ( tcClockDontCare, tcClockRoot, tcTimeNormal ); // 'ComboBox' theme data TThemedComboBox = ( tcComboBoxDontCare, tcComboBoxRoot, tcDropDownButtonNormal, tcDropDownButtonHot, tcDropDownButtonPressed, tcDropDownButtonDisabled ); // 'Edit' theme data TThemedEdit = ( teEditDontCare, teEditRoot, teEditTextNormal, teEditTextHot, teEditTextSelected, teEditTextDisabled, teEditTextFocused, teEditTextReadOnly, teEditTextAssist, teEditCaret ); // 'ExplorerBar' theme data TThemedExplorerBar = ( tebExplorerBarDontCare, tebExplorerBarRoot, tebHeaderBackgroundNormal, tebHeaderBackgroundHot, tebHeaderBackgroundPressed, tebHeaderCloseNormal, tebHeaderCloseHot, tebHeaderClosePressed, tebHeaderPinNormal, tebHeaderPinHot, tebHeaderPinPressed, tebHeaderPinSelectedNormal, tebHeaderPinSelectedHot, tebHeaderPinSelectedPressed, tebIEBarMenuNormal, tebIEBarMenuHot, tebIEBarMenuPressed, tebNormalGroupBackground, tebNormalGroupCollapseNormal, tebNormalGroupCollapseHot, tebNormalGroupCollapsePressed, tebNormalGroupExpandNormal, tebNormalGroupExpandHot, tebNormalGroupExpandPressed, tebNormalGroupHead, tebSpecialGroupBackground, tebSpecialGroupCollapseSpecial, tebSpecialGroupCollapseHot, tebSpecialGroupCollapsePressed, tebSpecialGroupExpandSpecial, tebSpecialGroupExpandHot, tebSpecialGroupExpandPressed, tebSpecialGroupHead ); // 'Header' theme data TThemedHeader = ( thHeaderDontCare, thHeaderRoot, thHeaderItemNormal, thHeaderItemHot, thHeaderItemPressed, thHeaderItemLeftNormal, thHeaderItemLeftHot, thHeaderItemLeftPressed, thHeaderItemRightNormal, thHeaderItemRightHot, thHeaderItemRightPressed, thHeaderSortArrowSortedUp, thHeaderSortArrowSortedDown ); // 'ListView' theme data TThemedListview = ( tlListviewDontCare, tlListviewRoot, tlListItemNormal, tlListItemHot, tlListItemSelected, tlListItemDisabled, tlListItemSelectedNotFocus, tlListGroup, tlListDetail, tlListSortDetail, tlEmptyText ); // 'Menu' theme data TThemedMenu = ( tmMenuDontCare, tmMenuRoot, tmMenuItemNormal, tmMenuItemSelected, tmMenuItemDemoted, tmMenuDropDown, tmMenuBarItem, tmMenuBarDropDown, tmChevron, tmSeparator ); // 'Page' theme data TThemedPage = ( tpPageDontCare, tpPageRoot, tpUpNormal, tpUpHot, tpUpPressed, tpUpDisabled, tpDownNormal, tpDownHot, tpDownPressed, tpDownDisabled, tpUpHorzNormal, tpUpHorzHot, tpUpHorzPressed, tpUpHorzDisabled, tpDownHorzNormal, tpDownHorzHot, tpDownHorzPressed, tpDownHorzDisabled ); // 'Progress' theme data TThemedProgress = ( tpProgressDontCare, tpProgressRoot, tpBar, tpBarVert, tpChunk, tpChunkVert ); // 'Rebar' theme data TThemedRebar = ( trRebarDontCare, trRebarRoot, trGripper, trGripperVert, trBandNormal, trBandHot, trBandPressed, trBandDisabled, trBandChecked, trBandHotChecked, trChevronNormal, trChevronHot, trChevronPressed, trChevronDisabled, trChevronVertNormal, trChevronVertHot, trChevronVertPressed, trChevronVertDisabled ); // 'ScrollBar' theme data TThemedScrollBar = ( tsScrollBarDontCare, tsScrollBarRoot, tsArrowBtnUpNormal, tsArrowBtnUpHot, tsArrowBtnUpPressed, tsArrowBtnUpDisabled, tsArrowBtnDownNormal, tsArrowBtnDownHot, tsArrowBtnDownPressed, tsArrowBtnDownDisabled, tsArrowBtnLeftNormal, tsArrowBtnLeftHot, tsArrowBtnLeftPressed, tsArrowBtnLeftDisabled, tsArrowBtnRightNormal, tsArrowBtnRightHot, tsArrowBtnRightPressed, tsArrowBtnRightDisabled, tsThumbBtnHorzNormal, tsThumbBtnHorzHot, tsThumbBtnHorzPressed, tsThumbBtnHorzDisabled, tsThumbBtnVertNormal, tsThumbBtnVertHot, tsThumbBtnVertPressed, tsThumbBtnVertDisabled, tsLowerTrackHorzNormal, tsLowerTrackHorzHot, tsLowerTrackHorzPressed, tsLowerTrackHorzDisabled, tsUpperTrackHorzNormal, tsUpperTrackHorzHot, tsUpperTrackHorzPressed, tsUpperTrackHorzDisabled, tsLowerTrackVertNormal, tsLowerTrackVertHot, tsLowerTrackVertPressed, tsLowerTrackVertDisabled, tsUpperTrackVertNormal, tsUpperTrackVertHot, tsUpperTrackVertPressed, tsUpperTrackVertDisabled, tsGripperHorzNormal, tsGripperHorzHot, tsGripperHorzPressed, tsGripperHorzDisabled, tsGripperVertNormal, tsGripperVertHot, tsGripperVertPressed, tsGripperVertDisabled, tsSizeBoxRightAlign, tsSizeBoxLeftAlign ); // 'Spin' theme data TThemedSpin = ( tsSpinDontCare, tsSpinRoot, tsUpNormal, tsUpHot, tsUpPressed, tsUpDisabled, tsDownNormal, tsDownHot, tsDownPressed, tsDownDisabled, tsUpHorzNormal, tsUpHorzHot, tsUpHorzPressed, tsUpHorzDisabled, tsDownHorzNormal, tsDownHorzHot, tsDownHorzPressed, tsDownHorzDisabled ); // 'StartPanel' theme data TThemedStartPanel = ( tspStartPanelDontCare, tspStartPanelRoot, tspUserPane, tspMorePrograms, tspMoreProgramsArrowNormal, tspMoreProgramsArrowHot, tspMoreProgramsArrowPressed, tspProgList, tspProgListSeparator, tspPlacesList, tspPlacesListSeparator, tspLogOff, tspLogOffButtonsNormal, tspLogOffButtonsHot, tspLogOffButtonsPressed, tspUserPicture, tspPreview ); // 'Status' theme data TThemedStatus = ( tsStatusDontCare, tsStatusRoot, tsPane, tsGripperPane, tsGripper ); // 'Tab' theme data TThemedTab = ( ttTabDontCare, ttTabRoot, ttTabItemNormal, ttTabItemHot, ttTabItemSelected, ttTabItemDisabled, ttTabItemFocused, ttTabItemLeftEdgeNormal, ttTabItemLeftEdgeHot, ttTabItemLeftEdgeSelected, ttTabItemLeftEdgeDisabled, ttTabItemLeftEdgeFocused, ttTabItemRightEdgeNormal, ttTabItemRightEdgeHot, ttTabItemRightEdgeSelected, ttTabItemRightEdgeDisabled, ttTabItemRightEdgeFocused, ttTabItemBothEdgeNormal, ttTabItemBothEdgeHot, ttTabItemBothEdgeSelected, ttTabItemBothEdgeDisabled, ttTabItemBothEdgeFocused, ttTopTabItemNormal, ttTopTabItemHot, ttTopTabItemSelected, ttTopTabItemDisabled, ttTopTabItemFocused, ttTopTabItemLeftEdgeNormal, ttTopTabItemLeftEdgeHot, ttTopTabItemLeftEdgeSelected, ttTopTabItemLeftEdgeDisabled, ttTopTabItemLeftEdgeFocused, ttTopTabItemRightEdgeNormal, ttTopTabItemRightEdgeHot, ttTopTabItemRightEdgeSelected, ttTopTabItemRightEdgeDisabled, ttTopTabItemRightEdgeFocused, ttTopTabItemBothEdgeNormal, ttTopTabItemBothEdgeHot, ttTopTabItemBothEdgeSelected, ttTopTabItemBothEdgeDisabled, ttTopTabItemBothEdgeFocused, ttPane, ttBody ); // 'TaskBand' theme data TThemedTaskBand = ( ttbTaskBandDontCare, ttbTaskBandRoot, ttbGroupCount, ttbFlashButton, ttpFlashButtonGroupMenu ); // 'TaskBar' theme data TThemedTaskBar = ( ttTaskBarDontCare, ttTaskBarRoot, ttbTimeNormal ); // 'ToolBar' theme data TThemedToolBar = ( ttbToolBarDontCare, ttbToolBarRoot, ttbButtonNormal, ttbButtonHot, ttbButtonPressed, ttbButtonDisabled, ttbButtonChecked, ttbButtonCheckedHot, ttbDropDownButtonNormal, ttbDropDownButtonHot, ttbDropDownButtonPressed, ttbDropDownButtonDisabled, ttbDropDownButtonChecked, ttbDropDownButtonCheckedHot, ttbSplitButtonNormal, ttbSplitButtonHot, ttbSplitButtonPressed, ttbSplitButtonDisabled, ttbSplitButtonChecked, ttbSplitButtonCheckedHot, ttbSplitButtonDropDownNormal, ttbSplitButtonDropDownHot, ttbSplitButtonDropDownPressed, ttbSplitButtonDropDownDisabled, ttbSplitButtonDropDownChecked, ttbSplitButtonDropDownCheckedHot, ttbSeparatorNormal, ttbSeparatorHot, ttbSeparatorPressed, ttbSeparatorDisabled, ttbSeparatorChecked, ttbSeparatorCheckedHot, ttbSeparatorVertNormal, ttbSeparatorVertHot, ttbSeparatorVertPressed, ttbSeparatorVertDisabled, ttbSeparatorVertChecked, ttbSeparatorVertCheckedHot ); // 'ToolTip' theme data TThemedToolTip = ( tttToolTipDontCare, tttToolTipRoot, tttStandardNormal, tttStandardLink, tttStandardTitleNormal, tttStandardTitleLink, tttBaloonNormal, tttBaloonLink, tttBaloonTitleNormal, tttBaloonTitleLink, tttCloseNormal, tttCloseHot, tttClosePressed ); // 'TrackBar' theme data TThemedTrackBar = ( ttbTrackBarDontCare, ttbTrackBarRoot, ttbTrack, ttbTrackVert, ttbThumbNormal, ttbThumbHot, ttbThumbPressed, ttbThumbFocused, ttbThumbDisabled, ttbThumbBottomNormal, ttbThumbBottomHot, ttbThumbBottomPressed, ttbThumbBottomFocused, ttbThumbBottomDisabled, ttbThumbTopNormal, ttbThumbTopHot, ttbThumbTopPressed, ttbThumbTopFocused, ttbThumbTopDisabled, ttbThumbVertNormal, ttbThumbVertHot, ttbThumbVertPressed, ttbThumbVertFocused, ttbThumbVertDisabled, ttbThumbLeftNormal, ttbThumbLeftHot, ttbThumbLeftPressed, ttbThumbLeftFocused, ttbThumbLeftDisabled, ttbThumbRightNormal, ttbThumbRightHot, ttbThumbRightPressed, ttbThumbRightFocused, ttbThumbRightDisabled, ttbThumbTics, ttbThumbTicsVert ); // 'TrayNotify' theme data TThemedTrayNotify = ( ttnTrayNotifyDontCare, ttnTrayNotifyRoot, ttnBackground, ttnAnimBackground ); // 'Treeview' theme data TThemedTreeview = ( ttTreeviewDontCare, ttTreeviewRoot, ttItemNormal, ttItemHot, ttItemSelected, ttItemDisabled, ttItemSelectedNotFocus, ttGlyphClosed, ttGlyphOpened, ttBranch ); // 'Window' theme data TThemedWindow = ( twWindowDontCare, twWindowRoot, twCaptionActive, twCaptionInactive, twCaptionDisabled, twSmallCaptionActive, twSmallCaptionInactive, twSmallCaptionDisabled, twMinCaptionActive, twMinCaptionInactive, twMinCaptionDisabled, twSmallMinCaptionActive, twSmallMinCaptionInactive, twSmallMinCaptionDisabled, twMaxCaptionActive, twMaxCaptionInactive, twMaxCaptionDisabled, twSmallMaxCaptionActive, twSmallMaxCaptionInactive, twSmallMaxCaptionDisabled, twFrameLeftActive, twFrameLeftInactive, twFrameRightActive, twFrameRightInactive, twFrameBottomActive, twFrameBottomInactive, twSmallFrameLeftActive, twSmallFrameLeftInactive, twSmallFrameRightActive, twSmallFrameRightInactive, twSmallFrameBottomActive, twSmallFrameBottomInactive, twSysButtonNormal, twSysButtonHot, twSysButtonPushed, twSysButtonDisabled, twMDISysButtonNormal, twMDISysButtonHot, twMDISysButtonPushed, twMDISysButtonDisabled, twMinButtonNormal, twMinButtonHot, twMinButtonPushed, twMinButtonDisabled, twMDIMinButtonNormal, twMDIMinButtonHot, twMDIMinButtonPushed, twMDIMinButtonDisabled, twMaxButtonNormal, twMaxButtonHot, twMaxButtonPushed, twMaxButtonDisabled, twCloseButtonNormal, twCloseButtonHot, twCloseButtonPushed, twCloseButtonDisabled, twSmallCloseButtonNormal, twSmallCloseButtonHot, twSmallCloseButtonPushed, twSmallCloseButtonDisabled, twMDICloseButtonNormal, twMDICloseButtonHot, twMDICloseButtonPushed, twMDICloseButtonDisabled, twRestoreButtonNormal, twRestoreButtonHot, twRestoreButtonPushed, twRestoreButtonDisabled, twMDIRestoreButtonNormal, twMDIRestoreButtonHot, twMDIRestoreButtonPushed, twMDIRestoreButtonDisabled, twHelpButtonNormal, twHelpButtonHot, twHelpButtonPushed, twHelpButtonDisabled, twMDIHelpButtonNormal, twMDIHelpButtonHot, twMDIHelpButtonPushed, twMDIHelpButtonDisabled, twHorzScrollNormal, twHorzScrollHot, twHorzScrollPushed, twHorzScrollDisabled, twHorzThumbNormal, twHorzThumbHot, twHorzThumbPushed, twHorzThumbDisabled, twVertScrollNormal, twVertScrollHot, twVertScrollPushed, twVertScrollDisabled, twVertThumbNormal, twVertThumbHot, twVertThumbPushed, twVertThumbDisabled, twDialog, twCaptionSizingTemplate, twSmallCaptionSizingTemplate, twFrameLeftSizingTemplate, twSmallFrameLeftSizingTemplate, twFrameRightSizingTemplate, twSmallFrameRightSizingTemplate, twFrameBottomSizingTemplate, twSmallFrameBottomSizingTemplate ); PThemedElementDetails = ^TThemedElementDetails; TThemedElementDetails = record Element: TThemedElement; Part, State: Integer; end; TImageListItem = class(TObject) List: TImageList; Name: string; end; TThemeServices = class(TObject) private FThemeNames: TStrings; FThemeIndex: Integer; FThemesDir: string; FOnThemeChange: TNotifyEvent; FImageLists: TObjectList; FEmptyImageList: TImageList; function GetThemesAvailable: Boolean; function GetThemesEnabled: Boolean; function GetThemeCount: Integer; function GetThemeNames(Index: Integer): string; procedure SetThemeIndex(Value: Integer); procedure SetThemesDir(const Value: string); procedure DrawEdgedBitmap(DC: QPainterH; const R: TRect; const Name: string; Index: Integer); overload; procedure DrawEdgedBitmap(DC: QPainterH; const R: TRect; Bmp: TBitmap); overload; procedure StretchBitmap(DC: QPainterH; const R: TRect; const Name: string; Index: Integer; BmpRect: PRect = nil); procedure DrawBitmap(DC: QPainterH; const R: TRect; const Name: string; Index: Integer); procedure DrawRepeatedBitmap(DC: QPainterH; const R: TRect; const Name: string; Index: Integer; const BmpRect: TRect; Direction: Integer; Distance: Integer); procedure DrawHeader(DC: QPainterH; State: Integer; R: TRect); procedure DrawEdgedBitmapTransparent(DC: QPainterH; const R: TRect; Bmp: TBitmap; TransparentBody: Boolean); overload; procedure DrawEdgedBitmapTransparent(DC: QPainterH; const R: TRect; TransparentBody: Boolean; const Name: string; Index: Integer); overload; procedure DrawEdgedBitmapBorder(DC: QPainterH; const R: TRect; Bmp: TBitmap); overload; procedure DrawEdgedBitmapBorder(DC: QPainterH; const R: TRect; const Name: string; Index: Integer); overload; protected procedure LoadThemeNames; procedure LoadThemeImages(const Filename: string; Count: Integer); procedure DoOnThemeChange; virtual; protected function GetImages(const Name: string): TImageList; procedure DrawPushButton(DC: QPainterH; State: Integer; R: TRect); procedure DrawRadioButton(DC: QPainterH; State: Integer; R: TRect); procedure DrawCheckBox(DC: QPainterH; State: Integer; R: TRect); procedure DrawGroupBox(DC: QPainterH; State: Integer; R: TRect); procedure DrawEditText(DC: QPainterH; State: Integer; R: TRect); procedure DrawToolBarButton(DC: QPainterH; State: Integer; R: TRect); procedure DrawToolBarSeparator(DC: QPainterH; State: Integer; R: TRect); procedure DrawToolBarSeparatorVert(DC: QPainterH; State: Integer; R: TRect); procedure DrawScrollBar(DC: QPainterH; State: Integer; R: TRect); procedure DrawTab(DC: QPainterH; State: Integer; R: TRect); procedure DrawProgressBar(DC: QPainterH; State: Integer; R: TRect); procedure DrawComboBox(DC: QPainterH; State: Integer; R: TRect); procedure DrawTrackBar(DC: QPainterH; State: Integer; R: TRect); protected // implemented painting function procedure DrawThemeBackground(Element: TThemedElement; DC: QPainterH; Part, State: Integer; R: TRect; ClipRect: PRect); function IsThemeBackgroundPartiallyTransparent(Element: TThemedElement; Part, State: Integer): Boolean; procedure DrawThemeParentBackground(Window: QWidgetH; Target: QPainterH; ClipRect: PRect); procedure DrawThemeText(Element: TThemedElement; DC: QPainterH; Part, State: Integer; const S: WideString; Flags, Flags2: Integer; const R: TRect); procedure GetThemeBackgroundContentRect(Element: TThemedElement; DC: QPainterH; Part, State: Integer; const BoundingRect: TRect; RetVal: PRect); public constructor Create; destructor Destroy; override; property ThemeIndex: Integer read FThemeIndex write SetThemeIndex; property ThemeCount: Integer read GetThemeCount; property ThemeNames[Index: Integer]: string read GetThemeNames; property ThemesDir: string read FThemesDir write SetThemesDir; function GetElementDetails(Detail: TThemedButton): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedClock): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedComboBox): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedEdit): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedExplorerBar): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedHeader): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedListView): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedMenu): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedPage): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedProgress): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedRebar): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedScrollBar): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedSpin): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedStartPanel): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedStatus): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedTab): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedTaskBand): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedTaskBar): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedToolBar): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedToolTip): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedTrackBar): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedTrayNotify): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedTreeview): TThemedElementDetails; overload; function GetElementDetails(Detail: TThemedWindow): TThemedElementDetails; overload; function ContentRect(DC: QPainterH; Details: TThemedElementDetails; BoundingRect: TRect): TRect; overload; function ContentRect(Canvas: TCanvas; Details: TThemedElementDetails; BoundingRect: TRect): TRect; overload; procedure DrawEdge(DC: QPainterH; Details: TThemedElementDetails; const R: TRect; Edge, Flags: Cardinal; ContentRect: PRect = nil); overload; procedure DrawEdge(Canvas: TCanvas; Details: TThemedElementDetails; const R: TRect; Edge, Flags: Cardinal; ContentRect: PRect = nil); overload; procedure DrawElement(DC: QPainterH; Details: TThemedElementDetails; const R: TRect; ClipRect: PRect = nil); overload; procedure DrawElement(Canvas: TCanvas; Details: TThemedElementDetails; const R: TRect; ClipRect: PRect = nil); overload; procedure DrawParentBackground(Window: QWidgetH; Target: QPainterH; Details: PThemedElementDetails; OnlyIfTransparent: Boolean; Bounds: PRect = nil); overload; procedure DrawParentBackground(Window: QWidgetH; Target: TCanvas; Details: PThemedElementDetails; OnlyIfTransparent: Boolean; Bounds: PRect = nil); overload; procedure DrawText(DC: QPainterH; Details: TThemedElementDetails; const S: WideString; R: TRect; Flags, Flags2: Cardinal); overload; procedure DrawText(Canvas: TCanvas; Details: TThemedElementDetails; const S: WideString; R: TRect; Flags, Flags2: Cardinal); overload; function HasTransparentParts(Details: TThemedElementDetails): Boolean; procedure PaintBorder(Control: TWinControl; EraseLRCorner: Boolean; Painter: QPainterH = nil); procedure UpdateThemes; property ThemesAvailable: Boolean read GetThemesAvailable; property ThemesEnabled: Boolean read GetThemesEnabled; property OnThemeChange: TNotifyEvent read FOnThemeChange write FOnThemeChange; end; TPainterCanvas = class(TCanvas) protected procedure BeginPainting; override; public constructor Create(AHandle: QPainterH); destructor Destroy; override; end; function ThemeServices: TThemeServices; //---------------------------------------------------------------------------------------------------------------------- implementation const File_Button = 'Button.bmp'; File_CheckBox = 'CheckBox.bmp'; File_RadioButton = 'RadioButton.bmp'; File_EditText = 'EditText.bmp'; File_GroupBox = 'GroupBox.bmp'; File_ToolButton = 'ToolBarButton.bmp'; File_ToolButtonSep = 'ToolBarSep.bmp'; File_ScrollBar = 'ScrollBar.bmp'; File_Arrows = 'Arrows.bmp'; File_Tabs = 'Tabs.bmp'; File_TabBody = 'TabBody.bmp'; File_ProgressBar = 'ProgressBar.bmp'; File_ComboBox = 'ComboBox.bmp'; File_TrackBar = 'TrackBar.bmp'; File_Header = 'Header.bmp'; BP_PUSHBUTTON = 1; BP_RADIOBUTTON = 2; BP_CHECKBOX = 3; BP_GROUPBOX = 4; EP_EDITTEXT = 1; EP_CARET = 2; TP_BUTTON = 1; TP_DROPDOWNBUTTON = 2; TP_SPLITBUTTON = 3; TP_SPLITBUTTONDROPDOWN = 4; TP_SEPARATOR = 5; TP_SEPARATORVERT = 6; SBP_ARROWBTN = 1; SBP_THUMBBTNHORZ = 2; SBP_THUMBBTNVERT = 3; SBP_LOWERTRACKHORZ = 4; SBP_UPPERTRACKHORZ = 5; SBP_LOWERTRACKVERT = 6; SBP_UPPERTRACKVERT = 7; SBP_GRIPPERHORZ = 8; SBP_GRIPPERVERT = 9; SBP_SIZEBOX = 10; TABP_TABITEM = 1; TABP_TABITEMLEFTEDGE = 2; TABP_TABITEMRIGHTEDGE = 3; TABP_TABITEMBOTHEDGE = 4; TABP_TOPTABITEM = 5; TABP_TOPTABITEMLEFTEDGE = 6; TABP_TOPTABITEMRIGHTEDGE = 7; TABP_TOPTABITEMBOTHEDGE = 8; TABP_PANE = 9; TABP_BODY = 10; PP_BAR = 1; PP_BARVERT = 2; PP_CHUNK = 3; PP_CHUNKVERT = 4; CP_DROPDOWNBUTTON = 1; TKP_TRACK = 1; TKP_TRACKVERT = 2; TKP_THUMB = 3; TKP_THUMBBOTTOM = 4; TKP_THUMBTOP = 5; TKP_THUMBVERT = 6; TKP_THUMBLEFT = 7; TKP_THUMBRIGHT = 8; TKP_TICS = 9; TKP_TICSVERT = 10; HP_HEADERITEM = 1; HP_HEADERITEMLEFT = 2; HP_HEADERITEMRIGHT = 3; HP_HEADERSORTARROW = 4; var InternalThemeServices: TThemeServices; procedure NotImplemented; begin raise Exception.Create('Theming not implemented for this control'); end; procedure QExcludeClipRect(DC: QPainterH; x0, y0, x1, y1: Integer); var ExcludeRgn, Rgn: QRegionH; Matrix: QWMatrixH; begin if QPainter_hasWorldXForm(DC) then begin Matrix := QPainter_worldMatrix(DC); QWMatrix_map(Matrix, x0, y0, @x0, @y0); QWMatrix_map(Matrix, x1, y1, @x1, @y1); end; ExcludeRgn := QRegion_create(x0, y0, x1 - x0, y1 - y0, QRegionRegionType_Rectangle); Rgn := QPainter_clipRegion(DC); QRegion_subtract(Rgn, Rgn, ExcludeRgn); QPainter_setClipRegion(DC, Rgn); QPainter_setClipping(DC, True); QRegion_destroy(ExcludeRgn); end; procedure QIntersectClipRect(DC: QPainterH; ClipRect: TRect); var IntersectRgn, Rgn: QRegionH; Matrix: QWMatrixH; begin if QPainter_hasWorldXForm(DC) then begin Matrix := QPainter_worldMatrix(DC); QWMatrix_map(Matrix, PRect(@ClipRect), PRect(@ClipRect)); end; IntersectRgn := QRegion_create(@ClipRect, QRegionRegionType_Rectangle); Rgn := QPainter_clipRegion(DC); if QRegion_isNull(Rgn) then Rgn := IntersectRgn else QRegion_intersect(Rgn, Rgn, IntersectRgn); QPainter_setClipRegion(DC, Rgn); QPainter_setClipping(DC, True); QRegion_destroy(IntersectRgn); end; procedure SetClipRect(DC: QPainterH; ClipRect: TRect); begin QPainter_save(DC); QIntersectClipRect(DC, ClipRect); end; procedure ResetClipRect(DC: QPainterH); begin QPainter_restore(DC); end; procedure StretchDraw(Canvas: TCanvas; DestR: TRect; Bmp: TBitmap); begin Canvas.StretchDraw(DestR, Bmp); end; procedure TThemeServices.DrawEdgedBitmap(DC: QPainterH; const R: TRect; Bmp: TBitmap); var DestR, SrcR: TRect; Canvas: TCanvas; x2, y2, ix2, iy2: Integer; DestBmp: TBitmap; procedure DrawPart(vDestR: TRect; const vSourceR: TRect); begin OffsetRect(vDestR, R.Left, R.Top); DestBmp.Width := vSourceR.Right - vSourceR.Left; DestBmp.Height := vSourceR.Bottom - vSourceR.Top; DestBmp.Canvas.Start; try bitBlt(DestBmp.Handle, 0, 0, Bmp.Handle, vSourceR.Left, vSourceR.Top, DestBmp.Width, DestBmp.Height, RasterOp_CopyROP, True); if (vDestR.Right - vDestR.Left = DestBmp.Width) and (vDestR.Bottom - vDestR.Top = DestBmp.Height) then Canvas.Draw(vDestR.Left, vDestR.Top, DestBmp) else StretchDraw(Canvas, vDestR, DestBmp); finally DestBmp.Canvas.Stop; end; end; const ItemSize = 3; begin x2 := R.Right - R.Left; y2 := R.Bottom - R.Top; ix2 := Bmp.Width; iy2 := Bmp.Height; if (ix2 = 0) or (iy2 = 0) or (x2 = 0) or (y2 = 0) or (R.Left > R.Right) or (R.Bottom < R.Top) then Exit; Bmp.Transparent := False; Bmp.Canvas.Start; DestBmp := TBitmap.Create; Canvas := TPainterCanvas.Create(DC); try // innen DestR := Rect(ItemSize, ItemSize, x2 - ItemSize, y2 - ItemSize); SrcR := Rect(ItemSize, ItemSize, ix2 - ItemSize, iy2 - ItemSize); DrawPart(DestR, SrcR); // oben DestR := Rect(ItemSize, 0, x2 - ItemSize, ItemSize); SrcR := Rect(ItemSize, 0, ix2 - ItemSize, ItemSize); DrawPart(DestR, SrcR); // unten DestR := Rect(ItemSize, y2 - ItemSize, x2 - ItemSize, y2); SrcR := Rect(ItemSize, iy2 - ItemSize, ix2 - ItemSize, iy2); DrawPart(DestR, SrcR); // links DestR := Rect(0, ItemSize, ItemSize, y2 - ItemSize); SrcR := Rect(0, ItemSize, ItemSize, iy2 - ItemSize); DrawPart(DestR, SrcR); // rechts DestR := Rect(x2 - ItemSize, ItemSize, x2, y2 - ItemSize); SrcR := Rect(ix2 - ItemSize, ItemSize, ix2, iy2 - ItemSize); DrawPart(DestR, SrcR); // Ecke links oben SrcR := Rect(0, 0, ItemSize, ItemSize); DestR := Rect(0, 0, ItemSize, ItemSize); DrawPart(DestR, SrcR); // Ecke rechts oben DestR := Rect(x2 - ItemSize, 0, x2, ItemSize); SrcR := Rect(ix2 - ItemSize, 0, ix2, ItemSize); DrawPart(DestR, SrcR); // Ecke links unten DestR := Rect(0, y2 - ItemSize, ItemSize, y2); SrcR := Rect(0, iy2 - ItemSize, ItemSize, iy2); DrawPart(DestR, SrcR); // Ecke rechts unten DestR := Rect(x2 - ItemSize, y2 - ItemSize, x2, y2); SrcR := Rect(ix2 - ItemSize, iy2 - ItemSize, ix2, iy2); DrawPart(DestR, SrcR); finally Canvas.Free; DestBmp.Free; Bmp.Canvas.Stop; end; end; procedure TThemeServices.DrawEdgedBitmapTransparent(DC: QPainterH; const R: TRect; Bmp: TBitmap; TransparentBody: Boolean); var DestR, SrcR: TRect; Canvas: TCanvas; x2, y2, ix2, iy2: Integer; DestBmp: TBitmap; procedure DrawPart(const vDestR, vSourceR: TRect); begin stretchBlt(DestBmp.Handle, @vDestR, Bmp.Handle, @vSourceR, RasterOp_CopyROP, True); end; const ItemSize = 3; begin x2 := R.Right - R.Left; y2 := R.Bottom - R.Top; ix2 := Bmp.Width; iy2 := Bmp.Height; if (ix2 = 0) or (iy2 = 0) or (x2 = 0) or (y2 = 0) or (R.Left > R.Right) or (R.Bottom < R.Top) then Exit; Canvas := TPainterCanvas.Create(DC); Bmp.Transparent := False; Bmp.Canvas.Start; DestBmp := TBitmap.Create; try DestBmp.Canvas.Brush.Color := clFuchsia; DestBmp.Width := x2; DestBmp.Height := y2; DestBmp.Canvas.Start; if not TransparentBody then begin // innen DestR := Rect(ItemSize, ItemSize, x2 - ItemSize, y2 - ItemSize); SrcR := Rect(ItemSize, ItemSize, ix2 - ItemSize, iy2 - ItemSize); DrawPart(DestR, SrcR); end; // oben DestR := Rect(ItemSize, 0, x2 - ItemSize, ItemSize); SrcR := Rect(ItemSize, 0, ix2 - ItemSize, ItemSize); DrawPart(DestR, SrcR); // unten DestR := Rect(ItemSize, y2 - ItemSize, x2 - ItemSize, y2); SrcR := Rect(ItemSize, iy2 - ItemSize, ix2 - ItemSize, iy2); DrawPart(DestR, SrcR); // links DestR := Rect(0, ItemSize, ItemSize, y2 - ItemSize); SrcR := Rect(0, ItemSize, ItemSize, iy2 - ItemSize); DrawPart(DestR, SrcR); // rechts DestR := Rect(x2 - ItemSize, ItemSize, x2, y2 - ItemSize); SrcR := Rect(ix2 - ItemSize, ItemSize, ix2, iy2 - ItemSize); DrawPart(DestR, SrcR); // Ecke links oben SrcR := Rect(0, 0, ItemSize, ItemSize); DestR := Rect(0, 0, ItemSize, ItemSize); DrawPart(DestR, SrcR); // Ecke rechts oben DestR := Rect(x2 - ItemSize, 0, x2, ItemSize); SrcR := Rect(ix2 - ItemSize, 0, ix2, ItemSize); DrawPart(DestR, SrcR); // Ecke links unten DestR := Rect(0, y2 - ItemSize, ItemSize, y2); SrcR := Rect(0, iy2 - ItemSize, ItemSize, iy2); DrawPart(DestR, SrcR); // Ecke rechts unten DestR := Rect(x2 - ItemSize, y2 - ItemSize, x2, y2); SrcR := Rect(ix2 - ItemSize, iy2 - ItemSize, ix2, iy2); DrawPart(DestR, SrcR); DestBmp.TransparentColor := clFuchsia; Canvas.Draw(R.Left, R.Top, DestBmp); finally Canvas.Free; DestBmp.Canvas.Stop; DestBmp.Free; Bmp.Canvas.Stop; end; end; procedure TThemeServices.DrawEdgedBitmapBorder(DC: QPainterH; const R: TRect; Bmp: TBitmap); // draws only the border var DestR, SrcR: TRect; Matrix: QWMatrixH; x2, y2, ix2, iy2: Integer; procedure DrawPart(vDestR: TRect; const vSourceR: TRect); begin if Matrix <> nil then QWMatrix_map(Matrix, PRect(@vDesTR), PRect(@vDestR)); stretchBlt(QPainter_device(DC), @vDestR, Bmp.Handle, @vSourceR, RasterOp_CopyROP, False); end; const ItemSize = 3; begin x2 := R.Right - R.Left; y2 := R.Bottom - R.Top; ix2 := Bmp.Width; iy2 := Bmp.Height; if (ix2 = 0) or (iy2 = 0) or (x2 = 0) or (y2 = 0) or (R.Left > R.Right) or (R.Bottom < R.Top) then Exit; if QPainter_hasWorldXForm(DC) then Matrix := QPainter_worldMatrix(DC) else Matrix := nil; Bmp.Canvas.Start; try // oben DestR := Rect(ItemSize, 0, x2 - ItemSize, ItemSize); SrcR := Rect(ItemSize, 0, ix2 - ItemSize, ItemSize); DrawPart(DestR, SrcR); // unten DestR := Rect(ItemSize, y2 - ItemSize, x2 - ItemSize, y2); SrcR := Rect(ItemSize, iy2 - ItemSize, ix2 - ItemSize, iy2); DrawPart(DestR, SrcR); // links DestR := Rect(0, ItemSize, ItemSize, y2 - ItemSize); SrcR := Rect(0, ItemSize, ItemSize, iy2 - ItemSize); DrawPart(DestR, SrcR); // rechts DestR := Rect(x2 - ItemSize, ItemSize, x2, y2 - ItemSize); SrcR := Rect(ix2 - ItemSize, ItemSize, ix2, iy2 - ItemSize); DrawPart(DestR, SrcR); // Ecke links oben SrcR := Rect(0, 0, ItemSize, ItemSize); DestR := Rect(0, 0, ItemSize, ItemSize); DrawPart(DestR, SrcR); // Ecke rechts oben DestR := Rect(x2 - ItemSize, 0, x2, ItemSize); SrcR := Rect(ix2 - ItemSize, 0, ix2, ItemSize); DrawPart(DestR, SrcR); // Ecke links unten DestR := Rect(0, y2 - ItemSize, ItemSize, y2); SrcR := Rect(0, iy2 - ItemSize, ItemSize, iy2); DrawPart(DestR, SrcR); // Ecke rechts unten DestR := Rect(x2 - ItemSize, y2 - ItemSize, x2, y2); SrcR := Rect(ix2 - ItemSize, iy2 - ItemSize, ix2, iy2); DrawPart(DestR, SrcR); finally Bmp.Canvas.Stop; end; end; procedure TThemeServices.DrawEdgedBitmap(DC: QPainterH; const R: TRect; const Name: string; Index: Integer); var Bmp: TBitmap; Img: TImageList; begin Bmp := TBitmap.Create; try Img := GetImages(Name); if (Index >= Img.Count) or (Index < 0) then Index := Img.Count - 1; Img.GetBitmap(Index, Bmp); DrawEdgedBitmap(DC, R, Bmp); finally Bmp.Free; end; end; procedure TThemeServices.DrawEdgedBitmapTransparent(DC: QPainterH; const R: TRect; TransparentBody: Boolean; const Name: string; Index: Integer); var Bmp: TBitmap; Img: TImageList; begin Bmp := TBitmap.Create; try Img := GetImages(Name); if (Index >= Img.Count) or (Index < 0) then Index := Img.Count - 1; Img.GetBitmap(Index, Bmp); DrawEdgedBitmapTransparent(DC, R, Bmp, TransparentBody); finally Bmp.Free; end; end; procedure TThemeServices.DrawEdgedBitmapBorder(DC: QPainterH; const R: TRect; const Name: string; Index: Integer); var Bmp: TBitmap; Img: TImageList; begin Bmp := TBitmap.Create; try Img := GetImages(Name); if (Index >= Img.Count) or (Index < 0) then Index := Img.Count - 1; Img.GetBitmap(Index, Bmp); DrawEdgedBitmapBorder(DC, R, Bmp); finally Bmp.Free; end; end; procedure TThemeServices.StretchBitmap(DC: QPainterH; const R: TRect; const Name: string; Index: Integer; BmpRect: PRect = nil); var Bmp: TBitmap; Img: TImageList; Canvas: TCanvas; Width, Height: Integer; begin Bmp := TBitmap.Create; try Img := GetImages(Name); if (Index >= Img.Count) or (Index < 0) then Index := Img.Count - 1; Img.GetBitmap(Index, Bmp); if Assigned(BmpRect) then begin Width := BmpRect.Right - BmpRect.Left; Height := BmpRect.Bottom - BmpRect.Top; Bmp.Canvas.CopyRect( Rect(0, 0, Width, Height), Bmp.Canvas, Rect(BmpRect.Left, BmpRect.Top, BmpRect.Right, BmpRect.Bottom) ); Bmp.Width := Width; Bmp.Height := Height; end; Bmp.TransparentColor := clFuchsia; Canvas := TPainterCanvas.Create(DC); try StretchDraw(Canvas, R, Bmp); finally Canvas.Free; end; finally Bmp.Free; end; end; procedure TThemeServices.DrawBitmap(DC: QPainterH; const R: TRect; const Name: string; Index: Integer); var Bmp: TBitmap; Img: TImageList; Canvas: TCanvas; begin Bmp := TBitmap.Create; try Img := GetImages(Name); if (Index >= Img.Count) or (Index < 0) then Index := Img.Count - 1; Img.GetBitmap(Index, Bmp); Bmp.TransparentColor := clFuchsia; Canvas := TPainterCanvas.Create(DC); SetClipRect(DC, R); try Canvas.Draw(R.Left, R.Top, Bmp); finally ResetClipRect(DC); Canvas.Free; end; finally Bmp.Free; end; end; procedure TThemeServices.DrawRepeatedBitmap(DC: QPainterH; const R: TRect; const Name: string; Index: Integer; const BmpRect: TRect; Direction: Integer; Distance: Integer); // Direction: 0 = Horz repeat // 1 = Vert repeat var Bmp: TBitmap; Img: TImageList; Canvas: TCanvas; x, y, Width, Height: Integer; begin Bmp := TBitmap.Create; try Img := GetImages(Name); if (Index >= Img.Count) or (Index < 0) then Index := Img.Count - 1; Img.GetBitmap(Index, Bmp); Width := BmpRect.Right - BmpRect.Left; Height := BmpRect.Bottom - BmpRect.Top; Bmp.Canvas.CopyRect( Rect(0, 0, Width, Height), Bmp.Canvas, Rect(BmpRect.Left, BmpRect.Top, BmpRect.Right, BmpRect.Bottom) ); Bmp.Width := Width; Bmp.Height := Height; Bmp.TransparentColor := clFuchsia; Canvas := TPainterCanvas.Create(DC); SetClipRect(Canvas.Handle, R); try if Direction = 0 then begin x := R.Left; while x <= R.Right do begin StretchDraw(Canvas, Rect(x, R.Top, x + Width, R.Bottom), Bmp); Inc(x, Width + Distance); end; end else begin y := R.Top; while y <= R.Bottom do begin StretchDraw(Canvas, Rect(R.Left, y, R.Right, y + Height), Bmp); Inc(y, Height + Distance); end; end; finally ResetClipRect(Canvas.Handle); Canvas.Free; end; finally Bmp.Free; end; end; procedure TThemeServices.DrawPushButton(DC: QPainterH; State: Integer; R: TRect); begin InflateRect(R, -1, -1); DrawEdgedBitmapTransparent(DC, R, False, File_Button, State - 1); end; procedure TThemeServices.DrawRadioButton(DC: QPainterH; State: Integer; R: TRect); begin Dec(R.Right); Dec(R.Bottom); StretchBitmap(DC, R, File_RadioButton, State - 1); end; procedure TThemeServices.DrawCheckBox(DC: QPainterH; State: Integer; R: TRect); begin StretchBitmap(DC, R, File_CheckBox, State - 1); end; procedure TThemeServices.DrawGroupBox(DC: QPainterH; State: Integer; R: TRect); begin DrawEdgedBitmapTransparent(DC, R, True, File_GroupBox, State - 1); end; procedure TThemeServices.DrawEditText(DC: QPainterH; State: Integer; R: TRect); var BodyRect: TRect; begin if QPainter_clipRegion(DC) <> nil then begin BodyRect := R; InflateRect(BodyRect, -2, -2); if QRegion_contains(QPainter_clipRegion(DC), PRect(@BodyRect)) then DrawEdgedBitmap(DC, R, File_EditText, State - 1) else DrawEdgedBitmapBorder(DC, R, File_EditText, State - 1); end else DrawEdgedBitmap(DC, R, File_EditText, State - 1) end; procedure TThemeServices.DrawToolBarButton(DC: QPainterH; State: Integer; R: TRect); begin DrawEdgedBitmapTransparent(DC, R, False, File_ToolButton, State - 1); end; procedure TThemeServices.DrawToolBarSeparator(DC: QPainterH; State: Integer; R: TRect); begin Inc(R.Left, (R.Left + R.Right) div 2 - 2); DrawBitmap(DC, R, File_ToolButtonSep, 0); end; procedure TThemeServices.DrawToolBarSeparatorVert(DC: QPainterH; State: Integer; R: TRect); begin Inc(R.Left, (R.Left + R.Right) div 2 - 2); DrawBitmap(DC, R, File_ToolButtonSep, 1); end; procedure TThemeServices.DrawScrollBar(DC: QPainterH; State: Integer; R: TRect); var Index: Integer; begin if State <= 16 then begin DrawEdgedBitmap(DC, R, File_ScrollBar, (State - 1) mod 8); Inc(R.Left, (R.Right - R.Left) div 2 - (12 div 2)); Inc(R.Top, (R.Bottom - R.Top) div 2 - (12 div 2)); if (State - 1) mod 4 = 3 then Index := 1 else Index := 0; Index := Index + ((State - 1) div 4) * 2; case Index of 0, 1: Inc(R.Left); 2, 3: Inc(R.Left); 4, 5: ; 6, 7: Inc(R.Left); end; DrawBitmap(DC, R, File_Arrows, Index); end else DrawEdgedBitmap(DC, R, File_ScrollBar, State - 1 - 16); end; procedure TThemeServices.DrawTab(DC: QPainterH; State: Integer; R: TRect); begin if State = -1 then DrawEdgedBitmap(DC, R, File_TabBody, 0) else if State = -2 then DrawEdgedBitmap(DC, R, File_TabBody, 1) else DrawEdgedBitmapTransparent(DC, R, False, File_Tabs, State - 1); end; procedure TThemeServices.DrawProgressBar(DC: QPainterH; State: Integer; R: TRect); begin case State of 1: DrawEdgedBitmapTransparent(DC, R, False, File_ProgressBar, 0); 2: DrawEdgedBitmapTransparent(DC, R, False, File_ProgressBar, 1); 3: DrawRepeatedBitmap(DC, R, File_ProgressBar, 2, Rect(0, 0, 8, 21), 0, 2); 4: DrawRepeatedBitmap(DC, R, File_ProgressBar, 2, Rect(8, 0, 30, 8), 1, 2); end; end; procedure TThemeServices.DrawComboBox(DC: QPainterH; State: Integer; R: TRect); begin DrawEdgedBitmapTransparent(DC, R, False, File_ComboBox, (State - 1) mod 8); Inc(R.Left, (R.Right - R.Left) div 2 - (12 div 2)); Inc(R.Top, (R.Bottom - R.Top) div 2 - (12 div 2)); Inc(R.Left); Inc(R.Top); if State = 4 then DrawBitmap(DC, R, File_Arrows, 3) else DrawBitmap(DC, R, File_Arrows, 2); end; procedure TThemeServices.DrawTrackBar(DC: QPainterH; State: Integer; R: TRect); var BmpRect: TRect; begin if State < 0 then begin if State < -200 then begin // left/right BmpRect := Rect(0, 5, 21, 5 + 11); StretchBitmap(DC, R, File_TrackBar, State + 200 - 1, @BmpRect); end else begin // bottom/top BmpRect := Rect(5, 0, 5 + 11, 21); StretchBitmap(DC, R, File_TrackBar, State + 100 - 1, @BmpRect); end; end else DrawEdgedBitmapTransparent(DC, R, False, File_TrackBar, State - 1); end; procedure TThemeServices.DrawHeader(DC: QPainterH; State: Integer; R: TRect); begin DrawEdgedBitmap(DC, R, File_Header, State - 1); end; procedure TThemeServices.DrawThemeBackground(Element: TThemedElement; DC: QPainterH; Part, State: Integer; R: TRect; ClipRect: PRect); begin if ClipRect <> nil then SetClipRect(DC, ClipRect^); try case Element of teButton: begin case Part of BP_PUSHBUTTON: DrawPushButton(DC, State, R); BP_RADIOBUTTON: DrawRadioButton(DC, State, R); BP_CHECKBOX: DrawCheckBox(DC, State, R); BP_GROUPBOX: DrawGroupBox(DC, State, R); end; end; teEdit: begin case Part of EP_EDITTEXT: DrawEditText(DC, State, R); EP_CARET: DrawEditText(DC, State, R); end; end; teToolBar: begin if Part in [TP_BUTTON, TP_DROPDOWNBUTTON, TP_SPLITBUTTON] then if State = 1 then Exit; case Part of TP_BUTTON: DrawToolBarButton(DC, State, R); TP_DROPDOWNBUTTON: DrawToolBarButton(DC, State + Ord(ttbDropDownButtonNormal) - Ord(ttbButtonNormal), R); TP_SPLITBUTTON: DrawToolBarButton(DC, State + Ord(ttbSplitButtonNormal) - Ord(ttbButtonNormal), R); TP_SEPARATOR: DrawToolBarSeparator(DC, State, R); TP_SEPARATORVERT: DrawToolBarSeparatorVert(DC, State, R); end; end; teScrollBar: begin DrawScrollBar(DC, State, R); end; teTab: begin case Part of TABP_PANE: DrawTab(DC, -1, R); TABP_BODY: DrawTab(DC, -2, R); else DrawTab(DC, State, R); end; end; teProgress: begin case Part of PP_BAR: DrawProgressBar(DC, 1, R); PP_BARVERT: DrawProgressBar(DC, 2, R); PP_CHUNK: DrawProgressBar(DC, 3, R); PP_CHUNKVERT: DrawProgressBar(DC, 4, R); end; end; teComboBox: begin case Part of CP_DROPDOWNBUTTON: DrawComboBox(DC, State, R); end; end; teTrackBar: begin case Part of TKP_THUMBBOTTOM, TKP_THUMBTOP: DrawTrackBar(DC, -100 + State, R); TKP_THUMBLEFT, TKP_THUMBRIGHT: DrawTrackBar(DC, -200 + State, R); else DrawTrackBar(DC, State, R); end; end; teHeader: begin DrawHeader(DC, State, R); end; end; finally if ClipRect <> nil then ResetClipRect(DC); end; end; function TThemeServices.IsThemeBackgroundPartiallyTransparent(Element: TThemedElement; Part, State: Integer): Boolean; begin Result := False; end; type TOpenWidgetControl = class(TWidgetControl); procedure TThemeServices.DrawThemeParentBackground(Window: QWidgetH; Target: QPainterH; ClipRect: PRect); var Canvas: TCanvas; R, CR: TRect; Pixmap: QPixmapH; begin QWidget_geometry(Window, @R); Window := QWidget_parentWidget(Window); if Window = nil then Exit; Canvas := TPainterCanvas.Create(Target); if ClipRect <> nil then SetClipRect(Canvas.Handle, ClipRect^); try CR := R; OffsetRect(CR, -CR.Left, -CR.Top); Canvas.Brush.Color := QColorColor(QWidget_backgroundColor(Window)); Pixmap := QWidget_backgroundPixmap(Window); if Pixmap <> nil then QPainter_drawPixmap(Target, 0, 0, Pixmap, R.Left, R.Top, R.Right - R.Left, R.Bottom - R.Top) else Canvas.FillRect(CR); finally if ClipRect <> nil then ResetClipRect(Canvas.Handle); Canvas.Free; end; end; procedure TThemeServices.DrawThemeText(Element: TThemedElement; DC: QPainterH; Part, State: Integer; const S: WideString; Flags, Flags2: Integer; const R: TRect); var Canvas: TCanvas; begin QPainter_save(DC); Canvas := TPainterCanvas.Create(DC); try case Element of teButton: begin case Part of BP_GROUPBOX: Canvas.Font.Color := clBlue; end; end; end; Canvas.TextRect(R, R.Left, R.Top, S, Flags); finally Canvas.Free; QPainter_restore(DC); end; end; procedure TThemeServices.GetThemeBackgroundContentRect(Element: TThemedElement; DC: QPainterH; Part, State: Integer; const BoundingRect: TRect; RetVal: PRect); begin if RetVal = nil then Exit; case Element of teProgress: begin RetVal^ := BoundingRect; InflateRect(RetVal^, -2, -2); end; else NotImplemented; end; end; function ThemeServices: TThemeServices; begin if InternalThemeServices = nil then InternalThemeServices := TThemeServices.Create; Result := InternalThemeServices; end; constructor TThemeServices.Create; begin inherited Create; FThemesDir := ExtractFilePath(ParamStr(0)); FImageLists := TObjectList.Create; FEmptyImageList := TImageList.Create(nil); FThemeIndex := -1; FThemeNames := TStringList.Create; LoadThemeNames; UpdateThemes; end; destructor TThemeServices.Destroy; begin FThemeNames.Clear; FThemeIndex := -1; UpdateThemes; // destroy graphic objects FThemeNames.Free; FEmptyImageList.Free; FImageLists.Free; inherited Destroy; end; function TThemeServices.GetThemesAvailable: Boolean; begin Result := FThemeNames.Count > 0; end; function TThemeServices.GetThemesEnabled: Boolean; begin Result := ThemesAvailable and (ThemeIndex <> -1); end; procedure TThemeServices.DoOnThemeChange; begin if Assigned(FOnThemeChange) then FOnThemeChange(Self); end; procedure TThemeServices.LoadThemeNames; var sr: TSearchRec; begin FThemeIndex := -1; FThemeNames.Clear; if FindFirst(ThemesDir + 'Themes' + PathDelim + '*', faAnyFile, sr) = 0 then try repeat if (sr.Attr and faDirectory <> 0) and (sr.Name <> '.') and (sr.Name <> '..') then FThemeNames.Add(sr.Name); until FindNext(sr) <> 0; finally FindClose(sr); end; if FThemeNames.Count > 0 then FThemeIndex := 0; end; function TThemeServices.GetThemeCount: Integer; begin Result := FThemeNames.Count; end; function TThemeServices.GetThemeNames(Index: Integer): string; begin Result := FThemeNames[Index]; end; procedure TThemeServices.SetThemeIndex(Value: Integer); begin if Value <> FThemeIndex then begin FThemeIndex := Value; UpdateThemes; end; end; procedure TThemeServices.SetThemesDir(const Value: string); begin if Value <> FThemesDir then begin FThemesDir := IncludeTrailingPathDelimiter(Value); LoadThemeNames; UpdateThemes; end; end; procedure TThemeServices.LoadThemeImages(const Filename: string; Count: Integer); var Item: TImageListItem; Bmp: TBitmap; begin if FileExists(ThemesDir + 'Themes' + PathDelim + ThemeNames[FThemeIndex] + PathDelim + Filename) then begin Bmp := TBitmap.Create; try Bmp.LoadFromFile(ThemesDir + 'Themes' + PathDelim + ThemeNames[FThemeIndex] + PathDelim + Filename); Item := TImageListItem.Create; FImageLists.Add(Item); Item.Name := Filename; Item.List := TImageList.Create(nil); Item.List.Masked := False; Item.List.Width := Bmp.Width div Count; Item.List.Height := Bmp.Height; Item.List.Add(Bmp, nil); finally Bmp.Free; end; end; end; procedure TThemeServices.UpdateThemes; var i: Integer; begin FImageLists.Clear; if not ThemesEnabled then Exit; LoadThemeImages(File_Button, 5); LoadThemeImages(File_CheckBox, 12); LoadThemeImages(File_RadioButton, 8); LoadThemeImages(File_GroupBox, 3); LoadThemeImages(File_EditText, 1); LoadThemeImages(File_ToolButton, 6 * 3); LoadThemeImages(File_ToolButtonSep, 2); LoadThemeImages(File_ScrollBar, 34); LoadThemeImages(File_Arrows, 4 * 2); LoadThemeImages(File_Tabs, 8 * 5); LoadThemeImages(File_TabBody, 2); LoadThemeImages(File_ProgressBar, 3); LoadThemeImages(File_ComboBox, 4); LoadThemeImages(File_TrackBar, 34); LoadThemeImages(File_Header, 11); for i := 0 to Screen.CustomFormCount - 1 do begin if TForm(Screen.CustomForms[i]).Visible then TForm(Screen.CustomForms[i]).Invalidate; end; DoOnThemeChange; end; function TThemeServices.GetImages(const Name: string): TImageList; var i: Integer; Item: TImageListItem; begin Result := FEmptyImageList; for i := 0 to FImageLists.Count - 1 do begin Item := TImageListItem(FImageLists[i]); if Item.Name = Name then begin Result := Item.List; Break; end; end; end; function TThemeServices.GetElementDetails(Detail: TThemedButton): TThemedElementDetails; var Base: Integer; begin Result.Element := teButton; with Result do begin case Detail of tbPushButtonNormal..tbPushButtonDefaulted: begin Part := BP_PUSHBUTTON; Base := Ord(tbPushButtonNormal); end; tbRadioButtonUncheckedNormal..tbRadioButtonCheckedDisabled: begin Part := BP_RADIOBUTTON; Base := Ord(tbRadioButtonUncheckedNormal); end; tbCheckBoxUncheckedNormal..tbCheckBoxMixedDisabled: begin Part := BP_CHECKBOX; Base := Ord(tbCheckBoxUncheckedNormal); end; tbGroupBoxNormal..tbGroupBoxDisabled: begin Part := BP_GROUPBOX; Base := Ord(tbGroupBoxNormal); end; tbUserButton: begin Part := BP_GROUPBOX; Base := Ord(tbUserButton); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end; end; function TThemeServices.GetElementDetails(Detail: TThemedClock): TThemedElementDetails; begin NotImplemented; end; //---------------------------------------------------------------------------------------------------------------------- function TThemeServices.GetElementDetails(Detail: TThemedComboBox): TThemedElementDetails; var Base: Integer; begin Result.Element := teComboBox; with Result do begin case Detail of tcDropDownButtonNormal..tcDropDownButtonDisabled: begin Part := CP_DROPDOWNBUTTON; Base := Ord(tcDropDownButtonNormal); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end; end; function TThemeServices.GetElementDetails(Detail: TThemedEdit): TThemedElementDetails; var Base: Integer; begin Result.Element := teEdit; with Result do begin case Detail of teEditTextNormal..teEditTextAssist: begin Part := EP_EDITTEXT; Base := Ord(teEditTextNormal); end; teEditCaret: begin Part := EP_CARET; Base := Ord(teEditCaret); NotImplemented; end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end; end; function TThemeServices.GetElementDetails(Detail: TThemedExplorerBar): TThemedElementDetails; {var Base: Integer;} begin { Result.Element := teExplorerBar; with Result do begin case Detail of tebHeaderBackgroundNormal..tebHeaderBackgroundPressed: begin Part := EBP_HEADERBACKGROUND; Base := Ord(tebHeaderBackgroundNormal); end; tebHeaderCloseNormal..tebHeaderClosePressed: begin Part := EBP_HEADERCLOSE; Base := Ord(tebHeaderCloseNormal); end; tebHeaderPinNormal..tebHeaderPinSelectedPressed: begin Part := EBP_HEADERPIN; Base := Ord(tebHeaderPinSelectedNormal); end; tebIEBarMenuNormal..tebIEBarMenuPressed: begin Part := EBP_IEBARMENU; Base := Ord(tebIEBarMenuNormal); end; tebNormalGroupBackground: begin Part := EBP_NORMALGROUPBACKGROUND; Base := Ord(tebNormalGroupBackground); end; tebNormalGroupCollapseNormal..tebNormalGroupCollapsePressed: begin Part := EBP_NORMALGROUPCOLLAPSE; Base := Ord(tebNormalGroupCollapseNormal); end; tebNormalGroupExpandNormal..tebNormalGroupExpandPressed: begin Part := EBP_NORMALGROUPEXPAND; Base := Ord(tebNormalGroupExpandNormal); end; tebNormalGroupHead: begin Part := EBP_NORMALGROUPHEAD; Base := Ord(tebNormalGroupHead); end; tebSpecialGroupBackground: begin Part := EBP_SPECIALGROUPBACKGROUND; Base := Ord(tebSpecialGroupBackground); end; tebSpecialGroupCollapseSpecial..tebSpecialGroupCollapsePressed: begin Part := EBP_SPECIALGROUPCOLLAPSE; Base := Ord(tebSpecialGroupCollapseSpecial); end; tebSpecialGroupExpandSpecial..tebSpecialGroupExpandPressed: begin Part := EBP_SPECIALGROUPEXPAND; Base := Ord(tebSpecialGroupExpandSpecial); end; tebSpecialGroupHead: begin Part := EBP_SPECIALGROUPHEAD; Base := Ord(tebSpecialGroupHead); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end;} NotImplemented; end; function TThemeServices.GetElementDetails(Detail: TThemedHeader): TThemedElementDetails; var Base: Integer; begin Result.Element := teHeader; with Result do begin Base := Ord(thHeaderItemNormal); case Detail of thHeaderItemNormal..thHeaderItemPressed: begin Part := HP_HEADERITEM; //Base := Ord(thHeaderItemNormal); end; thHeaderItemLeftNormal..thHeaderItemLeftPressed: begin Part := HP_HEADERITEMLEFT; //Base := Ord(thHeaderItemLeftNormal); end; thHeaderItemRightNormal..thHeaderItemRightPressed: begin Part := HP_HEADERITEMRIGHT; //Base := Ord(thHeaderItemRightNormal); end; thHeaderSortArrowSortedUp..thHeaderSortArrowSortedDown: begin Part := HP_HEADERSORTARROW; //Base := Ord(thHeaderSortArrowSortedUp); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end; end; function TThemeServices.GetElementDetails(Detail: TThemedListview): TThemedElementDetails; {var Base: Integer;} begin { Result.Element := teListView; with Result do begin case Detail of tlListItemNormal..tlListItemSelectedNotFocus: begin Part := LVP_LISTITEM; Base := Ord(tlListItemNormal); end; tlListGroup: begin Part := LVP_LISTGROUP; Base := Ord(tlListGroup); end; tlListDetail: begin Part := LVP_LISTDETAIL; Base := Ord(tlListDetail); end; tlListSortDetail: begin Part := LVP_LISTSORTEDDETAIL; Base := Ord(tlListSortDetail); end; tlEmptyText: begin Part := LVP_EMPTYTEXT; Base := Ord(tlEmptyText); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end;} NotImplemented; end; function TThemeServices.GetElementDetails(Detail: TThemedMenu): TThemedElementDetails; {var Base: Integer;} begin { Result.Element := teMenu; with Result do begin case Detail of tmMenuItemNormal..tmMenuItemDemoted: begin Part := MP_MENUITEM; Base := Ord(tmMenuItemNormal); end; tmMenuDropDown: begin Part := MP_MENUDROPDOWN; Base := Ord(tmMenuDropDown); end; tmMenuBarItem: begin Part := MP_MENUBARITEM; Base := Ord(tmMenuBarItem); end; tmMenuBarDropDown: begin Part := MP_MENUBARDROPDOWN; Base := Ord(tmMenuBarDropDown); end; tmChevron: begin Part := MP_CHEVRON; Base := Ord(tmChevron); end; tmSeparator: begin Part := MP_SEPARATOR; Base := Ord(tmSeparator); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end;} NotImplemented; end; function TThemeServices.GetElementDetails(Detail: TThemedPage): TThemedElementDetails; {var Base: Integer;} begin { Result.Element := tePage; with Result do begin case Detail of tpUpNormal..tpUpDisabled: begin Part := PGRP_UP; Base := Ord(tpUpNormal); end; tpDownNormal..tpDownDisabled: begin Part := PGRP_DOWN; Base := Ord(tpDownNormal); end; tpUpHorzNormal..tpUpHorzDisabled: begin Part := PGRP_UPHORZ; Base := Ord(tpUpHorzNormal); end; tpDownHorzNormal..tpDownHorzDisabled: begin Part := PGRP_DOWNHORZ; Base := Ord(tpDownHorzNormal); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end;} NotImplemented; end; function TThemeServices.GetElementDetails(Detail: TThemedProgress): TThemedElementDetails; var Base: Integer; begin Result.Element := teProgress; with Result do begin case Detail of tpBar: begin Part := PP_BAR; Base := Ord(tpBar); end; tpBarVert: begin Part := PP_BARVERT; Base := Ord(tpBarVert); end; tpChunk: begin Part := PP_CHUNK; Base := Ord(tpChunk); end; tpChunkVert: begin Part := PP_CHUNKVERT; Base := Ord(tpChunkVert); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end; end; function TThemeServices.GetElementDetails(Detail: TThemedRebar): TThemedElementDetails; {var Base: Integer;} begin { Result.Element := teRebar; with Result do begin case Detail of trGripper: begin Part := RP_GRIPPER; Base := Ord(trGripper); end; trGripperVert: begin Part := RP_GRIPPERVERT; Base := Ord(trGripperVert); end; trBandNormal..trBandHotChecked: begin Part := RP_BAND; Base := Ord(trBandNormal); end; trChevronNormal..trChevronDisabled: begin Part := RP_CHEVRON; Base := Ord(trChevronNormal); end; trChevronVertNormal..trChevronVertDisabled: begin Part := RP_CHEVRONVERT; Base := Ord(trChevronVertNormal); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end;} NotImplemented; end; function TThemeServices.GetElementDetails(Detail: TThemedScrollBar): TThemedElementDetails; var Base: Integer; begin Result.Element := teScrollBar; with Result do begin case Detail of tsArrowBtnUpNormal..tsArrowBtnRightDisabled: begin Part := SBP_ARROWBTN; //Base := Ord(tsArrowBtnUpNormal); end; tsThumbBtnHorzNormal..tsThumbBtnHorzDisabled: begin Part := SBP_THUMBBTNHORZ; //Base := Ord(tsThumbBtnHorzNormal); end; tsThumbBtnVertNormal..tsThumbBtnVertDisabled: begin Part := SBP_THUMBBTNVERT; //Base := Ord(tsThumbBtnVertNormal); end; tsLowerTrackHorzNormal..tsLowerTrackHorzDisabled: begin Part := SBP_LOWERTRACKHORZ; //Base := Ord(tsLowerTrackHorzNormal); end; tsUpperTrackHorzNormal..tsUpperTrackHorzDisabled: begin Part := SBP_UPPERTRACKHORZ; //Base := Ord(tsUpperTrackHorzNormal); end; tsLowerTrackVertNormal..tsLowerTrackVertDisabled: begin Part := SBP_LOWERTRACKVERT; //Base := Ord(tsLowerTrackVertNormal); end; tsUpperTrackVertNormal..tsUpperTrackVertDisabled: begin Part := SBP_UPPERTRACKVERT; //Base := Ord(tsUpperTrackVertNormal); end; tsGripperHorzNormal..tsGripperHorzDisabled: begin Part := SBP_GRIPPERHORZ; //Base := Ord(tsGripperHorzNormal); end; tsGripperVertNormal..tsGripperVertDisabled: begin Part := SBP_GRIPPERVERT; //Base := Ord(tsGripperVertNormal); end; tsSizeBoxRightAlign..tsSizeBoxLeftAlign: begin Part := SBP_SIZEBOX; //Base := Ord(tsSizeBoxRightAlign); end; else Part := 0; //Base := 0; end; Base := Ord(tsArrowBtnUpNormal); State := Ord(Detail) - Base + 1; end; end; function TThemeServices.GetElementDetails(Detail: TThemedSpin): TThemedElementDetails; {var Base: Integer;} begin { Result.Element := teSpin; with Result do begin case Detail of tsUpNormal..tsUpDisabled: begin Part := SPNP_UP; Base := Ord(tsUpNormal); end; tsDownNormal..tsDownDisabled: begin Part := SPNP_DOWN; Base := Ord(tsDownNormal); end; tsUpHorzNormal..tsUpHorzDisabled: begin Part := SPNP_UPHORZ; Base := Ord(tsUpHorzNormal); end; tsDownHorzNormal..tsDownHorzDisabled: begin Part := SPNP_DOWNHORZ; Base := Ord(tsDownHorzNormal); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end;} NotImplemented; end; function TThemeServices.GetElementDetails(Detail: TThemedStartPanel): TThemedElementDetails; {var Base: Integer;} begin { Result.Element := teStartPanel; with Result do begin case Detail of tspUserPane: begin Part := SPP_USERPANE; Base := Ord(tspUserPane); end; tspMorePrograms: begin Part := SPP_MOREPROGRAMS; Base := Ord(tspMorePrograms); end; tspMoreProgramsArrowNormal..tspMoreProgramsArrowPressed: begin Part := SPP_MOREPROGRAMSARROW; Base := Ord(tspMoreProgramsArrowNormal); end; tspProgList: begin Part := SPP_PROGLIST; Base := Ord(tspProgList); end; tspProgListSeparator: begin Part := SPP_PROGLISTSEPARATOR; Base := Ord(tspProgListSeparator); end; tspPlacesList: begin Part := SPP_PLACESLIST; Base := Ord(tspPlacesList); end; tspPlacesListSeparator: begin Part := SPP_PLACESLISTSEPARATOR; Base := Ord(tspPlacesListSeparator); end; tspLogOff: begin Part := SPP_LOGOFF; Base := Ord(tspLogOff); end; tspLogOffButtonsNormal..tspLogOffButtonsPressed: begin Part := SPP_LOGOFFBUTTONS; Base := Ord(tspLogOffButtonsNormal); end; tspUserPicture: begin Part := SPP_USERPICTURE; Base := Ord(tspUserPicture); end; tspPreview: begin Part := SPP_PREVIEW; Base := Ord(tspPreview); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end;} NotImplemented; end; function TThemeServices.GetElementDetails(Detail: TThemedStatus): TThemedElementDetails; {var Base: Integer;} begin { Result.Element := teStatus; with Result do begin case Detail of tsPane: begin Part := SP_PANE; Base := Ord(tsPane); end; tsGripperPane: begin Part := SP_GRIPPERPANE; Base := Ord(tsGripperPane); end; tsGripper: begin Part := SP_GRIPPER; Base := Ord(tsGripper); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end;} NotImplemented; end; function TThemeServices.GetElementDetails(Detail: TThemedTab): TThemedElementDetails; var Base: Integer; begin Result.Element := teTab; with Result do begin Base := Ord(ttTabItemNormal); case Detail of ttTabItemNormal..ttTabItemFocused: begin Part := TABP_TABITEM; //Base := Ord(ttTabItemNormal); end; ttTabItemLeftEdgeNormal..ttTabItemLeftEdgeFocused: begin Part := TABP_TABITEMLEFTEDGE; //Base := Ord(ttTabItemLeftEdgeNormal); end; ttTabItemRightEdgeNormal..ttTabItemRightEdgeFocused: begin Part := TABP_TABITEMRIGHTEDGE; //Base := Ord(ttTabItemRightEdgeNormal); end; ttTabItemBothEdgeNormal..ttTabItemBothEdgeFocused: begin Part := TABP_TABITEMBOTHEDGE; //Base := Ord(ttTabItemBothEdgeNormal); end; ttTopTabItemNormal..ttTopTabItemFocused: begin Part := TABP_TOPTABITEM; //Base := Ord(ttTopTabItemNormal); end; ttTopTabItemLeftEdgeNormal..ttTopTabItemLeftEdgeFocused: begin Part := TABP_TOPTABITEMLEFTEDGE; //Base := Ord(ttTopTabItemLeftEdgeNormal); end; ttTopTabItemRightEdgeNormal..ttTopTabItemRightEdgeFocused: begin Part := TABP_TOPTABITEMRIGHTEDGE; //Base := Ord(ttTopTabItemRightEdgeNormal); end; ttTopTabItemBothEdgeNormal..ttTopTabItemBothEdgeFocused: begin Part := TABP_TOPTABITEMBOTHEDGE; //Base := Ord(ttTopTabItemBothEdgeNormal); end; ttPane: begin Part := TABP_PANE; Base := Ord(ttPane); end; ttBody: begin Part := TABP_BODY; Base := Ord(ttBody); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end; end; //---------------------------------------------------------------------------------------------------------------------- function TThemeServices.GetElementDetails(Detail: TThemedTaskBand): TThemedElementDetails; {var Base: Integer;} begin { Result.Element := teTaskBand; with Result do begin case Detail of ttbGroupCount: begin Part := TDP_GROUPCOUNT; Base := Ord(ttbGroupCount); end; ttbFlashButton: begin Part := TDP_FLASHBUTTON; Base := Ord(ttbFlashButton); end; ttpFlashButtonGroupMenu: begin Part := TDP_FLASHBUTTONGROUPMENU; Base := Ord(ttpFlashButtonGroupMenu); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end;} NotImplemented; end; function TThemeServices.GetElementDetails(Detail: TThemedTaskBar): TThemedElementDetails; {var Base: Integer;} begin { Result.Element := teTaskBar; with Result do begin case Detail of ttbTimeNormal: begin Part := CLP_TIME; Base := Ord(ttbTimeNormal); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end;} NotImplemented; end; function TThemeServices.GetElementDetails(Detail: TThemedToolBar): TThemedElementDetails; var Base: Integer; begin Result.Element := teToolBar; with Result do begin case Detail of ttbButtonNormal..ttbButtonCheckedHot: begin Part := TP_BUTTON; Base := Ord(ttbButtonNormal); end; ttbDropDownButtonNormal..ttbDropDownButtonCheckedHot: begin Part := TP_DROPDOWNBUTTON; Base := Ord(ttbDropDownButtonNormal); end; ttbSplitButtonNormal..ttbSplitButtonCheckedHot: begin Part := TP_SPLITBUTTON; Base := Ord(ttbSplitButtonNormal); end; ttbSplitButtonDropDownNormal..ttbSplitButtonDropDownCheckedHot: begin Part := TP_SPLITBUTTONDROPDOWN; Base := Ord(ttbSplitButtonDropDownNormal); end; ttbSeparatorNormal..ttbSeparatorCheckedHot: begin Part := TP_SEPARATOR; Base := Ord(ttbSeparatorNormal); end; ttbSeparatorVertNormal..ttbSeparatorVertCheckedHot: begin Part := TP_SEPARATORVERT; Base := Ord(ttbSeparatorVertNormal); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end; end; function TThemeServices.GetElementDetails(Detail: TThemedToolTip): TThemedElementDetails; {var Base: Integer;} begin { Result.Element := teToolTip; with Result do begin case Detail of tttStandardNormal..tttStandardLink: begin Part := TTP_STANDARD; Base := Ord(tttStandardNormal); end; tttStandardTitleNormal..tttStandardTitleLink: begin Part := TTP_STANDARDTITLE; Base := Ord(tttStandardTitleNormal); end; tttBaloonNormal..tttBaloonLink: begin Part := TTP_BALLOON; Base := Ord(tttBaloonNormal); end; tttBaloonTitleNormal..tttBaloonTitleLink: begin Part := TTP_BALLOONTITLE; Base := Ord(tttBaloonTitleNormal); end; tttCloseNormal..tttClosePressed: begin Part := TTP_CLOSE; Base := Ord(tttCloseNormal); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end;} NotImplemented; end; function TThemeServices.GetElementDetails(Detail: TThemedTrackBar): TThemedElementDetails; var Base: Integer; begin Result.Element := teTrackBar; with Result do begin Base := Ord(ttbTrack); case Detail of ttbTrack: begin Part := TKP_TRACK; //Base := Ord(ttbTrack); end; ttbTrackVert: begin Part := TKP_TRACKVERT; //Base := Ord(ttbTrackVert); end; ttbThumbNormal..ttbThumbDisabled: begin Part := TKP_THUMB; //Base := Ord(ttbThumbNormal); end; ttbThumbBottomNormal..ttbThumbBottomDisabled: begin Part := TKP_THUMBBOTTOM; //Base := Ord(ttbThumbBottomNormal); end; ttbThumbTopNormal..ttbThumbTopDisabled: begin Part := TKP_THUMBTOP; //Base := Ord(ttbThumbTopNormal); end; ttbThumbVertNormal..ttbThumbVertDisabled: begin Part := TKP_THUMBVERT; //Base := Ord(ttbThumbVertNormal); end; ttbThumbLeftNormal..ttbThumbLeftDisabled: begin Part := TKP_THUMBLEFT; //Base := Ord(ttbThumbLeftNormal); end; ttbThumbRightNormal..ttbThumbRightDisabled: begin Part := TKP_THUMBRIGHT; //Base := Ord(ttbThumbRightNormal); end; ttbThumbTics: begin Part := TKP_TICS; //Base := Ord(ttbThumbTics); end; ttbThumbTicsVert: begin Part := TKP_TICSVERT; //Base := Ord(ttbThumbTicsVert); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end; end; function TThemeServices.GetElementDetails(Detail: TThemedTrayNotify): TThemedElementDetails; {var Base: Integer;} begin { Result.Element := teTrayNotify; with Result do begin case Detail of ttnBackground: begin Part := TNP_BACKGROUND; Base := Ord(ttnBackground); end; ttnAnimBackground: begin Part := TNP_ANIMBACKGROUND; Base := Ord(ttnAnimBackground); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end;} NotImplemented; end; function TThemeServices.GetElementDetails(Detail: TThemedTreeview): TThemedElementDetails; {var Base: Integer;} begin { Result.Element := teTreeView; with Result do begin case Detail of ttItemNormal..ttItemSelectedNotFocus: begin Part := TVP_TREEITEM; Base := Ord(ttItemNormal); end; ttGlyphClosed..ttGlyphOpened: begin Part := TVP_GLYPH; Base := Ord(ttGlyphClosed); end; ttBranch: begin Part := TVP_BRANCH; Base := Ord(ttBranch); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end;} NotImplemented; end; function TThemeServices.GetElementDetails(Detail: TThemedWindow): TThemedElementDetails; {var Base: Integer;} begin { Result.Element := teWindow; with Result do begin case Detail of twCaptionActive..twCaptionDisabled: begin Part := WP_CAPTION; Base := Ord(twCaptionActive); end; twSmallCaptionActive..twSmallCaptionDisabled: begin Part := WP_SMALLCAPTION; Base := Ord(twSmallCaptionActive); end; twMinCaptionActive..twMinCaptionDisabled: begin Part := WP_MINCAPTION; Base := Ord(twMinCaptionActive); end; twSmallMinCaptionActive..twSmallMinCaptionDisabled: begin Part := WP_SMALLMINCAPTION; Base := Ord(twSmallMinCaptionActive); end; twMaxCaptionActive..twMaxCaptionDisabled: begin Part := WP_MAXCAPTION; Base := Ord(twMaxCaptionActive); end; twSmallMaxCaptionActive..twSmallMaxCaptionDisabled: begin Part := WP_SMALLMAXCAPTION; Base := Ord(twSmallMaxCaptionActive); end; twFrameLeftActive..twFrameLeftInactive: begin Part := WP_FRAMELEFT; Base := Ord(twFrameLeftActive); end; twFrameRightActive..twFrameRightInactive: begin Part := WP_FRAMERIGHT; Base := Ord(twFrameRightActive); end; twFrameBottomActive..twFrameBottomInactive: begin Part := WP_FRAMEBOTTOM; Base := Ord(twFrameBottomActive); end; twSmallFrameLeftActive..twSmallFrameLeftInactive: begin Part := WP_SMALLFRAMELEFT; Base := Ord(twSmallFrameLeftActive); end; twSmallFrameRightActive..twSmallFrameRightInactive: begin Part := WP_SMALLFRAMERIGHT; Base := Ord(twSmallFrameRightActive); end; twSmallFrameBottomActive..twSmallFrameBottomInactive: begin Part := WP_SMALLFRAMEBOTTOM; Base := Ord(twSmallFrameBottomActive); end; twSysButtonNormal..twSysButtonDisabled: begin Part := WP_SYSBUTTON; Base := Ord(twSysButtonNormal); end; twMDISysButtonNormal..twMDISysButtonDisabled: begin Part := WP_MDISYSBUTTON; Base := Ord(twMDISysButtonNormal); end; twMinButtonNormal..twMinButtonDisabled: begin Part := WP_MINBUTTON; Base := Ord(twMinButtonNormal); end; twMDIMinButtonNormal..twMDIMinButtonDisabled: begin Part := WP_MDIMINBUTTON; Base := Ord(twMDIMinButtonNormal); end; twMaxButtonNormal..twMaxButtonDisabled: begin Part := WP_MAXBUTTON; Base := Ord(twMaxButtonNormal); end; twCloseButtonNormal..twCloseButtonDisabled: begin Part := WP_CLOSEBUTTON; Base := Ord(twCloseButtonNormal); end; twSmallCloseButtonNormal..twSmallCloseButtonDisabled: begin Part := WP_SMALLCLOSEBUTTON; Base := Ord(twSmallCloseButtonNormal); end; twMDICloseButtonNormal..twMDICloseButtonDisabled: begin Part := WP_MDICLOSEBUTTON; Base := Ord(twMDICloseButtonNormal); end; twRestoreButtonNormal..twRestoreButtonDisabled: begin Part := WP_RESTOREBUTTON; Base := Ord(twRestoreButtonNormal); end; twMDIRestoreButtonNormal..twMDIRestoreButtonDisabled: begin Part := WP_MDIRESTOREBUTTON; Base := Ord(twMDIRestoreButtonNormal); end; twHelpButtonNormal..twHelpButtonDisabled: begin Part := WP_HELPBUTTON; Base := Ord(twHelpButtonNormal); end; twMDIHelpButtonNormal..twMDIHelpButtonDisabled: begin Part := WP_MDIHELPBUTTON; Base := Ord(twMDIHelpButtonNormal); end; twHorzScrollNormal..twHorzScrollDisabled: begin Part := WP_HORZSCROLL; Base := Ord(twHorzScrollNormal); end; twHorzThumbNormal..twHorzThumbDisabled: begin Part := WP_HORZTHUMB; Base := Ord(twHorzThumbNormal); end; twVertScrollNormal..twVertScrollDisabled: begin Part := WP_VERTSCROLL; Base := Ord(twVertScrollNormal); end; twVertThumbNormal..twVertThumbDisabled: begin Part := WP_VERTTHUMB; Base := Ord(twVertThumbNormal); end; twDialog: begin Part := WP_DIALOG; Base := Ord(twDialog); end; twCaptionSizingTemplate: begin Part := WP_CAPTIONSIZINGTEMPLATE; Base := Ord(twCaptionSizingTemplate); end; twSmallCaptionSizingTemplate: begin Part := WP_SMALLCAPTIONSIZINGTEMPLATE; Base := Ord(twSmallCaptionSizingTemplate); end; twFrameLeftSizingTemplate: begin Part := WP_FRAMELEFTSIZINGTEMPLATE; Base := Ord(twFrameLeftSizingTemplate); end; twSmallFrameLeftSizingTemplate: begin Part := WP_SMALLFRAMELEFTSIZINGTEMPLATE; Base := Ord(twSmallFrameLeftSizingTemplate); end; twFrameRightSizingTemplate: begin Part := WP_FRAMERIGHTSIZINGTEMPLATE; Base := Ord(twFrameRightSizingTemplate); end; twSmallFrameRightSizingTemplate: begin Part := WP_SMALLFRAMERIGHTSIZINGTEMPLATE; Base := Ord(twSmallFrameRightSizingTemplate); end; twFrameBottomSizingTemplate: begin Part := WP_FRAMEBOTTOMSIZINGTEMPLATE; Base := Ord(twFrameBottomSizingTemplate); end; twSmallFrameBottomSizingTemplate: begin Part := WP_SMALLFRAMEBOTTOMSIZINGTEMPLATE; Base := Ord(twSmallFrameBottomSizingTemplate); end; else Part := 0; Base := 0; end; State := Ord(Detail) - Base + 1; end;} NotImplemented; end; function TThemeServices.ContentRect(DC: QPainterH; Details: TThemedElementDetails; BoundingRect: TRect): TRect; begin with Details do GetThemeBackgroundContentRect(Element, DC, Part, State, BoundingRect, @Result); end; function TThemeServices.ContentRect(Canvas: TCanvas; Details: TThemedElementDetails; BoundingRect: TRect): TRect; begin Canvas.Start; try Result := ContentRect(Canvas.Handle, Details, BoundingRect); finally Canvas.Stop; end; end; procedure TThemeServices.DrawEdge(DC: QPainterH; Details: TThemedElementDetails; const R: TRect; Edge, Flags: Cardinal; ContentRect: PRect = nil); begin NotImplemented; { with Details do DrawThemeEdge(Theme[Element], HDC(QPainter_handle(DC)), Part, State, R, Edge, Flags, ContentRect);} end; //---------------------------------------------------------------------------------------------------------------------- procedure TThemeServices.DrawEdge(Canvas: TCanvas; Details: TThemedElementDetails; const R: TRect; Edge, Flags: Cardinal; ContentRect: PRect = nil); begin Canvas.Start; try DrawEdge(Canvas.Handle, Details, R, Edge, Flags, ContentRect); finally Canvas.Stop; end; end; procedure TThemeServices.DrawElement(DC: QPainterH; Details: TThemedElementDetails; const R: TRect; ClipRect: PRect = nil); begin with Details do DrawThemeBackground(Element, DC, Part, State, R, ClipRect); end; procedure TThemeServices.DrawElement(Canvas: TCanvas; Details: TThemedElementDetails; const R: TRect; ClipRect: PRect = nil); begin Canvas.Start; try DrawElement(Canvas.Handle, Details, R, ClipRect); finally Canvas.Stop; end; end; procedure TThemeServices.DrawParentBackground(Window: QWidgetH; Target: QPainterH; Details: PThemedElementDetails; OnlyIfTransparent: Boolean; Bounds: PRect = nil); var DoDraw: Boolean; ABounds: TRect; Control: TWidgetControl; Widget: TWidgetControl; Pt: TPoint; begin if OnlyIfTransparent and Assigned(Details) then begin with Details^ do DoDraw := IsThemeBackgroundPartiallyTransparent(Element, Part, State); end else DoDraw := True; if DoDraw then begin Control := FindControl(Window); if Control <> nil then begin Widget := Control.Parent; while (Widget <> nil) and (TOpenWidgetControl(Widget).Masked) do Widget := Widget.Parent; if (Widget <> nil) and (Widget is TTabSheet) then begin if (TTabSheet(Widget).PageControl <> nil) and (TTabSheet(Widget).PageControl.Style = tsTabs) then begin ABounds := TTabSheet(Widget).ClientRect; Pt := Control.ClientToScreen(Point(0, 0)); Pt := Widget.ScreenToClient(Pt); OffsetRect(ABounds, -Pt.X, -Pt.Y); ThemeServices.DrawElement(Target, GetElementDetails(ttBody), ABounds, Bounds); Exit; end; end; end; DrawThemeParentBackground(Window, Target, Bounds); end; end; procedure TThemeServices.DrawParentBackground(Window: QWidgetH; Target: TCanvas; Details: PThemedElementDetails; OnlyIfTransparent: Boolean; Bounds: PRect = nil); begin Target.Start; try DrawParentBackground(Window, Target.Handle, Details, OnlyIfTransparent, Bounds); finally Target.Stop; end; end; procedure TThemeServices.DrawText(DC: QPainterH; Details: TThemedElementDetails; const S: WideString; R: TRect; Flags, Flags2: Cardinal); begin with Details do DrawThemeText(Element, DC, Part, State, S, Flags, Flags2, R); end; //---------------------------------------------------------------------------------------------------------------------- procedure TThemeServices.DrawText(Canvas: TCanvas; Details: TThemedElementDetails; const S: WideString; R: TRect; Flags, Flags2: Cardinal); begin with Details do DrawThemeText(Element, Canvas.Handle, Part, State, S, Flags, Flags2, R); end; function TThemeServices.HasTransparentParts(Details: TThemedElementDetails): Boolean; begin with Details do Result := IsThemeBackgroundPartiallyTransparent(Element, Part, State); end; type TOpenFrameControl = class(TFrameControl); procedure TThemeServices.PaintBorder(Control: TWinControl; EraseLRCorner: Boolean; Painter: QPainterH = nil); var EmptyRect, DrawRect: TRect; Details: TThemedElementDetails; DC: QPainterH; begin with Control do begin if (Control is TFrameControl) and not (Control is TCustomForm) and (TOpenFrameControl(Control).BorderStyle in [bsSingle, bsSunken3d]) then begin DrawRect := Control.BoundsRect; OffsetRect(DrawRect, -DrawRect.Left, -DrawRect.Top); if Painter <> nil then DC := Painter else begin DC := QPainter_create; QPainter_begin(DC, TOpenFrameControl(Control).GetPaintDevice); end; try EmptyRect := DrawRect; if EraseLRCorner then begin {AStyle := GetWindowLong(HWND(QWidget_winId(Handle)), GWL_STYLE); if ((AStyle and WS_HSCROLL) <> 0) and ((AStyle and WS_VSCROLL) <> 0) then begin W := GetSystemMetrics(SM_CXVSCROLL); H := GetSystemMetrics(SM_CYHSCROLL); InflateRect(EmptyRect, -2, -2); with EmptyRect do EmptyRect := Rect(Right - W, Bottom - H, Right, Bottom); FillRect(DC, EmptyRect, GetSysColorBrush(COLOR_BTNFACE)); end;} end; QPainter_save(DC); try QPainter_setClipRect(DC, @DrawRect); // ignore old clip region with DrawRect do QExcludeClipRect(DC, Left + 2, Top + 2, Right - 2, Bottom - 2); Details := GetElementDetails(teEditTextNormal); DrawElement(DC, Details, DrawRect); finally QPainter_restore(DC); end; finally if Painter = nil then begin QPainter_end(DC); QPainter_destroy(DC); end; end; end; end; end; { TPainterCanvas } procedure TPainterCanvas.BeginPainting; begin // do nothing end; constructor TPainterCanvas.Create(AHandle: QPainterH); begin inherited Create; Handle := AHandle; Start(False); end; destructor TPainterCanvas.Destroy; begin Stop; inherited Destroy; end; initialization finalization InternalThemeServices.Free; end.
program telefonia; type linea = record numero :integer; minutos :real; datos :real; end; cliente = record codigo :integer; cantidadLineas :integer; minutos :real; datos :real; end; procedure leerCliente(var c:cliente); begin write('Ingrese el código del cliente: '); readln(c.codigo); write('Ingrese la cantidad de líneas del cliente: '); readln(c.cantidadLineas); end; procedure leerLinea(var l :linea); begin write('Ingrese el número de telefono: '); readln(l.numero); write('Ingrese la cantidad de minutos consumidos: '); readln(l.minutos); write('Ingrese la cantidad de MBs consumidos: '); readln(l.datos); end; procedure procesarCliente(var c :cliente); var i :integer; l :linea; begin for i := 1 to c.cantidadLineas do begin writeln('Procesando lína nro ', i); leerLinea(l); c.minutos := c.minutos + l.minutos; c.datos := c.datos + l.datos; end; end; function calcularFacturacion(c:cliente):real; begin calcularFacturacion := c.minutos * 3.4 + c.datos * 1.35; end; var clienteActual :cliente; i :integer; begin for i := 1 to 9300 do begin clienteActual.minutos := 0; clienteActual.datos := 0; leerCliente(clienteActual); procesarCliente(clienteActual); writeln('El cliente debe abonar $', calcularFacturacion(clienteActual):8:2); end; end.
unit VerObjectImages; interface type TVersionableObjectImage = class public constructor Create(Indent, loBound, hiBound : integer); destructor Destroy; override; private fProps : TStringList; public procedure Load( end; implementation end. // CLOSE THE DOOR...
{ CSI 1101-X, Winter 1999 } { Assignment 3 } { Identification: Mark Sattolo, student# 428500 } { tutorial group DGD-4, t.a. = Manon Sanscartier } program a3 (input,output) ; type element_type = real ; pointer = ^node ; node = record value: element_type ; next: pointer end ; list = pointer ; { variable for the main program - NOT to be referenced anywhere else } var YESorNO: char ; {** The following global variable is used for memory management. You might find it useful while debugging your code, but the solutions you hand in must not refer to this variable in any way. **} memory_count: integer ; {******** MEMORY MANAGEMENT PROCEDURES ***********} { get_node - Returns a pointer to a new node. } procedure get_node( var P: pointer ); begin memory_count := memory_count + 1 ; new( P ) end ; { return_node - Make the node pointed at by P "free" (available to get_node). } procedure return_node(var P: pointer) ; begin memory_count := memory_count - 1 ; P^.value := -7777.77 ; { "scrub" memory to aid debugging } P^.next := P ; { "scrub" memory to aid debugging } dispose( P ) end ; {****************************************************************} { create_empty - sets list L to be empty. } procedure create_empty ( var L: list ) ; begin L := nil end ; procedure write_list ( var L:list ); var p: pointer ; { temporary pointer } size: integer ; { keep track of list size } begin if L = nil then writeln('Empty list.') else begin size := 0 ; p := L ; while p <> nil do { traverse list } begin write( ' ', p^.value:7:2 ) ; { write values } p := p^.next ; size := size + 1 ; { increment size } end ; { while } writeln; { writeln('Size of List is: ', size, '.') ; // don't want for A3 } end ; { else } end ; { procedure } procedure insert_at_front(var L:list; V: element_type) ; var p: pointer; { temporary pointer } begin get_node(p) ; p^.value := V ; { new node gets V } p^.next := L ; { new node continues with rest of list } L := p ; { list now starts at new node } end; { procedure } procedure insert_after_P( V: element_type; P: pointer) ; var q : pointer ; { temporary pointer } begin get_node(q) ; q^.value := V ; { new node gets V} q^.next := p^.next ; { new node continues with tail of P } p^.next := q ; { P now continues with the new node } end; { procedure } procedure destroy( var L:list ) ; { Base case: L = Nil: do nothing. General case: 1) make the recursive call to destroy the 'tail' 2) then, return the 'head' node, and all of L has been destroyed. } begin if L <> Nil then { General case } begin destroy (L^.next) ; { step 1 } return_node (L) ; { step 2 } end { i.e. Base case = "else, do nothing" } end; { procedure } function is_increasing( L:list ): boolean ; { Base case: L = Nil or L = singleton General case: 1) test the first two values: if (L1 > L2) then the function returns false. 2) otherwise make the recursive call to L^.next } begin if (L = Nil) or (L^.next = Nil) then { Base case, gets true } is_increasing := true else if L^.value > L^.next^.value then { General case, step 1 } is_increasing := false else is_increasing := is_increasing (L^.next) ; { step 2 } end; { function } procedure insert_increasing_rec( var L:list; V: element_type ) ; { Base case: L is already in increasing order (given), thus if L = Nil or if V <= L1, can insert V at the front of L as the first step. General case: if the base case doesn't hold, make the recursive call to insert V in the 'tail', and V will be inserted at the correct postion in L. } begin if (V <= L^.value) or (L = Nil) then { Base case } insert_at_front (L, V) else insert_increasing_rec (L^.next, V) ; { General case } end; { procedure } procedure insert_increasing_loop( var L:list; V: element_type ) ; { 1) L is already in increasing order (given), thus if L = Nil or if V <= L1, can insert V at the front of L as the first step. 2) If cannot insert V at the front of L, need to use 'insert_after_P' and so need to set a temporary pointer "temp" to traverse the list. 3) Set temp to L initially, then start a loop to move temp to the next node as long as there is a next node and it has a value less than V. 4) When the loop has finished, temp is pointing at a node with a value less than V, where there is no next node or the value of the next node is greater than V, so now call 'insert_after_P' with temp and V, and V is inserted in the proper position in L. } var temp: pointer ; { a temporary pointer needed to traverse the list in the while loop } begin if (V <= L^.value) or (L = Nil) then { step 1 } insert_at_front (L, V) else begin temp := L ; { step 2 } while (temp^.next <> Nil) and (V > temp^.next^.value) do temp := temp^.next ; { step 3 } insert_after_P (V, temp) ; { step 4 } end ; end; { procedure } procedure assignment3 ; var Lf, Lsr, Lsl: list ; val: element_type ; begin create_empty( Lf ); create_empty( Lsr ); create_empty( Lsl ); writeln('enter a list of reals, all values on one line'); while (not eoln) do begin read(val) ; writeln('inserting this value: ',val:4:1); write('at_front: '); insert_at_front(Lf,val) ; write_list(Lf); write('increasing, recursively: '); insert_increasing_rec(Lsr,val) ; write_list(Lsr); if not is_increasing(Lsr) then writeln('*** this list is NOT in increasing order'); write('increasing, loop: '); insert_increasing_loop(Lsl,val) ; if not is_increasing(Lsl) then writeln('*** this list is NOT in increasing order'); write_list(Lsl); writeln end ; readln ; { clear the empty line } if is_increasing(Lf) then begin writeln('*** tricky - you entered the values in decreasing order'); writeln end ; { to finish off, return all the nodes in all lists back to the global pool } writeln('about to destroy the lists') ; destroy( Lf ); destroy( Lsr ); destroy( Lsl ); writeln end; {****** YOU MUST CHANGE THIS PROCEDURE TO DESCRIBE YOURSELF ******} procedure identify_myself ; { Writes who you are to the screen } begin writeln ; writeln('CSI 1101-X (winter, 1999). Assignment 3.') ; writeln('Mark Sattolo, student# 428500.') ; writeln('tutorial section DGD-4, t.a. = Manon Sanscartier') ; writeln end ; begin { main program } memory_count := 0 ; identify_myself ; repeat assignment3 ; writeln('Amount of dynamic memory allocated but not returned (should be 0) ', memory_count:0) ; writeln('Do you wish to continue (y or n) ?') ; readln(YESorNO); until (YESorNO <> 'y') end.
//Exercício 8: Uma empresa paga R$10,00 por hora normal trabalhada e R$15,00 por hora extra. Escreva um algoritmo que //leia o total de horas normais e o total de horas extras trabalhadas por um empregado em um ano e calcule o salário //anual deste trabalhador. { Solução em Portugol Algoritmo Exercicio8; Const valor_hora_normal = 10; valor_hora_extra = 15; Var salario_anual, hora_normal, hora_extra: real; Inicio exiba("Programa que calcula o salário anual de um trabalhador."); exiba("Digite a quantidade de horas normais trabalhadas no ano: "); leia(hora_normal); exiba("Digite a quantidade de horas extras trabalhadas no ano: "); leia(hora_extra); salario_anual <- hora_normal * valor_hora_normal + hora_extra * valor_hora _extra; exiba("O salário anual desse trabalhador é: ",salario_anual); Fim. } // Solução em Pascal Program Exercicio8; uses crt; const valor_hora_normal = 10; valor_hora_extra = 15; var salario_anual, hora_normal, hora_extra: real; begin clrscr; writeln('Programa que calcula o salário anual de um trabalhador.'); writeln('Digite a quantidade de horas normais trabalhadas no ano: '); readln(hora_normal); writeln('Digite a quantidade de horas extras trabalhadas no ano: '); readln(hora_extra); salario_anual := hora_normal * valor_hora_normal + hora_extra * valor_hora_extra; writeln('O salário anual desse trabalhador é: ',salario_anual:0:2); repeat until keypressed; end.
{$A+,B-,D+,E+,F-,G+,I-,L+,N-,O-,P-,Q-,R-,S-,T-,V+,X+,Y+} {$M 8192,0,0} {BP 7.0 compiler options} Program Unpacker; {PKUnlite by BUGSY/OBSESSiON 18-09-1997, Just to show how DumpExe API works. } Uses Crt, Dos, UnpUtil; Const RetFFound = 0; LoadError = 1; FreeError = 2; EndOfProgram = 3; VersionError = 4; SizeError = 5; DumpError = 6; Type LoadAndExecType = Record Environment , OfsParam , SegParam : Word; FCB : Array [1..4] Of Word; _SP , _SS , _IP , _CS : Word; End; DumpExeRegsType = Record _cs , _ip , _ss , _sp , _psp : Word; End; Str80 = String[80]; Var OldSS , OldSP , FileError , ChildePSP : Word; ExecName , Parameter : String; LoadAndExec : LoadAndExecType; DumpExeRegs : DumpExeRegsType; DumpNo : Byte; Dump1Seg : Word; Locked : Boolean; Procedure Error (Err : Byte); Begin If Err <> 255 Then Write ('Error (',Err,') : '); TextColor(LightGreen); Case Err Of 1 : WriteLn ('Invalid function number.'); 2 : WriteLn ('File not found.'); 3 : WriteLn ('Path not found.'); 4 : WriteLn ('Too many open files.'); 5 : WriteLn ('File access denied.'); 6 : WriteLn ('Invalid file handle.'); 8 : WriteLn ('Not enough memory'); 10 : WriteLn ('Invalid environment'); 11 : WriteLn ('Invalid format'); 12 : WriteLn ('Invalid file access code.'); 15 : WriteLn ('Invalid drive number.'); 16 : WriteLn ('Cannot remove current directory.'); 17 : WriteLn ('Cannot rename across drives.'); 18 : WriteLn ('No more files.'); 100 : WriteLn ('Disk read error.'); 101 : WriteLn ('Disk write error.'); 102 : WriteLn ('File not assigned.'); 103 : WriteLn ('File not open.'); 104 : WriteLn ('File not open for input.'); 105 : WriteLn ('File not open for output.'); 106 : WriteLn ('Invalid numeric format.'); 150 : WriteLn ('Disk is write-protected.'); 151 : WriteLn ('Bad drive request struct length.'); 152 : WriteLn ('Drive not ready.'); 154 : WriteLn ('CRC error in data.'); 156 : WriteLn ('Disk seek error.'); 157 : WriteLn ('Unknown media type.'); 158 : WriteLn ('Sector Not Found.'); 159 : WriteLn ('Printer out of paper.'); 160 : WriteLn ('Device write fault.'); 161 : WriteLn ('Device read fault.'); 162 : WriteLn ('Hardware failure.'); 200 : WriteLn ('Division by zero.'); 201 : WriteLn ('Range check error.'); 202 : WriteLn ('Stack overflow error.'); 203 : WriteLn ('Heap overflow error.'); 204 : WriteLn ('Invalid pointer operation.'); 205 : WriteLn ('Floating point overflow.'); 206 : WriteLn ('Floating point underflow.'); 207 : WriteLn ('Invalid floating point operation.'); 208 : WriteLn ('Overlay manager not installed.'); 209 : WriteLn ('Overlay file read error.'); 210 : WriteLn ('Object not initialized.'); 211 : WriteLn ('Call to abstract method.'); 212 : WriteLn ('Stream registration error.'); 213 : WriteLn ('Collection index out of range.'); 214 : WriteLn ('Collection overflow error.'); 215 : WriteLn ('Arithmetic overflow error.'); 216 : WriteLn ('General Protection fault.'); 246 : WriteLn ('Infile is not packed with PKLite.'); 247 : WriteLn ('Infile is NOT an EXE.'); 248 : WriteLn ('Can''t read from infile.'); 249 : WriteLn ('There was an error writeing the dump.'); 250 : WriteLn ('Can''t autodetect the size by ''stack''.'); 251 : WriteLn ('Invalid DumpExe API version. Version 2.4 expected !'); 252 : WriteLn ('Program could not be unpacked.'); 253 : WriteLn ('Can''t free memory.'); 255 : Begin WriteLn ('USAGE : UNPACKER.EXE infile.ext'); TextColor(White); WriteLn; WriteLn ('Unpacker is ONLY ment as an example on how to use the DumpExe API.'); WriteLn ('It can currently unpack PKLite 2.01 for dos. Please take a look at'); WriteLn ('the source code for further information on how to use the DumpExe API.'); WriteLn; End; Else WriteLn ('No error text defined, sorry ...'); {hmmmmm....} End; LastInitText; Halt (Err); End; Function TraceFile : Byte; label NewInt01Hand; Var Ct : Byte; OldInt01 : Procedure; Begin GetIntVec ($01, @OldInt01); ExecName := ParamStr(1); ExecName[Length (ExecName)+1] := #0; Parameter[0] := #$00; Parameter[1] := #$0D; With LoadAndExec Do Begin Environment := $0000; OfsParam := ofs (Parameter); SegParam := seg (Parameter); For Ct := 1 To 4 Do FCB[Ct] := $FFFF; End; SwapVectors; FileError := 0; Locked := False; asm push bp mov byte ptr @retfcount, 0 xor ah, ah {Get DumpExe API version} {int 0fbh} db 0cdh db IntFB cmp bx, 0240h je @VersionOK mov @result, VersionError jmp @GetOut @APIAddress: {Emulate an interrupt call} pushf db 9ah {call xxxx:xxxx} @APIOfs: dw 0 @APISeg: dw 0 ret @VersionOK: mov ah, 01h {int 0fbh} db 0cdh {Get DumpExe API Address & secure DumpExe API session} db IntFB mov word ptr @APISeg, es mov word ptr @APIOfs, di mov Locked, True push ds mov ax, 2501h push cs pop ds mov dx, offset @NewInt01Hand int 21h pop ds mov dx, offset ExecName + 1 push ds pop es mov bx, offset LoadAndExec mov ax, 4B01h int 21h mov FileError, ax mov @result, LoadError jc @GetOut mov ah, 62h int 21h mov ChildePSP, bx mov OldSS, ss mov OldSP, sp mov al, 1 pushf mov bp, sp or ss:[bp+1], al popf cli mov ss, LoadAndExec._SS mov sp, LoadAndExec._SP sti push LoadAndExec._CS push LoadAndExec._IP mov es, ChildePSP mov word ptr es:[000ch], cs mov word ptr es:[000ah], offset @EndOfProg mov ds, LoadAndExec._CS cld xor ax, ax mov bx, ax mov cx, ax mov dx, ax mov si, ax mov di, ax mov bp, ax {set trap flag and retf} retf @retfcount: db 0 @NewInt01Hand: { int 02 {Used to trigger softice (use bpint 02)} pusha push es mov bp, sp cmp byte ptr @retfcount, 3 je @RetFFound mov al, 3 or ss:[bp+10h+2+5], al {set trap and interruptflag on return} les di, ss:[bp+10h+2] cmp byte ptr es:[di], 0cbh {retf opcode} jne @NextIns inc byte ptr @retfcount @NextIns: pop es popa iret @EndOfProg: mov bl, EndOfProgram jmp @StopTrace @RetFFound: mov bl, RetFFound jmp @StopTrace @StopTrace: mov ax, SEG OldSS mov ds, ax cmp bl, RetFFound jne @RetFNotFound les di, ss:[bp+10h+2h] mov DumpExeRegs._cs, es mov DumpExeRegs._ip, di mov DumpExeRegs._ss, ss mov DumpExeRegs._sp, sp add DumpExeRegs._sp, 10h+2h+6h @RetFNotFound: cli mov ss, OldSS mov sp, OldSP sti pop bp push bp mov @result, bl mov ah, 50h {Set PSP segment} mov bx, PrefixSeg int 21h pop bp push bp cmp @result, EndOfProgram je @GetOut mov es, ChildePSP mov DumpExeRegs._psp, es push es mov es, es:[2ch] {Free environment of the loaded program} mov ah, 49h int 21h pop es mov ah, 03h {Fill DumpExe API registers} mov al, DumpNo mov si, Offset DumpExeRegs call @APIAddress cmp DumpNo, 1 jne @NoAutoSizeError mov ah, 04h {Autodetect size (by stack) for BOTH dumps} mov al, DumpNo mov bl, 02h call @APIAddress cmp al, 0 je @NoAutoSizeError mov @Result, SizeError jmp @GetOut @NoAutoSizeError: mov ah, 06h mov al, DumpNo call @APIAddress cmp al, 0 je @NoDumpError mov @Result, DumpError jmp @GetOut @NoDumpError: cmp DumpNo, 1 jne @SecondDump mov word ptr Dump1Seg, es mov ah, 4ah mov bx, 100h int 21h jmp @GetOut @FreeFirstDump: cmp Dump1Seg, 0 je @GetOut mov es, Dump1Seg mov Dump1Seg, 0 @SecondDump: mov ah, 49h {Free memory of the loaded program} int 21h jnc @FreeFirstDump pop bp push bp mov @result, FreeError @GetOut: pop bp cmp Locked, True jne @NotLocked mov ah, 02h {Unlock DumpExe API session} call @APIAddress mov Locked, False @NotLocked: end; SwapVectors; SetIntVec ($01, @OldInt01); End; Procedure WriteFailed; Begin TextColor (LightRed); WriteLn ('FAILED'); TextColor (White); End; Procedure WriteIfError(RetVal : Byte); Begin If RetVal = RetFFound Then Begin WriteLn('OK'); Exit; End; WriteFailed; Case RetVal Of LoadError : Error(FileError); FreeError : Error(253); EndOfProgram : Error(252); VersionError : Error(251); SizeError : Error(250); DumpError : Error(249); Else Error(0); End; End; Procedure WriteFailedWithError(Err : Byte; ErrText : Str80 ); Begin WriteFailed; WriteLn (ErrText); LastInitText; Halt(Err); End; Procedure Init; Var InFile : File; Buff : Array[1..32] Of Char; Res, Ct : Integer; Begin DumpNo := 1; Clrscr; WriteTitleText; TextColor (White); If ParamCount <> 1 Then Error (255); Write ('þ DumpExe API is resident '); If NOT DumpExeAPIResident Then WriteFailedWithError(3,'Please start DUMPAPI.EXE before using UNPACKER.EXE'); WriteLn ('OK'); WriteLn; Assign(InFile, ParamStr(1)); Reset (InFile,1); Res := IOresult; If Res <> 0 Then Error (Res); BlockRead(InFile, Buff,SizeOf(Buff), Ct); Close(InFile); If Ct <> SizeOf(Buff) Then Error(248); If NOT (((Buff[1] = 'M') AND (Buff[2] = 'Z')) OR {Test if file is an EXE} ((Buff[1] = 'Z') AND (Buff[2] = 'M'))) Then Error (247); If ((Buff[31] <> 'P') OR (Buff[32] <> 'K')) Then Error (246); {PKLited ?} End; Procedure UnpackFile; Begin WriteLn ('Unpacking file : ', ParamStr(1)); WriteLn; Write('Making first dump '); WriteIfError(TraceFile); Inc(DumpNo); Write('Making second dump '); WriteIfError(TraceFile); WriteLn; WriteLn ('Use MAKEEXE.EXE to create an unpacked exefile.'); LastInitText; End; Begin Init; UnpackFile; End.
unit ElevationMonikerFactory; interface uses System.SysUtils, System.Win.ComObj, Winapi.Windows, System.Win.ComConst; type TElevationMonikerFactory = class(TTypedComObjectFactory) private FLocalizedStringResId: AnsiString; FIconResId: AnsiString; public constructor Create(const ANameResourceId: AnsiString; const AIconResourceId: AnsiString; AComServer: TComServerObject; ATypedComClass: TTypedComClass; const AClassID: TGUID; AInstancing: TClassInstancing; AThreadingModel: TThreadingModel = tmSingle); procedure UpdateRegistry(ARegister: Boolean); override; end; implementation function ConvertStringSecurityDescriptorToSecurityDescriptor( StringSecurityDescriptor: PAnsiChar; StringSDRevision: Cardinal; var SecurityDescriptor: PSecurityDescriptor; var SecurityDescriptorSize: Cardinal ): LongBool; stdcall; external advapi32 name 'ConvertStringSecurityDescriptorToSecurityDescriptorA'; procedure CreateRegKeyEx(const AKey, AValueName, AValue: AnsiString; APtr: Pointer; ALen: Integer; AValueType: Cardinal = REG_SZ; ARootKey: DWORD = HKEY_CLASSES_ROOT); var Handle: HKEY; Status, Disposition: Integer; V: DWORD; begin Status := RegCreateKeyExA( ARootKey, PAnsiChar(AKey), 0, '', REG_OPTION_NON_VOLATILE, KEY_READ or KEY_WRITE, nil, Handle, @Disposition ); if (Status = 0) then begin try case AValueType of REG_SZ: begin Status := RegSetValueExA( Handle, PAnsiChar(AValueName), 0, AValueType, PAnsiChar(AValue), Length(AValue) + 1 ); end; REG_BINARY: begin Status := RegSetValueExA( Handle, PAnsiChar(AValueName), 0, AValueType, APtr, ALen ); end; REG_DWORD: begin V := StrToInt(AValue); Status := RegSetValueExA( Handle, PAnsiChar(AValueName), 0, AValueType, @V, SizeOf(DWORD) ); end; else raise Exception.CreateFmt( 'Unsupported registry value type (%d)!', [AValueType] ); end; finally RegCloseKey(Handle); end; end; if (Status <> 0) then raise EOleRegistrationError.CreateRes(@SCreateRegKeyError); end; procedure SetAccessPermissionsForLUAServer(const AKey, AValueName: AnsiString); const SDDL_REVISION_1 = 1; var PSD: PSecurityDescriptor; L: Cardinal; Handle: HKEY; hr: HRESULT; begin { Request local call permissions for InteractiveUser and System. } if not ConvertStringSecurityDescriptorToSecurityDescriptor( 'O:BAG:BAD:(A;;0x3;;;IU)(A;;0x3;;;SY)', SDDL_REVISION_1, PSD, L ) then RaiseLastOSError; try hr := RegOpenKeyExA( HKEY_CLASSES_ROOT, PAnsiChar(AKey), 0, KEY_READ or KEY_WRITE, Handle ); if hr = ERROR_SUCCESS then begin try hr := RegSetValueExA( Handle, PAnsiChar(AValueName), 0, REG_BINARY, PSD, L ); if hr <> ERROR_SUCCESS then RaiseLastOSError; finally RegCloseKey(Handle); end; end else RaiseLastOSError; finally LocalFree(Cardinal(PSD)); end; end; { TElevationMonikerFactory } constructor TElevationMonikerFactory.Create(const ANameResourceId: AnsiString; const AIconResourceId: AnsiString; AComServer: TComServerObject; ATypedComClass: TTypedComClass; const AClassID: TGUID; AInstancing: TClassInstancing; AThreadingModel: TThreadingModel); begin inherited Create( AComServer, ATypedComClass, AClassID, AInstancing, AThreadingModel ); { Save the id of the resource, that holds the application name and icon. } FLocalizedStringResId := ANameResourceId; FIconResId := AIconResourceId; end; procedure TElevationMonikerFactory.UpdateRegistry(ARegister: Boolean); var ID, ClassKey, FullFileName, FileName: AnsiString; begin ID := GUIDToString(Self.ClassID); ClassKey := 'CLSID\' + ID; FullFileName := ComServer.ServerFileName; FileName := ExtractFileName(FullFileName); try if ARegister then begin inherited UpdateRegistry(ARegister); { DLL out-of-process hosting requirements. } CreateRegKey('AppID\' + ID, '', Description); CreateRegKey('AppID\' + ID, 'DllSurrogate', ''); CreateRegKey('AppID\' + FileName, 'AppID', ID); { Over-The-Shoulder activation requirements. } SetAccessPermissionsForLUAServer('AppID\' + ID, 'AccessPermission'); { COM object elevation requirements. } CreateRegKey(ClassKey, 'AppID', ID); CreateRegKey(ClassKey, 'LocalizedString', '@' + FullFileName + ',-' + FLocalizedStringResId); CreateRegKey(ClassKey + '\Elevation', 'IconReference', '@' + FullFileName + ',-' + FIconResId); CreateRegKeyEx(ClassKey + '\Elevation', 'Enabled', '1', nil, 0, REG_DWORD); end else begin DeleteRegKey(ClassKey + '\Elevation'); DeleteRegKey('AppID\' + ID); DeleteRegKey('AppID\' + FileName); inherited UpdateRegistry(aRegister); end; except on E: EOleRegistrationError do raise; on E: Exception do raise EOleRegistrationError.Create(E.Message, 0, E.HelpContext); end; end; end.
unit clOS; interface uses Vcl.Forms, Vcl.Dialogs, System.SysUtils, System.Classes, System.DateUtils, clOcorrenciasJornal, System.UITypes, Winapi.Windows, clEntregador, clCliente; type TOS = class(TObject) private FNumero: Integer; FData: System.TDateTime; FCliente: Integer; FCadastro: Integer; FPlaca: String; FRota: String; FKMInicial: Integer; FHoraSaida: System.TTime; FKMFinal: Integer; FHoraRetorno: System.TTime; FServico: String; FValor: Double; FStatus: String; FLog: String; entregador: TEntregador; clientes : TCliente; procedure SetNumero(val: Integer); procedure SetData(val: System.TDateTime); procedure SetCliente(val: Integer); procedure SetCadastro(val: Integer); procedure SetPlaca(val: String); procedure SetRota(val: String); procedure SetKMInicial(val: Integer); procedure SetHoraSaida(val: System.TTime); procedure SetKMFinal(val: Integer); procedure SetHoraRetorno(val: System.TTime); procedure SetServico(val: String); procedure SetValor(val: Double); procedure SetStatus(val: String); procedure SetLog(val: String); public property Numero: Integer read FNumero write SetNumero; property Data: System.TDateTime read FData write SetData; property Cliente: Integer read FCliente write SetCliente; property Cadastro: Integer read FCadastro write SetCadastro; property Placa: String read FPlaca write SetPlaca; property Rota: String read FRota write SetRota; property KMInicial: Integer read FKMInicial write SetKMInicial; property HoraSaida: System.TTime read FHoraSaida write SetHoraSaida; property KMFinal: Integer read FKMFinal write SetKMFinal; property HoraRetorno: System.TTime read FHoraRetorno write SetHoraRetorno; property Servico: String read FServico write SetServico; property Valor: Double read FValor write SetValor; property Status: String read FStatus write SetStatus; property Log: String read FLog write SetLog; function Localizar: Boolean; function SetupClass(iOs: Integer): Boolean; constructor Create; destructor Destroy; override; end; implementation uses udm, ufrmLocalizar, clUtil, uGlobais; procedure TOS.SetNumero(val: Integer); begin FNumero := val; end; procedure TOS.SetData(val: System.TDateTime); begin FData := val; end; procedure TOS.SetCliente(val: Integer); begin FCliente := val; end; procedure TOS.SetCadastro(val: Integer); begin FCadastro := val; end; procedure TOS.SetPlaca(val: String); begin FPlaca := val; end; procedure TOS.SetRota(val: String); begin FRota := val; end; procedure TOS.SetKMInicial(val: Integer); begin FKMInicial := val; end; procedure TOS.SetHoraSaida(val: System.TTime); begin FHoraSaida := val; end; procedure TOS.SetKMFinal(val: Integer); begin FKMFinal := val; end; procedure TOS.SetHoraRetorno(val: System.TTime); begin FHoraRetorno := val; end; procedure TOS.SetServico(val: String); begin FServico := val; end; procedure TOS.SetValor(val: Double); begin FValor := val; end; procedure TOS.SetStatus(val: String); begin FStatus := val; end; procedure TOS.SetLog(val: String); begin FLog := val; end; function TOS.Localizar: Boolean; var sSQL : String; begin Result := False; sSQL := 'SELECT ' + 'A.NUM_OS AS "Número", ' + 'B.NOM_CLIENTE AS "Solicitante", ' + 'C.DES_RAZAO_SOCIAL AS "Motorista", ' + 'A.DES_PLACA AS "Placa", ' + 'A.DES_ROTA AS "Rota" ' + 'FROM TSV_ORDEM_SERVICO AS A ' + 'LEFT JOIN TBCLIENTES AS B ' + 'ON B.COD_CLIENTE = A.COD_CLIENTE ' + 'LEFT JOIN TBENTREGADORES AS C ' + 'ON C.COD_CADASTRO = A.COD_CADASTRO'; dm.qryPesquisa.Close; dm.qryPesquisa.SQL.Clear; dm.qryPesquisa.SQL.Text := sSQL; dm.qryPesquisa.Open; if dm.qryPesquisa.IsEmpty then begin dm.qryPesquisa.Close; dm.qryPesquisa.SQL.Clear; Exit; end; if not Assigned(frmLocalizar) then begin frmLocalizar := TfrmLocalizar.Create(Application); end; frmLocalizar.cboCamposDisplay.Clear; frmLocalizar.cboCamposSQL.Clear; frmLocalizar.cboCamposDisplay.Items.Add('Número'); frmLocalizar.cboCamposSQL.Items.Add('NUM_OS'); frmLocalizar.cboCamposDisplay.Items.Add('Solicitante'); frmLocalizar.cboCamposSQL.Items.Add('NOM_CLIENTE'); frmLocalizar.cboCamposDisplay.Items.Add('Motorista'); frmLocalizar.cboCamposSQL.Items.Add('DES_RAZAO_SOCIAL'); frmLocalizar.cboCamposDisplay.Items.Add('Placa'); frmLocalizar.cboCamposSQL.Items.Add('DES_PLACA'); frmLocalizar.cboCamposDisplay.Items.Add('Rota'); frmLocalizar.cboCamposSQL.Items.Add('DES_ROTA'); frmLocalizar.cboCamposDisplay.ItemIndex := 0; frmLocalizar.cboCamposSQL.ItemIndex := 0; if frmLocalizar.ShowModal = mrOk then begin if not SetupClass(dm.qryPesquisa.Fields[0].AsInteger) then begin Application.MessageBox('Erro ao tentar configurar os campos!', PChar('Atenção ' + uGlobais.sUsuario), MB_OK + MB_ICONEXCLAMATION); dm.qryPesquisa.Close; dm.qryPesquisa.SQL.Clear; FreeAndNil(frmLocalizar); Exit; end; end; dm.qryPesquisa.Close; dm.qryPesquisa.SQL.Clear; FreeAndNil(frmLocalizar); Result := True; end; function TOS.SetupClass(iOs: Integer): Boolean; begin Result := False; if iOs = 0 then begin Exit; end; dm.qryOS.Close; dm.qryOS.Filter := 'NUM_OS = ' + IntToStr(iOs); dm.qryOS.Open(); if not dm.qryOS.IsEmpty then begin Self.Numero := dm.qryOS.FieldByName('NUM_OS').AsInteger; Self.Data := dm.qryOS.FieldByName('DAT_OS').AsDateTime; Self.Cliente := dm.qryOS.FieldByName('COD_CLIENTE').AsInteger; Self.Cadastro := dm.qryOS.FieldByName('COD_CADASTRO').AsInteger; Self.Placa := dm.qryOS.FieldByName('DES_PLACA').AsString; Self.Rota := dm.qryOS.FieldByName('DES_ROTA').AsString; Self.KMInicial := dm.qryOS.FieldByName('QTD_KM_INICIAL').AsInteger; Self.HoraSaida := dm.qryOS.FieldByName('DAT_HORA_SAIDA').AsDateTime; Self.KMFinal := dm.qryOS.FieldByName('QTD_KM_FINAL').AsInteger; Self.HoraRetorno := dm.qryOS.FieldByName('DAT_HORA_RETORNO').AsDateTime; Self.Servico := dm.qryOS.FieldByName('DES_SERVICO').AsString; Self.Valor := dm.qryOS.FieldByName('VAL_OS').AsFloat; Self.Status := dm.qryOS.FieldByName('DOM_STATUS').AsString; Self.Log := dm.qryOS.FieldByName('DES_LOG').AsString; Result := True; end; dm.qryOS.Close; dm.qryOS.Filter := ''; end; constructor TOS.Create; begin inherited Create; entregador := TEntregador.Create(); clientes := TCliente.Create(); end; destructor TOS.Destroy; begin entregador.Free; clientes.Free; inherited Destroy; end; end.
unit pedidoU; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, ZAbstractRODataset, ZAbstractDataset, ZDataset, ZAbstractConnection, ZConnection, Vcl.Buttons, Vcl.Mask, Vcl.DBCtrls, Vcl.ComCtrls, System.UITypes, ProdutoPedidoClass; type TpedidoF = class(TForm) bxListaPedido: TGroupBox; dbPedido: TDBGrid; bxInclusaoPedido: TGroupBox; edNumPedido: TEdit; lbNumPedido: TLabel; edDataEmissao: TEdit; lbDataEmissao: TLabel; edCodCliente: TEdit; lbCodCliente: TLabel; btnConsCliente: TBitBtn; edNomeCliente: TEdit; lbCodProduto: TLabel; edCodProduto: TEdit; btnConsProduto: TBitBtn; edDescricaoProduto: TEdit; lbQuantidade: TLabel; edQuantidade: TEdit; lbValorUnitario: TLabel; edValorUnitario: TEdit; lbValorTotal: TLabel; edValorTotal: TEdit; btnIncluirProduto: TBitBtn; btnCancelarProduto: TBitBtn; btnExcluirProduto: TBitBtn; dbProdutoTmp: TDBGrid; lbSomaProduto: TLabel; edSomaProduto: TDBEdit; btnExcluirPedido: TBitBtn; bxBotoes: TGroupBox; btnGravar: TBitBtn; btnSair: TBitBtn; btnCancelar: TBitBtn; lbConsultar: TLabel; edConsultar: TEdit; btnLimparConsulta: TBitBtn; bxEmissao: TGroupBox; lbDataEmisInicial: TLabel; lbDataEmisFinal: TLabel; edDataEmissaoInicial: TDateTimePicker; edDataEmissaoFinal: TDateTimePicker; btnFiltrar: TBitBtn; btnCarregarPedido: TBitBtn; procedure LimparCampos; procedure LimparCamposProduto; procedure DesativarCamposProduto; procedure AtivarCamposProduto; procedure VerificarCliProd; procedure CalcularTotalProduto; procedure ExcluirProdutoLista; function ValidarPedido: boolean; function GravarPedido: boolean; procedure ProcessarFiltro; procedure btnSairClick(Sender: TObject); procedure btnLimparConsultaClick(Sender: TObject); procedure edCodClienteExit(Sender: TObject); procedure edCodProdutoExit(Sender: TObject); procedure btnConsClienteClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnConsProdutoClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure edQuantidadeExit(Sender: TObject); procedure edValorUnitarioExit(Sender: TObject); procedure edValorUnitarioKeyPress(Sender: TObject; var Key: Char); procedure btnCancelarProdutoClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure btnIncluirProdutoClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure dbProdutoTmpDblClick(Sender: TObject); procedure btnExcluirProdutoClick(Sender: TObject); procedure edNumPedidoExit(Sender: TObject); procedure btnGravarClick(Sender: TObject); procedure dbPedidoDblClick(Sender: TObject); procedure dbPedidoTitleClick(Column: TColumn); procedure btnFiltrarClick(Sender: TObject); procedure btnExcluirPedidoClick(Sender: TObject); procedure btnCarregarPedidoClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var pedidoF: TpedidoF; PedProd: TPedidoProduto; iOrdem: integer; iOrdemDesc: boolean; iOrdemTitle: String; implementation uses DMU, funcoesU, fmConsCadClienteU, fmConsCadProdutoU, fmCancPedidoU; {$R *.dfm} procedure TpedidoF.ProcessarFiltro; var cWhere, sConsultar, cDesc, cOrd: String; begin cWhere := ''; cOrd := iif(iOrdemDesc,' desc',''); sConsultar := Trim(edConsultar.Text); if (Length(sConsultar) > 0) then cDesc := '%'+sConsultar+'%' else cDesc := ''; if (edDataEmissaoInicial.Date > edDataEmissaoFinal.Date) then begin ShowMessage('A data de Emissão Inicial deve ser menor/igual a Final.'); exit; end; DM.pedidoDB.Connected := True; DM.Pedido.DisableControls; try with DM.Pedido do begin Close; SQL.Clear; SQL.Add('select p.*, '); SQL.Add('c.nome as nomecliente, '); SQL.Add('c.cidade as cidadecliente, '); SQL.Add('c.uf as ufcliente '); SQL.Add('from pedido as p '); SQL.Add('left join cliente as c on c.id = p.id_cliente '); if (Length(cDesc) > 0) then begin if (Length(cWhere) > 0) then cWhere := cWhere+' or '; cWhere := cWhere + '( c.nome like :vdesc or ' + 'c.cidade like :vdesc or c.uf like :vdesc ) '; end; if (Length(cWhere) > 0) then cWhere := cWhere+' and '; cWhere := cWhere + '( date(p.dataemissao) >= :vdataemiini and '+ 'date(p.dataemissao) <= :vdataemifin ) '; if (Length(cWhere) > 0) then SQL.Add(' where '+cWhere); if (iOrdem = 0) then SQL.Add('order by p.id'+cOrd) else if (iOrdem = 1) then SQL.Add('Order by p.dataemissao'+cOrd+', c.nome') else if (iOrdem = 2) then SQL.Add('Order by p.valortotal'+cOrd+', c.nome') else if (iOrdem = 3) then SQL.Add('Order by p.id_cliente'+cOrd+', p.dataemissao') else if (iOrdem = 4) then SQL.Add('Order by c.nome'+cOrd+', p.dataemissao') else if (iOrdem = 5) then SQL.Add('Order by c.cidade'+cOrd+', c.nome, p.dataemissao') else if (iOrdem = 6) then SQL.Add('Order by c.uf'+cOrd+', c.cidade, c.nome, p.dataemissao'); if (Length(cDesc) > 0) then ParamByName('vdesc').Value := cdesc; ParamByName('vdataemiini').Value := FormatDateTime('yyyy/mm/dd',edDataEmissaoInicial.Date); ParamByName('vdataemifin').Value := FormatDateTime('yyyy/mm/dd',edDataEmissaoFinal.Date); Open; end; finally DM.pedido.EnableControls; dbPedido.Refresh; end; end; function TpedidoF.GravarPedido: boolean; var bNovo: boolean; iIDPedido, iIDPedProd, iIDProduto, iQuant: integer; dValorTotalNota, dVlUnit, dVlTotal: double; begin DM.somaprodtmp.Open; DM.somaprodtmp.Refresh; dValorTotalNota := DM.somaprodtmp.FindField('soma').AsFloat; if (Length(Trim(edNumPedido.Text)) = 0) then begin bNovo := True; iIDPedido := 0; end else begin bNovo := False; iIDPedido := StrToInt(edNumPedido.Text); end; try with DM.SQLSalvar do begin SQL.Clear; SQL.Add('start transaction;'); ExecSQL; SQL.Clear; if bNovo then begin SQL.Add('insert into pedido ( '); SQL.Add('dataemissao, id_cliente, '); SQL.Add('valortotal ) '); SQL.Add('values ('); SQL.Add(':vdataemissao, :vid_cliente, '); SQL.Add(':vvalortotal ) '); ParamByName('vdataemissao').Value := now; ParamByName('vid_cliente').Value := StrToInt(edCodCliente.Text); end else begin SQL.Add('update pedido set '); SQL.Add('valortotal = :vvalortotal '); SQL.Add('where id = :vid '); ParamByName('vid').Value := iIDPedido; end; ParamByName('vvalortotal').Value := dValorTotalNota; ExecSQL; end; if bNovo then begin with DM.SQLLocalizar do begin Close; SQL.Clear; SQL.Add('select max(id) as maxid from pedido'); Open; if (RecordCount > 0) then begin iIDPedido := FindField('maxid').AsInteger; Close; end else begin Close; SQL.Clear; SQL.Add('rollback;'); ExecSQL; Result := False; exit; end; end; end; edNumPedido.Text := IntToStr(iIDPedido); with DM.SQLLocalizar do begin Close; SQL.Clear; SQL.Add('select id from pedidoproduto '); SQL.Add('where id = :vid '); end; with DM.SQLInsert do begin SQL.Clear; SQL.Add('insert into pedidoproduto ('); SQL.Add('id_pedido, id_produto, '); SQL.Add('quantidade, valorunitario, '); SQL.Add('valortotal, idalterado) '); SQL.Add('values ( '); SQL.Add(':vid_pedido, :vid_produto, '); SQL.Add(':vquantidade, :vvalorunitario, '); SQL.Add(':vvalortotal, :vidalterado) '); ParamByName('vid_pedido').Value := iIDPedido; ParamByName('vidalterado').Value := 1; end; with DM.SQLUpdate do begin SQL.Clear; SQL.Add('update pedidoproduto set '); SQL.Add('quantidade = :vquantidade, '); SQL.Add('valorunitario = :vvalorunitario, '); SQL.Add('valortotal = :vvalortotal, '); SQL.Add('idalterado = :vidalterado '); SQL.Add('where id = :vid '); ParamByName('vidalterado').Value := 1; end; with DM.pedidoprodutotmp do begin DisableControls; Open; Refresh; First; while not Eof do begin iQuant := FindField('quantidade').AsInteger; dVlUnit := FindField('valorunitario').AsFloat; dVlTotal := FindField('valortotal').AsFloat; iIDPedProd := FindField('id_pedidoproduto').AsInteger; DM.SQLLocalizar.Close; DM.SQLLocalizar.ParamByName('vid').Value := iIDPedProd; DM.SQLLocalizar.Open; if (DM.SQLLocalizar.RecordCount > 0) then begin DM.SQLUpdate.ParamByName('vid').Value := iIDPedProd; DM.SQLUpdate.ParamByName('vquantidade').Value := iQuant; DM.SQLUpdate.ParamByName('vvalorunitario').Value := dVlUnit; DM.SQLUpdate.ParamByName('vvalortotal').Value := dVlTotal; DM.SQLUpdate.ExecSQL; end else begin iIDProduto := FindField('id_produto').AsInteger; DM.SQLInsert.ParamByName('vid_produto').Value := iIDProduto; DM.SQLInsert.ParamByName('vquantidade').Value := iQuant; DM.SQLInsert.ParamByName('vvalorunitario').Value := dVlUnit; DM.SQLInsert.ParamByName('vvalortotal').Value := dVlTotal; DM.SQLInsert.ExecSQL; end; Next; end; EnableControls; end; with DM.SQLUpdate do begin SQL.Clear; SQL.Add('delete from pedidoproduto '); SQL.Add('where id_pedido = :vid_pedido and '); SQL.Add('idalterado = 0 '); ParamByName('vid_pedido').Value := iIDPedido; ExecSQL; SQL.Clear; SQL.Add('update pedidoproduto set '); SQL.Add('idalterado = 0 '); SQL.Add('where id_pedido = :vid_pedido '); ParamByName('vid_pedido').Value := iIDPedido; ExecSQL; SQL.Clear; SQL.Add('commit;'); ExecSQL; end; Result := True; except DM.pedidoprodutotmp.EnableControls; with DM.SQLSalvar do begin SQL.Clear; SQL.Add('rollback;'); ExecSQL; end; Result := False; end; end; function TpedidoF.ValidarPedido: boolean; var cMensagem: WideString; begin cMensagem := ''; if not LocalizarSQL('cliente',edCodCliente.Text) then begin cMensagem := cMensagem + '- O Campo Código do Cliente esta inválido!'+#13+#10; end; if (DM.pedidoprodutotmp.RecordCount <= 0) then begin cMensagem := cMensagem + '- Deve ser informado no mínimo um produto!'+#13+#10; end; if (Length(Trim(cMensagem)) > 0) then begin cMensagem := 'ATENÇÂO!'+#13#10+#13#10+ 'Divergência(s) encontrada(s) no preenchimento.'+#13+#10+ #13+#10+cMensagem+#13+#10+ 'Corrija e tente salvar novamente.'+#13+#10; Result := False; end else begin Result := True; end; end; procedure TpedidoF.VerificarCliProd; begin if ((DM.pedidoprodutotmp.RecordCount > 0) and LocalizarSQL('cliente',edCodCliente.Text)) then begin btnGravar.Enabled := True; btnCancelar.Enabled := True; end else begin btnGravar.Enabled := False; end; end; procedure TpedidoF.ExcluirProdutoLista; var iID: integer; begin if (DM.pedidoprodutotmp.RecordCount = 0) then exit; if (PedProd <> nil) then FreeAndNil(PedProd); PedProd := TPedidoProduto.Create; iID := DM.pedidoprodutotmp.FindField('id').AsInteger; if PedProd.LerProdPed(iID) then btnExcluirProdutoClick(nil); end; procedure TpedidoF.DesativarCamposProduto; begin edCodProduto.Enabled := True; btnConsProduto.Enabled := True; lbQuantidade.Enabled := False; lbValorUnitario.Enabled := False; lbValorTotal.Enabled := False; edQuantidade.Enabled := False; edValorUnitario.Enabled := False; edValorTotal.Enabled := False; btnExcluirProduto.Enabled := False; btnCancelarProduto.Enabled := False; btnIncluirProduto.Enabled := False; end; procedure TpedidoF.AtivarCamposProduto; begin lbQuantidade.Enabled := True; lbValorUnitario.Enabled := True; lbValorTotal.Enabled := True; edQuantidade.Enabled := True; edValorUnitario.Enabled := True; edValorTotal.Enabled := True; btnCancelarProduto.Enabled := True; btnIncluirProduto.Enabled := True; end; procedure TpedidoF.LimparCampos; begin edNumPedido.Clear; edDataEmissao.Text := DateToStr(now); edCodCliente.Clear; edNomeCliente.Clear; LimparCamposProduto; edCodCLiente.Enabled := True; btnConsCliente.Enabled := True; btnExcluirPedido.Visible := True; btnCarregarPedido.Visible := True; end; procedure TpedidoF.LimparCamposProduto; begin if (PedProd <> nil) then FreeAndNil(PedProd); PedProd := TPedidoProduto.Create; edCodProduto.Clear; edDescricaoProduto.Clear; edQuantidade.Text := '1'; edValorUnitario.Text := '0,00'; edValorTotal.Text := '0,00'; DesativarCamposProduto; VerificarCliProd; if (DM.pedidoprodutotmp.RecordCount > 0) then begin edNumPedido.Enabled := False; btnCancelar.Enabled := True; end else begin edNumPedido.Enabled := True; btnCancelar.Enabled := False; end; dbProdutoTmp.Refresh; end; procedure TpedidoF.CalcularTotalProduto; var dQuant, dVlUnitario, dVlTotal: double; begin dQuant := StrParaFloat(edQuantidade.Text); dVlUnitario := StrParaFloat(edValorUnitario.Text); dVlTotal := (dQuant * dVlUnitario); edValorTotal.Text := FormatFloat('###,##0.00',dVlTotal); end; procedure TpedidoF.dbPedidoDblClick(Sender: TObject); begin if (DM.pedido.RecordCount = 0) then exit; if (not edNumPedido.Enabled) then exit; edNumPedido.Text := DM.pedido.FindField('id').AsString; edNumPedidoExit(nil); end; procedure TpedidoF.dbPedidoTitleClick(Column: TColumn); var nOrdem: integer; nOrdemTitle: String; begin nOrdem := Column.ID; if (nOrdem <> iOrdem) then begin dbPedido.Columns[iOrdem].Title.Caption := iOrdemTitle; iOrdemTitle := dbPedido.Columns[nOrdem].Title.Caption; dbPedido.Columns[nOrdem].Title.Font.Color := clBlue; dbPedido.Columns[nOrdem].Title.Font.Style := [fsBold]; dbPedido.Columns[iOrdem].Title.Font.Color := clWindowText; dbPedido.Columns[iOrdem].Title.Font.Style := []; iOrdem := nOrdem; iOrdemDesc := False; ProcessarFiltro; end else begin iOrdemDesc := not iOrdemDesc; if (iOrdemDesc) then begin iOrdemTitle := dbPedido.Columns[iOrdem].Title.Caption; nOrdemTitle := iOrdemTitle + '(v)'; dbPedido.Columns[iOrdem].Title.Caption := nOrdemTitle; end else begin dbPedido.Columns[iOrdem].Title.Caption := iOrdemTitle; end; ProcessarFiltro; end; end; procedure TpedidoF.dbProdutoTmpDblClick(Sender: TObject); var iID: integer; begin if (DM.pedidoprodutotmp.RecordCount = 0) then exit; if (PedProd <> nil) then FreeAndNil(PedProd); PedProd := TPedidoProduto.Create; iID := DM.pedidoprodutotmp.FindField('id').AsInteger; if PedProd.LerProdPed(iID) then begin edCodProduto.Text := PedProd.sID_Produto; edQuantidade.Text := PedProd.sQuantidade; edValorUnitario.Text := PedProd.sValorUnitario; edValorTotal.Text := PedProd.sValorTotal; edDescricaoProduto.Text := PedProd.sDescProduto; btnExcluirProduto.Enabled := True; AtivarCamposProduto; edCodProduto.Enabled := False; btnConsProduto.Enabled := False; edQuantidade.SetFocus; end; end; procedure TpedidoF.btnCancelarClick(Sender: TObject); begin if (PedProd <> nil) then FreeAndNil(PedProd); PedProd := TPedidoProduto.Create; PedProd.CriarTabelaTemp; LimparCampos; edNumPedido.SetFocus; end; procedure TpedidoF.btnCancelarProdutoClick(Sender: TObject); begin LimparCamposProduto; edCodProduto.SetFocus; end; procedure TpedidoF.btnCarregarPedidoClick(Sender: TObject); begin if (fmCancPedidoF=nil) then Application.CreateForm(TfmCancPedidoF, fmCancPedidoF) else fmCancPedidoF.Pedido.Refresh; with fmCancPedidoF do begin try Caption := 'Carregar Pedido'; btnExcluirPedido.Visible := False; btnCarregarPedido.Top := btnExcluirPedido.Top; btnCarregarPedido.Left := btnExcluirPedido.Left; btnCarregarPedido.Visible := True; ShowModal; if (ModalResult = mrOk) then begin pedidoF.edNumPedido.Text := edNumPedido.Text; pedidoF.edNumPedidoExit(nil); end; finally btnCarregarPedido.Visible := False; btnExcluirPedido.Visible := True; Caption := 'Cancelar Pedido'; end; end; end; procedure TpedidoF.btnConsClienteClick(Sender: TObject); begin if (fmConsCadClienteF=nil) then Application.CreateForm(TfmConsCadClienteF, fmConsCadClienteF) else fmConsCadClienteF.Cliente.Refresh; fmConsCadClienteF.ShowModal; if (fmConsCadClienteF.ModalResult = mrOk) then begin edCodCliente.Text := fmConsCadClienteF.Cliente.FindField('id').AsString; edCodClienteExit(nil); end; end; procedure TpedidoF.btnConsProdutoClick(Sender: TObject); begin if (fmConsCadProdutoF=nil) then Application.CreateForm(TfmConsCadProdutoF, fmConsCadProdutoF) else fmConsCadProdutoF.Produto.Refresh; fmConsCadProdutoF.ShowModal; if (fmConsCadProdutoF.ModalResult = mrOk) then begin edCodProduto.Text := fmConsCadProdutoF.Produto.FindField('id').AsString; edCodProdutoExit(nil); end; end; procedure TpedidoF.btnExcluirPedidoClick(Sender: TObject); begin if (fmCancPedidoF=nil) then Application.CreateForm(TfmCancPedidoF, fmCancPedidoF) else fmCancPedidoF.Pedido.Refresh; DM.pedido.DisableControls; try fmCancPedidoF.ShowModal; finally DM.pedido.Refresh; DM.pedido.EnableControls; dbPedido.Refresh; end; end; procedure TpedidoF.btnExcluirProdutoClick(Sender: TObject); begin if MessageDlg('Deseja Excluir o Produto: '+PedProd.sDescProduto+'?',mtConfirmation,[mbyes,mbno],0)=mryes then begin if PedProd.Excluir then btnCancelarProdutoClick(nil) else ShowMessage('Não foi possível excluir o produto.'); end; end; procedure TpedidoF.btnFiltrarClick(Sender: TObject); begin ProcessarFiltro; dbPedido.SetFocus; end; procedure TpedidoF.btnGravarClick(Sender: TObject); begin if not ValidarPedido then exit; if GravarPedido then begin DM.pedido.Refresh; ShowMessage('Pedido Número: '+edNumPedido.Text+' Gravado com sucesso.'); btnCancelarClick(nil); end else begin ShowMessage('ATENÇÂO! O pedido não foi gravado.'); end; end; procedure TpedidoF.btnIncluirProdutoClick(Sender: TObject); var cMensagem: WideString; begin PedProd.ID := 0; PedProd.ID_PedidoProduto := 0; PedProd.sID_Produto := edCodProduto.Text; PedProd.sQuantidade := edQuantidade.Text; PedProd.sValorUnitario := edValorUnitario.Text; PedProd.sValorTotal := edValorTotal.Text; cMensagem := PedProd.Validar; if (Length(cMensagem) > 0) then begin ShowMessage(cMensagem); exit; end; if not PedProd.Salvar then ShowMessage('Erro ao Salvar Produto!') else btnCancelarProdutoClick(nil); end; procedure TpedidoF.btnLimparConsultaClick(Sender: TObject); begin edConsultar.Clear; end; procedure TpedidoF.btnSairClick(Sender: TObject); begin Close; end; procedure TpedidoF.edCodClienteExit(Sender: TObject); begin btnGravar.Enabled := False; btnExcluirPedido.Visible := True; btnCarregarPedido.Visible := True; edNomeCliente.Clear; if (Length(Trim(edCodCliente.Text)) = 0) then exit; if (StrToInt(edCodCliente.Text) = 0) then exit; if LocalizarSQL('cliente',edCodCliente.Text) then begin edNomeCliente.Text := DM.SQLLocalizar.FindField('nome').AsString; btnExcluirPedido.Visible := False; btnCarregarPedido.Visible := False; if (DM.pedidoprodutotmp.RecordCount > 0) then begin btnGravar.Enabled := True; btnCancelar.Enabled := True; edNumPedido.Enabled := False; end else begin btnCancelar.Enabled := False; edNumPedido.Enabled := True; end; if btnConsCliente.Focused then edCodProduto.SetFocus; end else begin edNomeCliente.Text := 'cliente não localizado'; end; end; procedure TpedidoF.edCodProdutoExit(Sender: TObject); begin if (Length(Trim(edCodProduto.Text)) = 0) then exit; if (StrToInt(edCodProduto.Text) = 0) then exit; if LocalizarSQL('produto',edCodProduto.Text) then begin edDescricaoProduto.Text := DM.SQLLocalizar.FindField('descricao').AsString; edValorUnitario.Text := FormatFloat('###,##0.00',DM.SQLLocalizar.FindField('precovenda').AsFloat); CalcularTotalProduto; AtivarCamposProduto; if btnConsProduto.Focused then edQuantidade.SetFocus; end else begin edDescricaoProduto.Text := 'produto não localizado'; edValorUnitario.Text := '0,00'; DesativarCamposProduto; end; end; procedure TpedidoF.edNumPedidoExit(Sender: TObject); begin btnGravar.Enabled := False; if (Length(Trim(edNumPedido.Text)) = 0) then exit; if (StrToInt(edNumPedido.Text) = 0) then exit; if LocalizarSQL('pedido',edNumPedido.Text) then begin with DM.SQLLocalizar do begin edDataEmissao.Text := FindField('dataemissao').Value; edCodCliente.Text := FindField('id_cliente').AsString; end; if LocalizarSQL('cliente',edCodCliente.Text) then edNomeCliente.Text := DM.SQLLocalizar.FindField('nome').AsString else edNomeCliente.Text := 'cliente não encontrado'; if (PedProd <> nil) then FreeAndNil(PedProd); PedProd := TPedidoProduto.Create; PedProd.CriarTabelaTemp; PedProd.LerProdutos(StrToInt(edNumPedido.Text)); dbProdutoTmp.Refresh; edNumPedido.Enabled := False; edCodCliente.Enabled := False; btnConsCliente.Enabled := False; btnCancelar.Enabled := True; btnExcluirPedido.Visible := False; btnCarregarPedido.Visible := False; edCodProduto.SetFocus; end else begin ShowMessage('Pedido não localizado.'); edNumPedido.Clear; end; end; procedure TpedidoF.edQuantidadeExit(Sender: TObject); begin if (Length(Trim(edQuantidade.Text)) = 0) then edQuantidade.Text := '1'; if (StrToInt(edQuantidade.Text) <= 0) then edQuantidade.Text := '1'; CalcularTotalProduto; end; procedure TpedidoF.edValorUnitarioExit(Sender: TObject); begin if (Length(Trim(edValorUnitario.Text)) = 0) then edValorUnitario.Text := '0,00'; edValorUnitario.Text := FormatFloat('###,##0.00',StrParaFloat(edValorUnitario.Text)); if StrParaFloat(edValorUnitario.Text) <= 0 then ShowMessage('Valor Unitário não pode ser Zero!'); CalcularTotalProduto; end; procedure TpedidoF.edValorUnitarioKeyPress(Sender: TObject; var Key: Char); begin FormatarComoMoeda((Sender as TEdit), Key); end; procedure TpedidoF.FormActivate(Sender: TObject); begin DM.pedidodb.Connected := True; if (PedProd <> nil) then FreeAndNil(PedProd); PedProd := TPedidoProduto.Create; PedProd.CriarTabelaTemp; LimparCampos; DM.pedido.Open; end; procedure TpedidoF.FormClose(Sender: TObject; var Action: TCloseAction); begin if MessageDlg('Deseja sair do sistema?',mtConfirmation,[mbyes,mbno],0)<>mryes then begin Action := caNone; exit; end; if (fmCancPedidoF<>nil) then FreeAndNil(fmCancPedidoF); if (fmConsCadProdutoF<>nil) then FreeAndNil(fmConsCadProdutoF); if (fmConsCadClienteF<>nil) then FreeAndNil(fmConsCadClienteF); if (PedProd<>nil) then FreeAndNil(PedProd); DM.pedidodb.Connected := False; Application.Terminate; end; procedure TpedidoF.FormCreate(Sender: TObject); begin iOrdem := 0; dbPedido.Columns[iOrdem].Title.Font.Color := clBlue; dbPedido.Columns[iOrdem].Title.Font.Style := [fsBold]; iOrdemTitle := dbPedido.Columns[iOrdem].Title.Caption; iOrdemDesc := False; btnGravar.Enabled := False; btnCancelar.Enabled := False; edConsultar.Clear; edDataEmissaoInicial.DateTime := now-8; edDataEmissaoFinal.DateTime := now; ProcessarFiltro; end; procedure TpedidoF.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_F2) then begin if edCodCliente.Focused then btnConsClienteClick(nil) else if edCodProduto.Focused then btnConsProdutoClick(nil) else dbPedido.SetFocus; end; if (Key = VK_DELETE) then begin if dbProdutoTmp.Focused then ExcluirProdutoLista; end; if (Key = VK_RETURN) then begin if dbProdutoTmp.Focused then dbProdutoTmpDblClick(nil) else if dbPedido.Focused then dbPedidoDblClick(nil); end; end; end.
unit WinSockRDOConnection; interface uses SmartThreads, Classes, ComObj, Windows, {$IFDEF AutoServer} RDOClient_TLB, {$ENDIF} RDOInterfaces, SocketComp, SyncObjs; type TWinSockRDOConnection = {$IFDEF AutoServer} class( TAutoObject, IRDOConnectionInit, IRDOServerConnection, IRDOConnection ) {$ELSE} class( TInterfacedObject, IRDOConnectionInit, IRDOServerConnection, IRDOConnection ) {$ENDIF} private fPort : integer; fServer : string; fUnsentQueries : TList; fSentQueries : TList; fSenderThread : TSmartThread; fMsgLoopThread : TSmartThread; fUnsentQueriesLock : TCriticalSection; fSentQueriesLock : TCriticalSection; fSocketComponent : TClientSocket; fReceivedText : string; fConnectionEvent : THandle; fUnsentQueryWaiting : THandle; fQueryServer : IRDOQueryServer; fQueryQueue : TList; fQueryWaiting : THandle; fQueryQueueLock : TCriticalSection; fQueryThreads : TList; fMaxQueryThreads : integer; fTerminateEvent : THandle; // these variables are only for debug fSentQueriesCount : integer; fEnQueuedQueries : integer; // procedure DoRead( Sender : TObject; Socket : TCustomWinSocket ); procedure HandleError( Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : integer ); procedure HandleConnect( Sender : TObject; Socket : TCustomWinSocket ); protected function Get_Server : WideString; safecall; procedure Set_Server( const Value : WideString ); safecall; function Get_Port : Integer; safecall; procedure Set_Port( Value : Integer ); safecall; function Connect( TimeOut : Integer ) : WordBool; safecall; procedure Disconnect; safecall; protected procedure SetQueryServer( const QueryServer : IRDOQueryServer ); function GetMaxQueryThreads : integer; procedure SetMaxQueryThreads( MaxQueryThreads : integer ); protected function SendReceive( const QueryText : string; out ErrorCode : integer; TimeOut : integer ) : string; stdcall; procedure Send( const QueryText : string ); stdcall; function GetLocalAddress : string; stdcall; function GetLocalHost : string; stdcall; function GetLocalPort : integer; stdcall; {$IFDEF AutoServer} protected procedure Initialize; override; {$ELSE} public constructor Create; {$ENDIF} destructor Destroy; override; end; implementation uses {$IFDEF AutoServer} ComServ, {$ENDIF} SysUtils, WinSock, RDOUtils, RDOProtocol, {$IFDEF Logs} LogFile, {$ENDIF} ErrorCodes; // Query id generation routines and variables const DefRDOPort = 5000; const DefMaxQueryThreads = 5; var LastQueryId : word; function GenerateQueryId : integer; begin Result := LastQueryId; LastQueryId := ( LastQueryId + 1 ) mod 65536 end; type TQueryToSend = record Id : word; Text : string; WaitForAnsw : boolean; Result : string; Event : THandle; ErrorCode : integer; end; PQueryToSend = ^TQueryToSend; type TQueryToService = record QueryText : string; end; PQueryToService = ^TQueryToService; // Delphi classes associated to the threads in charge of the connection type TSenderThread = class( TSmartThread ) private fConnection : TWinSockRDOConnection; constructor Create( theConnection : TWinSockRDOConnection ); protected procedure Execute; override; end; type TMsgLoopThread = class( TSmartThread ) private fConnection : TWinSockRDOConnection; constructor Create( theConnection : TWinSockRDOConnection ); protected procedure Execute; override; end; type TServicingQueryThread = class( TSmartThread ) private fConnection : TWinSockRDOConnection; public constructor Create( theConnection : TWinSockRDOConnection ); procedure Execute; override; end; // TSenderThread constructor TSenderThread.Create( theConnection : TWinSockRDOConnection ); begin fConnection := theConnection; inherited Create( false ) end; procedure TSenderThread.Execute; var QueryToSend : PQueryToSend; SenderThreadEvents : array [ 1 .. 2 ] of THandle; begin with fConnection do begin SenderThreadEvents[ 1 ] := fUnsentQueryWaiting; SenderThreadEvents[ 2 ] := fTerminateEvent; while not Terminated do begin WaitForMultipleObjects( 2, @SenderThreadEvents[ 1 ], false, INFINITE ); fUnsentQueriesLock.Acquire; try if fUnsentQueries.Count <> 0 then begin QueryToSend := fUnsentQueries[ 0 ]; fUnsentQueries.Delete( 0 ) end else begin QueryToSend := nil; ResetEvent( fUnsentQueryWaiting ) end finally fUnsentQueriesLock.Release end; if QueryToSend <> nil then if QueryToSend.WaitForAnsw then begin fSentQueriesLock.Acquire; try fSentQueries.Add( QueryToSend ) finally fSentQueriesLock.Release end; try inc( fSentQueriesCount ); fSocketComponent.Socket.SendText( CallId + Blank + IntToStr( QueryToSend.Id ) + Blank + QueryToSend.Text ) except {$IFDEF Logs} LogThis( 'Error sending query' ); {$ENDIF} fSentQueriesLock.Acquire; try fSentQueries.Remove( QueryToSend ) finally fSentQueriesLock.Release end; QueryToSend.ErrorCode := errSendError; SetEvent( QueryToSend.Event ) end end else begin try inc( fSentQueriesCount ); fSocketComponent.Socket.SendText( CallId + Blank + QueryToSend.Text ) except {$IFDEF Logs} LogThis( 'Error sending query' ); {$ENDIF} end; Dispose( QueryToSend ) end; end end end; // TMsgLoopThread constructor TMsgLoopThread.Create( theConnection : TWinSockRDOConnection ); begin fConnection := theConnection; // FreeOnTerminate := true; // Priority := tpHighest; inherited Create( false ) end; procedure TMsgLoopThread.Execute; var Msg : TMsg; begin try fConnection.fSocketComponent.Open; except {$IFDEF Logs} LogThis( 'Error establishing connection' ) {$ENDIF} end; while not Terminated do begin if PeekMessage( Msg, 0, 0, 0, PM_REMOVE ) then DispatchMessage( Msg ) else MsgWaitForMultipleObjects( 1, fConnection.fTerminateEvent, false, INFINITE, QS_ALLINPUT ) end end; // TServicingQueryThread constructor TServicingQueryThread.Create( theConnection : TWinSockRDOConnection ); begin fConnection := theConnection; inherited Create( false ) end; procedure TServicingQueryThread.Execute; var QueryResult : string; QueryToService : PQueryToService; QueryThreadEvents : array [ 1 .. 2 ] of THandle; begin with fConnection do begin QueryThreadEvents[ 1 ] := fQueryWaiting; QueryThreadEvents[ 2 ] := fTerminateEvent; while not Terminated do begin WaitForMultipleObjects( 2, @QueryThreadEvents[ 1 ], false, INFINITE ); fQueryQueueLock.Acquire; try if fQueryQueue.Count <> 0 then begin QueryToService := fQueryQueue[ 0 ]; fQueryQueue.Delete( 0 ) end else begin QueryToService := nil; ResetEvent( fQueryWaiting ) end finally fQueryQueueLock.Release end; if QueryToService <> nil then begin QueryResult := fQueryServer.ExecQuery( QueryToService.QueryText ); Dispose( QueryToService ); if QueryResult <> '' then try fSocketComponent.Socket.SendText( AnswerId + QueryResult ); {$IFDEF Logs} LogThis( 'Result : ' + QueryResult ); {$ENDIF} except {$IFDEF Logs} LogThis( 'Error sending query result' ) {$ENDIF} end else begin {$IFDEF Logs} LogThis( 'No result' ) {$ENDIF} end end end end end; // TWinSockRDOConnection {$IFDEF AutoServer} procedure TWinSockRDOConnection.Initialize; {$ELSE} constructor TWinSockRDOConnection.Create; {$ENDIF} begin inherited; fSocketComponent := TClientSocket.Create( nil ); fSocketComponent.Active := false; fUnsentQueriesLock := TCriticalSection.Create; fSentQueriesLock := TCriticalSection.Create; fUnsentQueries := TList.Create; fSentQueries := TList.Create; fPort := DefRDOPort; fUnsentQueryWaiting := CreateEvent( nil, true, false, nil ); fQueryQueue := TList.Create; fQueryThreads := TList.Create; fMaxQueryThreads := DefMaxQueryThreads; fQueryWaiting := CreateEvent( nil, true, false, nil ); fQueryQueueLock := TCriticalSection.Create; fTerminateEvent := CreateEvent( nil, true, false, nil ) end; destructor TWinSockRDOConnection.Destroy; procedure FreeQueryQueue; var QueryIdx : integer; begin for QueryIdx := 0 to fQueryQueue.Count - 1 do Dispose( PQueryToService( fQueryQueue[ QueryIdx ] ) ); fQueryQueue.Free end; begin Disconnect; fUnsentQueriesLock.Free; fSentQueriesLock.Free; fSocketComponent.Free; fUnsentQueries.Free; fSentQueries.Free; CloseHandle( fUnsentQueryWaiting ); FreeQueryQueue; CloseHandle( fQueryWaiting ); fQueryQueueLock.Free; CloseHandle( fTerminateEvent ); {$IFDEF Logs} LogThis( 'Enqueued queries : ' + IntToStr( fEnqueuedQueries ) ); LogThis( 'Sent queries : ' + IntToStr( fSentQueriesCount ) ); {$ENDIF} inherited end; function TWinSockRDOConnection.Get_Server : WideString; begin Result := fServer end; procedure TWinSockRDOConnection.Set_Server( const Value : WideString ); begin fServer := Value end; function TWinSockRDOConnection.Get_Port : Integer; begin Result := fPort end; procedure TWinSockRDOConnection.Set_Port( Value : Integer ); begin fPort := Value end; function TWinSockRDOConnection.GetLocalHost : string; begin Result := fSocketComponent.Socket.LocalHost end; function TWinSockRDOConnection.GetLocalAddress : string; begin Result := fSocketComponent.Socket.LocalAddress end; function TWinSockRDOConnection.GetLocalPort : integer; begin Result := fSocketComponent.Socket.LocalPort end; function TWinSockRDOConnection.Connect( TimeOut : Integer ) : WordBool; var WaitRes : cardinal; ThreadIdx : integer; begin Result := true; try ResetEvent( fTerminateEvent ); with fSocketComponent do if not Active then begin ClientType := ctNonBlocking; if inet_addr( PChar( fServer ) ) = INADDR_NONE then Host := fServer else Address := fServer; Port := fPort; OnRead := DoRead; OnError := HandleError; OnConnect := HandleConnect; fConnectionEvent := CreateEvent( nil, false, false, nil ); try fMsgLoopThread := TMsgLoopThread.Create( Self ); WaitRes := WaitForSingleObject( fConnectionEvent, TimeOut ); if WaitRes = WAIT_OBJECT_0 then begin fSenderThread := TSenderThread.Create( Self ); for ThreadIdx := 1 to fMaxQueryThreads do fQueryThreads.Add( TServicingQueryThread.Create( Self ) ) end else begin SetEvent( fTerminateEvent ); fMsgLoopThread.Free; // fMsgLoopThread.Terminate; fMsgLoopThread := nil end; Result := WaitRes = WAIT_OBJECT_0 finally CloseHandle( fConnectionEvent ) end end except Disconnect; Result := false end end; procedure TWinSockRDOConnection.Disconnect; procedure FreeQueryThreads; var ThreadIdx : integer; aQueryThread : TSmartThread; begin for ThreadIdx := 0 to fQueryThreads.Count - 1 do begin aQueryThread := TSmartThread( fQueryThreads[ ThreadIdx ] ); aQueryThread.Free end; fQueryThreads.Free end; begin SetEvent( fTerminateEvent ); if fSocketComponent.Active then try fSocketComponent.Close except {$IFDEF Logs} LogThis( 'Error closing connection' ) {$ENDIF} end; if fMsgLoopThread <> nil then begin // fMsgLoopThread.Terminate; fMsgLoopThread.Free; fMsgLoopThread := nil end; if fSenderThread <> nil then begin fSenderThread.Free; fSenderThread := nil end; FreeQueryThreads end; procedure TWinSockRDOConnection.SetQueryServer( const QueryServer : IRDOQueryServer ); begin fQueryServer := QueryServer end; function TWinSockRDOConnection.GetMaxQueryThreads : integer; begin Result := fMaxQueryThreads end; procedure TWinSockRDOConnection.SetMaxQueryThreads( MaxQueryThreads : integer ); begin fMaxQueryThreads := MaxQueryThreads end; function TWinSockRDOConnection.SendReceive( const QueryText : string; out ErrorCode : integer; TimeOut : integer ) : string; var theQuery : PQueryToSend; WaitRes : cardinal; begin try New( theQuery ); try theQuery.Id := GenerateQueryId; theQuery.Text := QueryText; {$IFDEF Logs} LogThis( 'Sending and waiting: ' + QueryText ); {$ENDIF} theQuery.WaitForAnsw := true; theQuery.Result := ''; theQuery.Event := CreateEvent( nil, false, false, nil ); try theQuery.ErrorCode := errNoError; fUnsentQueriesLock.Acquire; try fUnsentQueries.Add( theQuery ); inc( fEnQueuedQueries ); if fUnsentQueries.Count = 1 then SetEvent( fUnsentQueryWaiting ); fUnsentQueriesLock.Release; WaitRes := WaitForSingleObject( theQuery.Event, TimeOut ); if WaitRes = WAIT_OBJECT_0 then begin Result := theQuery.Result; ErrorCode := theQuery.ErrorCode; {$IFDEF Logs} LogThis( 'Result : ' + Result ) {$ENDIF} end else begin Result := ''; {$IFDEF Logs} LogThis( 'Query timed out' ); {$ENDIF} ErrorCode := errQueryTimedOut; fSentQueriesLock.Acquire; try fSentQueries.Remove( theQuery ) finally fSentQueriesLock.Release end end except fUnsentQueriesLock.Release; ErrorCode := errQueryQueueOverflow end finally CloseHandle( theQuery.Event ) end finally Dispose( theQuery ) end except ErrorCode := errUnknownError end end; procedure TWinSockRDOConnection.Send( const QueryText : string ); var theQuery : PQueryToSend; begin New( theQuery ); theQuery.Text := QueryText; {$IFDEF Logs} LogThis( 'Sending : ' + QueryText ); {$ENDIF} theQuery.WaitForAnsw := false; fUnsentQueriesLock.Acquire; try try fUnsentQueries.Add( theQuery ); inc( fEnQueuedQueries ); if fUnsentQueries.Count = 1 then SetEvent( fUnsentQueryWaiting ) except Dispose( theQuery ) end finally fUnsentQueriesLock.Release end end; procedure TWinSockRDOConnection.DoRead( Sender : TObject; Socket : TCustomWinSocket ); function FindServicedQuery( QueryText : string ) : PQueryToSend; var CharIdx : integer; IdDigits : string; QueryId : integer; QueryIdx : integer; SentQueries : integer; ServicedQuery : PQueryToSend; QueryTextLen : integer; begin IdDigits := ''; CharIdx := 1; SkipSpaces( QueryText, CharIdx ); IdDigits := ReadNumber( QueryText, CharIdx ); try QueryId := StrToInt( IdDigits ); except QueryId := -1 end; if QueryId <> -1 then begin QueryIdx := 0; SentQueries := fSentQueries.Count; while ( QueryIdx < SentQueries ) and ( QueryId <> PQueryToSend( fSentQueries[ QueryIdx ] ).Id ) do inc( QueryIdx ); if QueryIdx < SentQueries then begin ServicedQuery := fSentQueries[ QueryIdx ]; QueryTextLen := Length( QueryText ); while CharIdx <= QueryTextLen do begin ServicedQuery.Result := ServicedQuery.Result + QueryText[ CharIdx ]; inc( CharIdx ) end; Result := ServicedQuery end else Result := nil end else Result := nil; end; var ServicedQuery : PQueryToSend; QueryText : string; QueryToService : PQueryToService; NonWSPCharIdx : integer; begin try fReceivedText := fReceivedText + Socket.ReceiveText except {$IFDEF Logs} LogThis( 'Error reading from socket' ) {$ENDIF} end; QueryText := GetQueryText( fReceivedText ); if QueryText <> '' then repeat NonWSPCharIdx := 1; SkipSpaces( QueryText, NonWSPCharIdx ); if QueryText[ NonWSPCharIdx ] = AnswerId then begin Delete( QueryText, NonWSPCharIdx, 1 ); fSentQueriesLock.Acquire; try ServicedQuery := FindServicedQuery( QueryText ); if ServicedQuery <> nil then begin fSentQueries.Remove( ServicedQuery ); ServicedQuery.ErrorCode := errNoError; SetEvent( ServicedQuery.Event ) end finally fSentQueriesLock.Release end end else if QueryText[ NonWSPCharIdx ] = CallId then begin Delete( QueryText, NonWSPCharIdx, 1 ); if fQueryServer <> nil then begin New( QueryToService ); QueryToService.QueryText := QueryText; fQueryQueueLock.Acquire; try fQueryQueue.Add( QueryToService ); if fQueryQueue.Count = 1 then SetEvent( fQueryWaiting ) finally fQueryQueueLock.Release end end else Socket.SendText( AnswerId + CreateErrorMessage( errRDOServerNotInitialized ) ) end; QueryText := GetQueryText( fReceivedText ) until QueryText = '' end; procedure TWinSockRDOConnection.HandleError( Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : integer ); begin case ErrorEvent of {$IFDEF Logs} eeGeneral: LogThis( 'General socket error' ); eeSend: LogThis( 'Error writing to socket' ); eeReceive: LogThis( 'Error reading from socket' ); {$ENDIF} eeConnect: begin ErrorCode := 0; {$IFDEF Logs} LogThis( 'Error establishing connection' ) {$ENDIF} end; eeDisconnect: begin ErrorCode := 0; {$IFDEF Logs} LogThis( 'Error closing connection' ) {$ENDIF} end; {$IFDEF Logs} eeAccept: LogThis( 'Error accepting connection' ) {$ENDIF} end end; procedure TWinSockRDOConnection.HandleConnect( Sender : TObject; Socket : TCustomWinSocket ); begin SetEvent( fConnectionEvent ) end; initialization LastQueryId := 0; {$IFDEF AutoServer} TAutoObjectFactory.Create( ComServer, TWinSockRDOConnection, Class_WinSockRDOConnection, ciMultiInstance ) {$ENDIF} end.
(* * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The Initial Developer of this code is John Hansen. * Portions created by John Hansen are Copyright (C) 2009 John Hansen. * All Rights Reserved. * *) unit uCmdLineUtils; interface uses Classes; function progName : string; procedure PrintVersion(const ts : string = ''); procedure PrintUsageError(const ts : string = ''); function redirectErrorsToFile : boolean; procedure setErrorOutputFile(var F : TextFile); function getIncludePath : string; implementation uses SysUtils, ParamUtils, uVersionInfo, uLocalizedStrings; function progName : string; begin Result := ExtractFileName(ParamStr(0)); Result := ChangeFileExt(Result, ''); end; procedure PrintVersion(const ts : string); var V : TVersionInfo; app, tmp : string; begin app := ParamStr(0); V := GetVersionInfo(app); tmp := V.ProductName + VersionString + V.ProductVersion + ' (' + V.FileVersion; if ts <> '' then tmp := tmp + ',' + BuiltString + ts; tmp := tmp + ')'; Writeln(tmp); Writeln(' ' + V.LegalCopyright); end; procedure PrintUsageError(const ts : string); begin PrintVersion(ts); Writeln(Format(UsageErrorMessage, [progName])); end; function redirectErrorsToFile : boolean; begin Result := ParamSwitch('-E', false); end; procedure setErrorOutputFile(var F : TextFile); var val, dir : string; begin val := ''; if ParamSwitch('-E', false) then begin val := ParamValue('-E', false); dir := ExtractFilePath(val); if dir <> '' then ForceDirectories(dir); end; AssignFile(F, val); Rewrite(F); end; function getIncludePath : string; begin Result := ExtractFilePath(ParamStr(0)); if ParamSwitch('-I', false) then begin Result := ParamValue('-I', false); end; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, jpeg, ExtCtrls, StdCtrls, Menus; type TFloatPoint = record x, y : Double; end; TCalcCoords = function(x,y:Integer): TFloatPoint of object; TForm1 = class(TForm) Image1: TImage; Image2: TImage; Button1: TButton; MainMenu1: TMainMenu; File1: TMenuItem; SaveImage1: TMenuItem; SaveDialog1: TSaveDialog; RadioGroup1: TRadioGroup; procedure Button1Click(Sender: TObject); procedure SaveImage1Click(Sender: TObject); private { Private-Deklarationen } function Scale(x,y:Integer):TFloatPoint; function Sinus1(x,y:Integer):TFloatPoint; function Sinus2(x,y:Integer):TFloatPoint; function Gedreht(x,y:Integer):TFloatPoint; function Gedreht2(x,y:Integer):TFloatPoint; function Quadrat(x,y:Integer):TFloatPoint; function Quadrat2(x,y:Integer):TFloatPoint; procedure GetCalcMethod(var x:TCalcCoords); procedure Test(const src, dst : TBitmap); public { Public-Deklarationen } end; var Form1: TForm1; implementation {$R *.DFM} uses UFloatCanvas; procedure TForm1.Button1Click(Sender: TObject); var bm : TBitmap; begin bm := TBitmap.Create; bm.Width := Image2.Width; bm.Height := Image2.Height; bm.PixelFormat := pf24bit; Image2.Picture.Graphic := bm; bm.Canvas.TextOut(30,30, 'test'); test(Image1.Picture.Bitmap, Image2.Picture.Bitmap); end; procedure TForm1.Test(const src, dst : TBitmap); var x, y : Integer; color : TColor; cv : TFloatCanvas; f : TCalcCoords; coord : TFloatPoint; begin GetCalcMethod(f); cv := TFloatCanvas.Create(src.Canvas); for y := 0 to dst.Height-1 do begin for x := 0 to dst.Width-1 do begin // schräges Bild // color := cv.Pixels[x*0.9 + 0.1*y ,y*0.4-0.1*x]; coord := f(x,y); color := cv.Pixels[coord.x, coord.y]; dst.Canvas.Pixels[x,y] := color; end; end; end; procedure TForm1.SaveImage1Click(Sender: TObject); begin if SaveDialog1.Execute then Image2.Picture.SaveToFile(SaveDialog1.FileName); end; function TForm1.Scale(x, y: Integer): TFloatPoint; begin Result.x := x*2; Result.y := y*2; end; function TForm1.Sinus1(x, y: Integer): TFloatPoint; begin Result.x := x*0.9 + 7 * sin(y / 10); Result.y := y + 7 * sin(x / 10); end; function TForm1.Sinus2(x, y: Integer): TFloatPoint; var d : Double; begin d := SQRT(SQR(x - 200) + SQR(y-200)) * 0.5; Result.x := x - 5 * cos(d); Result.y := y + 5 * sin(d); end; function TForm1.Gedreht(x, y: Integer): TFloatPoint; begin Result.x := x*1.4 + 0.1*y; Result.y := y*1.4 - 0.1*x; end; function TForm1.Gedreht2(x, y: Integer): TFloatPoint; const d = 600; scale = 10; a = 0.01; b = 0.005; cd = 2; begin // Result.x := x*1.4 + 0.2*y - 20; // Result.y := y*1.4 - 0.1*x - 20; Result.x := x / (a*x + b *y +cd) * scale -90; Result.y := y / (a*x + b *y +cd) * scale -90; end; function TForm1.Quadrat(x, y: Integer): TFloatPoint; begin Result.x := x*1.4 + (200-x)*(200-x)*0.009; Result.y := y*1.4; end; function TForm1.Quadrat2(x, y: Integer): TFloatPoint; begin Result.x := x*1.4 + (200-x)*(200-y)*0.009; Result.y := y*1.4; end; procedure TForm1.GetCalcMethod(var x:TCalcCoords); begin case RadioGroup1.ItemIndex of 0: x := Sinus1; 1: x := Sinus2; 2: x := Gedreht; 3: x := Gedreht2; 4: x := Quadrat; 5: x := Quadrat2; else x := Scale; end; end; end.
//Exercício 10: Escreva um algoritmo para calcular e exibir a quantidade de latas de tinta necessárias para pintar uma //parede de 5 metros de largura por 2 metros de altura. Considere que o consumo de tinta é de 3 litros por metro quadrado //e a quantidade de tinta por lata é de 2 litros. { Solução em Portugol Algoritmo Exercicio10; Const consumo_tinta = 3; volume_lata = 2; altura = 2; largura = 5; Var quantidade_latas: real; Inicio exiba("Programa que diz quantas latas são necessárias para pintar uma parede."); quantidade_latas <- (consumo_tinta * altura * largura)/volume_lata; exiba("A quantidade de latas para pintar a parede é: ",quantidade_latas); Fim. } // Solução em Pascal Program Exercicio; uses crt; const consumo_tinta = 3; volume_lata = 2; altura = 2; largura = 5; var quantidade_latas: real; begin clrscr; writeln('Programa que diz quantas latas são necessárias para pintar uma parede.'); quantidade_latas := (consumo_tinta * altura * largura)/volume_lata; writeln('A quantidade de latas para pintar a parede é: ',quantidade_latas:0:0); repeat until keypressed; end.
unit USigns; interface uses Classes, SysUtils, Graphics, Controls, Types, // self-made units UMapCommon, UConfig, UCommon; type NSignParam = (spID, spName, spInfo, sptest); TSignConfig = class(TConfig) private protected function GetItem(Index: Integer; Param: NSignParam): string; procedure SetItem(Index: Integer; Param: NSignParam; const Value: string); function GetWItem(Index, Param: Integer): string; override; procedure SetWItem(Index, Param: Integer; const Value: string); override; function GetParamCnt: Integer; override; function GetParamName(Param: Integer): string; override; public property Items[Index: Integer; Param: NSignParam]: string read GetItem write SetItem; function IDString(Index: Integer; Param: NSignParam): string; function GetRandDefText(): string; end; CSign = class(THODObject) private public Deleted: Boolean; X, Y, ID: Integer; constructor Create(AX, AY: Integer; AID: Integer = 0); overload; constructor Create(AString: string); overload; procedure Edit(AX, AY, AID: Integer); function ToString(): string; function ToPoint(): TPoint; class procedure Split(Astr: string; out AX, AY, AID: Integer); end; CSignList = class(TObjList) private function GetItem(Index: Integer): CSign; procedure SetItem(Index: Integer; const Value: CSign); public function Add(const Value: CSign): Integer; function Find(AX, AY: Integer; FindPrm: NFindParam = fpNumber): Integer; function FindItemByID(ID: Integer): CSign; property Items[Index: Integer]: CSign read GetItem write SetItem; default; function GetText(AX, AY: Integer): string; end; const SignsMapSectionName = '[Signs]'; DefaultTextSection = 'Default'; Delim = '|'; SignParamColWidths: array[NSignParam] of Integer = (20, 90, 500, 20); SignParamColCount = Ord(High(NSignParam)) + 1; SignParamType: array[NSignParam] of NParamType = (npInteger, npString, npString, npBoolean); var SignParamNames: array[NSignParam] of string; function SignConfig(): TSignConfig; function SignList(): CSignList; implementation uses uUtils, TypInfo; var TheSignList: CSignList; TheSignConfig: TSignConfig; function SignConfig(): TSignConfig; begin Result := TheSignConfig; end; function SignList(): CSignList; begin Result := TheSignList; end; { TSignConfig } function TSignConfig.GetItem(Index: Integer; Param: NSignParam): string; begin if Param = spID then Result := IntToStr(Index) else Result := FWrapper.ReadString(IDString(Index, Param)); end; function TSignConfig.GetParamCnt: Integer; begin Result := SignParamColCount; end; function TSignConfig.GetParamName(Param: Integer): string; begin Result := SignParamNames[NSignParam(Param)]; end; function TSignConfig.GetRandDefText: string; begin Result := Wrapper.ReadString(DefaultTextSection + Wrapper.Delim + IntToStr(Random(Wrapper.GetChildCount(DefaultTextSection)))); end; function TSignConfig.GetWItem(Index, Param: Integer): string; begin Result := Items[Index, NsignParam(Param)]; end; function TSignConfig.IDString(Index: Integer; Param: NSignParam): string; begin Result := Format('%d%s%s', [Index, FWrapper.Delim, SignParamNames[Param]]); end; procedure TSignConfig.SetItem(Index: Integer; Param: NSignParam; const Value: string); begin if Param <> spID then FWrapper.WriteString(IDString(Index, Param), Value); end; procedure TSignConfig.SetWItem(Index, Param: Integer; const Value: string); begin Items[Index, NsignParam(Param)] := Value; end; { CSign } constructor CSign.Create(AX, AY, AID: Integer); begin inherited Create(); X := AX; Y := AY; ID := AID; end; constructor CSign.Create(AString: string); begin inherited Create(); Split(AString, X, Y, ID); end; procedure CSign.Edit(AX, AY, AID: Integer); begin X := AX; Y := AY; ID := AID; end; class procedure CSign.Split(Astr: string; out AX, AY, AID: Integer); var sl : Tstringlist; begin sl := Tstringlist.Create; try sl.Delimiter := delim; sl.DelimitedText := AStr; Ax := StrToIntDef(sl[0], 0); Ay := StrToIntDef(sl[1], 0); AID := StrToIntDef(sl[2], 0); finally sl.Free; end; end; function CSign.ToPoint: TPoint; begin try Result := Point(x, y); except end; end; function CSign.ToString: string; begin Result := Format('%d%s%d%s%d', [X, delim, Y, delim, ID]); end; { CSignList } function CSignList.Add(const Value: CSign): Integer; begin Result := inherited Add(Value); end; function CSignList.Find(AX, AY: Integer; FindPrm: NFindParam = fpNumber): Integer; var j: Integer; begin Result := -1; for j := 0 to Count - 1 do if (Items[j].X = AX) and (Items[j].Y = AY) then begin case FindPrm of fpNumber: Result := j; fpID: Result := Items[j].ID; end; Exit; end; end; function CSignList.FindItemByID(ID: Integer): CSign; var j: Integer; begin Result := nil; for j := 0 to Count - 1 do if (Items[j].ID = ID) then begin Result := Items[j]; Exit; end; end; function CSignList.GetItem(Index: Integer): CSign; begin Result := inherited Get(Index); end; function CSignList.GetText(AX, AY: Integer): string; var id: Integer; begin id := Find(AX, AY, fpID); if (id = -1) or (id = 0) then Result := SignConfig.GetRandDefText else Result := SignConfig.Items[id, spinfo]; end; procedure CSignList.SetItem(Index: Integer; const Value: CSign); begin inherited Put(Index, Value); end; var I: NSignParam; initialization TheSignConfig := TSignConfig.Create(TIniWrapper); TheSignConfig.LoadFromFile(Path + 'data\Signs.ini'); TheSignList := CSignList.Create(); for i := Low(NSignParam) to High(NSignParam) do SignParamNames[i] := EnumText(TypeInfo(NSignParam), Ord(i)); finalization FreeAndNil(TheSignConfig); FreeAndNil(TheSignList); end.
unit xn.list.index; interface uses System.SysUtils, System.Generics.Collections, System.Generics.Defaults, xn.list, xn.Types, xn.list.observable; type TxnListIndexEnumerator<T> = class; TxnComparison<T> = reference to function(const aValue: T): Integer; IxnComparer<T> = interface ['{57923A26-26C6-47AD-AE9F-EE58F0FE0316}'] function Comparison(const aValue: T): Integer; end; TxnComparer<T> = class(TInterfacedObject, IxnComparer<T>) private fComparison: TxnComparison<T>; public constructor Create(aComparison: TxnComparison<T>); class function Construct(aComparison: TxnComparison<T>): IxnComparer<T>; function Comparison(const aValue: T): Integer; end; IxnListIndex<T> = interface(IxnItemsNotify) ['{7F4738B8-A53D-4EEB-AE16-66C97D62E64A}'] function GetEnumerator: TxnListIndexEnumerator<T>; function Seek1(aItem: T): Integer; function Seek2(aItem: T): Integer; function Seek1b(aComparer: IxnComparer<T>): Integer; function Count: Integer; function ItemGet(aIndex: Integer): T; property Items[aIndex: Integer]: T read ItemGet; default; end; TxnListIndex<T> = class(TInterfacedObject, IxnListIndex<T>) strict private fComparer: IComparer<T>; private fList: IxnList<T>; fIndex: TList<Integer>; procedure NotifyAdd(aIndex: Integer); procedure NotifyModify(aIndex: Integer); procedure NotifyDelete(aIndex: Integer); procedure NotifyClear; procedure NotifySort; public constructor Create(aList: IxnListNotify<T>; aComparer: IComparer<T>); destructor Destroy; override; class function ConstructIndex(aList: IxnListNotify<T>; aComparer: IComparer<T>): IxnListIndex<T>; procedure Notify(aAction: TxnNotifyAction; aIndex: Integer); function GetEnumerator: TxnListIndexEnumerator<T>; function Seek1(aItem: T): Integer; function Seek2(aItem: T): Integer; function Seek1b(aComparer: IxnComparer<T>): Integer; function Count: Integer; function ItemGet(aIndex: Integer): T; property Items[aIndex: Integer]: T read ItemGet; default; end; TxnListIndexEnumerator<T> = class private fList: TxnListIndex<T>; fIndex: Integer; public constructor Create(aList: TxnListIndex<T>); function GetCurrent: T; function MoveNext: boolean; property Current: T read GetCurrent; end; implementation { TxnListIndex<T> } procedure TxnListIndex<T>.Notify(aAction: TxnNotifyAction; aIndex: Integer); begin case aAction of naAdd: NotifyAdd(aIndex); naModify: NotifyModify(aIndex); naDelete: NotifyDelete(aIndex); naClear: NotifyClear; naSort: NotifySort; end; end; procedure TxnListIndex<T>.NotifyAdd(aIndex: Integer); var s: Integer; begin // posizione nell'indice s := Seek2(fList.Items[aIndex]); // add a indice if s < 0 then fIndex.Add(aIndex) else fIndex.Insert(s, aIndex) end; procedure TxnListIndex<T>.NotifyClear; begin fIndex.Clear; end; procedure TxnListIndex<T>.NotifyModify(aIndex: Integer); var i: Integer; begin for i := fIndex.Count - 1 downto 0 do if fIndex[i] = aIndex then fIndex.Delete(i); NotifyAdd(aIndex); end; procedure TxnListIndex<T>.NotifySort; var i: Integer; begin fIndex.Clear; for i := 0 to fList.Count - 1 do NotifyAdd(i); end; procedure TxnListIndex<T>.NotifyDelete(aIndex: Integer); var i: Integer; begin for i := fIndex.Count - 1 downto 0 do if fIndex[i] > aIndex then fIndex[i] := fIndex[i] - 1 else if fIndex[i] = aIndex then fIndex.Delete(i) end; function TxnListIndex<T>.Count: Integer; begin Result := fIndex.Count end; constructor TxnListIndex<T>.Create(aList: IxnListNotify<T>; aComparer: IComparer<T>); begin fList := aList; fComparer := aComparer; fIndex := TList<Integer>.Create; end; destructor TxnListIndex<T>.Destroy; begin fIndex.Free; inherited; end; class function TxnListIndex<T>.ConstructIndex(aList: IxnListNotify<T>; aComparer: IComparer<T>): IxnListIndex<T>; begin Result := TxnListIndex<T>.Create(aList, aComparer); aList.NotifyRegister(Result); end; function TxnListIndex<T>.GetEnumerator: TxnListIndexEnumerator<T>; begin Result := TxnListIndexEnumerator<T>.Create(Self); end; function TxnListIndex<T>.ItemGet(aIndex: Integer): T; begin Result := fList[fIndex[aIndex]] end; function TxnListIndex<T>.Seek1(aItem: T): Integer; var iStart: Integer; iStop: Integer; iPivot: Integer; IComparer: Integer; begin // returns the actual index of the item in the list // -1 if the item is not found iStart := 0; iStop := fIndex.Count - 1; if fIndex.Count = 0 then exit(-1); Result := -1; while iStart <= iStop do begin iPivot := (iStart + iStop) div 2; IComparer := fComparer.Compare(Items[iPivot], aItem); if IComparer = 0 then exit(iPivot) else if IComparer > 0 then iStop := iPivot - 1 else iStart := iPivot + 1; end; end; function TxnListIndex<T>.Seek1b(aComparer: IxnComparer<T>): Integer; var iStart: Integer; iStop: Integer; iPivot: Integer; IComparer: Integer; begin // returns the actual index of the item in the list // -1 if the item is not found iStart := 0; iStop := fIndex.Count - 1; if fIndex.Count = 0 then exit(-1); Result := -1; while iStart <= iStop do begin iPivot := (iStart + iStop) div 2; IComparer := aComparer.Comparison(Items[iPivot]); if IComparer = 0 then exit(iPivot) else if IComparer > 0 then iStop := iPivot - 1 else iStart := iPivot + 1; end; end; function TxnListIndex<T>.Seek2(aItem: T): Integer; var iStart: Integer; iStop: Integer; oStart: Integer; oStop: Integer; iPivot: Integer; IComparer: Integer; iOther: Integer; begin // returns the expected index of the item in the list // -1 if the item is after the last item of the list iStart := 0; oStart := 0; iStop := fIndex.Count - 1; oStop := fIndex.Count - 1; if fIndex.Count = 0 then exit(0); Result := -1; while iStart <= iStop do begin iPivot := (iStart + iStop) div 2; IComparer := fComparer.Compare(Items[iPivot], aItem); if IComparer = 0 then exit(iPivot) else if IComparer > 0 then begin if iPivot > oStart then begin iOther := fComparer.Compare(Items[iPivot - 1], aItem); if iOther = 0 then exit(iPivot - 1) else if iOther < 0 then exit(iPivot); end; iStop := iPivot - 1 end else begin if iPivot < oStop then begin iOther := fComparer.Compare(Items[iPivot + 1], aItem); if iOther = 0 then exit(iPivot + 1) else if iOther > 0 then exit(iPivot + 1); end; iStart := iPivot + 1; end; end; if fComparer.Compare(Items[oStart], aItem) > 0 then exit(oStart); end; { TxnListIndexEnumerator<T> } constructor TxnListIndexEnumerator<T>.Create(aList: TxnListIndex<T>); begin inherited Create; fIndex := -1; fList := aList; end; function TxnListIndexEnumerator<T>.GetCurrent: T; begin Result := fList.fList[fList.fIndex[fIndex]] end; function TxnListIndexEnumerator<T>.MoveNext: boolean; begin Result := fIndex < fList.fIndex.Count - 1; if Result then Inc(fIndex); end; { TxnComparer<T> } function TxnComparer<T>.Comparison(const aValue: T): Integer; begin Result := fComparison(aValue) end; class function TxnComparer<T>.Construct(aComparison: TxnComparison<T>): IxnComparer<T>; begin Result := TxnComparer<T>.Create(aComparison); end; constructor TxnComparer<T>.Create(aComparison: TxnComparison<T>); begin fComparison := aComparison; end; end.
unit infosistemas.model.clientes; interface uses System.SysUtils, System.Classes, Data.DB, Datasnap.DBClient, infosistemas.business.mail, infosistemas.system.winshell, infosistemas.model.exceptions, infosistemas.view.messages; type TDMClientes = class(TDataModule) CdsClientes: TClientDataSet; DsrClientes: TDataSource; CdsClientesCPF: TStringField; CdsClientesNOME: TStringField; CdsClientesIDENTIDADE: TStringField; CdsClientesTELEFONE: TStringField; CdsClientesMAIL: TStringField; CdsClientesCEP: TStringField; CdsClientesLOGRADOURO: TStringField; CdsClientesNUMERO: TSmallintField; CdsClientesCOMPLEMENTO: TStringField; CdsClientesBAIRRO: TStringField; CdsClientesCIDADE: TStringField; CdsClientesUF: TStringField; CdsClientesPAIS: TStringField; procedure CdsClientesCPFValidate(Sender: TField); procedure CdsClientesAfterPost(DataSet: TDataSet); procedure CdsClientesBeforePost(DataSet: TDataSet); private { Private declarations } FSendMessage: boolean; public { Public declarations } end; var DMClientes: TDMClientes; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} uses infosistemas.business.clientes; {$R *.dfm} procedure TDMClientes.CdsClientesAfterPost(DataSet: TDataSet); var Mailer: TMailSender; aCustomerData: TStringList; aAttachmentFile: string; begin //Somente gera o XML e envia o email quando os dados do cliente são inseridos. if not FSendMessage then Exit; //to-do: alterar para trabalhar apenas de forma assíncrona. Esse processo deveria //apenas registrar que um cliente foi inserido. Outro processo, de forma //assíncrona, deveria se encarregar do envio do email. Mailer := TMailSender.Create(TShellFolders.GetCommonAppDataFolder + '\'); aCustomerData := TStringList.Create; try aCustomerData.NameValueSeparator := '='; aCustomerData.AddPair('CPF', Dataset.FindField('CPF').AsString); aCustomerData.AddPair('Identidade', Dataset.FindField('IDENTIDADE').AsString); aCustomerData.AddPair('Nome', Dataset.FindField('NOME').AsString); aCustomerData.AddPair('Telefone', Dataset.FindField('TELEFONE').AsString); aCustomerData.AddPair('Email', Dataset.FindField('MAIL').AsString); aCustomerData.AddPair('CEP', Dataset.FindField('CEP').AsString); aCustomerData.AddPair('Logradouro', Dataset.FindField('LOGRADOURO').AsString); aCustomerData.AddPair('Numero', Dataset.FindField('NUMERO').AsString); aCustomerData.AddPair('Bairro', Dataset.FindField('BAIRRO').AsString); aCustomerData.AddPair('Cidade', Dataset.FindField('CIDADE').AsString); aCustomerData.AddPair('UF', Dataset.FindField('UF').AsString); aCustomerData.AddPair('Pais', Dataset.FindField('PAIS').AsString); if not Dataset.FindField('COMPLEMENTO').IsNull then aCustomerData.AddPair('Complemento', Dataset.FindField('COMPLEMENTO').AsString) else aCustomerData.AddPair('Complemento', ''); //Cria e salva o anexo XML com os dado do cliente. aAttachmentFile := Mailer.CreateAttachmentFile(ACustomerData.Text); //Finalmente, envia o email. Somente envia se o anexo for salvo com sucesso. if not aAttachmentFile.IsEmpty then Mailer.SendMail(aCustomerData.Text, ACustomerData.Values['Email'], aAttachmentFile); finally if Assigned(aCustomerData) then FreeAndNil(aCustomerData); if Assigned(Mailer) then FreeAndNil(Mailer); end; end; procedure TDMClientes.CdsClientesBeforePost(DataSet: TDataSet); var Mailer: TMailSender; begin //Indica que o envio de email será feito apenas para clientes novos. FSendMessage := Dataset.State = dsInsert; Mailer := TMailSender.Create('');//Nesse contexto, o parâmetro pode ser uma string vazia. try //Valida se o email informado é correto. if not Mailer.IsValidMail(Dataset.FieldByName('MAIL').AsString) then begin FSendMessage := False; //Não enviará mensagem para a caixa inválida. raise EInvalidMailInfo.Create(TMessagesConst.InvalidMail); end; finally FreeAndNil(Mailer); end; end; procedure TDMClientes.CdsClientesCPFValidate(Sender: TField); var aCliente: TClientesUtils; begin aCliente := TClientesUtils.Create; try if not aCliente.ValidateCPF(Sender.AsString) then begin Sender.FocusControl; end; finally if Assigned(aCliente) then FreeAndNil(aCliente); end; end; end.
unit DAO.PlanilhaEntradaCarriers; interface uses Generics.Collections, System.Classes, System.SysUtils, Forms, Windows, Model.PlanilhaEntradaCarriers; type TPlanilhaEntradaCarriersDAO = class public function GetPlanilha(sFile: String): TObjectList<TPlanilhaEntradaCarriers>; end; implementation { TPlanilhaEntradaCarriersDAO } uses Common.Utils; function TPlanilhaEntradaCarriersDAO.GetPlanilha(sFile: String): TObjectList<TPlanilhaEntradaCarriers>; var ArquivoCSV: TextFile; sLinha: String; sDetalhe: TStringList; entradas : TObjectList<TPlanilhaEntradaCarriers>; i : Integer; begin try entradas := TObjectList<TPlanilhaEntradaCarriers>.Create; if not FileExists(sFile) then begin Application.MessageBox(PChar('Arquivo ' + sFile + ' não foi encontrado!'), 'Atenção', MB_ICONWARNING + MB_OK); Exit; end; AssignFile(ArquivoCSV, sFile); if sFile.IsEmpty then Exit; sDetalhe := TStringList.Create; sDetalhe.StrictDelimiter := True; sDetalhe.Delimiter := ';'; Reset(ArquivoCSV); Readln(ArquivoCSV, sLinha); sDetalhe.DelimitedText := sLinha; if Pos('Nr Rota;',sLinha) = 0 then begin Application.MessageBox('Arquivo informado não foi identificado como a Planilha de Entrada da Carriers!', 'Atenção', MB_ICONWARNING + MB_OK); Exit; end; sDetalhe.DelimitedText := sLinha; i := 0; while not Eoln(ArquivoCSV) do begin Readln(ArquivoCSV, sLinha); sDetalhe.DelimitedText := sLinha; if TUtils.ENumero(sDetalhe[6]) then begin entradas.Add(TPlanilhaEntradaCarriers.Create); i := entradas.Count - 1; entradas[i].NRRota := sDetalhe[0]; entradas[i].Rota := sDetalhe[1]; entradas[i].Motorista := sDetalhe[2]; entradas[i].OrdemRota := sDetalhe[3]; entradas[i].Embarcador := sDetalhe[4]; entradas[i].Destinatario := sDetalhe[5]; entradas[i].NREntrega := sDetalhe[6]; entradas[i].NF := sDetalhe[7]; entradas[i].Pedido := sDetalhe[8]; entradas[i].Tipo := sDetalhe[9]; entradas[i].TipoFrete := sDetalhe[10]; entradas[i].Volumes := sDetalhe[11]; entradas[i].ACobrar := sDetalhe[12]; entradas[i].OBSEntrega := sDetalhe[13]; entradas[i].IDViagem := sDetalhe[14]; entradas[i].DataEntrega := sDetalhe[15]; entradas[i].DataOcorrencia := sDetalhe[16]; entradas[i].Ocorrencia := sDetalhe[17]; entradas[i].IDRemessa := sDetalhe[18]; entradas[i].Endereco := sDetalhe[19]; entradas[i].Bairro := sDetalhe[20]; entradas[i].Municipio := sDetalhe[21]; entradas[i].CEP := sDetalhe[22]; entradas[i].SituacaoEntrega := sDetalhe[23]; entradas[i].FreteRemessa := sDetalhe[24]; entradas[i].FreteCobrar := sDetalhe[25]; entradas[i].Peso := sDetalhe[26]; entradas[i].Valor := sDetalhe[27]; entradas[i].Tentativa := sDetalhe[28]; entradas[i].Coleta := sDetalhe[29]; entradas[i].Viagem := sDetalhe[30]; entradas[i].TipoBaixa := sDetalhe[31]; entradas[i].IDVolume := sDetalhe[32]; entradas[i].Situacao := sDetalhe[33]; entradas[i].OBS := sDetalhe[34]; entradas[i].NomeBase := sDetalhe[35]; entradas[i].Latitude := sDetalhe[36]; entradas[i].Longitude := sDetalhe[37]; entradas[i].IDPedido := sDetalhe[38]; end; end; Result := entradas; finally CloseFile(ArquivoCSV); end; end; end.
unit StringUtilsTests; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testutils, testregistry; type TStringUtilsTests = class(TTestCase) published procedure TestGetWordAtPosition; end; implementation uses StringUtils; procedure TStringUtilsTests.TestGetWordAtPosition; const Phrase = 'Write your own test'; begin CheckEquals('', TStringUtils.GetWordAtCursor(Phrase, 0)); CheckEquals('Write', TStringUtils.GetWordAtCursor(Phrase, 3)); CheckEquals('Write', TStringUtils.GetWordAtCursor(Phrase, 5)); CheckEquals('your', TStringUtils.GetWordAtCursor(Phrase, 10)); CheckEquals('own', TStringUtils.GetWordAtCursor(Phrase, 13)); end; initialization RegisterTest(TStringUtilsTests); end.
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi by Dennis D. Spreen <dennis@spreendigital.de> see Behavior3.pas header for full license information } unit Behavior3.Helper; interface uses Behavior3.Core.BehaviorTree, Behavior3.Core.BaseNode, Behavior3.Core.Tick; type TB3BehaviorTreeHelper = class helper for TB3BehaviorTree protected function GetRoot: TB3BaseNode; inline; procedure SetRoot(const Value: TB3BaseNode); inline; procedure SetNodes(const Value: TB3BaseNodeDictionary); inline; function GetNodes: TB3BaseNodeDictionary; inline; public property Root: TB3BaseNode read GetRoot write SetRoot; property Nodes: TB3BaseNodeDictionary read GetNodes write SetNodes; end; TB3TickHelper = class helper for TB3Tick protected function GetTree: TB3BehaviorTree; inline; procedure SetTree(const Value: TB3BehaviorTree); inline; function GetOpenNodes: TB3BaseNodeList; inline; public property Tree: TB3BehaviorTree read GetTree write SetTree; property _OpenNodes: TB3BaseNodeList read GetOpenNodes; end; implementation { TB3BehaviorTreeHelper } function TB3BehaviorTreeHelper.GetNodes: TB3BaseNodeDictionary; begin Result := TB3BaseNodeDictionary(FNodes); end; function TB3BehaviorTreeHelper.GetRoot: TB3BaseNode; begin Result := TB3BaseNode(FRoot); end; procedure TB3BehaviorTreeHelper.SetNodes(const Value: TB3BaseNodeDictionary); begin FNodes := Value; end; procedure TB3BehaviorTreeHelper.SetRoot(const Value: TB3BaseNode); begin FRoot := Value; end; { TB3TickHelper } function TB3TickHelper.GetOpenNodes: TB3BaseNodeList; begin Result := TB3BaseNodeList(F_OpenNodes); end; function TB3TickHelper.GetTree: TB3BehaviorTree; begin Result := TB3BehaviorTree(FTree); end; procedure TB3TickHelper.SetTree(const Value: TB3BehaviorTree); begin FTree := Value; end; end.
unit tfwIntegerToEnumName; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\tfwIntegerToEnumName.pas" // Стереотип: "SimpleClass" // Элемент модели: "TtfwIntegerToEnumName" MUID: (553128CE018D) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , tfwRegisterableWordPrim , TypInfo , tfwScriptingInterfaces ; type TtfwIntegerToEnumName = class(TtfwRegisterableWordPrim) private f_TypeInfo: PTypeInfo; protected procedure DoDoIt(const aCtx: TtfwContext); override; public class procedure Register(aTypeInfo: PTypeInfo); function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; end;//TtfwIntegerToEnumName {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , SysUtils , tfwStringToEnumValue //#UC START# *553128CE018Dimpl_uses* //#UC END# *553128CE018Dimpl_uses* ; class procedure TtfwIntegerToEnumName.Register(aTypeInfo: PTypeInfo); //#UC START# *553129980377_553128CE018D_var* var l_Inst : TtfwIntegerToEnumName; //#UC END# *553129980377_553128CE018D_var* begin //#UC START# *553129980377_553128CE018D_impl* l_Inst := Create; try l_Inst.f_TypeInfo := aTypeInfo; l_Inst.RegisterInstance(aTypeInfo.Name + ':ValueToName'); finally FreeAndNil(l_Inst); end;//try..finally TtfwStringToEnumValue.Register(aTypeInfo); //#UC END# *553129980377_553128CE018D_impl* end;//TtfwIntegerToEnumName.Register procedure TtfwIntegerToEnumName.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_553128CE018D_var* //#UC END# *4DAEEDE10285_553128CE018D_var* begin //#UC START# *4DAEEDE10285_553128CE018D_impl* aCtx.rEngine.PushString(GetEnumName(f_TypeInfo, aCtx.rEngine.PopInt)); //#UC END# *4DAEEDE10285_553128CE018D_impl* end;//TtfwIntegerToEnumName.DoDoIt function TtfwIntegerToEnumName.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; //#UC START# *551544E2001A_553128CE018D_var* //#UC END# *551544E2001A_553128CE018D_var* begin //#UC START# *551544E2001A_553128CE018D_impl* Result := TypeInfo(String); //#UC END# *551544E2001A_553128CE018D_impl* end;//TtfwIntegerToEnumName.GetResultTypeInfo initialization TtfwIntegerToEnumName.RegisterClass; {* Регистрация TtfwIntegerToEnumName } {$IfEnd} // NOT Defined(NoScripts) end.
{*******************************************************} { } { This unit manage all XML message for the jabber exchange } { } { Copyright (C) 2014 } { } {*******************************************************} unit fmxJabberXml; interface uses classes, sysutils, OXmlPDOM, FmxJabberTools, fmx.dialogs, system.StrUtils; type TfmxJabberXml = class private fUsername : String; // Connected username fPassword : String; // password fServer : String; // jabber server fAlreadyLogged : Boolean; // Already logged flag fOnInitConnection : TOnInitConnection; //On connection initialized event fOnCryptedSASL : TOnResponseWithStrData; // On decrypting SASL fOnSuccessSASL : TOnResponseWithStrData; // Decrypt successful fOnBindInit : TOnResponseWithNoData; // On bind process fOnSessionInit : TOnResponseWithNoData; // on session initialized fOnIqRequest : TOnResponseWithStrData; // On received an IQ request fOnGettingContacts : TOnResponseWithStrData; // On getting contacts list fOnFaillure : TOnResponseWithStrData; // On faillure from server fOnUpdateRoster : TOnUpdateRoster; // On contact informations updated fOnAskToAddRosterStatus : TOnAddRequestStatus; // On asked to add a contact fOnAskedForSubscription : TOnResponseWithStrData; // when a contact ask to add you fOnMessageReceived : TOnMessageReceived; // On received a message from a contact fOnPresenceCallback : TOnPresenceCallBack; // On received a status change from a contact procedure ProcessStreamStreamResponse(AResponse : PxmlNode); // Process StreamStream Response procedure ProcessStreamFeaturesResponse(AResponse : PxmlNode); // process stream:feature Response procedure ProcessSASLResponse(AResponse: PxmlNode); // process SASL Response procedure ProcessSASLSuccessResponse(AResponse : PxmlNode); // process SASL success response procedure ProcessIQResponse(AResponse : PxmlNode); // process IQ Request procedure ProcessFaillureResponse(AResponse : PxmlNode); // process faillure Response procedure ProcessMessageResponse(AResponse : PxmlNode); // process Message Response procedure ProcessPresenceResponse(AResponse : PxmlNode); // process presence Response function GetMechanism(AMchanismsNode : PXMLNode) : TMechanism; // Get mechanism to use for authentification from server response public Constructor Create; Destructor Destroy;Override; //Return requests as xml function CreateInitRequest(AServer : string) : String; function CreateAuthRequest(Amechanism : TMechanism) : string; function CreateSASLRequest(ACrypted : String) : String; function CreateResourceRequest(AResource : String) : string; function CreateInitBindRequest(AResource : String) : String; function CreateInitSessionRequest(AUniqueID : String) : String; function CreatePresenceRequest(Astatus : TUserStatus; AMsg : String) : string; function CreateIQResponse(AId, AServer: string): String; function CreateGetcontactsRequest : String; function CreateAddContactRequest(AFrom, AUsername, AJID, AGroup : String) : string; function CreateSendMessageRequest(AFrom, ATo, AType, ABody: string): string; function CreateDeleteRosterRequest(AFrom, ATo : String) : string; //Parse server response procedure ParseServerResponse(AXmlResponse : string); //public roperties property OnInitConnection : TOnInitConnection read fOnInitConnection write fOnInitConnection; property OnCryptedSASL : TOnResponseWithStrData read fOnCryptedSASL write fOnCryptedSASL; property OnSuccessSASL : TOnResponseWithStrData read fOnSuccessSASL write fOnSuccessSASL; property OnBindInit : TOnResponseWithNoData read fOnBindInit write fOnBindInit; property OnSessionInit : TOnResponseWithNoData read fOnSessionInit write fOnSessionInit; property OnIqRequest : TOnResponseWithStrData read fOnIqRequest write fOnIqRequest; property OnGettingContacts : TOnResponseWithStrData read fOnGettingContacts write fOnGettingContacts; property OnFaillure : TOnResponseWithStrData read fOnFaillure write fOnFaillure; property OnUpdateRoster : TOnUpdateRoster read fOnUpdateRoster write fOnUpdateRoster; property OnAskToAddRosterStatus : TOnAddRequestStatus read fOnAskToAddRosterStatus write fOnAskToAddRosterStatus; property OnAskedForSubscription : TOnResponseWithStrData read fOnAskedForSubscription write fOnAskedForSubscription; property OnMessageReceived : TOnMessageReceived read fOnMessageReceived write fOnMessageReceived; property OnPresenceCallback : TOnPresenceCallBack read fOnPresenceCallback write fOnPresenceCallback; property Username : String read fUsername; property Password : String read fPassword; property Server : String read fServer; end; implementation { TfmxJabberXml } constructor TfmxJabberXml.Create; begin end; destructor TfmxJabberXml.Destroy; begin inherited; end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.GetMechanism Arguments: AMchanismsNode: PXMLNode Result: TMechanism -------------------------------------------------------------------------------} function TfmxJabberXml.GetMechanism(AMchanismsNode: PXMLNode): TMechanism; var i : integer; wStrList : TStringlist; begin try result := mecNONE; wStrList := TStringList.Create; try for i := 0 to AMchanismsNode.ChildNodes.Count -1 do wStrList.Add(AMchanismsNode.ChildNodes[i].ChildNodes[0].NodeValue); if wStrList.IndexOf('DIGEST-MD5') <> -1 then result := mecDIGEST_MD5 else if wStrList.IndexOf('PLAIN') <> -1 then result := mecPLAIN; finally wStrList.free; end; except On E:Exception do Raise Exception.create('[TfmxJabberXml.GetMechanism] : '+E.message); end; end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.CreateAddContactRequest Arguments: AFrom, AUsername, AJID, AGroup: String Result: string -------------------------------------------------------------------------------} function TfmxJabberXml.CreateAddContactRequest(AFrom, AUsername, AJID, AGroup: String): string; begin Result := '<presence to="' + AJID + '" type="subscribe"/>' end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.CreateAuthRequest Arguments: Amechanism: TMechanism Result: string -------------------------------------------------------------------------------} function TfmxJabberXml.CreateAuthRequest(Amechanism: TMechanism): string; var wMechanismStr : string; begin case Amechanism of mecDIGEST_MD5: wMechanismStr := 'DIGEST-MD5'; mecPLAIN: wMechanismStr := 'PLAIN'; end; Result := ('<auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" mechanism="' + wMechanismStr + '"/>'); end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.CreateDeleteRosterRequest Arguments: Afrom, ATo: String Result: string -------------------------------------------------------------------------------} function TfmxJabberXml.CreateDeleteRosterRequest(Afrom, ATo: String): string; begin Result := '<iq from="' + Afrom +'" type="set" id="roster_4"><query xmlns="jabber:iq:roster"><item jid="'+ATo+'" subscription="remove"/></query></iq>'; end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.CreateGetcontactsRequest Arguments: None Result: String -------------------------------------------------------------------------------} function TfmxJabberXml.CreateGetcontactsRequest: String; begin Result := '<iq type="get" id="roster_1" ><query xmlns="jabber:iq:roster"/></iq>'; end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.CreateInitBindRequest Arguments: AResource : String Result: String -------------------------------------------------------------------------------} function TfmxJabberXml.CreateInitBindRequest(AResource : String): String; begin Result := '<iq type="set" id="bind_1"><bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"><resource>' + AResource +'</resource></bind></iq>'; end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.CreateInitRequest Arguments: AServer : string Result: String -------------------------------------------------------------------------------} function TfmxJabberXml.CreateInitRequest(AServer : string): String; begin fAlreadyLogged := False; Result := '<?xml version="1.0"?><stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" to="' + AServer + '" version="1.0" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace">'; end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.CreateInitSessionRequest Arguments: AUniqueID: String Result: String -------------------------------------------------------------------------------} function TfmxJabberXml.CreateInitSessionRequest(AUniqueID: String): String; begin Result := '<iq type="set" id="'+ Trim(AUniqueID) +'"><session xmlns="urn:ietf:params:xml:ns:xmpp-session"/></iq>'; end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.CreateIQResponse Author: kelhedadi DateTime: 2014.04.18 Arguments: AId, AServer: string Result: String -------------------------------------------------------------------------------} function TfmxJabberXml.CreateIQResponse(AId, AServer: string): String; begin Result := '<iq type="result" to="'+AServer+'" id="'+AId+'"/>'; end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.CreatePresenceRequest Arguments: Astatus: TUserStatus; AMsg : String Result: string -------------------------------------------------------------------------------} function TfmxJabberXml.CreatePresenceRequest( Astatus: TUserStatus; AMsg : String): string; var wStatutsStr : String; begin wStatutsStr := ''; case Astatus of usOnline : wStatutsStr := ''; usAway : wStatutsStr := 'away'; usDNotDistrub : wStatutsStr := 'dnd'; usFreeForChat : wStatutsStr := 'chat'; usExtendedAway : wStatutsStr := 'xa'; end; Result := '<presence><show>' + wStatutsStr + '</show><priority>0</priority><Status>' + AMsg + '</Status></presence>' end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.CreateResourceRequest Arguments: AResource: String Result: string -------------------------------------------------------------------------------} function TfmxJabberXml.CreateResourceRequest(AResource: String): string; begin Result := '<iq type="set" id="session_1"><session xmlns="urn:ietf:params:xml:ns:xmpp-session"/></iq>'; end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.CreateSASLRequest Arguments: ACrypted: String Result: String -------------------------------------------------------------------------------} function TfmxJabberXml.CreateSASLRequest(ACrypted: String): String; begin try if ACrypted <> '' then result := '<response xmlns="urn:ietf:params:xml:ns:xmpp-sasl">' + ACrypted + '</response>' else Result := '<response xmlns="urn:ietf:params:xml:ns:xmpp-sasl"/>'; except On E:Exception do Raise Exception.create('[TfmxJabberXml.CreateSASLRequest] : '+E.message); end; end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.CreateSendMessageRequest Arguments: AFrom, ATo, AType, ABody: string Result: string -------------------------------------------------------------------------------} function TfmxJabberXml.CreateSendMessageRequest(AFrom, ATo, AType, ABody: string): string; begin Result := Format('<message to="%s" from="%s" type="%s" id="%s"><body>%s</body></message>', [ATo, AFrom, AType,GetUniqueID ,ABody]); end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.ParseServerResponse Arguments: AXmlResponse: string Result: None -------------------------------------------------------------------------------} procedure TfmxJabberXml.ParseServerResponse(AXmlResponse: string); var wXml : OXmlPDOM.IXMLDocument; wFixedXml : String; wNode : PXMLNode; i : integer; begin try if pos('<?xml', AXmlResponse) > 0 then AXmlResponse := Copy(AXmlResponse, 39,99999); wFixedXml := '<?xml version="1.0" encoding="UTF-8"?><Jab>' + AXmlResponse; if Pos('stream:stream',wFixedXml) > 0 then wFixedXml := wFixedXml + '</stream:stream></Jab>' else wFixedXml := wFixedXml + '</Jab>'; // showmessage('Received : ' + #13 + AXmlResponse); wXml := CreateXMLDoc; try wXml.LoadFromXML(wFixedXml); for i := 0 to wXml.DocumentElement.ChildCount -1 do begin wNode := wXml.DocumentElement.ChildNodes[i]; if CompareText(wNode.NodeName, 'stream:stream') = 0 then ProcessStreamStreamResponse( wNode ) else if CompareText(wNode.NodeName, 'stream:features') = 0 then ProcessStreamFeaturesResponse( wNode ) else if CompareText(wNode.NodeName, 'challenge') = 0 then begin ProcessSaSLResponse(wNode); end else if CompareText(wNode.NodeName, 'success') = 0 then begin ProcessSASLSuccessResponse(wNode); end else if CompareText(wNode.Attributes['id'],'bind_1') = 0 then begin if Assigned(fOnSessionInit) then fOnSessionInit(); end else if CompareText(wNode.NodeName, 'iq') = 0 then begin ProcessIQResponse(wNode); end else if CompareText(wNode.NodeName, 'presence') = 0 then begin ProcessPresenceResponse(wNode); end else if CompareText(wNode.NodeName, 'message') = 0 then begin ProcessMessageResponse(wNode); end else if CompareText(wNode.NodeName, 'failure') = 0 then begin ProcessFaillureResponse(wNode); end end; finally wXml := nil; end; except On E:Exception do Raise Exception.create('[TfmxJabberXml.ParseServerResponse] : '+E.message); end; end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.ProcessStreamFeaturesResponse Arguments: AResponse: PxmlNode Result: None -------------------------------------------------------------------------------} procedure TfmxJabberXml.ProcessStreamFeaturesResponse(AResponse: PxmlNode); var wId : string; wFeaturesNode : PxmlNode; wUseSASL : Boolean; wCompression : string; wMechanism : TMechanism; wNode : PxmlNode; begin try wUseSASL := False; wMechanism := mecNONE; wId := AResponse.Attributes['id']; wFeaturesNode := AResponse; if wFeaturesNode.SelectNode('./mechanisms',wNode) then begin wUseSASL := CompareText(wNode.Attributes['xmlns'],XMLNS_XMPP_SASL) = 0; wMechanism := GetMechanism(wNode); wMechanism := GetMechanism(wNode); end; if wFeaturesNode.SelectNode('./compression',wNode) then wCompression := wNode.ChildNodes[0].NodeValue; if wFeaturesNode.SelectNode('./mechanisms',wNode) then begin if Assigned(fOnInitConnection) then fOnInitConnection(wId,wCompression, wUseSASL, wMechanism); end; if wFeaturesNode.SelectNode('./bind',wNode) then begin if Assigned(fOnBindInit) then fOnBindInit(); end; except On E:Exception do Raise Exception.create('[TfmxJabberXml.ProcessStreamFeaturesResponse] : '+E.message); end; end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.ProcessStreamStreamResponse Arguments: AResponse: PxmlNode Result: None -------------------------------------------------------------------------------} procedure TfmxJabberXml.ProcessStreamStreamResponse(AResponse: PxmlNode); var wFeaturesNode : PxmlNode; begin try if AResponse.ChildNodes.Count > 0 then begin if AResponse.SelectNode('./stream:features',wFeaturesNode) then begin ProcessStreamFeaturesResponse(wFeaturesNode); end end except On E:Exception do Raise Exception.create('[TfmxJabberXml.ProcessInitResponse] : '+E.message); end; end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.ProcessFaillureResponse Arguments: AResponse: PxmlNode Result: None -------------------------------------------------------------------------------} procedure TfmxJabberXml.ProcessFaillureResponse(AResponse: PxmlNode); var wRootNode : PxmlNode; begin wRootNode := AResponse; if wRootNode.ChildNodes.Count > 0 then begin if CompareText(wRootNode.ChildNodes[0].NodeName,'not-authorized') = 0 then if assigned(fOnFaillure) then fOnFaillure('Authentification failed'); end; end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.ProcessIQResponse Arguments: AResponse: PxmlNode Result: None -------------------------------------------------------------------------------} procedure TfmxJabberXml.ProcessIQResponse(AResponse: PxmlNode); procedure GetContactData( ANode : PXMLNode; var Aname,AJID,ASubscription,AGroup : String); begin Aname := ANode.Attributes['name']; AJID := ANode.Attributes['jid']; ASubscription := ANode.Attributes['subscription']; if ANode.ChildCount > 0 then AGroup := ANode.nodevalue; // read group end; var wId, wType : String; i,k : integer; wstrList : TStringList; wName, wJid, wSubscription : String; wGroup : string; wContact : String; wContacts : String; wQueryNode : PXMLNode; begin try wId := AResponse.Attributes['id']; wType := AResponse.Attributes['type']; if (CompareText(wId,'roster_2') = 0) and (CompareText(wType,'result') = 0) then begin // GetContactData( AResponse.ChildNodes[0].ChildNodes[0], wName, wJID, wSubscription, wGroup ); // if assigned(fOnUpdateRoster) then // fOnUpdateRoster(wName, wJID, wSubscription, wGroup); end else if (CompareText(wId,'roster_1') = 0) and (CompareText(wType,'result') = 0) then begin // getting contacts list wstrList := TStringList.Create; try for i := 0 to AResponse.ChildNodes[0].ChildCount -1 do begin wGroup := ''; GetContactData( AResponse.ChildNodes[0].ChildNodes[i], wName, wJID, wSubscription, wGroup ); wContact := Format('"%s","%s","%s","%s"',[wName, wJID, wSubscription, wGroup]); wstrList.Add(wContact); end; wContacts := wstrList.CommaText; finally wstrList.Free; end; if Assigned(fOnGettingContacts) then fOnGettingContacts(wContacts); end else if (CompareText(wType,'set') = 0) then begin wQueryNode := AResponse.ChildNodes[0]; if CompareText(wQueryNode.nodename,'Query') = 0 then begin if CompareText(wQueryNode.Attributes['xmlns'],'jabber:iq:roster') = 0 then begin for k := 0 to wQueryNode.ChildCount -1 do begin // if wQueryNode.ChildNodes[k].HasAttribute('ask') then // begin // if assigned(fOnAskForSubscription) then // fOnAskForSubscription(wQueryNode.ChildNodes[k].Attributes['jid']); // end // else // if wQueryNode.ChildNodes[k].HasAttribute('subscription') then // begin // wGroup := ''; // GetContactData(wQueryNode.ChildNodes[k], wName, wJID, wSubscription, wGroup ); // if Comparetext(wSubscription , 'from') = 0 then // if assigned(fOnAddRoster) then // fOnAddRoster(wName, wJID, wSubscription, wGroup); // end; end; end; end else begin for i := 0 to AResponse.ChildNodes[0].ChildCount -1 do begin end; end; end else if pos('jabber:iq:roster', AResponse.xml) = 0 then begin // last authentification IQstep if assigned(fOnIqRequest) then fOnIqRequest(wId); end except On E:Exception do Raise Exception.create('[TfmxJabberXml.ProcessIQResponse] : '+E.message); end; end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.ProcessMessageResponse Arguments: AResponse: PxmlNode Result: None -------------------------------------------------------------------------------} procedure TfmxJabberXml.ProcessMessageResponse(AResponse: PxmlNode); var wFrom : String; wMessage : String; begin wFrom := AResponse.Attributes['from']; wMessage := AResponse.ChildNodes[0].ChildNodes[0].NodeValue; if Assigned(fOnMessageReceived) then fOnMessageReceived(wFrom, wMessage); end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.ProcessPresenceResponse Arguments: AResponse: PxmlNode Result: None -------------------------------------------------------------------------------} procedure TfmxJabberXml.ProcessPresenceResponse(AResponse: PxmlNode); var wFrom : string; wTo : string; wMessage : string; wStatus : TUserStatus; wShow : string; begin wStatus := usInVisible; if CompareText(AResponse.NodeName, 'presence') = 0 then begin wFrom := AResponse.Attributes['from']; wTo := AResponse.Attributes['to']; if AResponse.Attributes['type'] ='subscribe' then begin if assigned(fOnAskedForSubscription) then fOnAskedForSubscription(wFrom); end else if AResponse.Attributes['type'] ='subscribed' then begin if Assigned(fOnAskToAddRosterStatus) then fOnAskToAddRosterStatus(wFrom, True); end else if AResponse.Attributes['type'] ='unsubscribed' then begin if Assigned(fOnAskToAddRosterStatus) then fOnAskToAddRosterStatus(wFrom, False); end; if AResponse.SelectNode('Status') <> nil then if AResponse.SelectNode('Status').HasChildNodes then wMessage := AResponse.SelectNode('Status').childnodes[0].nodevalue; if AResponse.SelectNode('show') <> nil then if AResponse.SelectNode('show').HasChildNodes then wShow := AResponse.SelectNode('show').childnodes[0].nodevalue; if wShow = '' then wStatus := usOnline else if wShow = 'away' then wStatus := usAway else if wShow = 'dnd' then wStatus := usDNotDistrub else if wShow = 'chat' then wStatus := usFreeForChat else if wShow = 'xa' then wStatus := usExtendedAway; end; if assigned(fOnPresenceCallback) then fOnPresenceCallback(wFrom, wTo,wMessage, wStatus); end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.ProcessSASLResponse Arguments: AResponse: PxmlNode Result: None -------------------------------------------------------------------------------} procedure TfmxJabberXml.ProcessSASLResponse(AResponse: PxmlNode); var wCrypted : String; begin try wCrypted := AResponse.ChildNodes[0].NodeValue; if Assigned(fOnCryptedSASL) then fOnCryptedSASL(wCrypted); except On E:Exception do Raise Exception.create('[TfmxJabberXml.ProcessSASLResponse] : '+E.message); end; end; {------------------------------------------------------------------------------- Procedure: TfmxJabberXml.ProcessSASLSuccessResponse Arguments: AResponse: PxmlNode Result: None -------------------------------------------------------------------------------} procedure TfmxJabberXml.ProcessSASLSuccessResponse(AResponse: PxmlNode); begin try fAlreadyLogged := True; if CompareText(AResponse.Attributes['xmlns'] , XMLNS_XMPP_SASL ) = 0 then if Assigned(fOnSuccessSASL) then fOnSuccessSASL('<stream:stream xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams" to="%s" version="1.0">'); except On E:Exception do Raise Exception.create('[TfmxJabberXml.ProcessSASLSuccessResponse] : '+E.message); end; end; end.
unit ConnectingWindow; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ColoredGauge, BlockTicker, ExtCtrls, InternationalizerComponent; type TConnectingWin = class(TForm) VUGauge: TColorGauge; BlockTicker: TBlockTicker; Timer: TTimer; InternationalizerComponent1: TInternationalizerComponent; procedure TimerTimer(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormHide(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private fTimeout : integer; fMaxTimeout : integer; private procedure SetMaxTimeout( value : integer ); public property Timeout : integer read fTimeout write fTimeout; property MaxTimeout : integer read fMaxTimeout write SetMaxTimeout; public procedure Display( msg : string ); end; var ConnectingWin: TConnectingWin; implementation {$R *.DFM} uses MathUtils; procedure TConnectingWin.TimerTimer(Sender: TObject); begin BlockTicker.Tick; if fMaxTimeout > 0 then begin inc( fTimeout, Timer.Interval ); VUGauge.Position := min( 100, 100*fTimeout div fMaxTimeout ); end; end; procedure TConnectingWin.FormShow(Sender: TObject); begin Timer.Enabled := true; end; procedure TConnectingWin.SetMaxTimeout( value : integer ); var str : string; begin fMaxTimeout := value; fTimeout := 0; str := BlockTicker.Caption; BlockTicker.Caption := ''; BlockTicker.Caption := str; VUGauge.Position := 0; end; procedure TConnectingWin.Display( msg : string ); begin BlockTicker.Caption := msg; Show; end; procedure TConnectingWin.FormHide(Sender: TObject); begin Timer.Enabled := false; end; procedure TConnectingWin.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; end.
unit MergeRouteRequestUnit; interface uses REST.Json.Types, GenericParametersUnit, CommonTypesUnit; type TMergeRouteRequest = class(TGenericParameters) private [JSONName('route_ids')] FRouteIds: TStringArray; public property RouteIds: TStringArray read FRouteIds write FRouteIds; end; implementation end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: François PIETTE Description: TWSocket class encapsulate the Windows Socket paradigm EMail: francois.piette@pophost.eunet.be francois.piette@rtfm.be http://www.rtfm.be/fpiette Creation: April 1996 Version: 4.04 Support: Use the mailing list twsocket@rtfm.be See website for details. Legal issues: Copyright (C) 1996, 1997, 1998, 1999 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@pophost.eunet.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. History: Jul 18, 1996 Move all low level socket to winsock to be Delphi 2.x compatible Sep 18, 1996 Use structured exception for handling errors Sep 19, 1996 Check csDestroying before invoking event handler Nov 04, 1996 Better error handling Jan 31, 1997 Changed property assignation for Addr, Port and Proto Added notification handler Feb 14, 1997 Corrected bug in property assignation for Addr, Port and Proto Mar 26, 1997 Make UDP protocol work correctly Enable UDP broadcasting by using addr 255.255.255.255 Apr 1, 1997 Added class function when independent of any open socket Moved InitData as global Added ReceivedFrom function Added ResolveHost function Jul 22, 1997 Adapted to Delphi 3 which has a modified winsock.accept Aug 13, 1997 'sin' member made public Aug 24, 1997 Create the only help Makes writing HSocket the same as calling Dup. Sep 5, 1997 Version 2.01, added WinsockInfo function Sep 21, 1997 Version 2.02, make it really thread safe created global WSocketVersion Sep 25, 1997 Version 2.04, port to C++Builder Sep 27, 1997 Version 2.05. All class methods converted to global procedure or function because C++Builder do not like class method very much. Old class method New global function ---------------- ------------------- WinsockInfo WinsockInfo SocketErrorDesc WSocketErrorDesc GetHostByAddr WSocketGetHostByAddr GetHostByName WSocketGetHostByName ResolveHost WSocketResolveHost HostName LocalHostName Oct 02, 1997 V2.06 Added a check in destructor to avoid calling WSACleanup at design time which crashes the excellent Eagle Software CDK. Oct 16, 1997 V2.07 Added PortNum property with numeric value for Port. Added RcvdCount property to return the number of characters received in the buffer but not read yet. Do not confuse with ReadCount which returns the number of chars already received. Added a check for FWait assignation in front of ReadLine Prefixed each TSocketState value by 'ws' to avoid name conflict. Moved FHSocket member to private section because the property HSocket does the right job. Added a check for state closed when changing Port, Proto and Addr. Oct 22, 1997 V2.08 Added Flush method (asked by john@nexnix.co.uk) and FlushTimeout property (default to 60 seconds). Oct 22, 1997 V2.09 Added SendFlags property to enable sending in or out of band data (normal or urgent, see RFC-1122) Oct 28, 1997 V2.10 Added an OnLineTooLong event and code to handle the case where ReadLine has been called and the buffer overflowed (line long) Oct 29, 1997 V2.11 Added DnsLookup functionnality (DnsLookup method, DnsResult property and DnsLookupDone event). Calling the connect method with a hostname work well except that it could block for a long period (ie: 2 minutes) if DNS do not respond. Calling the connect method with a numeric IP address will never block. So you can call DnsLookup to start hostname resolution in the background, after some time you evenutually receive the OnDnsLookupDone event. The copy the DnsResult property to the Addr property and call connect. Oct 30, 1997 V2.12 added a check in DnsLookup to handel numeric IP which do not require any lookup. The numeric IP is treated immediately and immediately trigger the DnsLookupDone event. I modified the code to be compatible with Delphi 1. Oct 31, 1997 V2.13 added CancelDnsLookup procedure. Nov 09, 1997 V2.14 add LocalIPList function to get the list of local IP addresses (you have two IP addresses when connected to a LAN and an ISP). Nov 11, 1997 V2.15 Made TCustomWSocket with virtual functions. This will allow to easily descend a new component from TCustomWSocket. Make ReadLine stop when the connection is broken. Nov 12, 1997 V2.16 Corrected bug (Justin Yunke <yunke@productivity.org>) in LocalIPList: phe should be checked for nil. Nov 18, 1997 Added ReceiveStr function (Suggested by FLDKNHA@danisco.com) Nov 30, 1997 V2.18 Added a call to OnDnsLookupDone when canceling. Dec 04, 1997 V2.19 Added LocalPort property and SessionConnected event for UDP socket. V2.20 Modified MessageLoop and ProcessMessages to process not only the socket messages, but all messages (necessary if the thread has several TWSocket for example). Dec 09, 1997 V2.21 Corrected a minor bug in ReceiveStr. Detected by david@e.co.za (David Butler). Dec 10, 1997 V2.22 Corrected a minor bug in Send which now correctly returns the number of bytes sent. Detected by james.huggins@blockbuster.com Dec 16, 1997 V2.23 Corrected a bug which prevented the receiving of datagram from a UDP socket. Thank to Mark Melvin (melvin@misrg.ml.org) for pointing it. Dec 20, 1997 V2.24 Added the PeekData function as suggested by Matt Rose mcrose@avproinc.com Dec 26, 1997 V2.25 Added the Text property as suggested by Daniel P. Stasinski <dse@pacific.net>. Made GetXPort work even when listening as suggested by is81024@cis.nctu.edu.tw. Jan 10, 1998 V2.26 Check for null hostname in DNSLookup Added DnsResultList with all IP addresses returned form DNS Jan 13, 1998 V2.27 a Added MultiThreaaded property to tell the component that it is working in a thread and should take care of it (call internal ProcessMessages in place of Application.ProcessMessages, and do not use the WaitCtrl object). Jan 15, 1998 V2.28 WMAsyncSelect revisited to work properly with NT winsock 2. Feb 10, 1998 V2.29 Added an OnError event. If not assigned, then the component raise an exception when the error occurs. Feb 14, 1998 V2.30 Published Text property Feb 16, 1998 V2.31 Added virtual methods to trigger events Renamed all event handler variable to begin with FOn Feb 26, 1998 V2.32 Added procedure PutDataInSendBuffer and PutStringInSendBuffer Using PutDataInSendBuffer you can place data in the send buffer without actualy trying to send it. This allows to place several (probably small) data chunk before the component attempt to send it. This prevent small packet to be sent. You can call Send(nil, 0) to force the component to begin to send data. If the buffer was not empty, PutDataInSendBuffer will just queue data to the buffer. This data will be sent in sequence. Mar 02, 1998 V2.33 Changed the error check with WSAstartup as pointed out by Donald Strenczewilk (dstrenz@servtech.com) Mar 06, 1998 V2.34 Added a runtime property to change the buffer size. Mar 27, 1998 V2.35 Adapted for C++Builder 3 Apr 08, 1998 V2.36 Made SetDefaultValue virtual Apr 13, 1998 V2.37 Reset FDnsLookupHandle to 0 after a failed call to WSACancelAsyncRequest Apr 22, 1998 V2.38 Published AllSent property to let outside know if our buffer has some data unsent. Apr 28, 1998 V2.39 Added LingerOnOff and LingerTimeout. Default values are wsLingerOn and timeout = 0 to behave by default as before. This value is setup just before Connect. Call SetLingerOption to set the linger option on the fly (the connection must be established to set the option). See winsock.closesocket on line help (winsock.hlp or win32.hlp) for a dsicussion of this option usage. May 06, 1998 V2.40 Added a workaround for Trumpet winsock inet_addr bug. Thanks to Andrej Cuckov <andrej@cuckov.com> for his code. May 18, 1998 V2.41 Jan Tomasek <xtomasej@feld.cvut.cz> found that Trumpet Winsock (Win 3.11) has some bugs and suggested a workaround in TryToSend procedure. This workaround makes TWSocket blocking in some cases. A new property enables the workaround. See code. Jun 01, 1998 V2.42 In finalization section, check for not assigned IPList. Jun 15, 1998 V2.43 Added code to finalization section to unload winsock if still loaded at that point (this happend if no socket where created but WinsockInfo called). Suggested by Daniel Fazekas <fdsoft@dns.gyor-ph.hu> Jun 27, 1998 V2.44 Added checks for valid arguments in SetPort, SetProto and SetAddr. Deferred address resolution until Connect or Listen. Jul 08, 1998 V2.45 Adadpted for Delphi 4 Jul 20, 1998 V2.46 Added SetWindowLong(FWindowHandle, 0, 0) in the destructor and a check for TWSocket class in XSocketWindowProc. Added virtual method RealSend. Jul 23, 1998 V2.47 Added a TriggerSessionClosed from TryToSend in case of send error. This was called before, but with a nul error argument. Now it correctly gives the error number. Added a trashcan to receive data if no OnDataAvailable event handler is installed. Just receive the data and throw it away. Added reverse dns lookup asynchronous code (IP -> HostName). Thanks to Daniel Fazekas <fdsoft@dns.gyor-ph.hu> for his code. Jul 30, 1998 V2.48 Changed local variable "error" by FLastError in SocketError to make it available from the OnError handler. Thanks to dana@medical-info.com for finding this bug. In Abort procedure, deleted all buffered data because it was send the next time the socket is opened ! Added CancelDnsLookup in Abort procedure. Aug 28, 1998 V2.49 Made InternalClose and ReceiveStr virtual Sep 01, 1998 V2.50 Ignore CancelDnsLookup exception during destroy Sep 29, 1998 V2.51 In InternalClose, protect AssignDefaultValue with try/except because SessionClosed event handler may have destroyed the component. Oct 11, 1998 V2.52 Changed Shutdown(2) to Shutdown(1) in Internal Close to prevent data lost on send. You may have to call Shutdown(2) in your own code before calling Close to have the same behaviour as before. Changed argument type for ASyncReceive and passed 0 from FD_CLOSE message handler. Oct 28, 1998 V2.53 Made WSocketLoadWinsock and WSocketUnloadWinsock public. Nov 11, 1998 V2.54 Added OnDisplay event for debugging purpose Nov 16, 1998 V2.55 Ignore WSANOTINITIALIZED error calling CloseSocket. This occurs when using TWSocket from a DLL and the finalization section is called before destroying TWSocket components (this is a program logic error). Made some properties and methods protected instead of private. Made some methods virtual. Added an Error argument to InternalClose. Added DoRecv virtual function. Added WSocketResolvePort Added WSocketResolveProto Deferred port and protocol resolution until really needed Transformed Listen to procedure (in case of failure Listen always calls SocketError which triggers an exception or the OnError event). Nov 22, 1998 V3.00 Skipped from V2.55 to V3.00. Socks support is major update! Added SOCKS5 support for TCP connection and simple usercode paswword authentication. Consider the socks code as beta ! New properties: SocksServer, SocksPort, SocksUsercode, SocksPassword, FSocksAuthentication. New events: OnSocksError, OnSocksConnected, OnSocksAuthState. I used WinGate 2.1d to test my code. Unfortunately WinGate do not correctly handle user authentication, so the code here is just untested... Dec 05, 1998 V3.10 Removed ReadLine feature using TWait component. Added new TCustomLineWSocket and TCustomSyncWSocket. Those modifications implies that the ReadLine functionnality is slightly changed. Notably, the end of line marker is now configurable and remains in the received line unless a timeout occurs or the buffer is too small. Dec 10, 1998 V3.11 Added missing code to resolve port in the Listen method. Dec 12, 1998 V3.12 Added write method for LocalPort property. Thanks to Jan Tomasek <xtomasej@feld.cvut.cz> for his code. Added background exception handling. Fixed a bug in TCustomLineWSocket.TriggerDataAvailable which was not calling the inherited function when it actually should. Added a check on multithreaded in WaitForClose to call the correct ProcessMessages procedure. Added SOCKS4 support (only tcp connect is supported). Dec 28, 1998 V3.13 Changed WSocketResolveHost to check for invalid numeric IP addresses whitout trying to use them as hostnames. Dec 30, 1998 V3.14 Changed SetPort to SetRemotePort to solve the SetPort syndrome with BCB. Also chnaged GetPort to be consistant. Jan 12, 1999 V3.15 Introduced DoRecvFrom virtual function. This correct a bug introduced in V3.14 related to UDP and RecvFrom. Jan 23, 1999 V3.16 Changed FRcvdFlag computation in DoRecv and DoRecvFrom because it caused problems with HTTP component and large blocks. Removed modification by Jan Tomasek in TriggerDataAvailable Jan 30, 1999 V3.17 Added WSocketResolveIp function. Checked for tcp protocol before setting linger off in abort. Moved a lot of variables from private to protected sections. Removed check for Assigned(FOnDataSent) in WMASyncSelect. Feb 03, 1999 V3.18 Removed useless units in the uses clause. Feb 14, 1999 V4.00 Jump to next major version number because lots of fundamental changes have been done. See below. Use runtime dynamic link with winsock. All winsock functions used by TWSocket are linked at runtime instead of loadtime. This allows programs to run without winsock installed, provided program doesn't try to use TWSocket or winsock function without first checking for winsock installation. Removed WSocketLoadWinsock and all use to DllStarted because it is no longer necessary because winsock is automatically loaded and initialized with the first call to a winsock function. Added MessagePump to centralize call to the message pump. It is a virtual procedure so that you can override it to cutomize your message pump. Also changed slightly ProcessMessages to closely match what is done in the forms unit. Removed old stuff related to WaitCtrl (was already excluded from compilation using a conditional directive). Added NOFORMS conditional compilation to exclude the Forms unit from wsocket. This will reduce exe or dll size by 100 to 150KB. To use this feature, you have to add NOFORMS in your project options in the "defines" edit box in the "directory/conditional" tab. Then you must add a message pump to your application and call it from TWSocket.OnMessagePump event handler. TWSocket really need a message pump in order to receive messages from winsock. Depending on how your application is built, you can use either TWSocket.MessageLoop or TWSocket.ProcessMessages to quickly build a working message pump. Or you may build your own custom message pump taylored to your needs. Your message pump must set TWSocket.Terminated property to TRUE when your application terminates or you may experience long delays when closing your application. You may use NOFORMS setting even if you use the forms unit (GUI application). Simply call Application.ProcessMessages in the OnMessagePump event handler. OnMessagePump event is not visible in the object inspector. You must assign it at run-time before using the component and after having created it (in a GUI application you can do that in the FormCreate event, in a console application, you can do it right after TWSocket.Create call). Feb 17, 1999 V4.01 Added LineEcho and LineEdit features. Feb 27, 1999 V4.02 Added TCustomLineWSocket.GetRcvdCount to make RcvdCount property and ReceiveStr work in line mode. Mar 01, 1999 V4.03 Added conditional compile for BCB4. Thanks to James Legg <jlegg@iname.com>. Mar 14, 1999 V4.04 Corrected a bug: wsocket hangup when there was no OnDataAvailable handler and line mode was on. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit WSocket; {$B-} { Enable partial boolean evaluation } {$T-} { Untyped pointers } {$IFNDEF VER80} { Not for Delphi 1 } {$J+} { Allow typed constant to be modified } {$ENDIF} {$IFDEF VER110} { C++ Builder V3.0 } {$ObjExportAll On} {$ENDIF} interface uses WinTypes, WinProcs, Messages, Classes, SysUtils, {$IFNDEF NOFORMS} { See comments in history at 14/02/99 } Forms, {$ENDIF} WSockBuf, WinSock; const WSocketVersion = 403; CopyRight : String = ' TWSocket (c) 96-99 F. Piette V4.03 '; WM_ASYNCSELECT = WM_USER + 1; WM_ASYNCGETHOSTBYNAME = WM_USER + 2; WM_ASYNCGETHOSTBYADDR = WM_USER + 3; WM_TRIGGER_DATA_AVAILABLE = WM_USER + 20; WSA_WSOCKET_TIMEOUT = 12001; {$IFDEF WIN32} winsocket = 'wsock32.dll'; { 32 bits TCP/IP system DLL } {$ELSE} winsocket = 'winsock.dll'; { 16 bits TCP/IP system DLL } {$ENDIF} type ESocketException = class(Exception); TBgExceptionEvent = procedure (Sender : TObject; E : Exception; var CanClose : Boolean) of object; TSocketState = (wsInvalidState, wsOpened, wsBound, wsConnecting, wsConnected, wsAccepting, wsListening, wsClosed); TSocketSendFlags = (wsSendNormal, wsSendUrgent); TSocketLingerOnOff = (wsLingerOff, wsLingerOn, wsLingerNoSet); TDataAvailable = procedure (Sender: TObject; Error: word) of object; TDataSent = procedure (Sender: TObject; Error: word) of object; TSessionClosed = procedure (Sender: TObject; Error: word) of object; TSessionAvailable = procedure (Sender: TObject; Error: word) of object; TSessionConnected = procedure (Sender: TObject; Error: word) of object; TDnsLookupDone = procedure (Sender: TObject; Error: Word) of object; TChangeState = procedure (Sender: TObject; OldState, NewState : TSocketState) of object; TDebugDisplay = procedure (Sender: TObject; var Msg : String) of object; TWSocketSyncNextProc = procedure of object; {$IFDEF VER110} { C++Builder V3 } TSocket = integer; {$ENDIF} TCustomWSocket = class(TComponent) private FDnsResult : String; FDnsResultList : TStrings; FASocket : TSocket; { Accepted socket } FBufList : TList; FBufSize : Integer; FSendFlags : Integer; FLastError : Integer; FWindowHandle : HWND; FDnsLookupBuffer : array [0..MAXGETHOSTSTRUCT] of char; FDnsLookupHandle : THandle; {$IFDEF VER80} FTrumpetCompability : Boolean; {$ENDIF} protected FHSocket : TSocket; FAddrStr : String; FAddrResolved : Boolean; FAddrFormat : Integer; FAddrAssigned : Boolean; FProto : integer; FProtoAssigned : Boolean; FProtoResolved : Boolean; FLocalPortResolved : Boolean; FProtoStr : String; FPortStr : String; FPortAssigned : Boolean; FPortResolved : Boolean; FPortNum : Integer; FLocalPortStr : String; FLocalPortNum : Integer; FType : integer; FLingerOnOff : TSocketLingerOnOff; FLingerTimeout : Integer; { In seconds, 0 = disabled } ReadLineCount : Integer; bWrite : Boolean; nMoreCnt : Integer; bMoreFlag : Boolean; nMoreMax : Integer; bAllSent : Boolean; FReadCount : LongInt; FPaused : Boolean; FCloseInvoked : Boolean; FFlushTimeout : Integer; FMultiThreaded : Boolean; FState : TSocketState; FRcvdFlag : Boolean; FTerminated : Boolean; FOnSessionAvailable : TSessionAvailable; FOnSessionConnected : TSessionConnected; FOnSessionClosed : TSessionClosed; FOnChangeState : TChangeState; FOnDataAvailable : TDataAvailable; FOnDataSent : TDataSent; FOnLineTooLong : TNotifyEvent; FOnDnsLookupDone : TDnsLookupDone; FOnError : TNotifyEvent; FOnBgException : TBgExceptionEvent; FOnDisplay : TDebugDisplay; FOnMessagePump : TNotifyEvent; procedure WndProc(var MsgRec: TMessage); virtual; procedure SocketError(sockfunc: string); procedure WMASyncSelect(var msg: TMessage); message WM_ASYNCSELECT; procedure WMAsyncGetHostByName(var msg: TMessage); message WM_ASYNCGETHOSTBYNAME; procedure WMAsyncGetHostByAddr(var msg: TMessage); message WM_ASYNCGETHOSTBYADDR; procedure ChangeState(NewState : TSocketState); procedure TryToSend; procedure ASyncReceive(Error : Word); procedure AssignDefaultValue; virtual; procedure InternalClose(bShut : Boolean; Error : Word); virtual; procedure Notification(AComponent: TComponent; operation: TOperation); override; procedure SetSendFlags(newValue : TSocketSendFlags); function GetSendFlags : TSocketSendFlags; procedure SetAddr(InAddr : String); function GetAddr : String; procedure SetRemotePort(sPort : String); virtual; function GetRemotePort : String; procedure SetLocalPort(sLocalPort : String); procedure SetProto(sProto : String); virtual; function GetProto : String; function GetRcvdCount : LongInt; virtual; procedure BindSocket; virtual; procedure SendText(Str : String); function RealSend(Data : Pointer; Len : Integer) : Integer; virtual; procedure RaiseExceptionFmt(const Fmt : String; args : array of const); virtual; procedure RaiseException(const Msg : String); virtual; procedure HandleBackGroundException(E: Exception); virtual; procedure TriggerDisplay(Msg : String); function TriggerDataAvailable(Error : Word) : Boolean; virtual; procedure TriggerSessionAvailable(Error : Word); virtual; procedure TriggerSessionConnected(Error : Word); virtual; procedure TriggerSessionClosed(Error : Word); virtual; procedure TriggerDataSent(Error : Word); virtual; procedure TriggerChangeState(OldState, NewState : TSocketState); virtual; procedure TriggerDNSLookupDone(Error : Word); virtual; procedure TriggerError; virtual; function DoRecv(var Buffer; BufferSize : Integer; Flags : Integer) : Integer; virtual; function DoRecvFrom(FHSocket : TSocket; var Buffer; BufferSize : Integer; Flags : Integer; var From : TSockAddr; var FromLen : Integer) : Integer; virtual; public sin : TSockAddrIn; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Connect; virtual; procedure Close; virtual; procedure Abort; virtual; procedure Flush; virtual; procedure WaitForClose; virtual; procedure Listen; virtual; function Accept: TSocket; virtual; function Receive(Buffer : Pointer; BufferSize: integer) : integer; virtual; function ReceiveStr : string; virtual; function ReceiveFrom(Buffer : Pointer; BufferSize : Integer; var From : TSockAddr; var FromLen : Integer) : integer; virtual; function PeekData(Buffer : Pointer; BufferSize: integer) : integer; function Send(Data : Pointer; Len : Integer) : integer; virtual; function SendTo(Dest : TSockAddr; DestLen : Integer; Data : Pointer; Len : Integer) : integer; virtual; function SendStr(Str : String) : Integer; virtual; procedure DnsLookup(HostName : String); virtual; procedure ReverseDnsLookup(HostAddr: String); virtual; procedure CancelDnsLookup; virtual; function GetPeerAddr: string; virtual; function GetPeerName(var Name : TSockAddrIn; NameLen : Integer) : integer; virtual; function GetXPort: string; virtual; function TimerIsSet(var tvp : TTimeVal) : Boolean; virtual; procedure TimerClear(var tvp : TTimeVal); virtual; function TimerCmp(var tvp : TTimeVal; var uvp : TTimeVal; IsEqual : Boolean) : Boolean; virtual; function GetSockName(var saddr : TSockAddrIn; var saddrlen : Integer) : integer; virtual; procedure SetLingerOption; procedure Dup(NewHSocket : TSocket); virtual; procedure Shutdown(How : Integer); virtual; procedure Pause; virtual; procedure Resume; virtual; procedure PutDataInSendBuffer(Data : Pointer; Len : Integer); procedure PutStringInSendBuffer(Str : String); procedure DeleteBufferedData; procedure MessagePump; virtual; {$IFNDEF VER80} procedure MessageLoop; function ProcessMessage : Boolean; procedure ProcessMessages; {$ENDIF} {$IFDEF NOFORMS} property Terminated : Boolean read FTerminated write FTerminated; property OnMessagePump : TNotifyEvent read FOnMessagePump write FOnMessagePump; {$ENDIF} protected property PortNum : Integer read FPortNum; property Handle : HWND read FWindowHandle; property HSocket : TSocket read FHSocket write Dup; property Addr : string read GetAddr write SetAddr; property Port : string read GetRemotePort write SetRemotePort; property LocalPort : string read FLocalPortStr write SetLocalPort; property Proto : String read GetProto write SetProto; property MultiThreaded : Boolean read FMultiThreaded write FMultiThreaded; property DnsResult : String read FDnsResult; property DnsResultList : TStrings read FDnsResultList; property State : TSocketState read FState; property AllSent : Boolean read bAllSent; property ReadCount : LongInt read FReadCount; property RcvdCount : LongInt read GetRcvdCount; property LastError : Integer read FLastError; property BufSize : Integer read FBufSize write FBufSize; property OnDataAvailable : TDataAvailable read FOnDataAvailable write FOnDataAvailable; property OnDataSent : TDataSent read FOnDataSent write FOnDataSent; property OnSessionClosed : TSessionClosed read FOnSessionClosed write FOnSessionClosed; property OnSessionAvailable : TSessionAvailable read FOnSessionAvailable write FOnSessionAvailable; property OnSessionConnected : TSessionConnected read FOnSessionConnected write FOnSessionConnected; property OnChangeState : TChangeState read FOnChangeState write FOnChangeState; property OnLineTooLong : TNotifyEvent read FOnLineTooLong write FOnLineTooLong; property OnDnsLookupDone : TDnsLookupDone read FOnDnsLookupDone write FOnDnsLookupDone; property OnError : TNotifyEvent read FOnError write FOnError; property OnBgException : TBgExceptionEvent read FOnBgException write FOnBgException; property FlushTimeout : Integer read FFlushTimeOut write FFlushTimeout; property SendFlags : TSocketSendFlags read GetSendFlags write SetSendFlags; property Text: String read ReceiveStr write SendText; property LingerOnOff : TSocketLingerOnOff read FLingerOnOff write FLingerOnOff; property LingerTimeout : Integer read FLingerTimeout write FLingerTimeout; {$IFDEF VER80} property TrumpetCompability : Boolean read FTrumpetCompability write FTrumpetCompability; {$ENDIF} property OnDisplay : TDebugDisplay read FOnDisplay write FOnDisplay; end; TSocksState = (socksData, socksNegociateMethods, socksAuthenticate, socksConnect); TSocksAuthentication = (socksNoAuthentication, socksAuthenticateUsercode); TSocksAuthState = (socksAuthStart, socksAuthSuccess, socksAuthFailure, socksAuthNotRequired); TSocksAuthStateEvent = procedure(Sender : TObject; AuthState : TSocksAuthState) of object; TSocksErrorEvent = procedure(Sender : TObject; Error : Integer; Msg : String) of Object; TCustomSocksWSocket = class(TCustomWSocket) protected FSocksState : TSocksState; FSocksServer : String; FSocksLevel : String; FSocksPort : String; FSocksPortAssigned : Boolean; FSocksServerAssigned : Boolean; FSocksUsercode : String; FSocksPassword : String; FSocksAuthentication : TSocksAuthentication; FSocksAuthNumber : char; FBoundAddr : String; FBoundPort : String; FRcvBuf : array [0..127] of char; FRcvCnt : Integer; FRcvdCnt : Integer; FRcvdPtr : PChar; FOnSocksError : TSocksErrorEvent; FOnSocksConnected : TSessionConnected; FOnSocksAuthState : TSocksAuthStateEvent; procedure AssignDefaultValue; override; procedure TriggerSessionConnected(Error : Word); override; procedure TriggerSocksConnected(Error : Word); virtual; procedure TriggerSessionClosed(Error : Word); override; function TriggerDataAvailable(Error : Word) : Boolean; override; procedure SetSocksPort(sPort : String); virtual; procedure SetSocksServer(sServer : String); virtual; procedure TriggerSocksError(Error : Integer; Msg : String); virtual; procedure TriggerSocksAuthState(AuthState : TSocksAuthState); function GetRcvdCount : LongInt; override; procedure SetSocksLevel(newValue : String); function DoRecv(var Buffer; BufferSize : Integer; Flags : Integer) : Integer; override; procedure SocksDoConnect; procedure SocksDoAuthenticate; procedure DataAvailableError(ErrCode : Integer; Msg : String); public procedure Connect; override; procedure Listen; override; protected property SocksServer : String read FSocksServer write SetSocksServer; property SocksLevel : String read FSocksLevel write SetSocksLevel; property SocksPort : String read FSocksPort write SetSocksPort; property SocksUsercode : String read FSocksUsercode write FSocksUsercode; property SocksPassword : String read FSocksPassword write FSocksPassword; property SocksAuthentication : TSocksAuthentication read FSocksAuthentication write FSocksAuthentication; property OnSocksError : TSocksErrorEvent read FOnSocksError write FOnSocksError; property OnSocksConnected : TSessionConnected read FOnSocksConnected write FOnSocksConnected; property OnSocksAuthState : TSocksAuthStateEvent read FOnSocksAuthState write FOnSocksAuthState; end; TCustomLineWSocket = class (TCustomSocksWSocket) protected FRcvdPtr : PChar; FRcvBufSize : Integer; FRcvdCnt : Integer; FLineEnd : String; FLineMode : Boolean; FLineLength : Integer; { When a line is available } FLineReceivedFlag : Boolean; FLineEcho : Boolean; { Echo received data } FLineEdit : Boolean; { Edit received data } FTimeout : LongInt; { Given in milliseconds } FTimeStop : LongInt; { Milliseconds } procedure WndProc(var MsgRec: TMessage); override; procedure WMTriggerDataAvailable(var msg: TMessage); message WM_TRIGGER_DATA_AVAILABLE; function TriggerDataAvailable(Error : Word) : Boolean; override; procedure TriggerSessionClosed(Error : Word); override; procedure SetLineMode(newValue : Boolean); virtual; procedure EditLine(var Len : Integer); virtual; function GetRcvdCount : LongInt; override; function DoRecv(var Buffer; BufferSize : Integer; Flags : Integer) : Integer; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property LineLength : Integer read FLineLength; published property LineMode : Boolean read FLineMode write SetLineMode; property LineEnd : String read FLineEnd write FLineEnd; property LineEcho : Boolean read FLineEcho write FLineEcho; property LineEdit : Boolean read FLineEdit write FLineEdit; end; TCustomSyncWSocket = class(TCustomLineWSocket) protected FLinePointer : ^String; function Synchronize(Proc : TWSocketSyncNextProc; var DoneFlag : Boolean) : Integer; virtual; function WaitUntilReady(var DoneFlag : Boolean) : Integer; virtual; procedure InternalDataAvailable(Sender: TObject; Error: Word); public procedure ReadLine(Timeout : integer; var Buffer : String); end; TWSocket = class(TCustomSyncWSocket) public property PortNum; property Handle; property HSocket; property BufSize; property Text; property AllSent; {$IFDEF VER80} property TrumpetCompability; {$ENDIF} property OnDisplay; published property Addr; property Port; property Proto; property LocalPort; property DnsResult; property DnsResultList; property State; property ReadCount; property RcvdCount; property LastError; property MultiThreaded; property OnDataAvailable; property OnDataSent; property OnSessionClosed; property OnSessionAvailable; property OnSessionConnected; property OnSocksConnected; property OnChangeState; property OnLineTooLong; property OnDnsLookupDone; property OnError; property OnBgException; property FlushTimeout; property SendFlags; property LingerOnOff; property LingerTimeout; property SocksLevel; property SocksServer; property SocksPort; property SocksUsercode; property SocksPassword; property SocksAuthentication; property OnSocksError; property OnSocksAuthState; end; TSocksWSocket = class(TWSocket) end; procedure Register; function WinsockInfo : TWSADATA; function WSocketErrorDesc(error: integer) : string; function WSocketGetHostByAddr(Addr : String) : PHostEnt; function WSocketGetHostByName(Name : String) : PHostEnt; function LocalHostName : String; function LocalIPList : TStrings; function WSocketResolveIp(IpAddr : String) : String; function WSocketResolveHost(InAddr : String) : TInAddr; function WSocketResolvePort(Port : String; Proto : String) : Word; function WSocketResolveProto(sProto : String) : integer; procedure WSocketUnloadWinsock; { function WSocketLoadWinsock : Boolean; 14/02/99 } type {$IFDEF VER80} DWORD = LongInt; TWSAStartup = function (wVersionRequired: word; var WSData: TWSAData): Integer; TWSACleanup = function : Integer; TWSASetLastError = procedure (iError: Integer); TWSAGetLastError = function : Integer; TWSACancelAsyncRequest = function (hAsyncTaskHandle: THandle): Integer; TWSAAsyncGetHostByName = function (HWindow: HWND; wMsg: u_int; name, buf: PChar; buflen: Integer): THandle; TWSAAsyncGetHostByAddr = function (HWindow: HWND; wMsg: u_int; addr: PChar; len, Struct: Integer; buf: PChar; buflen: Integer): THandle; TWSAAsyncSelect = function (s: TSocket; HWindow: HWND; wMsg: u_int; lEvent: Longint): Integer; TGetServByName = function (name, proto: PChar): PServEnt; TGetProtoByName = function (name: PChar): PProtoEnt; TGetHostByName = function (name: PChar): PHostEnt; TGetHostName = function (name: PChar; len: Integer): Integer; TOpenSocket = function (af, Struct, protocol: Integer): TSocket; TShutdown = function (s: TSocket; how: Integer): Integer; TSetSockOpt = function (s: TSocket; level, optname: Integer; optval: PChar; optlen: Integer): Integer; TGetSockOpt = function (s: TSocket; level, optname: Integer; optval: PChar; var optlen: Integer): Integer; TSendTo = function (s: TSocket; var Buf; len, flags: Integer; var addrto: TSockAddr; tolen: Integer): Integer; TSend = function (s: TSocket; var Buf; len, flags: Integer): Integer; TRecv = function (s: TSocket; var Buf; len, flags: Integer): Integer; TRecvFrom = function (s: TSocket; var Buf; len, flags: Integer; var from: TSockAddr; var fromlen: Integer): Integer; Tntohs = function (netshort: u_short): u_short; Tntohl = function (netlong: u_long): u_long; TListen = function (s: TSocket; backlog: Integer): Integer; TIoctlSocket = function (s: TSocket; cmd: DWORD; var arg: u_long): Integer; TInet_ntoa = function (inaddr: TInAddr): PChar; TInet_addr = function (cp: PChar): u_long; Thtons = function (hostshort: u_short): u_short; Thtonl = function (hostlong: u_long): u_long; TGetSockName = function (s: TSocket; var name: TSockAddr; var namelen: Integer): Integer; TGetPeerName = function (s: TSocket; var name: TSockAddr; var namelen: Integer): Integer; TConnect = function (s: TSocket; var name: TSockAddr; namelen: Integer): Integer; TCloseSocket = function (s: TSocket): Integer; TBind = function (s: TSocket; var addr: TSockAddr; namelen: Integer): Integer; TAccept = function (s: TSocket; var addr: TSockAddr; var addrlen: Integer): TSocket; {$ELSE} TWSAStartup = function (wVersionRequired: word; var WSData: TWSAData): Integer; stdcall; TWSACleanup = function : Integer; stdcall; TWSASetLastError = procedure (iError: Integer); stdcall; TWSAGetLastError = function : Integer; stdcall; TWSACancelAsyncRequest = function (hAsyncTaskHandle: THandle): Integer; stdcall; TWSAAsyncGetHostByName = function (HWindow: HWND; wMsg: u_int; name, buf: PChar; buflen: Integer): THandle; stdcall; TWSAAsyncGetHostByAddr = function (HWindow: HWND; wMsg: u_int; addr: PChar; len, Struct: Integer; buf: PChar; buflen: Integer): THandle; stdcall; TWSAAsyncSelect = function (s: TSocket; HWindow: HWND; wMsg: u_int; lEvent: Longint): Integer; stdcall; TGetServByName = function (name, proto: PChar): PServEnt; stdcall; TGetProtoByName = function (name: PChar): PProtoEnt; stdcall; TGetHostByName = function (name: PChar): PHostEnt; stdcall; TGetHostName = function (name: PChar; len: Integer): Integer; stdcall; TOpenSocket = function (af, Struct, protocol: Integer): TSocket; stdcall; TShutdown = function (s: TSocket; how: Integer): Integer; stdcall; TSetSockOpt = function (s: TSocket; level, optname: Integer; optval: PChar; optlen: Integer): Integer; stdcall; TGetSockOpt = function (s: TSocket; level, optname: Integer; optval: PChar; var optlen: Integer): Integer; stdcall; TSendTo = function (s: TSocket; var Buf; len, flags: Integer; var addrto: TSockAddr; tolen: Integer): Integer; stdcall; TSend = function (s: TSocket; var Buf; len, flags: Integer): Integer; stdcall; TRecv = function (s: TSocket; var Buf; len, flags: Integer): Integer; stdcall; TRecvFrom = function (s: TSocket; var Buf; len, flags: Integer; var from: TSockAddr; var fromlen: Integer): Integer; stdcall; Tntohs = function (netshort: u_short): u_short; stdcall; Tntohl = function (netlong: u_long): u_long; stdcall; TListen = function (s: TSocket; backlog: Integer): Integer; stdcall; TIoctlSocket = function (s: TSocket; cmd: DWORD; var arg: u_long): Integer; stdcall; TInet_ntoa = function (inaddr: TInAddr): PChar; stdcall; TInet_addr = function (cp: PChar): u_long; stdcall; Thtons = function (hostshort: u_short): u_short; stdcall; Thtonl = function (hostlong: u_long): u_long; stdcall; TGetSockName = function (s: TSocket; var name: TSockAddr; var namelen: Integer): Integer; stdcall; TGetPeerName = function (s: TSocket; var name: TSockAddr; var namelen: Integer): Integer; stdcall; TConnect = function (s: TSocket; var name: TSockAddr; namelen: Integer): Integer; stdcall; TCloseSocket = function (s: TSocket): Integer; stdcall; TBind = function (s: TSocket; var addr: TSockAddr; namelen: Integer): Integer; stdcall; {$IFDEF VER90} { Delphi 2 has a special definition} TAccept = function (s: TSocket; var addr: TSockAddr; var addrlen: Integer): TSocket; stdcall; {$ELSE} TAccept = function (s: TSocket; addr: PSockAddr; addrlen: PInteger): TSocket; stdcall; {$ENDIF} {$ENDIF} var FWSAStartup : TWSAStartup; FWSACleanup : TWSACleanup; FWSASetLastError : TWSASetLastError; FWSAGetLastError : TWSAGetLastError; FWSACancelAsyncRequest : TWSACancelAsyncRequest; FWSAAsyncGetHostByName : TWSAAsyncGetHostByName; FWSAAsyncGetHostByAddr : TWSAAsyncGetHostByAddr; FWSAAsyncSelect : TWSAAsyncSelect; FGetServByName : TGetServByName; FGetProtoByName : TGetProtoByName; FGetHostByName : TGetHostByName; FGetHostName : TGetHostName; FOpenSocket : TOpenSocket; FShutdown : TShutdown; FSetSockOpt : TSetSockOpt; FGetSockOpt : TGetSockOpt; FSendTo : TSendTo; FSend : TSend; FRecv : TRecv; FRecvFrom : TRecvFrom; Fntohs : Tntohs; Fntohl : Tntohl; FListen : TListen; FIoctlSocket : TIoctlSocket; FInet_ntoa : TInet_ntoa; FInet_addr : TInet_addr; Fhtons : Thtons; Fhtonl : Thtonl; FGetSockName : TGetSockName; FGetPeerName : TGetPeerName; FConnect : TConnect; FCloseSocket : TCloseSocket; FBind : TBind; FAccept : TAccept; function WSocketGetProc(const ProcName : String) : Pointer; function WSocket_WSAStartup(wVersionRequired: word; var WSData: TWSAData): Integer; function WSocket_WSACleanup : Integer; procedure WSocket_WSASetLastError(iError: Integer); function WSocket_WSAGetLastError: Integer; function WSocket_WSACancelAsyncRequest(hAsyncTaskHandle: THandle): Integer; function WSocket_WSAAsyncGetHostByName(HWindow: HWND; wMsg: u_int; name, buf: PChar; buflen: Integer): THandle; function WSocket_WSAAsyncGetHostByAddr(HWindow: HWND; wMsg: u_int; addr: PChar; len, Struct: Integer; buf: PChar; buflen: Integer): THandle; function WSocket_WSAAsyncSelect(s: TSocket; HWindow: HWND; wMsg: u_int; lEvent: Longint): Integer; function WSocket_recv(s: TSocket; var Buf; len, flags: Integer): Integer; function WSocket_recvfrom(s: TSocket; var Buf; len, flags: Integer; var from: TSockAddr; var fromlen: Integer): Integer; function WSocket_getservbyname(name, proto: PChar): PServEnt; function WSocket_getprotobyname(name: PChar): PProtoEnt; function WSocket_gethostbyname(name: PChar): PHostEnt; function WSocket_gethostname(name: PChar; len: Integer): Integer; function WSocket_socket(af, Struct, protocol: Integer): TSocket; function WSocket_shutdown(s: TSocket; how: Integer): Integer; function WSocket_setsockopt(s: TSocket; level, optname: Integer; optval: PChar; optlen: Integer): Integer; function WSocket_getsockopt(s: TSocket; level, optname: Integer; optval: PChar; var optlen: Integer): Integer; function WSocket_sendto(s: TSocket; var Buf; len, flags: Integer; var addrto: TSockAddr; tolen: Integer): Integer; function WSocket_send(s: TSocket; var Buf; len, flags: Integer): Integer; function WSocket_ntohs(netshort: u_short): u_short; function WSocket_ntohl(netlong: u_long): u_long; function WSocket_listen(s: TSocket; backlog: Integer): Integer; function WSocket_ioctlsocket(s: TSocket; cmd: DWORD; var arg: u_long): Integer; function WSocket_inet_ntoa(inaddr: TInAddr): PChar; function WSocket_inet_addr(cp: PChar): u_long; function WSocket_htons(hostshort: u_short): u_short; function WSocket_htonl(hostlong: u_long): u_long; function WSocket_getsockname(s: TSocket; var name: TSockAddr; var namelen: Integer): Integer; function WSocket_getpeername(s: TSocket; var name: TSockAddr; var namelen: Integer): Integer; function WSocket_connect(s: TSocket; var name: TSockAddr; namelen: Integer): Integer; function WSocket_closesocket(s: TSocket): Integer; function WSocket_bind(s: TSocket; var addr: TSockAddr; namelen: Integer): Integer; {$IFDEF VER80} function WSocket_accept(s: TSocket; var addr: TSockAddr; var addrlen: Integer): TSocket; {$ELSE} {$IFDEF VER90} function WSocket_accept(s: TSocket; var addr: TSockAddr; var addrlen: Integer): TSocket; {$ELSE} function WSocket_accept(s: TSocket; addr: PSockAddr; addrlen: PInteger): TSocket; {$ENDIF} {$ENDIF} implementation const GSocketCount : integer = 0; { DllStarted : Boolean = FALSE; 14/02/99} FDllHandle : THandle = 0; FDllName : String = winsocket; socksNoError = 20000; socksProtocolError = 20001; socksVersionError = 20002; socksAuthMethodError = 20003; socksGeneralFailure = 20004; socksConnectionNotAllowed = 20005; socksNetworkUnreachable = 20006; socksHostUnreachable = 20007; socksConnectionRefused = 20008; socksTtlExpired = 20009; socksUnknownCommand = 20010; socksUnknownAddressType = 20011; socksUnassignedError = 20012; socksInternalError = 20013; socksDataReceiveError = 20014; socksAuthenticationFailed = 20015; socksRejectedOrFailed = 20016; socksHostResolutionFailed = 20017; var GInitData : TWSADATA; IPList : TStrings; procedure Register; begin RegisterComponents('FPiette', [TWSocket]); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFDEF VER80} procedure SetLength(var S: string; NewLength: Integer); begin S[0] := chr(NewLength); end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function atoi(value : string) : Integer; var i : Integer; begin Result := 0; i := 1; while (i <= Length(Value)) and (Value[i] = ' ') do i := i + 1; while (i <= Length(Value)) and (Value[i] >= '0') and (Value[i] <= '9')do begin Result := Result * 10 + ord(Value[i]) - ord('0'); i := i + 1; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function IsDigit(Ch : Char) : Boolean; begin Result := (ch >= '0') and (ch <= '9'); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFDEF VER80} function TrimRight(Str : String) : String; var i : Integer; begin i := Length(Str); while (i > 0) and (Str[i] = ' ') do i := i - 1; Result := Copy(Str, 1, i); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TrimLeft(Str : String) : String; var i : Integer; begin if Str[1] <> ' ' then Result := Str else begin i := 1; while (i <= Length(Str)) and (Str[i] = ' ') do i := i + 1; Result := Copy(Str, i, Length(Str) - i + 1); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function Trim(Str : String) : String; begin Result := TrimLeft(TrimRight(Str)); end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.RaiseException(const Msg : String); begin if Assigned(FOnError) then TriggerError else raise ESocketException.Create(Msg); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.RaiseExceptionFmt(const Fmt : String; args : array of const); begin if Assigned(FOnError) then TriggerError else raise ESocketException.CreateFmt(Fmt, args); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFDEF NEVER} { 14/02/99 } function LoadWinsock(FileName : PChar) : Boolean; var LastError : LongInt; begin if not DllStarted then begin LastError := WSocket_WSAStartup($101, GInitData); if LastError <> 0 then begin raise ESocketException.CreateFmt('%s: WSAStartup error #%d', [FileName, LastError]); end; DllStarted := TRUE; end; Result := TRUE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocketLoadWinsock : Boolean; begin Result := LoadWinsock(winsocket); end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure WSocketUnloadWinsock; begin {$IFDEF NEVER} { 14/02/99 } if DllStarted then begin DllStarted := FALSE; WSocket_WSACleanup; end; {$ENDIF} if FDllHandle <> 0 then begin WSocket_WSACleanup; FreeLibrary(FDllHandle); FDllHandle := 0; FWSAStartup := nil; FWSACleanup := nil; FWSASetLastError := nil; FWSAGetLastError := nil; FWSACancelAsyncRequest := nil; FWSAAsyncGetHostByName := nil; FWSAAsyncGetHostByAddr := nil; FWSAAsyncSelect := nil; FGetServByName := nil; FGetProtoByName := nil; FGetHostByName := nil; FGetHostName := nil; FOpenSocket := nil; FShutdown := nil; FSetSockOpt := nil; FGetSockOpt := nil; FSendTo := nil; FSend := nil; FRecv := nil; FRecvFrom := nil; Fntohs := nil; Fntohl := nil; FListen := nil; FIoctlSocket := nil; FInet_ntoa := nil; FInet_addr := nil; Fhtons := nil; Fhtonl := nil; FGetSockName := nil; FGetPeerName := nil; FConnect := nil; FCloseSocket := nil; FBind := nil; FAccept := nil; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocketGetProc(const ProcName : String) : Pointer; {$IFDEF VER80} var Error : THandle; Buf : String; LastError : LongInt; begin if FDllHandle = 0 then begin { Delphi 1 strings are not nul terminated } Buf := FDllName + #0; FDllHandle := LoadLibrary(@Buf[1]); if FDllHandle < HINSTANCE_ERROR then begin Error := FDllHandle; FDllHandle := 0; raise ESocketException.Create('Unable to load ' + FDllName + ' Error #' + IntToStr(Error)); end; LastError := WSocket_WSAStartup($101, GInitData); if LastError <> 0 then begin raise ESocketException.CreateFmt('%s: WSAStartup error #%d', [FDllName, LastError]); end; end; if Length(ProcName) = 0 then Result := nil else begin { Delphi 1 strings are not nul terminated } Buf := ProcName + #0; Result := GetProcAddress(FDllHandle, @Buf[1]); if Result = nil then raise ESocketException.Create('Procedure ' + ProcName + ' not found in ' + FDllName); end; end; {$ELSE} var LastError : LongInt; begin if FDllHandle = 0 then begin FDllHandle := LoadLibrary(@FDllName[1]); if FDllHandle = 0 then raise ESocketException.Create('Unable to load ' + FDllName + ' Error #' + IntToStr(GetLastError)); LastError := WSocket_WSAStartup($101, GInitData); if LastError <> 0 then begin raise ESocketException.CreateFmt('%s: WSAStartup error #%d', [FDllName, LastError]); end; end; if Length(ProcName) = 0 then Result := nil else begin Result := GetProcAddress(FDllHandle, @ProcName[1]); if Result = nil then raise ESocketException.Create('Procedure ' + ProcName + ' not found in ' + winsocket + ' Error #' + IntToStr(GetLastError)); end; end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_WSAStartup( wVersionRequired: word; var WSData: TWSAData): Integer; begin if @FWSAStartup = nil then @FWSAStartup := WSocketGetProc('WSAStartup'); Result := FWSAStartup(wVersionRequired, WSData); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_WSACleanup : Integer; begin if @FWSACleanup = nil then @FWSACleanup := WSocketGetProc('WSACleanup'); Result := FWSACleanup; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure WSocket_WSASetLastError(iError: Integer); begin if @FWSASetLastError = nil then @FWSASetLastError := WSocketGetProc('WSASetLastError'); FWSASetLastError(iError); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_WSAGetLastError: Integer; begin if @FWSAGetLastError = nil then @FWSAGetLastError := WSocketGetProc('WSAGetLastError'); Result := FWSAGetLastError; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_WSACancelAsyncRequest(hAsyncTaskHandle: THandle): Integer; begin if @FWSACancelAsyncRequest = nil then @FWSACancelAsyncRequest := WSocketGetProc('WSACancelAsyncRequest'); Result := FWSACancelAsyncRequest(hAsyncTaskHandle); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_WSAAsyncGetHostByName( HWindow: HWND; wMsg: u_int; name, buf: PChar; buflen: Integer): THandle; begin if @FWSAAsyncGetHostByName = nil then @FWSAAsyncGetHostByName := WSocketGetProc('WSAAsyncGetHostByName'); Result := FWSAAsyncGetHostByName(HWindow, wMsg, name, buf, buflen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_WSAAsyncGetHostByAddr( HWindow: HWND; wMsg: u_int; addr: PChar; len, Struct: Integer; buf: PChar; buflen: Integer): THandle; begin if @FWSAAsyncGetHostByAddr = nil then @FWSAAsyncGetHostByAddr := WSocketGetProc('WSAAsyncGetHostByAddr'); Result := FWSAAsyncGetHostByAddr(HWindow, wMsg, addr, len, struct, buf, buflen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_WSAAsyncSelect( s: TSocket; HWindow: HWND; wMsg: u_int; lEvent: Longint): Integer; begin if @FWSAAsyncSelect = nil then @FWSAAsyncSelect := WSocketGetProc('WSAAsyncSelect'); Result := FWSAAsyncSelect(s, HWindow, wMsg, lEvent); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_getservbyname(name, proto: PChar): PServEnt; begin if @Fgetservbyname = nil then @Fgetservbyname := WSocketGetProc('getservbyname'); Result := Fgetservbyname(name, proto); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_getprotobyname(name: PChar): PProtoEnt; begin if @Fgetprotobyname = nil then @Fgetprotobyname := WSocketGetProc('getprotobyname'); Result := Fgetprotobyname(name); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_gethostbyname(name: PChar): PHostEnt; begin if @Fgethostbyname = nil then @Fgethostbyname := WSocketGetProc('gethostbyname'); Result := Fgethostbyname(name); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_gethostname(name: PChar; len: Integer): Integer; begin if @Fgethostname = nil then @Fgethostname := WSocketGetProc('gethostname'); Result := Fgethostname(name, len); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_socket(af, Struct, protocol: Integer): TSocket; begin if @FOpenSocket= nil then @FOpenSocket := WSocketGetProc('socket'); Result := FOpenSocket(af, Struct, protocol); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_shutdown(s: TSocket; how: Integer): Integer; begin if @FShutdown = nil then @FShutdown := WSocketGetProc('shutdown'); Result := FShutdown(s, how); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_setsockopt(s: TSocket; level, optname: Integer; optval: PChar; optlen: Integer): Integer; begin if @FSetSockOpt = nil then @FSetSockOpt := WSocketGetProc('setsockopt'); Result := FSetSockOpt(s, level, optname, optval, optlen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_getsockopt( s: TSocket; level, optname: Integer; optval: PChar; var optlen: Integer): Integer; begin if @FGetSockOpt = nil then @FGetSockOpt := WSocketGetProc('getsockopt'); Result := FGetSockOpt(s, level, optname, optval, optlen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_sendto( s: TSocket; var Buf; len, flags: Integer; var addrto: TSockAddr; tolen: Integer): Integer; begin if @FSendTo = nil then @FSendTo := WSocketGetProc('sendto'); Result := FSendTo(s, Buf, len, flags, addrto, tolen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_send(s: TSocket; var Buf; len, flags: Integer): Integer; begin if @FSend = nil then @FSend := WSocketGetProc('send'); Result := FSend(s, Buf, len, flags); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_ntohs(netshort: u_short): u_short; begin if @Fntohs = nil then @Fntohs := WSocketGetProc('ntohs'); Result := Fntohs(netshort); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_ntohl(netlong: u_long): u_long; begin if @Fntohl = nil then @Fntohl := WSocketGetProc('ntohl'); Result := Fntohl(netlong); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_listen(s: TSocket; backlog: Integer): Integer; begin if @FListen = nil then @FListen := WSocketGetProc('listen'); Result := FListen(s, backlog); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_ioctlsocket(s: TSocket; cmd: DWORD; var arg: u_long): Integer; begin if @FIoctlSocket = nil then @FIoctlSocket := WSocketGetProc('ioctlsocket'); Result := FIoctlSocket(s, cmd, arg); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_inet_ntoa(inaddr: TInAddr): PChar; begin if @FInet_ntoa = nil then @FInet_ntoa := WSocketGetProc('inet_ntoa'); Result := FInet_ntoa(inaddr); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_inet_addr(cp: PChar): u_long; begin if @FInet_addr = nil then @FInet_addr := WSocketGetProc('inet_addr'); Result := FInet_addr(cp); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_htons(hostshort: u_short): u_short; begin if @Fhtons = nil then @Fhtons := WSocketGetProc('htons'); Result := Fhtons(hostshort); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_htonl(hostlong: u_long): u_long; begin if @Fhtonl = nil then @Fhtonl := WSocketGetProc('htonl'); Result := Fhtonl(hostlong); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_getsockname( s: TSocket; var name: TSockAddr; var namelen: Integer): Integer; begin if @FGetSockName = nil then @FGetSockName := WSocketGetProc('getsockname'); Result := FGetSockName(s, name, namelen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_getpeername( s: TSocket; var name: TSockAddr; var namelen: Integer): Integer; begin if @FGetPeerName = nil then @FGetPeerName := WSocketGetProc('getpeername'); Result := FGetPeerName(s, name, namelen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_connect( s: TSocket; var name: TSockAddr; namelen: Integer): Integer; begin if @FConnect= nil then @FConnect := WSocketGetProc('connect'); Result := FConnect(s, name, namelen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_closesocket(s: TSocket): Integer; begin if @FCloseSocket = nil then @FCloseSocket := WSocketGetProc('closesocket'); Result := FCloseSocket(s); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_bind( s: TSocket; var addr: TSockAddr; namelen: Integer): Integer; begin if @FBind = nil then @FBind := WSocketGetProc('bind'); Result := FBind(s, addr, namelen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_accept( s: TSocket; {$IFDEF VER80} { Delphi 1 } var addr: TSockAddr; var addrlen: Integer): TSocket; {$ELSE} {$IFDEF VER90} { Delphi 2 } var addr: TSockAddr; var addrlen: Integer): TSocket; {$ELSE}{ Delphi 3/4 } addr: PSockAddr; addrlen: PInteger): TSocket; {$ENDIF} {$ENDIF} begin if @FAccept = nil then @FAccept := WSocketGetProc('accept'); Result := FAccept(s, addr, addrlen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_recv(s: TSocket; var Buf; len, flags: Integer): Integer; begin if @FRecv= nil then @FRecv := WSocketGetProc('recv'); Result := FRecv(s, Buf, len, flags); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocket_recvfrom( s: TSocket; var Buf; len, flags: Integer; var from: TSockAddr; var fromlen: Integer): Integer; begin if @FRecvFrom = nil then @FRecvFrom := WSocketGetProc('recvfrom'); Result := FRecvFrom(s, Buf, len, flags, from, fromlen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WinsockInfo : TWSADATA; begin { LoadWinsock(winsocket); 14/02/99 } { Load winsock and initialize it as needed } WSocketGetProc(''); Result := GInitData; { If no socket created, then unload winsock immediately } if GSocketCount <= 0 then WSocketUnloadWinsock; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.Notification(AComponent: TComponent; operation: TOperation); begin inherited Notification(AComponent, operation); if operation = opRemove then begin end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.AssignDefaultValue; begin FillChar(sin, 0, Sizeof(sin)); sin.sin_family := AF_INET; FAddrFormat := PF_INET; FPortAssigned := FALSE; FAddrAssigned := FALSE; FAddrResolved := FALSE; FPortResolved := FALSE; FProtoResolved := FALSE; FLocalPortResolved := FALSE; FProtoAssigned := TRUE; FProto := IPPROTO_TCP; FProtoStr := 'tcp'; FType := SOCK_STREAM; FLocalPortStr := '0'; FLingerOnOff := wsLingerOn; FLingerTimeout := 0; FHSocket := INVALID_SOCKET; FState := wsClosed; bMoreFlag := FALSE; nMoreCnt := 0; nMoreMax := 24; bWrite := FALSE; bAllSent := TRUE; FPaused := FALSE; FReadCount := 0; FCloseInvoked := FALSE; FFlushTimeout := 60; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { All exceptions *MUST* be handled. If an exception is not handled, the } { application will be shut down ! } procedure TCustomWSocket.HandleBackGroundException(E: Exception); var CanAbort : Boolean; begin CanAbort := TRUE; { First call the error event handler, if any } if Assigned(FOnBgException) then begin try FOnBgException(Self, E, CanAbort); except end; end; { Then abort the socket } if CanAbort then begin try Abort; except end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { This procedure handle all messages for TWSocket. All exceptions must be } { handled or the application will be shutted down ! } { If WndProc is overriden in descendent components, then the same exception } { handling *MUST* be setup because descendent component code is executed } { before the base class code. } procedure TCustomWSocket.WndProc(var MsgRec: TMessage); begin try with MsgRec do begin if Msg = WM_ASYNCSELECT then WMASyncSelect(MsgRec) else if Msg = WM_ASYNCGETHOSTBYNAME then WMAsyncGetHostByName(MsgRec) else if Msg = WM_ASYNCGETHOSTBYADDR then WMAsyncGetHostByAddr(MsgRec) else Result := DefWindowProc(Handle, Msg, wParam, lParam); end; except on E:Exception do HandleBackGroundException(E); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFNDEF VER80} { This function is a callback function. It means that it is called by } { windows. This is the very low level message handler procedure setup to } { handle the message sent by windows (winsock) to handle messages. } function XSocketWindowProc( ahWnd : HWND; auMsg : Integer; awParam : WPARAM; alParam : LPARAM): Integer; stdcall; var Obj : TObject; MsgRec : TMessage; begin { At window creation asked windows to store a pointer to our object } Obj := TObject(GetWindowLong(ahWnd, 0)); { If the pointer doesn't represent a TWSocket, just call the default procedure} if not (Obj is TCustomWSocket) then Result := DefWindowProc(ahWnd, auMsg, awParam, alParam) else begin { Delphi use a TMessage type to pass parameter to his own kind of } { windows procedure. So we are doing the same... } MsgRec.Msg := auMsg; MsgRec.wParam := awParam; MsgRec.lParam := alParam; { May be a try/except around next line is needed. Not sure ! } TWSocket(Obj).WndProc(MsgRec); Result := MsgRec.Result; end; end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.MessagePump; begin {$IFDEF NOFORMS} { The Forms unit (TApplication object) has not been included. } { We used either an external message pump or our internal message pump. } { External message pump has to set Terminated property to TRUE when the } { application is terminated. } if Assigned(FOnMessagePump) then FOnMessagePump(Self) else Self.ProcessMessages; {$ELSE} {$IFNDEF VER80} { Delphi 1 doesn't support multithreading } if FMultiThreaded then Self.ProcessMessages else {$ENDIF} Application.ProcessMessages; {$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { This function is very similar to TApplication.ProcessMessage } { You can also use it if your application has no TApplication object (Forms } { unit not referenced at all). } {$IFNDEF VER80} function TCustomWSocket.ProcessMessage : Boolean; var Msg : TMsg; begin Result := FALSE; if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then begin Result := TRUE; if Msg.Message = WM_QUIT then FTerminated := TRUE else begin TranslateMessage(Msg); DispatchMessage(Msg); end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Loop thru message processing until all messages are processed. } { This function is very similar to TApplication.ProcessMessage } { This is intended for multithreaded application using TWSocket. } { You can also use it if your application has no TApplication object (Forms } { unit not referenced at all). } procedure TCustomWSocket.ProcessMessages; begin while Self.ProcessMessage do { loop }; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Loop thru message processing until the WM_QUIT message is received } { This is intended for multithreaded application using TWSocket. } { MessageLoop is different from ProcessMessages because it actually block } { if no message is available. The loop is broken when WM_QUIT is retrieved. } procedure TCustomWSocket.MessageLoop; var MsgRec : TMsg; begin { If GetMessage retrieves the WM_QUIT, the return value is FALSE and } { the message loop is broken. } while GetMessage(MsgRec, 0, 0, 0) do begin TranslateMessage(MsgRec); DispatchMessage(MsgRec) end; FTerminated := TRUE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { This global variable is used to store the windows class characteristic } { and is needed to register the window class used by TWSocket } var XSocketWindowClass: TWndClass = ( style : 0; lpfnWndProc : @XSocketWindowProc; cbClsExtra : 0; cbWndExtra : SizeOf(Pointer); hInstance : 0; hIcon : 0; hCursor : 0; hbrBackground : 0; lpszMenuName : nil; lpszClassName : 'XSocketWindowClass'); {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Allocate a window handle. This means registering a window class the first } { time we are called, and creating a new window each time we are called. } function XSocketAllocateHWnd(Obj : TObject): HWND; var TempClass : TWndClass; ClassRegistered : Boolean; begin { Check if the window class is already registered } XSocketWindowClass.hInstance := HInstance; ClassRegistered := GetClassInfo(HInstance, XSocketWindowClass.lpszClassName, TempClass); if not ClassRegistered then begin { Not yet registered, do it right now } Result := WinProcs.RegisterClass(XSocketWindowClass); if Result = 0 then Exit; end; { Now create a new window } Result := CreateWindowEx(WS_EX_TOOLWINDOW, XSocketWindowClass.lpszClassName, '', { Window name } WS_POPUP, { Window Style } 0, 0, { X, Y } 0, 0, { Width, Height } 0, { hWndParent } 0, { hMenu } HInstance, { hInstance } nil); { CreateParam } { if successfull, the ask windows to store the object reference } { into the reserved byte (see RegisterClass) } if (Result <> 0) and Assigned(Obj) then SetWindowLong(Result, 0, Integer(Obj)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Free the window handle } procedure XSocketDeallocateHWnd(Wnd: HWND); begin DestroyWindow(Wnd); end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TCustomWSocket.Create(AOwner: TComponent); begin inherited Create(AOwner); {$IFDEF VER80} { Delphi 16 bits has no thread, we can use the VCL } FWindowHandle := AllocateHWnd(WndProc); {$ELSE} { Delphi 32 bits has threads and VCL is not thread safe. } { We need to do our own way to be thread safe. } FWindowHandle := XSocketAllocateHWnd(Self); {$ENDIF} FBufList := TList.Create; FBufSize := 1514; { Default buffer size } FDnsResultList := TStringList.Create; AssignDefaultValue; GSocketCount := GSocketCount + 1; { LoadWinsock(WINSOCKET);} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TCustomWSocket.Destroy; begin try CancelDnsLookup; { Cancel any pending dns lookup } except { Ignore any exception here } end; if FState <> wsClosed then { Close the socket if not yet closed } Close; GSocketCount := GSocketCount - 1; if {**(not (csDesigning in ComponentState)) and **} { (DllStarted) and 14/02/99 } (GSocketCount <= 0) then begin WSocketUnloadWinsock; GSocketCount := 0; end; DeleteBufferedData; FBufList.Free; FDnsResultList.Free; { Remove the object reference from the window } SetWindowLong(FWindowHandle, 0, 0); {$IFDEF VER80} DeallocateHWnd(FWindowHandle); {$ELSE} XSocketDeallocateHWnd(FWindowHandle); {$ENDIF} inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.Dup(NewHSocket : TSocket); var iStatus : Integer; begin if (NewHSocket = 0) or (NewHSocket = INVALID_SOCKET) then begin WSocket_WSASetLastError(WSAEINVAL); SocketError('Dup'); Exit; end; if FState <> wsClosed then begin iStatus := WSocket_closesocket(FHSocket); FHSocket := INVALID_SOCKET; if iStatus <> 0 then begin SocketError('Dup (closesocket)'); Exit; end; ChangeState(wsClosed); end; FHsocket := NewHSocket; SetLingerOption; iStatus := WSocket_WSAASyncSelect( FHSocket, Handle, WM_ASYNCSELECT, FD_READ or FD_WRITE or FD_CLOSE or FD_CONNECT); if iStatus <> 0 then begin SocketError('WSAAsyncSelect'); Exit; end; ChangeState(wsConnected); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Get the number of char received and waiting to be read } function TCustomWSocket.GetRcvdCount : LongInt; begin if WSocket_ioctlsocket(FHSocket, FIONREAD, Result) = SOCKET_ERROR then begin Result := -1; SocketError('ioctlSocket'); Exit; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.ChangeState(NewState : TSocketState); var OldState : TSocketState; begin OldState := FState; FState := NewState; TriggerChangeState(OldState, NewState); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { DoRecv is a simple wrapper around winsock recv function to make it } { a virtual function. } function TCustomWSocket.DoRecv( var Buffer; BufferSize : Integer; Flags : Integer) : Integer; begin Result := WSocket_recv(FHSocket, Buffer, BufferSize, Flags); { FRcvdFlag := (Result > 0);} { If we received the requested size, we may need to receive more } FRcvdFlag := (Result >= BufferSize); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { The socket is non-blocking, so this routine will only receive as much } { data as it is available. } function TCustomWSocket.Receive(Buffer : Pointer; BufferSize: integer) : integer; begin Result := DoRecv(Buffer^, BufferSize, 0); if Result < 0 then FLastError := WSocket_WSAGetLastError else FReadCount := FReadCount + Result; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Receive as much data as possible into a string } { You should avoid this function and use Receive. Using string will be } { much slower because data will be copied several times. } { ReceiveStr will *NOT* wait for a line to be received. It just read } { already received characters and return them as a string. } function TCustomWSocket.ReceiveStr : string; var lCount : LongInt; begin SetLength(Result, 0); lCount := GetRcvdCount; {$IFDEF VER80} { Delphi 1 strings are limited } if lCount > High(Result) then lCount := High(Result); {$ENDIF} if lCount > 0 then begin SetLength(Result, lCount); lCount := DoRecv(Result[1], lCount, 0); if lCount > 0 then SetLength(Result, lCount) else SetLength(Result, 0); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomWSocket.DoRecvFrom( FHSocket : TSocket; var Buffer; BufferSize : Integer; Flags : Integer; var From : TSockAddr; var FromLen : Integer) : Integer; begin Result := WSocket_recvfrom(FHSocket, Buffer, BufferSize, Flags, From, FromLen); { FRcvdFlag := (Result > 0); } FRcvdFlag := (Result >= BufferSize); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomWSocket.ReceiveFrom( Buffer : Pointer; BufferSize : Integer; var From : TSockAddr; var FromLen : Integer) : integer; begin Result := DoRecvFrom(FHSocket, Buffer^, BufferSize, 0, From, FromLen); if Result < 0 then FLastError := WSocket_WSAGetLastError else FReadCount := FReadCount + Result; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomWSocket.PeekData(Buffer : Pointer; BufferSize: integer) : integer; begin Result := DoRecv(Buffer^, BufferSize, MSG_PEEK); if Result < 0 then FLastError := WSocket_WSAGetLastError; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function SearchChar(Data : PChar; Len : Integer; Ch : Char) : PChar; begin while Len > 0 do begin Len := Len - 1; if Data^ = Ch then begin Result := Data; exit; end; Data := Data + 1; end; Result := nil; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomWSocket.SendTo( Dest : TSockAddr; DestLen : Integer; Data : Pointer; Len : Integer) : integer; begin Result := WSocket_SendTo(FHSocket, Data^, Len, FSendFlags, TSockAddr(Dest), DestLen) end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomWSocket.RealSend(Data : Pointer; Len : Integer) : Integer; begin if FType = SOCK_DGRAM then Result := WSocket_SendTo(FHSocket, Data^, Len, FSendFlags, TSockAddr(sin), SizeOf(sin)) else Result := WSocket_Send(FHSocket, Data^, Len, FSendFlags); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.TryToSend; var oBuffer : TBuffer; Len : Integer; Count : Integer; Data : Pointer; LastError : Integer; p : PChar; bMore : Boolean; begin if (FHSocket = INVALID_SOCKET) or { No more socket } (FBufList.Count = 0) or { Nothing to send } (bMoreFlag and (nMoreCnt >= nMoreMax)) then { Waiting more signal } exit; bMore := TRUE; while bMore do begin oBuffer := FBufList.First; Data := oBuffer.Peek(Len); if Len <= 0 then begin { Buffer is empty } if FBufList.Count <= 1 then begin { Every thing has been sent } bAllSent := TRUE; bMore := FALSE; end else begin oBuffer.Free; FBufList.Delete(0); FBufList.Pack; end; end else begin if bMoreFlag then begin p := SearchChar(Data, Len, #10); if Assigned(p) then begin len := p - PChar(Data) + 1; nMoreCnt := nMoreCnt + 1; if nMoreCnt >= nMoreMax then bMore := FALSE; end; end; Count := RealSend(Data, Len); if Count = 0 then bMore := FALSE { Closed by remote } else if count = SOCKET_ERROR then begin LastError := WSocket_WSAGetLastError; if (LastError = WSAECONNRESET) or (LastError = WSAENOTSOCK) or (LastError = WSAENOTCONN) or (LastError = WSAEINVAL) then begin FCloseInvoked := TRUE; { 23/07/98 } Close; TriggerSessionClosed(LastError); { 23/07/98 } end else if LastError <> WSAEWOULDBLOCK then begin SocketError('TryToSend failed'); Exit; end; bMore := FALSE; end else begin oBuffer.Remove(Count); if Count < Len then begin { Could not write as much as we wanted. Stop sending } {$IFDEF VER80} { A bug in some Trumpet Winsock implementation break the } { background sending. Jan Tomasek <xtomasej@feld.cvut.cz> } if not TrumpetCompability then begin bWrite := FALSE; bMore := FALSE; end; {$ELSE} bWrite := FALSE; bMore := FALSE; {$ENDIF} end; end; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.PutStringInSendBuffer(Str : String); begin PutDataInSendBuffer(@Str[1], Length(Str)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.PutDataInSendBuffer(Data : Pointer; Len : Integer); var oBuffer : TBuffer; cWritten : Integer; bMore : Boolean; begin if Len <= 0 then exit; if FBufList.Count = 0 then begin oBuffer := TBuffer.Create(FBufSize); FBufList.Add(oBuffer); end else oBuffer := FBufList.Last; bMore := TRUE; while bMore do begin cWritten := oBuffer.Write(Data, Len); if cWritten >= Len then bMore := FALSE else begin Len := Len - cWritten; Data := PChar(Data) + cWritten; if Len < 0 then bMore := FALSE else begin oBuffer := TBuffer.Create(FBufSize); FBufList.Add(oBuffer); end; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Return -1 if error, else return number of byte written } function TCustomWSocket.Send(Data : Pointer; Len : Integer) : integer; begin if FState <> wsConnected then begin WSocket_WSASetLastError(WSAENOTCONN); SocketError('Send'); Result := -1; Exit; end; bAllSent := FALSE; if Len <= 0 then Result := 0 else begin Result := Len; PutDataInSendBuffer(Data, Len); end; if bAllSent then Exit; TryToSend; if bAllSent then begin { We post a message to fire the FD_WRITE message wich in turn will } { fire the OnDataSent event. We cannot fire the event ourself } { because the event handler will eventually call send again. } { Sending the message prevent recursive call and stack overflow. } { The PostMessage function posts (places) a message in a window's } { message queue and then returns without waiting for the } { corresponding window to process the message. The message will be } { seen and routed by Delphi a litle later, when we will be out of } { the send function. } PostMessage(Handle, WM_ASYNCSELECT, FHSocket, MakeLong(FD_WRITE, 0)); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Return -1 if error, else return number of byte written } function TCustomWSocket.SendStr(Str : String) : integer; begin Result := Send(@Str[1], Length(Str)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.SendText(Str : String); begin SendStr(Str); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.ASyncReceive(Error : Word); var bMore : Boolean; lCount : LongInt; TrashCan : array [0..1023] of char; begin bMore := TRUE; while bMore do begin FLastError := 0; try if not TriggerDataAvailable(Error) then begin { Nothing wants to receive, we will receive and throw away 23/07/98 } if DoRecv(TrashCan, SizeOf(TrashCan), 0) = SOCKET_ERROR then begin FLastError := WSocket_WSAGetLastError; if FLastError = WSAEWOULDBLOCK then begin FLastError := 0; break; end; end; end; if FLastError <> 0 then bMore := FALSE {* Check if we have something new arrived, if yes, process it *} else if WSocket_ioctlsocket(FHSocket, FIONREAD, lCount) = SOCKET_ERROR then begin FLastError := WSocket_WSAGetLastError; bMore := FALSE; end else if lCount = 0 then bMore := FALSE; except bMore := FALSE; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.WMASyncSelect(var msg: TMessage); var Check : Word; begin {TriggerDisplay('AsyncSelect ' + IntToStr(msg.wParam) + ', ' + IntToStr(msg.lParamLo));} { Verify that the socket handle is ours handle } if msg.wParam <> FHSocket then Exit; if FPaused then exit; Check := msg.lParamLo and FD_CONNECT; if Check <> 0 then begin ChangeState(wsConnected); TriggerSessionConnected(msg.lParamHi); if (msg.lParamHi <> 0) and (FState <> wsClosed) then Close; end; Check := msg.lParamLo and FD_READ; if Check <> 0 then begin ASyncReceive(msg.lParamHi); end; Check := msg.lParamLo and FD_WRITE; if Check <> 0 then begin TryToSend; { If you wants to test background exception, uncomment the next 2 lines. } { if bAllSent then } { raise Exception.Create('Test TWSocket exception'); } if bAllSent then TriggerDataSent(msg.lParamHi); end; Check := msg.lParamLo and FD_ACCEPT; if Check <> 0 then begin TriggerSessionAvailable(msg.lParamHi); end; Check := msg.lParamLo and FD_CLOSE; if Check <> 0 then begin {* In some strange situations I found that we receive a FD_CLOSE *} {* during the connection phase, breaking the connection early ! *} {* This occurs for example after a failed FTP transfert *} if FState <> wsConnecting then begin {* Check if we have something arrived, if yes, process it *} ASyncReceive(0); if Assigned(FOnSessionClosed) and (not FCloseInvoked) then begin FCloseInvoked := TRUE; TriggerSessionClosed(msg.lParamHi); end; if FState <> wsClosed then Close; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure GetIPList(phe : PHostEnt; ToList : TStrings); type TaPInAddr = array [0..255] of PInAddr; PaPInAddr = ^TaPInAddr; var pptr : PaPInAddr; I : Integer; begin pptr := PaPInAddr(Phe^.h_addr_list); I := 0; while pptr^[I] <> nil do begin ToList.Add(StrPas(WSocket_inet_ntoa(pptr^[I]^))); Inc(I); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.WMAsyncGetHostByName(var msg: TMessage); var Phe : Phostent; Error : Word; begin if msg.wParam <> LongInt(FDnsLookupHandle) then Exit; FDnsLookupHandle := 0; Error := Msg.LParamHi; if Error = 0 then begin Phe := PHostent(@FDnsLookupBuffer); if phe <> nil then begin GetIpList(Phe, FDnsResultList); FDnsResult := FDnsResultList.Strings[0]; end; end; TriggerDnsLookupDone(Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.WMAsyncGetHostByAddr(var msg: TMessage); var Phe : Phostent; Error : Word; begin if msg.wParam <> LongInt(FDnsLookupHandle) then Exit; FDnsLookupHandle := 0; Error := Msg.LParamHi; if Error = 0 then begin Phe := PHostent(@FDnsLookupBuffer); if phe <> nil then begin SetLength(FDnsResult, StrLen(Phe^.h_name)); StrCopy(@FDnsResult[1], Phe^.h_name); FDnsResultList.Clear; FDnsResultList.Add(FDnsResult); end; end; TriggerDnsLookupDone(Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.SetProto(sProto : String); begin if FProtoAssigned and (sProto = FProtoStr) then Exit; if FState <> wsClosed then begin RaiseException('Cannot change Proto if not closed'); Exit; end; FProtoStr := Trim(sProto); if Length(FProtoStr) = 0 then begin FProtoAssigned := FALSE; Exit; end; FProtoResolved := FALSE; FProtoAssigned := TRUE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomWSocket.GetProto : String; begin Result := FProtoStr; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.SetRemotePort(sPort : String); begin if FPortAssigned and (FPortStr = sPort) then Exit; if FState <> wsClosed then begin RaiseException('Cannot change Port if not closed'); Exit; end; FPortStr := Trim(sPort); if Length(FPortStr) = 0 then begin FPortAssigned := FALSE; Exit; end; FPortResolved := FALSE; FPortAssigned := TRUE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomWSocket.GetRemotePort : String; begin Result := FPortStr; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.SetLocalPort(sLocalPort : String); begin if FState <> wsClosed then begin RaiseException('Cannot change LocalPort if not closed'); Exit; end; FLocalPortStr := sLocalPort; FLocalPortResolved := FALSE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomWSocket.GetXPort: string; var saddr : TSockAddrIn; saddrlen : integer; port : integer; begin Result := 'error'; if FState in [wsConnected, wsBound, wsListening] then begin saddrlen := sizeof(saddr); if WSocket_GetSockName(FHSocket, TSockAddr(saddr), saddrlen) = 0 then begin port := WSocket_ntohs(saddr.sin_port); Result := Format('%d',[port]); end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.SetAddr(InAddr : String); begin if FAddrAssigned and (FAddrStr = InAddr) then Exit; if FState <> wsClosed then begin RaiseException('Cannot change Addr if not closed'); Exit; end; FAddrStr := Trim(InAddr); if Length(FAddrStr) = 0 then begin FAddrAssigned := FALSE; Exit; end; FAddrResolved := FALSE; FAddrAssigned := TRUE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocketResolveHost(InAddr : String) : TInAddr; var szData : array [0..256] of char; Phe : Phostent; IPAddr : u_long; begin if (Length(InAddr) = 0) or (Length(InAddr) >= SizeOf(szData)) then raise ESocketException.Create('WSocketResolveHost: ''' + InAddr + ''' Invalid Hostname.'); StrPCopy(szData, Trim(InAddr)); { if not DllStarted then LoadWinsock(WINSOCKET); 14/02/99 } if IsDigit(szData[0]) then begin { Address is a dotted numeric address like 192.161.124.32 } IPAddr := WSocket_inet_addr(szData); {$IFDEF VER80} { With Trumpet Winsock 2B and 30D (win 3.11), inet_addr returns faulty } { results for 0.0.0.0 } if (IPAddr = INADDR_NONE) and (StrComp(szData, '0.0.0.0') = 0) then begin Result.s_addr := 0; Exit; end; {$ENDIF} if IPAddr = u_long(INADDR_NONE) then begin if StrComp(szData, '255.255.255.255') = 0 then begin Result.s_addr := u_long(INADDR_BROADCAST); Exit; end; raise ESocketException.Create('WSocketResolveHost: ''' + InAddr + ''' Invalid IP address.'); end; Result.s_addr := IPAddr; Exit; end; { Address is a hostname } Phe := WSocket_GetHostByName(szData); if Phe = nil then raise ESocketException.CreateFmt( 'WSocketResolveHost: Cannot convert host address ''%s''', [InAddr]); Result.s_addr := PInAddr(Phe^.h_addr_list^)^.s_addr; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Convert port name or number to number in host order (ftp -> 21) } function WSocketResolvePort(Port : String; Proto : String) : Word; var szPort : array [0..31] of char; szProto : array [0..31] of char; Pse : Pservent; begin if (Length(Port) = 0) or (Length(Port) >= SizeOf(szPort)) then raise ESocketException.Create('WSocketResolvePort: Invalid Port.'); if IsDigit(Port[1]) then Result := atoi(Port) else begin StrPCopy(szPort, Trim(Port)); StrPCopy(szProto, Trim(Proto)); { if not DllStarted then LoadWinsock(WINSOCKET); 14/02/99 } if szProto[0] = #0 then Pse := WSocket_GetServByName(szPort, nil) else Pse := WSocket_GetServByName(szPort, szProto); if Pse = nil then raise ESocketException.CreateFmt( 'WSocketResolvePort: Cannot convert port ''%s''', [Port]); Result := WSocket_ntohs(Pse^.s_port); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocketResolveProto(sProto : String) : integer; var szProto : array [0..31] of char; Ppe : Pprotoent; begin if (Length(sProto) = 0) or (Length(sProto) >= SizeOf(szProto)) then raise ESocketException.Create('WSocketResolveProto: Invalid Protocol.'); sProto := Trim(sProto); if IsDigit(sProto[1]) then Result := atoi(sProto) else begin StrPCopy(szProto, sProto); { if not DllStarted then LoadWinsock(WINSOCKET); 14/02/99 } ppe := WSocket_getprotobyname(szProto); if Ppe = nil then raise ESocketException.CreateFmt( 'WSocketResolveProto: Cannot convert protocol ''%s''', [sProto]); Result := ppe^.p_proto; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomWSocket.GetAddr : String; begin Result := FAddrStr; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomWSocket.GetSockName(var saddr : TSockAddrIn; var saddrlen : Integer) : integer; begin Result := WSocket_GetSockName(FHSocket, TSockAddr(saddr), saddrlen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomWSocket.GetPeerAddr: string; var saddr : TSockAddrIn; saddrlen : integer; szAddr : PChar; begin Result := 'error'; if FState = wsConnected then begin saddrlen := sizeof(saddr); if WSocket_GetPeerName(FHSocket, TSockAddr(saddr), saddrlen) = 0 then begin szAddr := WSocket_inet_ntoa(saddr.sin_addr); Result := StrPas(szAddr); end else begin SocketError('GetPeerName'); Exit; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomWSocket.GetPeerName(var Name : TSockAddrIn; NameLen : Integer) : integer; begin if FState = wsConnected then Result := WSocket_GetPeerName(FHSocket, TSockAddr(Name), NameLen) else Result := SOCKET_ERROR; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.CancelDnsLookup; begin if FDnsLookupHandle = 0 then Exit; if WSocket_WSACancelAsyncRequest(FDnsLookupHandle) <> 0 then begin FDnsLookupHandle := 0; SocketError('WSACancelAsyncRequest'); Exit; end; FDnsLookupHandle := 0; if not (csDestroying in ComponentState) then TriggerDnsLookupDone(WSAEINTR); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.DnsLookup(HostName : String); var IPAddr : TInAddr; begin if HostName = '' then begin RaiseException('DNS lookup: invalid host name.'); TriggerDnsLookupDone(WSAEINVAL); Exit; end; { Cancel any pending lookup } if FDnsLookupHandle <> 0 then WSocket_WSACancelAsyncRequest(FDnsLookupHandle); FDnsResult := ''; FDnsResultList.Clear; {$IFDEF VER80} { Delphi 1 do not automatically add a terminating nul char } HostName := HostName + #0; {$ENDIF} IPAddr.S_addr := WSocket_inet_addr(@HostName[1]); if IPAddr.S_addr <> u_long(INADDR_NONE) then begin FDnsResult := StrPas(WSocket_inet_ntoa(IPAddr)); TriggerDnsLookupDone(0); Exit; end; FDnsLookupHandle := WSocket_WSAAsyncGetHostByName( FWindowHandle, WM_ASYNCGETHOSTBYNAME, @HostName[1], @FDnsLookupBuffer, SizeOf(FDnsLookupBuffer)); if FDnsLookupHandle = 0 then begin RaiseExceptionFmt( '%s: can''t start DNS lookup, error #%d', [HostName, WSocket_WSAGetLastError]); Exit; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.ReverseDnsLookup(HostAddr: String); var szAddr : array [0..256] of Char; lAddr : u_long; begin if HostAddr = '' then begin RaiseException('DNS lookup: invalid host name.'); TriggerDnsLookupDone(WSAEINVAL); Exit; end; { Cancel any pending lookup } if FDnsLookupHandle <> 0 then WSocket_WSACancelAsyncRequest(FDnsLookupHandle); FDnsResult := ''; FDnsResultList.Clear; StrPCopy(szAddr, HostAddr); lAddr := WSocket_inet_addr(szAddr); FDnsLookupHandle := WSocket_WSAAsyncGetHostByAddr( FWindowHandle, WM_ASYNCGETHOSTBYADDR, PChar(@lAddr), 4, PF_INET, @FDnsLookupBuffer, SizeOf(FDnsLookupBuffer)); if FDnsLookupHandle = 0 then RaiseExceptionFmt('%s: can''t start DNS lookup, error #%d', [HostAddr, WSocket_WSAGetLastError]); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.BindSocket; var SockName : TSockAddr; SockNamelen : Integer; LocalSockName : TSockAddrIn; begin FillChar(LocalSockName, Sizeof(LocalSockName), 0); SockNamelen := sizeof(LocalSockName); LocalSockName.sin_family := AF_INET; LocalSockName.sin_port := WSocket_htons(FLocalPortNum); LocalSockName.sin_addr.s_addr := INADDR_ANY; if WSocket_bind(HSocket, LocalSockName, SockNamelen) <> 0 then begin RaiseExceptionFmt('winsock.bind failed, error #%d', [WSocket_WSAGetLastError]); Exit; end; SockNamelen := sizeof(SockName); if WSocket_getsockname(FHSocket, SockName, SockNamelen) <> 0 then begin RaiseExceptionFmt('winsock.getsockname failed, error #%d', [WSocket_WSAGetLastError]); Exit; end; { FLocalPort := ntohs(SockName.sin_port); } FLocalPortNum := WSocket_ntohs(SockName.sin_port); FLocalPortStr := IntToStr(FLocalPortNum); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.SetLingerOption; var iStatus : integer; li : TLinger; begin if FLingerOnOff = wsLingerNoSet then Exit; { Option set is disabled, ignore } if FHSocket = INVALID_SOCKET then begin RaiseException('Cannot set linger option at this time'); Exit; end; li.l_onoff := Ord(FLingerOnOff); { 0/1 = disable/enable linger } li.l_linger := FLingerTimeout; { timeout in seconds } iStatus := WSocket_setsockopt(FHSocket, SOL_SOCKET, SO_LINGER, @li, SizeOf(li)); if iStatus <> 0 then begin SocketError('setsockopt(SO_LINGER)'); Exit; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.Connect; var iStatus : integer; optval : integer; begin if (FHSocket <> INVALID_SOCKET) and (FState <> wsClosed) then begin RaiseException('Connect: Socket already in use'); Exit; end; if not FPortAssigned then begin RaiseException('Connect: No Port Specified'); Exit; end; if not FAddrAssigned then begin RaiseException('Connect: No IP Address Specified'); Exit; end; if not FProtoAssigned then begin RaiseException('Connect: No Protocol Specified'); Exit; end; try if not FProtoResolved then begin { The next line will trigger an exception in case of failure } FProto := WSocketResolveProto(FProtoStr); if FProto = IPPROTO_UDP then FType := SOCK_DGRAM else FType := SOCK_STREAM; FProtoResolved := TRUE; end; if not FPortResolved then begin { The next line will trigger an exception in case of failure } FPortNum := WSocketResolvePort(FPortStr, GetProto); sin.sin_port := WSocket_htons(FPortNum); FPortResolved := TRUE; end; if not FLocalPortResolved then begin { The next line will trigger an exception in case of failure } FLocalPortNum := WSocketResolvePort(FLocalPortStr, GetProto); FLocalPortResolved := TRUE; end; if not FAddrResolved then begin { The next line will trigger an exception in case of failure } sin.sin_addr.s_addr := WSocketResolveHost(FAddrStr).s_addr; FAddrResolved := TRUE; end; except on E:Exception do begin RaiseException('connect: ' + E.Message); Exit; end; end; { Remove any data from the internal output buffer } { (should already be empty !) } DeleteBufferedData; FHSocket := WSocket_socket(FAddrFormat, FType, FProto); if FHSocket = INVALID_SOCKET then begin SocketError('Connect (socket)'); Exit; end; ChangeState(wsOpened); if FType = SOCK_DGRAM then begin BindSocket; if sin.sin_addr.S_addr = u_long(INADDR_BROADCAST) then begin OptVal := 1; iStatus := WSocket_setsockopt(FHSocket, SOL_SOCKET, SO_BROADCAST, PChar(@OptVal), SizeOf(OptVal)); if iStatus <> 0 then begin SocketError('setsockopt(SO_BROADCAST)'); Exit; end; end; end else begin { Socket type is SOCK_STREAM } if FLocalPortNum <> 0 then BindSocket; SetLingerOption; optval := -1; iStatus := WSocket_setsockopt(FHSocket, SOL_SOCKET, SO_KEEPALIVE, @optval, SizeOf(optval)); if iStatus <> 0 then begin SocketError('setsockopt(SO_KEEPALIVE)'); Exit; end; optval := -1; iStatus := WSocket_setsockopt(FHSocket, SOL_SOCKET, SO_REUSEADDR, @optval, SizeOf(optval)); if iStatus <> 0 then begin SocketError('setsockopt(SO_REUSEADDR)'); Exit; end; end; iStatus := WSocket_WSAASyncSelect(FHSocket, Handle, WM_ASYNCSELECT, FD_READ or FD_WRITE or FD_CLOSE or FD_ACCEPT or FD_CONNECT); if iStatus <> 0 then begin SocketError('WSAAsyncSelect'); Exit; end; if FType = SOCK_DGRAM then begin ChangeState(wsConnected); TriggerSessionConnected(0); end else begin iStatus := WSocket_connect(FHSocket, TSockAddr(sin), sizeof(sin)); if iStatus = 0 then ChangeState(wsConnecting) else begin iStatus := WSocket_WSAGetLastError; if iStatus = WSAEWOULDBLOCK then ChangeState(wsConnecting) else begin FLastError := WSocket_WSAGetLastError; SocketError('Connect'); Exit; end; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.Listen; var iStatus : integer; begin if not FPortAssigned then begin WSocket_WSASetLastError(WSAEINVAL); SocketError('listen: port not assigned'); Exit; end; if not FProtoAssigned then begin WSocket_WSASetLastError(WSAEINVAL); SocketError('listen: protocol not assigned'); Exit; end; if not FAddrAssigned then begin WSocket_WSASetLastError(WSAEINVAL); SocketError('listen: address not assigned'); Exit; end; try if not FProtoResolved then begin { The next line will trigger an exception in case of failure } FProto := WSocketResolveProto(FProtoStr); if FProto = IPPROTO_UDP then FType := SOCK_DGRAM else FType := SOCK_STREAM; FProtoResolved := TRUE; end; if not FPortResolved then begin { The next line will trigger an exception in case of failure } FPortNum := WSocketResolvePort(FPortStr, GetProto); sin.sin_port := WSocket_htons(FPortNum); FPortResolved := TRUE; end; if not FAddrResolved then begin { The next line will trigger an exception in case of failure } sin.sin_addr.s_addr := WSocketResolveHost(FAddrStr).s_addr; FAddrResolved := TRUE; end; except on E:Exception do begin RaiseException('listen: ' + E.Message); Exit; end; end; { Remove any data from the internal output buffer } { (should already be empty !) } DeleteBufferedData; FHSocket := WSocket_socket(FAddrFormat, FType, FProto); if FHSocket = INVALID_SOCKET then begin SocketError('socket'); exit; end; iStatus := WSocket_bind(FHSocket, TSockAddr(sin), sizeof(sin)); if iStatus = 0 then ChangeState(wsBound) else begin SocketError('Bind'); Close; exit; end; if FType = SOCK_DGRAM then begin ChangeState(wsListening); ChangeState(wsConnected); TriggerSessionConnected(0); end else if FType = SOCK_STREAM then begin iStatus := WSocket_listen(FHSocket, 5); if iStatus = 0 then ChangeState(wsListening) else begin SocketError('Listen'); Exit; end; end; iStatus := WSocket_WSAASyncSelect(FHSocket, Handle, WM_ASYNCSELECT, FD_READ or FD_WRITE or FD_ACCEPT or FD_CLOSE); if iStatus <> 0 then begin SocketError('WSAASyncSelect'); exit; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomWSocket.Accept: TSocket; var len : integer; begin if FState <> wsListening then begin WSocket_WSASetLastError(WSAEINVAL); SocketError('not a listening socket'); Result := INVALID_SOCKET; Exit; end; len := sizeof(sin); {$IFDEF VER100} { Delphi 3 has changed var parameters to pointers } FASocket := WSocket_accept(FHSocket, @sin, @len); {$ELSE} {$IFDEF VER93} { C++Builder 1 has changed var parameters to pointers } FASocket := WSocket_accept(FHSocket, @sin, @len); {$ELSE} {$IFDEF VER110} { C++Builder 3 has changed var parameters to pointers } FASocket := WSocket_accept(FHSocket, @sin, @len); {$ELSE} {$IFDEF VER120} { Delphi 4 has changed var parameters to pointers } FASocket := WSocket_accept(FHSocket, @sin, @len); {$ELSE} {$IFDEF VER125} { C++Builder 4 has changed var parameters to pointers } FASocket := WSocket_accept(FHSocket, @sin, @len); {$ELSE} FASocket := WSocket_accept(FHSocket, TSockAddr(sin), len); {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} if FASocket = INVALID_SOCKET then begin SocketError('Accept'); Result := INVALID_SOCKET; Exit; end else Result := FASocket; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.Pause; begin FPaused := TRUE; WSocket_WSAASyncSelect(FHSocket, Handle, 0, 0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.Resume; begin FPaused := FALSE; WSocket_WSAASyncSelect(FHSocket, Handle, WM_ASYNCSELECT, FD_READ or FD_WRITE or FD_CLOSE or FD_CONNECT); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.Shutdown(How : Integer); begin if FHSocket <> INVALID_SOCKET then WSocket_shutdown(FHSocket, How); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.DeleteBufferedData; var nItem : Integer; begin { Delete all data buffer } for nItem := 0 to FBufList.Count - 1 do TBuffer(FBufList.Items[nItem]).Free; FBufList.Clear; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.Abort; begin CancelDnsLookup; DeleteBufferedData; { Be sure to close as fast as possible (abortive close) } if (State = wsConnected) and (FProto = IPPROTO_TCP) then begin LingerOnOff := wsLingerOff; SetLingerOption; end; InternalClose(FALSE, 0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.Close; begin InternalClose(TRUE, 0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.Flush; begin while (FHSocket <> INVALID_SOCKET) and { No more socket } (not bAllSent) do begin { Nothing to send } { Break; } TryToSend; MessagePump; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.InternalClose(bShut : Boolean; Error : Word); var iStatus : integer; { Buffer : array [0..127] of Char; } begin if FHSocket = INVALID_SOCKET then begin if FState <> wsClosed then begin ChangeState(wsClosed); AssignDefaultValue; end; exit; end; if FState = wsClosed then Exit; { 11/10/98 called shutdown(1) instead of shutdonw(2). This disable only } { reception. Disabling data send produced data lost is some cases. For } { example when a client open the connection, send some data fast then close } { the connection immediately, even using the linger option. } if bShut then ShutDown(1); if FHSocket <> INVALID_SOCKET then begin repeat { Close the socket } iStatus := WSocket_closesocket(FHSocket); FHSocket := INVALID_SOCKET; if iStatus <> 0 then begin FLastError := WSocket_WSAGetLastError; if FLastError <> WSAEWOULDBLOCK then begin { Ignore the error occuring when winsock DLL not } { initialized (occurs when using TWSocket from a DLL) } if FLastError = WSANOTINITIALISED then break; SocketError('Disconnect (closesocket)'); Exit; end; MessagePump; end; until iStatus = 0; end; ChangeState(wsClosed); if (not (csDestroying in ComponentState)) and (not FCloseInvoked) and Assigned(FOnSessionClosed) then begin FCloseInvoked := TRUE; TriggerSessionClosed(Error); end; { 29/09/98 Protect AssignDefaultValue because SessionClosed event handler } { may have destroyed the component. } try AssignDefaultValue; except end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.WaitForClose; var lCount : LongInt; Status : Integer; Ch : Char; begin while (FHSocket <> INVALID_SOCKET) and (FState <> wsClosed) do begin MessagePump; if WSocket_ioctlsocket(FHSocket, FIONREAD, lCount) = SOCKET_ERROR then break; if lCount > 0 then TriggerDataAvailable(0); Status := DoRecv(Ch, 0, 0); if Status <= 0 then begin FLastError := WSocket_WSAGetLastError; if FLastError <> WSAEWOULDBLOCK then break; end; MessagePump; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocketGetHostByAddr(Addr : String) : PHostEnt; var szAddr : array[0..256] of char; lAddr : u_long; begin { if not DllStarted then LoadWinsock(WINSOCKET); 14/02/99 } StrPCopy(szAddr, Addr); lAddr := WSocket_inet_addr(szAddr); Result := winsock.gethostbyaddr(PChar(@lAddr), 4, PF_INET); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocketResolveIp(IpAddr : String) : String; var Phe : PHostEnt; begin phe := WSocketGetHostByAddr(IpAddr); if Phe = nil then Result := '' else begin SetLength(Result, StrLen(Phe^.h_name)); StrCopy(@Result[1], Phe^.h_name); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocketGetHostByName(Name : String) : PHostEnt; var szName : array[0..256] of char; begin { if not DllStarted then LoadWinsock(WINSOCKET); 14/02/99 } StrPCopy(szName, Name); Result := WSocket_gethostbyname(szName); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function LocalIPList : TStrings; var phe : PHostEnt; begin IPList.Clear; Result := IPList; phe := WSocketGetHostByName(LocalHostName); if phe <> nil then GetIpList(Phe, IPList); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function LocalHostName : String; var Buffer : array [0..63] of char; begin { if not DllStarted then LoadWinsock(WINSOCKET); 14/02/99 } if WSocket_gethostname(Buffer, SizeOf(Buffer)) <> 0 then raise ESocketException.Create('Winsock.GetHostName failed'); Result := StrPas(Buffer); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomWSocket.TimerIsSet(var tvp : TTimeVal) : Boolean; begin Result := (tvp.tv_sec <> 0) or (tvp.tv_usec <> 0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomWSocket.TimerCmp(var tvp : TTimeVal; var uvp : TTimeVal; IsEqual : Boolean) : Boolean; begin Result := (tvp.tv_sec = uvp.tv_sec) and (tvp.tv_usec = uvp.tv_usec); if not IsEqual then Result := not Result; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.TimerClear(var tvp : TTimeVal); begin tvp.tv_sec := 0; tvp.tv_usec := 0; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.SetSendFlags(newValue : TSocketSendFlags); begin case newValue of wsSendNormal: FSendFlags := 0; wsSendUrgent: FSendFlags := MSG_OOB; else RaiseException('Invalid SendFlags'); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomWSocket.GetSendFlags : TSocketSendFlags; begin case FSendFlags of 0 : Result := wsSendNormal; MSG_OOB : Result := wsSendUrgent; else RaiseException('Invalid internal SendFlags'); Result := wsSendNormal; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.TriggerDisplay(Msg : String); begin if Assigned(FOnDisplay) then FOnDisplay(Self, Msg); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.TriggerSessionAvailable(Error : Word); begin if Assigned(FOnSessionAvailable) then FOnSessionAvailable(Self, Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.TriggerSessionConnected(Error : Word); begin if Assigned(FOnSessionConnected) then FOnSessionConnected(Self, Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.TriggerSessionClosed(Error : Word); begin if Assigned(FOnSessionClosed) then FOnSessionClosed(Self, Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomWSocket.TriggerDataAvailable(Error : Word) : Boolean; begin Result := Assigned(FOnDataAvailable); if not Result then Exit; {$IFDEF TOMASEK} { 23/01/99 } { Do not allow FD_READ messages, this will prevent reentering the } { OnDataAvailable event handler. } WSocket_WSAASyncSelect(FHSocket, Handle, WM_ASYNCSELECT, FD_WRITE or FD_CLOSE or FD_CONNECT); try FRcvdFlag := TRUE; while Result and FRcvdFlag do begin { Trigger user code. This will normally call DoRecv which will } { update FRcvdFlag. } { If user code is wrong, we'll loop forever ! } FOnDataAvailable(Self, Error); Result := Assigned(FOnDataAvailable); end; finally { Allow all events now } WSocket_WSAASyncSelect(FHSocket, Handle, WM_ASYNCSELECT, FD_READ or FD_WRITE or FD_CLOSE or FD_CONNECT); end; {$ELSE} { 23/01/99 } FOnDataAvailable(Self, Error); { 23/01/99 } {$ENDIF} { 23/01/99 } end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.TriggerDataSent(Error : Word); begin if Assigned(FOnDataSent) then FOnDataSent(Self, Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.TriggerError; begin if Assigned(FOnError) then FOnError(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.TriggerDNSLookupDone(Error : Word); begin if Assigned(FOnDNSLookupDone) then FOnDNSLookupDone(Self, Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.TriggerChangeState(OldState, NewState : TSocketState); begin if Assigned(FOnChangeState) then FOnChangeState(Self, OldState, NewState); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomWSocket.SocketError(sockfunc: string); var Error : integer; Line : string; begin Error := WSocket_WSAGetLastError; Line := 'Error '+ IntToStr(Error) + ' in function ' + sockfunc + #13#10 + WSocketErrorDesc(Error); if (Error = WSAECONNRESET) or (Error = WSAENOTCONN) then begin WSocket_closesocket(FHSocket); FHSocket := INVALID_SOCKET; ChangeState(wsClosed); end; FLastError := Error; RaiseException(Line); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WSocketErrorDesc(error: integer) : string; begin case error of 0: WSocketErrorDesc := 'No Error'; WSAEINTR: WSocketErrorDesc := 'Interrupted system call'; WSAEBADF: WSocketErrorDesc := 'Bad file number'; WSAEACCES: WSocketErrorDesc := 'Permission denied'; WSAEFAULT: WSocketErrorDesc := 'Bad address'; WSAEINVAL: WSocketErrorDesc := 'Invalid argument'; WSAEMFILE: WSocketErrorDesc := 'Too many open files'; WSAEWOULDBLOCK: WSocketErrorDesc := 'Operation would block'; WSAEINPROGRESS: WSocketErrorDesc := 'Operation now in progress'; WSAEALREADY: WSocketErrorDesc := 'Operation already in progress'; WSAENOTSOCK: WSocketErrorDesc := 'Socket operation on non-socket'; WSAEDESTADDRREQ: WSocketErrorDesc := 'Destination address required'; WSAEMSGSIZE: WSocketErrorDesc := 'Message too long'; WSAEPROTOTYPE: WSocketErrorDesc := 'Protocol wrong type for socket'; WSAENOPROTOOPT: WSocketErrorDesc := 'Protocol not available'; WSAEPROTONOSUPPORT: WSocketErrorDesc := 'Protocol not supported'; WSAESOCKTNOSUPPORT: WSocketErrorDesc := 'Socket type not supported'; WSAEOPNOTSUPP: WSocketErrorDesc := 'Operation not supported on socket'; WSAEPFNOSUPPORT: WSocketErrorDesc := 'Protocol family not supported'; WSAEAFNOSUPPORT: WSocketErrorDesc := 'Address family not supported by protocol family'; WSAEADDRINUSE: WSocketErrorDesc := 'Address already in use'; WSAEADDRNOTAVAIL: WSocketErrorDesc := 'Address not available'; WSAENETDOWN: WSocketErrorDesc := 'Network is down'; WSAENETUNREACH: WSocketErrorDesc := 'Network is unreachable'; WSAENETRESET: WSocketErrorDesc := 'Network dropped connection on reset'; WSAECONNABORTED: WSocketErrorDesc := 'Connection aborted'; WSAECONNRESET: WSocketErrorDesc := 'Connection reset by peer'; WSAENOBUFS: WSocketErrorDesc := 'No buffer space available'; WSAEISCONN: WSocketErrorDesc := 'Socket is already connected'; WSAENOTCONN: WSocketErrorDesc := 'Socket is not connected'; WSAESHUTDOWN: WSocketErrorDesc := 'Can''t send after socket shutdown'; WSAETOOMANYREFS: WSocketErrorDesc := 'Too many references: can''t splice'; WSAETIMEDOUT: WSocketErrorDesc := 'Connection timed out'; WSAECONNREFUSED: WSocketErrorDesc := 'Connection refused'; WSAELOOP: WSocketErrorDesc := 'Too many levels of symbolic links'; WSAENAMETOOLONG: WSocketErrorDesc := 'File name too long'; WSAEHOSTDOWN: WSocketErrorDesc := 'Host is down'; WSAEHOSTUNREACH: WSocketErrorDesc := 'No route to host'; WSAENOTEMPTY: WSocketErrorDesc := 'Directory not empty'; WSAEPROCLIM: WSocketErrorDesc := 'Too many processes'; WSAEUSERS: WSocketErrorDesc := 'Too many users'; WSAEDQUOT: WSocketErrorDesc := 'Disc quota exceeded'; WSAESTALE: WSocketErrorDesc := 'Stale NFS file handle'; WSAEREMOTE: WSocketErrorDesc := 'Too many levels of remote in path'; WSASYSNOTREADY: WSocketErrorDesc := 'Network sub-system is unusable'; WSAVERNOTSUPPORTED: WSocketErrorDesc := 'WinSock DLL cannot support this application'; WSANOTINITIALISED: WSocketErrorDesc := 'WinSock not initialized'; WSAHOST_NOT_FOUND: WSocketErrorDesc := 'Host not found'; WSATRY_AGAIN: WSocketErrorDesc := 'Non-authoritative host not found'; WSANO_RECOVERY: WSocketErrorDesc := 'Non-recoverable error'; WSANO_DATA: WSocketErrorDesc := 'No Data'; else WSocketErrorDesc := 'Not a WinSock error'; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomSocksWSocket.AssignDefaultValue; begin inherited AssignDefaultValue; FSocksState := socksData; FSocksServer := ''; FSocksPort := ''; FSocksLevel := '5'; FRcvdCnt := 0; FSocksPortAssigned := FALSE; FSocksServerAssigned := FALSE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomSocksWSocket.SetSocksLevel(newValue : String); begin if State <> wsClosed then begin RaiseException('Can''t change socks level if not closed'); Exit; end; if (newValue <> '4') and (newValue <> '5') and (newValue <> '4A') and (newValue <> '4a') then begin RaiseException('Invalid socks level. Must be 4, 4A or 5.'); Exit; end; FSocksLevel := UpperCase(newValue); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomSocksWSocket.SetSocksPort(sPort : String); begin if State <> wsClosed then begin RaiseException('Can''t change socks port if not closed'); Exit; end; FSocksPort := Trim(sPort); if Length(FSocksPort) = 0 then begin FSocksPortAssigned := FALSE; Exit; end; FSocksPortAssigned := TRUE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomSocksWSocket.SetSocksServer(sServer : String); begin if State <> wsClosed then begin RaiseException('Can''t change socks server if not closed'); Exit; end; FSocksServer := Trim(sServer); if Length(FSocksServer) = 0 then begin FSocksServerAssigned := FALSE; Exit; end; FSocksServerAssigned := TRUE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomSocksWSocket.Listen; begin { Check if we really wants to use socks server } if not FSocksServerAssigned then begin { No socks server assigned, Listen as usual } inherited Listen; Exit; end; RaiseException('listening is not supported thru socks server'); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomSocksWSocket.Connect; begin { Check if we really wants to use socks server } if not FSocksServerAssigned then begin { No socks server assigned, connect as usual } inherited Connect; Exit; end; if LowerCase(FProtoStr) <> 'tcp' then begin RaiseException('tcp is the only protocol supported thru socks server'); Exit; end; try if not FPortResolved then begin { The next line will trigger an exception in case of failure } sin.sin_port := WSocket_htons(WSocketResolvePort(FSocksPort, FProtoStr)); FPortResolved := TRUE; end; if not FAddrResolved then begin { The next line will trigger an exception in case of failure } sin.sin_addr.s_addr := WSocketResolveHost(FSocksServer).s_addr; FAddrResolved := TRUE; end; { The next line will trigger an exception in case of failure } FPortNum := WSocketResolvePort(FPortStr, FProtoStr); except on E:Exception do begin RaiseException('connect: ' + E.Message); Exit; end; end; FSocksState := socksNegociateMethods; FRcvCnt := 0; inherited Connect; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {function BufToStr(Buf : PChar; Cnt : Integer) : String; begin Result := ''; while Cnt > 0 do begin if Buf^ in [#32..#126] then Result := Result + Buf^ else Result := Result + '#' + Format('%2.2d', [ord(Buf^)]); Inc(Buf); Dec(Cnt); end; end;} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomSocksWSocket.TriggerSessionConnected(Error : Word); var Buf : array [0..2] of char; begin if FSocksState = socksNegociateMethods then begin TriggerSocksConnected(Error); if Error <> 0 then begin inherited TriggerSessionConnected(Error); Exit; end; if FSocksLevel[1] = '4' then SocksDoConnect else begin if FSocksAuthentication = socksNoAuthentication then FSocksAuthNumber := #$00 { No authentification } else FSocksAuthNumber := #$02; { Usercode/Password } Buf[0] := #$05; { Version number } Buf[1] := #$01; { Number of methods } Buf[2] := FSocksAuthNumber; { Method identifier } {TriggerDisplay('Send = ''' + BufToStr(Buf, 3) + '''');} Send(@Buf, 3); end; end else inherited TriggerSessionConnected(Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomSocksWSocket.TriggerSessionClosed(Error : Word); begin if FSocksState = socksAuthenticate then TriggerSocksAuthState(socksAuthFailure); inherited TriggerSessionClosed(Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomSocksWSocket.TriggerSocksConnected(Error : Word); begin if Assigned(FOnSocksConnected) then FOnSocksConnected(Self, Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomSocksWSocket.TriggerSocksError(Error : Integer; Msg : String); begin if Assigned(FOnSocksError) then FOnSocksError(Self, Error, Msg); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomSocksWSocket.TriggerSocksAuthState(AuthState : TSocksAuthState); begin if Assigned(FOnSocksAuthState) then FOnSocksAuthState(Self, AuthState); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomSocksWSocket.SocksDoAuthenticate; var Buf : array [0..127] of char; I : Integer; begin FSocksState := socksAuthenticate; TriggerSocksAuthState(socksAuthStart); Buf[0] := #$01; {06/03/99} { Socks version } I := 1; Buf[I] := chr(Length(FSocksUsercode)); Move(FSocksUsercode[1], Buf[I + 1], Length(FSocksUsercode)); I := I + 1 + Length(FSocksUsercode); Buf[I] := chr(Length(FSocksPassword)); Move(FSocksPassword[1], Buf[I + 1], Length(FSocksPassword)); I := I + 1 + Length(FSocksPassword); try {TriggerDisplay('Send = ''' + BufToStr(Buf, I) + '''');} Send(@Buf, I); except end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomSocksWSocket.SocksDoConnect; type pu_long = ^u_long; var Buf : array [0..127] of char; I : Integer; ErrCode : Integer; begin FSocksState := socksConnect; if FSocksLevel[1] = '4' then begin Buf[0] := #4; Buf[1] := #1; PWORD(@Buf[2])^ := WSocket_ntohs(FPortNum); if FSocksLevel = '4A' then pu_long(@Buf[4])^ := WSocket_inet_addr('0.0.0.1') else begin try pu_long(@Buf[4])^ := WSocketResolveHost(FAddrStr).s_addr; except on E:Exception do begin ErrCode := socksHostResolutionFailed; TriggerSocksError(ErrCode, E.ClassName + ' ' + E.Message); InternalClose(TRUE, ErrCode); Exit; end; end; end; I := 8; if Length(FSocksUsercode) > 0 then begin { I'm not sure it has to be like that ! Should I also use the } { password or not ? } Move(FSocksUsercode[1], Buf[I], Length(FSocksUsercode)); I := I + Length(FSocksUsercode); end; Buf[I] := #0; Inc(I); if FSocksLevel = '4A' then begin Move(FAddrStr[1], Buf[I], Length(FAddrStr)); I := I + Length(FAddrStr); end; Buf[I] := #0; Inc(I); end else begin Buf[0] := #$05; { Socks version } Buf[1] := #$01; { Connect command } Buf[2] := #$00; { Reserved, must be $00 } Buf[3] := #$03; { Address type is domain name } Buf[4] := chr(Length(FAddrStr)); { Should check buffer overflow } Move(FAddrStr[1], Buf[5], Length(FAddrStr)); I := 5 + Length(FAddrStr); PWord(@Buf[I])^ := WSocket_htons(FPortNum); I := I + 2; end; try {TriggerDisplay('Send = ''' + BufToStr(Buf, I + 2) + '''');} Send(@Buf, I); except end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomSocksWSocket.DataAvailableError( ErrCode : Integer; Msg : String); begin TriggerSocksError(ErrCode, Msg); inherited TriggerSessionConnected(ErrCode); InternalClose(TRUE, ErrCode); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomSocksWSocket.TriggerDataAvailable(Error : Word) : Boolean; var Len : Integer; I : Integer; ErrCode : Word; ErrMsg : String; InAddr : TInAddr; AnsLen : Integer; begin if FSocksState = socksData then begin Result := inherited TriggerDataAvailable(Error); Exit; end; if Error <> 0 then begin DataAvailableError(Error, 'data receive error'); Result := FALSE; Exit; end; if FSocksState = socksNegociateMethods then begin Result := TRUE; Len := Receive(@FRcvBuf[FRcvCnt], Sizeof(FRcvBuf) - FRcvCnt - 1); if Len < 0 then Exit; FRcvCnt := FRcvCnt + Len; {TriggerDisplay('socksNegociateMethods FrcvBuf = ''' + BufToStr(FRcvBuf, FRcvCnt) + '''');} if FSocksLevel[1] = '4' then begin { We should never comes here } DataAvailableError(socksProtocolError, 'TWSocket logic error'); Exit; end else begin { SOCKS5 } { We are waiting only two bytes } if FRcvCnt < 2 then Exit; { if FRcvCnt <> 2 then begin 06/03/99} { DataAvailableError(socksProtocolError, 'too much data availaible');} { Exit; } { end; } FRcvCnt := 0; { Clear receive counter } if FRcvBuf[0] <> #$05 then begin DataAvailableError(socksVersionError, 'socks version error'); Exit; end; if FRcvBuf[1] = #$00 then begin { No authentication required } if FSocksAuthNumber <> #$00 then { We asked for authentification, so complains... } TriggerSocksAuthState(socksAuthNotRequired); end else if FRcvBuf[1] = #$02 then begin { Usercode/Password authentication required } SocksDoAuthenticate; Exit; end else begin DataAvailableError(socksAuthMethodError, 'authentification method not acceptable'); Exit; end; SocksDoConnect; end; end else if FSocksState = socksConnect then begin Result := TRUE; {TriggerDisplay('socksConnect FrcvBuf = ''' + BufToStr(FRcvBuf, FRcvCnt) + '''');} if FSocksLevel[1] = '4' then begin { We wants at most 8 characters } Len := Receive(@FRcvBuf[FRcvCnt], 8 - FRcvCnt); if Len < 0 then Exit; FRcvCnt := FRcvCnt + Len; { We are waiting for 8 bytes } if FRcvCnt < 8 then Exit; FRcvCnt := 0; { Clear receive counter } if FRcvBuf[0] <> #0 then begin DataAvailableError(socksVersionError, 'socks version error'); Exit; end; if FRcvBuf[1] = #$90 then begin case FRcvBuf[1] of #$91: ErrCode := socksRejectedOrFailed; #$92: ErrCode := socksConnectionRefused; #$93: ErrCode := socksAuthenticationFailed; else ErrCode := socksUnassignedError; end; case ErrCode of socksRejectedOrFailed : ErrMsg := 'request rejected or failed'; socksConnectionRefused : ErrMsg := 'connection refused'; socksAuthenticationFailed : ErrMsg := 'authentification failed'; else ErrMsg := 'unassigned error #' + IntToStr(Ord(FRcvBuf[1])); end; DataAvailableError(ErrCode, ErrMsg); Exit; end; FSocksState := socksData; inherited TriggerSessionConnected(0); Result := inherited TriggerDataAvailable(0); end else begin { SOCKS5 } Len := Receive(@FRcvBuf[FRcvCnt], Sizeof(FRcvBuf) - FRcvCnt - 1); if Len < 0 then Exit; FRcvCnt := FRcvCnt + Len; if FRcvCnt >= 1 then begin { First byte is version, we expect version 5 } if FRcvBuf[0] <> #$05 then begin DataAvailableError(socksVersionError, 'socks version error'); Exit; end; end; if FRcvCnt >= 2 then begin if FRcvBuf[1] <> #$00 then begin case FRcvBuf[1] of #1: ErrCode := socksGeneralFailure; #2: ErrCode := socksConnectionNotAllowed; #3: ErrCode := socksNetworkUnreachable; #4: ErrCode := socksHostUnreachable; #5: ErrCode := socksConnectionRefused; #6: ErrCode := socksTtlExpired; #7: ErrCode := socksUnknownCommand; #8: ErrCode := socksUnknownAddressType; else ErrCode := socksUnassignedError; end; case ErrCode of socksGeneralFailure : ErrMsg := 'general SOCKS server failure'; socksConnectionNotAllowed : ErrMsg := 'connection not allowed by ruleset'; socksNetworkUnreachable : ErrMsg := 'network unreachable'; socksHostUnreachable : ErrMsg := 'host unreachable'; socksConnectionRefused : ErrMsg := 'connection refused'; socksTtlExpired : ErrMsg := 'time to live expired'; socksUnknownCommand : ErrMsg := 'command not supported'; socksUnknownAddressType : ErrMsg := 'address type not supported'; else ErrMsg := 'unassigned error #' + IntToStr(Ord(FRcvBuf[1])); end; DataAvailableError(ErrCode, ErrMsg); Exit; end; end; if FRcvCnt < 5 then Exit; { We have enough data to learn the answer length } if FRcvBuf[3] = #$01 then AnsLen := 10 { IP V4 address } else if FRcvBuf[3] = #$03 then AnsLen := 7 + Ord(FRcvBuf[4]) { Domain name } else AnsLen := 5; { Other unsupported } if FRcvCnt < AnsLen then Exit; if FRcvBuf[3] = #$01 then begin { IP V4 address } Move(FRcvBuf[4], InAddr, 4); FBoundAddr := StrPas(WSocket_inet_ntoa(InAddr)); I := 4 + 4; end else if FRcvBuf[3] = #$03 then begin { Domain name } SetLength(FBoundAddr, Ord(FRcvBuf[4])); Move(FRcvBuf[4], FBoundAddr[1], Length(FBoundAddr)); I := 4 + Ord(FRcvBuf[4]) + 1; end else begin { Unsupported address type } DataAvailableError(socksUnknownAddressType, 'address type not supported'); Exit; end; FBoundPort := format('%d', [WSocket_ntohs(PWord(@FRcvBuf[I])^)]); I := I + 2; FSocksState := socksData; inherited TriggerSessionConnected(0); FRcvdCnt := FRcvCnt - I; if FRcvdCnt < 0 then FRcvdCnt := 0 else FRcvdPtr := @FRcvBuf[I]; Result := inherited TriggerDataAvailable(0); end; end else if FSocksState = socksAuthenticate then begin Result := TRUE; Len := Receive(@FRcvBuf[FRcvCnt], Sizeof(FRcvBuf) - FRcvCnt - 1); if Len < 0 then Exit; FRcvCnt := FRcvCnt + Len; {TriggerDisplay('socksAuthenticate FrcvBuf = ''' + BufToStr(FRcvBuf, FRcvCnt) + '''');} if FRcvCnt >= 1 then begin { First byte is version, we expect version 5 } if FRcvBuf[0] <> #$01 then begin { 06/03/99 } TriggerSocksAuthState(socksAuthFailure); DataAvailableError(socksVersionError, 'socks version error'); Exit; end; end; if FRcvCnt = 2 then begin { Second byte is status } if FRcvBuf[1] <> #$00 then begin TriggerSocksAuthState(socksAuthFailure); DataAvailableError(socksAuthenticationFailed, 'socks authentication failed'); Exit; end; end else if FRcvCnt > 2 then begin TriggerSocksAuthState(socksAuthFailure); DataAvailableError(socksProtocolError, 'too much data availaible'); Exit; end; FRcvCnt := 0; { 06/03/99 } TriggerSocksAuthState(socksAuthSuccess); SocksDoConnect; end else begin { We should never comes here ! } DataAvailableError(socksInternalError, 'internal error'); Result := FALSE; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomSocksWSocket.GetRcvdCount : LongInt; begin if FRcvdCnt <= 0 then Result := inherited GetRcvdCount else Result := FRcvdCnt; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomSocksWSocket.DoRecv( var Buffer; BufferSize : Integer; Flags : Integer) : Integer; begin if FRcvdCnt <= 0 then begin Result := inherited DoRecv(Buffer, BufferSize, Flags); Exit; end; { We already have received data into our internal buffer } if FRcvdCnt <= BufferSize then begin { User buffer is greater than received data, copy all and clear } Move(FRcvdPtr^, Buffer, FRcvdCnt); Result := FRcvdCnt; FRcvdCnt := 0; Exit; end; { User buffer is smaller, copy as much as possible } Move(FRcvdPtr^, Buffer, BufferSize); Result := BufferSize; FRcvdPtr := FRcvdPtr + BufferSize; FRcvdCnt := FRcvdCnt - BufferSize; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TCustomLineWSocket.Create(AOwner: TComponent); begin inherited Create(AOwner); FLineEnd := #13#10; FLineMode := FALSE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TCustomLineWSocket.Destroy; begin if FRcvdPtr <> nil then begin FreeMem(FRcvdPtr, FRcvBufSize); FRcvdPtr := nil; FRcvBufSize := 0; end; inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomLineWSocket.WndProc(var MsgRec: TMessage); begin with MsgRec do begin if Msg = WM_TRIGGER_DATA_AVAILABLE then begin { We *MUST* handle all exception to avoid application shutdown } try WMTriggerDataAvailable(MsgRec) except on E:Exception do HandleBackGroundException(E); end; end else inherited WndProc(MsgRec); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomLineWSocket.WMTriggerDataAvailable(var msg: TMessage); begin while FRcvdCnt > 0 do TriggerDataAvailable(0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomLineWSocket.SetLineMode(newValue : Boolean); begin if FLineMode = newValue then Exit; FLineMode := newValue; if (FRcvdCnt > 0) or (FLineLength > 0) then PostMessage(Handle, WM_TRIGGER_DATA_AVAILABLE, 0, 0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomLineWSocket.GetRcvdCount : LongInt; begin if not FLineMode then Result := inherited GetRcvdCount else Result := FLineLength; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomLineWSocket.DoRecv( var Buffer; BufferSize : Integer; Flags : Integer) : Integer; begin if FLineMode and (FLineLength > 0) then begin { We are in line mode an a line is received } if FLineLength <= BufferSize then begin { User buffer is greater than received data, copy all and clear } Move(FRcvdPtr^, Buffer, FLineLength); Result := FLineLength; FLineLength := 0; Exit; end; { User buffer is smaller, copy as much as possible } Move(FRcvdPtr^, Buffer, BufferSize); Result := BufferSize; { Move the end of line to beginning of buffer to be read the next time } Move(FRcvdPtr[BufferSize], FRcvdPtr^, FLineLength - BufferSize); FLineLength := FLineLength - BufferSize; Exit; end; if FLineMode or (FRcvdCnt <= 0) then begin { There is nothing in our internal buffer } Result := inherited DoRecv(Buffer, BufferSize, Flags); Exit; end; { We already have received data into our internal buffer } if FRcvdCnt <= BufferSize then begin { User buffer is greater than received data, copy all and clear } Move(FRcvdPtr^, Buffer, FRcvdCnt); Result := FRcvdCnt; FRcvdCnt := 0; Exit; end; { User buffer is smaller, copy as much as possible } Move(FRcvdPtr^, Buffer, BufferSize); Result := BufferSize; FRcvdPtr := FRcvdPtr + BufferSize; FRcvdCnt := FRcvdCnt - BufferSize; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Edit received data. Handle TAB and BACKSPACE characters. } { A data packet has been received into FRcvPtr buffer, starting from } { FRcvdCnt offset. Packet size if passed as the Len argument. } procedure TCustomLineWSocket.EditLine(var Len : Integer); var Buf : PChar; BufSize : Integer; I : Integer; J : Integer; Edited : Boolean; NewCnt : Integer; NewSize : Integer; const BackString : String = #8 + ' ' + #8; begin BufSize := 0; try Edited := FALSE; I := FRcvdCnt; J := FRcvdCnt; NewCnt := FRcvdCnt; { Loop to process all received char } while I < (FRcvdCnt + Len) do begin if FRcvdPtr[I] = #8 then begin { BACKSPACE character } if FLineEcho and (J > 0) then SendStr(BackString); if not Edited then begin { Not edited yet, so we allocate a buffer to store } { edited data and we remember we edited data. } Edited := TRUE; { Computer buffer size as a multiple of 256 bytes } BufSize := ((FRcvdCnt + Len + 256) shr 8) shl 8; GetMem(Buf, BufSize); { Copy data already processed } Move(FRcvdPtr^, Buf^, I); end; if J > 0 then begin Dec(J); if J < NewCnt then NewCnt := J; end; Inc(I); end else if FRcvdPtr[I] = #9 then begin { TAB character } if not Edited then begin { Not edited yet, so we allocate a buffer to store } { edited data and we remember we edited data. } Edited := TRUE; { Computer buffer size as a multiple of 256 bytes } BufSize := ((FRcvdCnt + Len + 256) shr 8) shl 8; GetMem(Buf, BufSize); { Copy data already processed } Move(FRcvdPtr^, Buf^, I); end; repeat if FLineEcho then SendStr(' '); Buf[J] := ' '; Inc(J); until (J and 7) = 0; Inc(I); end else begin if FLineEcho then Send(@FRcvdPtr[I], 1); if Edited then begin if J >= BufSize then begin { Need to allocate more buffer space } NewSize := BufSize + 256; {$IFDEF VER80} ReallocMem(Buf, BufSize, NewSize); {$ELSE} ReallocMem(Buf, NewSize); {$ENDIF} BufSize := NewSize; end; Buf[J] := FRcvdPtr[I]; end; Inc(I); Inc(J); end; end; if Edited then begin if J >= FRcvBufSize then begin { Current buffer is too small, allocate larger } NewSize := J + 1; {$IFDEF VER80} ReallocMem(FRcvdPtr, FRcvBufSize, NewSize); {$ELSE} ReallocMem(FRcvdPtr, NewSize); {$ENDIF} FRcvBufSize := NewSize; end; { Move edited data back to original buffer } Move(Buf^, FRcvdPtr^, J); FRcvdPtr[J] := #0; FRcvdCnt := NewCnt; Len := J - FRcvdCnt; end; finally if BufSize > 0 then FreeMem(Buf, BufSize); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomLineWSocket.TriggerDataAvailable(Error : Word) : Boolean; var Cnt : Integer; Len : Integer; NewSize : Integer; SearchFrom : Integer; I : Integer; Found : Boolean; begin if (not FLineMode) or (Length(FLineEnd) = 0) then begin { We are not in line mode } Result := inherited TriggerDataAvailable(Error); Exit; end; { We are in line mode. We receive data ourself } Result := TRUE; Cnt := inherited GetRcvdCount; if Cnt <= 0 then Exit; if (FRcvdCnt + Cnt + 1) > FRcvBufSize then begin { Current buffer is too small, allocate larger } NewSize := FRcvdCnt + Cnt + 1; {$IFDEF VER80} ReallocMem(FRcvdPtr, FRcvBufSize, NewSize); {$ELSE} ReallocMem(FRcvdPtr, NewSize); {$ENDIF} FRcvBufSize := NewSize; end; Len := Receive(FRcvdPtr + FRcvdCnt, Cnt); if Len <= 0 then Exit; FRcvdPtr[FRcvdCnt + Len] := #0; if FLineEdit then EditLine(Len) else if FLineEcho then Send(FRcvdPtr + FRcvdCnt, Len); SearchFrom := FRcvdCnt - Length(FLineEnd); if SearchFrom < 0 then SearchFrom := 0; FRcvdCnt := FRcvdCnt + Len; while FLineMode do begin Found := FALSE; I := SearchFrom; while I < (FRcvdCnt - Length(FLineEnd) + 1) do begin if FRcvdPtr[I] = FLineEnd[1] then begin Found := (StrLComp(@FRcvdPtr[I], @FLineEnd[1], Length(FLineEnd)) = 0); if Found then break; { Found the end of line marker } end; Inc(I); end; if not Found then break; FLineLength := I + Length(FLineEnd); FLineReceivedFlag := TRUE; { We received a complete line. We need to signal it to application } { The application may not have a large buffer so we may need } { several events to read the entire line. In the meanwhile, the } { application may turn line mode off. } while FLineMode and (FLineLength > 0) do begin if not inherited TriggerDataAvailable(0) then { There is no handler installed } FLineLength := 0; end; { Move remaining data in front of buffer } if FLineLength > 0 then begin { Line mode was turned off in the middle of a line read. } { We preserve unread line and other received data. } Move(FRcvdPtr[I], FRcvdPtr[FLineLength], FRcvdCnt - I); FRcvdCnt := FRcvdCnt - I + FLineLength; end else begin Move(FRcvdPtr[I + Length(FLineEnd)], FRcvdPtr[0], FRcvdCnt - I - Length(FLineEnd)); FRcvdCnt := FRcvdCnt - I - Length(FLineEnd); end; FRcvdPtr[FRcvdCnt] := #0; SearchFrom := 0; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomLineWSocket.TriggerSessionClosed(Error : Word); begin FLineReceivedFlag := TRUE; if FRcvdPtr <> nil then begin if FLineMode and (FRcvdCnt > 0) then begin FLineLength := FRcvdCnt; while FLineMode and (FLineLength > 0) do inherited TriggerDataAvailable(0); end; FreeMem(FRcvdPtr, FRcvBufSize); FRcvdPtr := nil; FRcvBufSize := 0; FRcvdCnt := 0; end; inherited TriggerSessionClosed(Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomSyncWSocket.InternalDataAvailable( Sender : TObject; Error : Word); var Len : Integer; begin SetLength(FLinePointer^, FLineLength); Len := Receive(@FLinePointer^[1], FLineLength); if Len <= 0 then FLinePointer^ := '' else SetLength(FLinePointer^, Len); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomSyncWSocket.WaitUntilReady(var DoneFlag : Boolean) : Integer; begin Result := 0; { Suppose success } FTimeStop := Integer(GetTickCount) + FTimeout; while TRUE do begin if DoneFlag then begin Result := 0; break; end; if ((FTimeout > 0) and (Integer(GetTickCount) > FTimeStop)) or {$IFNDEF NOFORMS} Application.Terminated or {$ENDIF} FTerminated then begin { Application is terminated or timeout occured } Result := WSA_WSOCKET_TIMEOUT; break; end; MessagePump; {$IFNDEF VER80} { Do not use 100% CPU, but slow down transfert on high speed LAN } Sleep(0); {$ENDIF} end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomSyncWSocket.Synchronize( Proc : TWSocketSyncNextProc; var DoneFlag : Boolean) : Integer; begin DoneFlag := FALSE; if Assigned(Proc) then Proc; Result := WaitUntilReady(DoneFlag); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomSyncWSocket.ReadLine( Timeout : Integer; { seconds if positive, milli-seconds if negative } var Buffer : String); var OldDataAvailable : TDataAvailable; OldLineMode : Boolean; Status : Integer; begin Buffer := ''; if FState <> wsConnected then begin RaiseException('ReadLine failed: not connected'); Exit; end; { Positive timeout means seconds. Negative means milli-seconds } { Null means 60 seconds. } if TimeOut = 0 then FTimeOut := 60000 else if TimeOut > 0 then FTimeOut := Timeout * 1000 else FTimeOut := -Timeout; FLineReceivedFlag := FALSE; FLinePointer := @Buffer; { Save existing OnDataAvailable handler and install our own } OldDataAvailable := FOnDataAvailable; FOnDataAvailable := InternalDataAvailable; { Save existing line mode and turn it on } OldLineMode := FLineMode; FLineMode := TRUE; try Status := Synchronize(nil, FLineReceivedFlag); if Status = WSA_WSOCKET_TIMEOUT then begin { Sender didn't send line end within allowed time. Get all } { data available so far. } if FRcvdCnt > 0 then begin SetLength(Buffer, FRcvdCnt); Move(FRcvdPtr^, Buffer[1], FRcvdCnt); FRcvdCnt := 0; end; end; { Should I raise an exception to tell the application that } { some error occured ? } finally FOnDataAvailable := OldDataAvailable; FLineMode := OldLineMode; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFDEF VER80} begin IPList := TStringList.Create; { Delphi 1 has no finalization. When your application terminates, you should add a call to WSocketUnloadWinsock to unload winsock from memory. It is done automatically for you when the last TWSocket component is destroyed but if you do any winsock call after that, you must call WSocketUnloadWinsock yourself. It is safe to call WSocketUnloadWinsock even if it has already been done. } {$ELSE} initialization IPList := TStringList.Create; finalization if Assigned(IPList) then begin IPList.Destroy; IPList := nil; end; WSocketUnloadWinsock; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
unit vcmTabsWordsPack; // Модуль: "w:\common\components\gui\Garant\VCM\vcmTabsWordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "vcmTabsWordsPack" MUID: (55AE40B600B7) {$Include w:\common\components\gui\Garant\VCM\vcmDefine.inc} interface {$If NOT Defined(NoVCM) AND NOT Defined(NoScripts) AND NOT Defined(NoTabs)} uses l3IntfUses ; {$IfEnd} // NOT Defined(NoVCM) AND NOT Defined(NoScripts) AND NOT Defined(NoTabs) implementation {$If NOT Defined(NoVCM) AND NOT Defined(NoScripts) AND NOT Defined(NoTabs)} uses l3ImplUses , tfwGlobalKeyWord , TypInfo , tfwScriptingInterfaces , l3TabbedContainersDispatcher , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *55AE40B600B7impl_uses* //#UC END# *55AE40B600B7impl_uses* ; type TkwVcmTabsCloseCurrent = {final} class(TtfwGlobalKeyWord) {* Слово скрипта vcm:tabs:CloseCurrent } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwVcmTabsCloseCurrent TkwVcmTabsClose = {final} class(TtfwGlobalKeyWord) {* Слово скрипта vcm:tabs:Close } private procedure vcm_tabs_Close(const aCtx: TtfwContext; aTabIndex: Integer); {* Реализация слова скрипта vcm:tabs:Close } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwVcmTabsClose TkwVcmTabsCloseAllButCurrent = {final} class(TtfwGlobalKeyWord) {* Слово скрипта vcm:tabs:CloseAllButCurrent } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwVcmTabsCloseAllButCurrent TkwVcmTabsActive = {final} class(TtfwGlobalKeyWord) {* Слово скрипта vcm:tabs:Active } private function vcm_tabs_Active(const aCtx: TtfwContext): Integer; {* Реализация слова скрипта vcm:tabs:Active } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwVcmTabsActive TkwVcmTabsSetActive = {final} class(TtfwGlobalKeyWord) {* Слово скрипта vcm:tabs:SetActive } private procedure vcm_tabs_SetActive(const aCtx: TtfwContext; aValue: Integer); {* Реализация слова скрипта vcm:tabs:SetActive } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwVcmTabsSetActive TkwVcmTabsCount = {final} class(TtfwGlobalKeyWord) {* Слово скрипта vcm:tabs:Count } private function vcm_tabs_Count(const aCtx: TtfwContext): Integer; {* Реализация слова скрипта vcm:tabs:Count } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwVcmTabsCount TkwVcmTabsOpenNewTab = {final} class(TtfwGlobalKeyWord) {* Слово скрипта vcm:tabs:OpenNewTab } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwVcmTabsOpenNewTab TkwVcmTabsCanOpenNewTab = {final} class(TtfwGlobalKeyWord) {* Слово скрипта vcm:tabs:CanOpenNewTab } private function vcm_tabs_CanOpenNewTab(const aCtx: TtfwContext): Boolean; {* Реализация слова скрипта vcm:tabs:CanOpenNewTab } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwVcmTabsCanOpenNewTab TkwVcmTabsDuplicate = {final} class(TtfwGlobalKeyWord) {* Слово скрипта vcm:tabs:Duplicate } private procedure vcm_tabs_Duplicate(const aCtx: TtfwContext; aTabIndex: Integer); {* Реализация слова скрипта vcm:tabs:Duplicate } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwVcmTabsDuplicate TkwVcmTabsCanDuplicate = {final} class(TtfwGlobalKeyWord) {* Слово скрипта vcm:tabs:CanDuplicate } private function vcm_tabs_CanDuplicate(const aCtx: TtfwContext; aTabIndex: Integer): Boolean; {* Реализация слова скрипта vcm:tabs:CanDuplicate } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwVcmTabsCanDuplicate TkwVcmTabsReopen = {final} class(TtfwGlobalKeyWord) {* Слово скрипта vcm:tabs:Reopen } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwVcmTabsReopen TkwVcmTabsCanReopen = {final} class(TtfwGlobalKeyWord) {* Слово скрипта vcm:tabs:CanReopen } private function vcm_tabs_CanReopen(const aCtx: TtfwContext): Boolean; {* Реализация слова скрипта vcm:tabs:CanReopen } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwVcmTabsCanReopen TkwVcmTabsGetIconIndex = {final} class(TtfwGlobalKeyWord) {* Слово скрипта vcm:tabs:GetIconIndex } private function vcm_tabs_GetIconIndex(const aCtx: TtfwContext; aTabIndex: Integer): Integer; {* Реализация слова скрипта vcm:tabs:GetIconIndex } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwVcmTabsGetIconIndex TkwVcmTabsGetCaption = {final} class(TtfwGlobalKeyWord) {* Слово скрипта vcm:tabs:GetCaption } private function vcm_tabs_GetCaption(const aCtx: TtfwContext; aTabIndex: Integer): AnsiString; {* Реализация слова скрипта vcm:tabs:GetCaption } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwVcmTabsGetCaption TkwVcmTabsCanUndock = {final} class(TtfwGlobalKeyWord) {* Слово скрипта vcm:tabs:CanUndock } private function vcm_tabs_CanUndock(const aCtx: TtfwContext; aTabIndex: Integer): Boolean; {* Реализация слова скрипта vcm:tabs:CanUndock } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwVcmTabsCanUndock TkwVcmTabsUndock = {final} class(TtfwGlobalKeyWord) {* Слово скрипта vcm:tabs:Undock } private procedure vcm_tabs_Undock(const aCtx: TtfwContext; aTabIndex: Integer); {* Реализация слова скрипта vcm:tabs:Undock } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwVcmTabsUndock class function TkwVcmTabsCloseCurrent.GetWordNameForRegister: AnsiString; begin Result := 'vcm:tabs:CloseCurrent'; end;//TkwVcmTabsCloseCurrent.GetWordNameForRegister function TkwVcmTabsCloseCurrent.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwVcmTabsCloseCurrent.GetResultTypeInfo function TkwVcmTabsCloseCurrent.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 0; end;//TkwVcmTabsCloseCurrent.GetAllParamsCount function TkwVcmTabsCloseCurrent.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([]); end;//TkwVcmTabsCloseCurrent.ParamsTypes procedure TkwVcmTabsCloseCurrent.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_55AE4C31002C_Word_var* //#UC END# *4DAEEDE10285_55AE4C31002C_Word_var* begin //#UC START# *4DAEEDE10285_55AE4C31002C_Word_impl* Tl3TabbedContainersDispatcher.Instance.GetActiveTabbedContainer.CloseSelectedTab; //#UC END# *4DAEEDE10285_55AE4C31002C_Word_impl* end;//TkwVcmTabsCloseCurrent.DoDoIt procedure TkwVcmTabsClose.vcm_tabs_Close(const aCtx: TtfwContext; aTabIndex: Integer); {* Реализация слова скрипта vcm:tabs:Close } //#UC START# *55AE4C470082_55AE4C470082_Word_var* //#UC END# *55AE4C470082_55AE4C470082_Word_var* begin //#UC START# *55AE4C470082_55AE4C470082_Word_impl* with Tl3TabbedContainersDispatcher.Instance.GetActiveTabbedContainer do CloseTab(Tabs[aTabIndex]); //#UC END# *55AE4C470082_55AE4C470082_Word_impl* end;//TkwVcmTabsClose.vcm_tabs_Close class function TkwVcmTabsClose.GetWordNameForRegister: AnsiString; begin Result := 'vcm:tabs:Close'; end;//TkwVcmTabsClose.GetWordNameForRegister function TkwVcmTabsClose.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwVcmTabsClose.GetResultTypeInfo function TkwVcmTabsClose.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwVcmTabsClose.GetAllParamsCount function TkwVcmTabsClose.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Integer)]); end;//TkwVcmTabsClose.ParamsTypes procedure TkwVcmTabsClose.DoDoIt(const aCtx: TtfwContext); var l_aTabIndex: Integer; begin try l_aTabIndex := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра aTabIndex: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except vcm_tabs_Close(aCtx, l_aTabIndex); end;//TkwVcmTabsClose.DoDoIt class function TkwVcmTabsCloseAllButCurrent.GetWordNameForRegister: AnsiString; begin Result := 'vcm:tabs:CloseAllButCurrent'; end;//TkwVcmTabsCloseAllButCurrent.GetWordNameForRegister function TkwVcmTabsCloseAllButCurrent.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwVcmTabsCloseAllButCurrent.GetResultTypeInfo function TkwVcmTabsCloseAllButCurrent.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 0; end;//TkwVcmTabsCloseAllButCurrent.GetAllParamsCount function TkwVcmTabsCloseAllButCurrent.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([]); end;//TkwVcmTabsCloseAllButCurrent.ParamsTypes procedure TkwVcmTabsCloseAllButCurrent.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_55AE4C630229_Word_var* //#UC END# *4DAEEDE10285_55AE4C630229_Word_var* begin //#UC START# *4DAEEDE10285_55AE4C630229_Word_impl* Tl3TabbedContainersDispatcher.Instance.GetActiveTabbedContainer.CloseAllButActiveTab; //#UC END# *4DAEEDE10285_55AE4C630229_Word_impl* end;//TkwVcmTabsCloseAllButCurrent.DoDoIt function TkwVcmTabsActive.vcm_tabs_Active(const aCtx: TtfwContext): Integer; {* Реализация слова скрипта vcm:tabs:Active } //#UC START# *55AE78F700E1_55AE78F700E1_Word_var* //#UC END# *55AE78F700E1_55AE78F700E1_Word_var* begin //#UC START# *55AE78F700E1_55AE78F700E1_Word_impl* Result := Tl3TabbedContainersDispatcher.Instance.GetActiveTabbedContainer.ActiveTab.VisibleIndex; //#UC END# *55AE78F700E1_55AE78F700E1_Word_impl* end;//TkwVcmTabsActive.vcm_tabs_Active class function TkwVcmTabsActive.GetWordNameForRegister: AnsiString; begin Result := 'vcm:tabs:Active'; end;//TkwVcmTabsActive.GetWordNameForRegister function TkwVcmTabsActive.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Integer); end;//TkwVcmTabsActive.GetResultTypeInfo function TkwVcmTabsActive.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 0; end;//TkwVcmTabsActive.GetAllParamsCount function TkwVcmTabsActive.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([]); end;//TkwVcmTabsActive.ParamsTypes procedure TkwVcmTabsActive.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushInt(vcm_tabs_Active(aCtx)); end;//TkwVcmTabsActive.DoDoIt procedure TkwVcmTabsSetActive.vcm_tabs_SetActive(const aCtx: TtfwContext; aValue: Integer); {* Реализация слова скрипта vcm:tabs:SetActive } //#UC START# *55AE790302E8_55AE790302E8_Word_var* //#UC END# *55AE790302E8_55AE790302E8_Word_var* begin //#UC START# *55AE790302E8_55AE790302E8_Word_impl* with Tl3TabbedContainersDispatcher.Instance.GetActiveTabbedContainer do ActiveTab := Tabs[aValue]; //#UC END# *55AE790302E8_55AE790302E8_Word_impl* end;//TkwVcmTabsSetActive.vcm_tabs_SetActive class function TkwVcmTabsSetActive.GetWordNameForRegister: AnsiString; begin Result := 'vcm:tabs:SetActive'; end;//TkwVcmTabsSetActive.GetWordNameForRegister function TkwVcmTabsSetActive.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwVcmTabsSetActive.GetResultTypeInfo function TkwVcmTabsSetActive.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwVcmTabsSetActive.GetAllParamsCount function TkwVcmTabsSetActive.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Integer)]); end;//TkwVcmTabsSetActive.ParamsTypes procedure TkwVcmTabsSetActive.DoDoIt(const aCtx: TtfwContext); var l_aValue: Integer; begin try l_aValue := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра aValue: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except vcm_tabs_SetActive(aCtx, l_aValue); end;//TkwVcmTabsSetActive.DoDoIt function TkwVcmTabsCount.vcm_tabs_Count(const aCtx: TtfwContext): Integer; {* Реализация слова скрипта vcm:tabs:Count } //#UC START# *55AE79190270_55AE79190270_Word_var* //#UC END# *55AE79190270_55AE79190270_Word_var* begin //#UC START# *55AE79190270_55AE79190270_Word_impl* Result := Tl3TabbedContainersDispatcher.Instance.GetActiveTabbedContainer.TabCount; //#UC END# *55AE79190270_55AE79190270_Word_impl* end;//TkwVcmTabsCount.vcm_tabs_Count class function TkwVcmTabsCount.GetWordNameForRegister: AnsiString; begin Result := 'vcm:tabs:Count'; end;//TkwVcmTabsCount.GetWordNameForRegister function TkwVcmTabsCount.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Integer); end;//TkwVcmTabsCount.GetResultTypeInfo function TkwVcmTabsCount.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 0; end;//TkwVcmTabsCount.GetAllParamsCount function TkwVcmTabsCount.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([]); end;//TkwVcmTabsCount.ParamsTypes procedure TkwVcmTabsCount.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushInt(vcm_tabs_Count(aCtx)); end;//TkwVcmTabsCount.DoDoIt class function TkwVcmTabsOpenNewTab.GetWordNameForRegister: AnsiString; begin Result := 'vcm:tabs:OpenNewTab'; end;//TkwVcmTabsOpenNewTab.GetWordNameForRegister function TkwVcmTabsOpenNewTab.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwVcmTabsOpenNewTab.GetResultTypeInfo function TkwVcmTabsOpenNewTab.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 0; end;//TkwVcmTabsOpenNewTab.GetAllParamsCount function TkwVcmTabsOpenNewTab.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([]); end;//TkwVcmTabsOpenNewTab.ParamsTypes procedure TkwVcmTabsOpenNewTab.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_55AE7931034C_Word_var* //#UC END# *4DAEEDE10285_55AE7931034C_Word_var* begin //#UC START# *4DAEEDE10285_55AE7931034C_Word_impl* Tl3TabbedContainersDispatcher.Instance.GetActiveTabbedContainer.OpenNewTab; //#UC END# *4DAEEDE10285_55AE7931034C_Word_impl* end;//TkwVcmTabsOpenNewTab.DoDoIt function TkwVcmTabsCanOpenNewTab.vcm_tabs_CanOpenNewTab(const aCtx: TtfwContext): Boolean; {* Реализация слова скрипта vcm:tabs:CanOpenNewTab } //#UC START# *55AE794F0259_55AE794F0259_Word_var* //#UC END# *55AE794F0259_55AE794F0259_Word_var* begin //#UC START# *55AE794F0259_55AE794F0259_Word_impl* Result := Tl3TabbedContainersDispatcher.Instance.GetActiveTabbedContainer.CanOpenNewTab; //#UC END# *55AE794F0259_55AE794F0259_Word_impl* end;//TkwVcmTabsCanOpenNewTab.vcm_tabs_CanOpenNewTab class function TkwVcmTabsCanOpenNewTab.GetWordNameForRegister: AnsiString; begin Result := 'vcm:tabs:CanOpenNewTab'; end;//TkwVcmTabsCanOpenNewTab.GetWordNameForRegister function TkwVcmTabsCanOpenNewTab.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwVcmTabsCanOpenNewTab.GetResultTypeInfo function TkwVcmTabsCanOpenNewTab.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 0; end;//TkwVcmTabsCanOpenNewTab.GetAllParamsCount function TkwVcmTabsCanOpenNewTab.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([]); end;//TkwVcmTabsCanOpenNewTab.ParamsTypes procedure TkwVcmTabsCanOpenNewTab.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushBool(vcm_tabs_CanOpenNewTab(aCtx)); end;//TkwVcmTabsCanOpenNewTab.DoDoIt procedure TkwVcmTabsDuplicate.vcm_tabs_Duplicate(const aCtx: TtfwContext; aTabIndex: Integer); {* Реализация слова скрипта vcm:tabs:Duplicate } //#UC START# *55DB1AF403B8_55DB1AF403B8_Word_var* //#UC END# *55DB1AF403B8_55DB1AF403B8_Word_var* begin //#UC START# *55DB1AF403B8_55DB1AF403B8_Word_impl* with Tl3TabbedContainersDispatcher.Instance do CloneTab(GetActiveTabbedContainer.TabByVisibleIndex[aTabIndex]); //#UC END# *55DB1AF403B8_55DB1AF403B8_Word_impl* end;//TkwVcmTabsDuplicate.vcm_tabs_Duplicate class function TkwVcmTabsDuplicate.GetWordNameForRegister: AnsiString; begin Result := 'vcm:tabs:Duplicate'; end;//TkwVcmTabsDuplicate.GetWordNameForRegister function TkwVcmTabsDuplicate.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwVcmTabsDuplicate.GetResultTypeInfo function TkwVcmTabsDuplicate.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwVcmTabsDuplicate.GetAllParamsCount function TkwVcmTabsDuplicate.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Integer)]); end;//TkwVcmTabsDuplicate.ParamsTypes procedure TkwVcmTabsDuplicate.DoDoIt(const aCtx: TtfwContext); var l_aTabIndex: Integer; begin try l_aTabIndex := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра aTabIndex: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except vcm_tabs_Duplicate(aCtx, l_aTabIndex); end;//TkwVcmTabsDuplicate.DoDoIt function TkwVcmTabsCanDuplicate.vcm_tabs_CanDuplicate(const aCtx: TtfwContext; aTabIndex: Integer): Boolean; {* Реализация слова скрипта vcm:tabs:CanDuplicate } //#UC START# *55DB1BAC0203_55DB1BAC0203_Word_var* //#UC END# *55DB1BAC0203_55DB1BAC0203_Word_var* begin //#UC START# *55DB1BAC0203_55DB1BAC0203_Word_impl* with Tl3TabbedContainersDispatcher.Instance do Result := CanCloneTab(GetActiveTabbedContainer.Tabs[aTabIndex]); //#UC END# *55DB1BAC0203_55DB1BAC0203_Word_impl* end;//TkwVcmTabsCanDuplicate.vcm_tabs_CanDuplicate class function TkwVcmTabsCanDuplicate.GetWordNameForRegister: AnsiString; begin Result := 'vcm:tabs:CanDuplicate'; end;//TkwVcmTabsCanDuplicate.GetWordNameForRegister function TkwVcmTabsCanDuplicate.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwVcmTabsCanDuplicate.GetResultTypeInfo function TkwVcmTabsCanDuplicate.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwVcmTabsCanDuplicate.GetAllParamsCount function TkwVcmTabsCanDuplicate.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Integer)]); end;//TkwVcmTabsCanDuplicate.ParamsTypes procedure TkwVcmTabsCanDuplicate.DoDoIt(const aCtx: TtfwContext); var l_aTabIndex: Integer; begin try l_aTabIndex := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра aTabIndex: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(vcm_tabs_CanDuplicate(aCtx, l_aTabIndex)); end;//TkwVcmTabsCanDuplicate.DoDoIt class function TkwVcmTabsReopen.GetWordNameForRegister: AnsiString; begin Result := 'vcm:tabs:Reopen'; end;//TkwVcmTabsReopen.GetWordNameForRegister function TkwVcmTabsReopen.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwVcmTabsReopen.GetResultTypeInfo function TkwVcmTabsReopen.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 0; end;//TkwVcmTabsReopen.GetAllParamsCount function TkwVcmTabsReopen.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([]); end;//TkwVcmTabsReopen.ParamsTypes procedure TkwVcmTabsReopen.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_55DB1B1500D4_Word_var* //#UC END# *4DAEEDE10285_55DB1B1500D4_Word_var* begin //#UC START# *4DAEEDE10285_55DB1B1500D4_Word_impl* with Tl3TabbedContainersDispatcher.Instance do ReopenClosedTab(GetActiveTabbedContainer); //#UC END# *4DAEEDE10285_55DB1B1500D4_Word_impl* end;//TkwVcmTabsReopen.DoDoIt function TkwVcmTabsCanReopen.vcm_tabs_CanReopen(const aCtx: TtfwContext): Boolean; {* Реализация слова скрипта vcm:tabs:CanReopen } //#UC START# *55DB1B7A0137_55DB1B7A0137_Word_var* //#UC END# *55DB1B7A0137_55DB1B7A0137_Word_var* begin //#UC START# *55DB1B7A0137_55DB1B7A0137_Word_impl* with Tl3TabbedContainersDispatcher.Instance do Result := CanReopenClosedTab(GetActiveTabbedContainer); //#UC END# *55DB1B7A0137_55DB1B7A0137_Word_impl* end;//TkwVcmTabsCanReopen.vcm_tabs_CanReopen class function TkwVcmTabsCanReopen.GetWordNameForRegister: AnsiString; begin Result := 'vcm:tabs:CanReopen'; end;//TkwVcmTabsCanReopen.GetWordNameForRegister function TkwVcmTabsCanReopen.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwVcmTabsCanReopen.GetResultTypeInfo function TkwVcmTabsCanReopen.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 0; end;//TkwVcmTabsCanReopen.GetAllParamsCount function TkwVcmTabsCanReopen.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([]); end;//TkwVcmTabsCanReopen.ParamsTypes procedure TkwVcmTabsCanReopen.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushBool(vcm_tabs_CanReopen(aCtx)); end;//TkwVcmTabsCanReopen.DoDoIt function TkwVcmTabsGetIconIndex.vcm_tabs_GetIconIndex(const aCtx: TtfwContext; aTabIndex: Integer): Integer; {* Реализация слова скрипта vcm:tabs:GetIconIndex } //#UC START# *560168780139_560168780139_Word_var* //#UC END# *560168780139_560168780139_Word_var* begin //#UC START# *560168780139_560168780139_Word_impl* with Tl3TabbedContainersDispatcher.Instance do Result := GetTabIcon(GetActiveTabbedContainer.TabByVisibleIndex[aTabIndex]); //#UC END# *560168780139_560168780139_Word_impl* end;//TkwVcmTabsGetIconIndex.vcm_tabs_GetIconIndex class function TkwVcmTabsGetIconIndex.GetWordNameForRegister: AnsiString; begin Result := 'vcm:tabs:GetIconIndex'; end;//TkwVcmTabsGetIconIndex.GetWordNameForRegister function TkwVcmTabsGetIconIndex.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Integer); end;//TkwVcmTabsGetIconIndex.GetResultTypeInfo function TkwVcmTabsGetIconIndex.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwVcmTabsGetIconIndex.GetAllParamsCount function TkwVcmTabsGetIconIndex.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Integer)]); end;//TkwVcmTabsGetIconIndex.ParamsTypes procedure TkwVcmTabsGetIconIndex.DoDoIt(const aCtx: TtfwContext); var l_aTabIndex: Integer; begin try l_aTabIndex := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра aTabIndex: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushInt(vcm_tabs_GetIconIndex(aCtx, l_aTabIndex)); end;//TkwVcmTabsGetIconIndex.DoDoIt function TkwVcmTabsGetCaption.vcm_tabs_GetCaption(const aCtx: TtfwContext; aTabIndex: Integer): AnsiString; {* Реализация слова скрипта vcm:tabs:GetCaption } //#UC START# *56727DFE03B2_56727DFE03B2_Word_var* //#UC END# *56727DFE03B2_56727DFE03B2_Word_var* begin //#UC START# *56727DFE03B2_56727DFE03B2_Word_impl* with Tl3TabbedContainersDispatcher.Instance do Result := GetTabCaption(GetActiveTabbedContainer.TabByVisibleIndex[aTabIndex]); //#UC END# *56727DFE03B2_56727DFE03B2_Word_impl* end;//TkwVcmTabsGetCaption.vcm_tabs_GetCaption class function TkwVcmTabsGetCaption.GetWordNameForRegister: AnsiString; begin Result := 'vcm:tabs:GetCaption'; end;//TkwVcmTabsGetCaption.GetWordNameForRegister function TkwVcmTabsGetCaption.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiString; end;//TkwVcmTabsGetCaption.GetResultTypeInfo function TkwVcmTabsGetCaption.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwVcmTabsGetCaption.GetAllParamsCount function TkwVcmTabsGetCaption.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Integer)]); end;//TkwVcmTabsGetCaption.ParamsTypes procedure TkwVcmTabsGetCaption.DoDoIt(const aCtx: TtfwContext); var l_aTabIndex: Integer; begin try l_aTabIndex := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра aTabIndex: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushString(vcm_tabs_GetCaption(aCtx, l_aTabIndex)); end;//TkwVcmTabsGetCaption.DoDoIt function TkwVcmTabsCanUndock.vcm_tabs_CanUndock(const aCtx: TtfwContext; aTabIndex: Integer): Boolean; {* Реализация слова скрипта vcm:tabs:CanUndock } //#UC START# *5698FB1801C8_5698FB1801C8_Word_var* //#UC END# *5698FB1801C8_5698FB1801C8_Word_var* begin //#UC START# *5698FB1801C8_5698FB1801C8_Word_impl* with Tl3TabbedContainersDispatcher.Instance.GetActiveTabbedContainer do Result := CanUndockFormFromTab(aTabIndex); //#UC END# *5698FB1801C8_5698FB1801C8_Word_impl* end;//TkwVcmTabsCanUndock.vcm_tabs_CanUndock class function TkwVcmTabsCanUndock.GetWordNameForRegister: AnsiString; begin Result := 'vcm:tabs:CanUndock'; end;//TkwVcmTabsCanUndock.GetWordNameForRegister function TkwVcmTabsCanUndock.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwVcmTabsCanUndock.GetResultTypeInfo function TkwVcmTabsCanUndock.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwVcmTabsCanUndock.GetAllParamsCount function TkwVcmTabsCanUndock.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Integer)]); end;//TkwVcmTabsCanUndock.ParamsTypes procedure TkwVcmTabsCanUndock.DoDoIt(const aCtx: TtfwContext); var l_aTabIndex: Integer; begin try l_aTabIndex := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра aTabIndex: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(vcm_tabs_CanUndock(aCtx, l_aTabIndex)); end;//TkwVcmTabsCanUndock.DoDoIt procedure TkwVcmTabsUndock.vcm_tabs_Undock(const aCtx: TtfwContext; aTabIndex: Integer); {* Реализация слова скрипта vcm:tabs:Undock } //#UC START# *5698FB610250_5698FB610250_Word_var* //#UC END# *5698FB610250_5698FB610250_Word_var* begin //#UC START# *5698FB610250_5698FB610250_Word_impl* with Tl3TabbedContainersDispatcher.Instance.GetActiveTabbedContainer do UndockFormFromTab(aTabIndex); //#UC END# *5698FB610250_5698FB610250_Word_impl* end;//TkwVcmTabsUndock.vcm_tabs_Undock class function TkwVcmTabsUndock.GetWordNameForRegister: AnsiString; begin Result := 'vcm:tabs:Undock'; end;//TkwVcmTabsUndock.GetWordNameForRegister function TkwVcmTabsUndock.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwVcmTabsUndock.GetResultTypeInfo function TkwVcmTabsUndock.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwVcmTabsUndock.GetAllParamsCount function TkwVcmTabsUndock.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Integer)]); end;//TkwVcmTabsUndock.ParamsTypes procedure TkwVcmTabsUndock.DoDoIt(const aCtx: TtfwContext); var l_aTabIndex: Integer; begin try l_aTabIndex := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра aTabIndex: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except vcm_tabs_Undock(aCtx, l_aTabIndex); end;//TkwVcmTabsUndock.DoDoIt initialization TkwVcmTabsCloseCurrent.RegisterInEngine; {* Регистрация vcm_tabs_CloseCurrent } TkwVcmTabsClose.RegisterInEngine; {* Регистрация vcm_tabs_Close } TkwVcmTabsCloseAllButCurrent.RegisterInEngine; {* Регистрация vcm_tabs_CloseAllButCurrent } TkwVcmTabsActive.RegisterInEngine; {* Регистрация vcm_tabs_Active } TkwVcmTabsSetActive.RegisterInEngine; {* Регистрация vcm_tabs_SetActive } TkwVcmTabsCount.RegisterInEngine; {* Регистрация vcm_tabs_Count } TkwVcmTabsOpenNewTab.RegisterInEngine; {* Регистрация vcm_tabs_OpenNewTab } TkwVcmTabsCanOpenNewTab.RegisterInEngine; {* Регистрация vcm_tabs_CanOpenNewTab } TkwVcmTabsDuplicate.RegisterInEngine; {* Регистрация vcm_tabs_Duplicate } TkwVcmTabsCanDuplicate.RegisterInEngine; {* Регистрация vcm_tabs_CanDuplicate } TkwVcmTabsReopen.RegisterInEngine; {* Регистрация vcm_tabs_Reopen } TkwVcmTabsCanReopen.RegisterInEngine; {* Регистрация vcm_tabs_CanReopen } TkwVcmTabsGetIconIndex.RegisterInEngine; {* Регистрация vcm_tabs_GetIconIndex } TkwVcmTabsGetCaption.RegisterInEngine; {* Регистрация vcm_tabs_GetCaption } TkwVcmTabsCanUndock.RegisterInEngine; {* Регистрация vcm_tabs_CanUndock } TkwVcmTabsUndock.RegisterInEngine; {* Регистрация vcm_tabs_Undock } TtfwTypeRegistrator.RegisterType(TypeInfo(Integer)); {* Регистрация типа Integer } TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean)); {* Регистрация типа Boolean } TtfwTypeRegistrator.RegisterType(@tfw_tiString); {* Регистрация типа AnsiString } {$IfEnd} // NOT Defined(NoVCM) AND NOT Defined(NoScripts) AND NOT Defined(NoTabs) end.
unit Androidapi.JNI.baidu.mapapi; // ==================================================== // Android Baidu Map SDK interface // package:com.baidu.map // author:Xubzhlin // email:371889755@qq.com // // date:2017.5.10 // version:4.3.0 // ==================================================== interface uses Androidapi.JNIBridge, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes; type // ===== Forward declarations ===== JModuleName = interface; // com.baidu.mapapi.ModuleName JCoordType = interface; // com.baidu.mapapi.CoordType JOpenLogUtil = interface; // com.baidu.mapapi.OpenLogUtil JSDKInitializer = interface; // com.baidu.mapapi.SDKInitializer JVersionInfo = interface; // com.baidu.mapapi.VersionInfo // ===== Interface declarations ===== JModuleNameClass = interface(JEnumClass) // or JObjectClass // SuperSignature: java/lang/Enum ['{5A2265E6-B6DE-42CA-8AFE-47412DC4349D}'] { static Property Methods } { class } function _GetTILE_OVERLAY_MODULE: JModuleName; // Lcom/baidu/mapapi/ModuleName; { static Methods } { class } function values: TJavaObjectArray<JModuleName>; cdecl; // ()[Lcom/baidu/mapapi/ModuleName; { class } function valueOf(P1: JString): JModuleName; cdecl; // (Ljava/lang/String;)Lcom/baidu/mapapi/ModuleName; { static Property } { class } property TILE_OVERLAY_MODULE: JModuleName read _GetTILE_OVERLAY_MODULE; end; [JavaSignature('com/baidu/mapapi/ModuleName')] JModuleName = interface(JEnum) // or JObject // SuperSignature: java/lang/Enum ['{BD0F990B-9259-48A5-A32E-2261F11EBC6D}'] { Property Methods } { methods } { Property } end; TJModuleName = class(TJavaGenericImport<JModuleNameClass, JModuleName>) end; JCoordTypeClass = interface(JEnumClass) // or JObjectClass // SuperSignature: java/lang/Enum ['{86BFBB2A-F389-4A52-B20F-080E02FB81CA}'] { static Property Methods } { class } function _GetGCJ02: JCoordType; // Lcom/baidu/mapapi/CoordType; { class } function _GetBD09LL: JCoordType; // Lcom/baidu/mapapi/CoordType; { static Methods } { class } function values: TJavaObjectArray<JCoordType>; cdecl; // ()[Lcom/baidu/mapapi/CoordType; { class } function valueOf(P1: JString): JCoordType; cdecl; // (Ljava/lang/String;)Lcom/baidu/mapapi/CoordType; { static Property } { class } property GCJ02: JCoordType read _GetGCJ02; { class } property BD09LL: JCoordType read _GetBD09LL; end; [JavaSignature('com/baidu/mapapi/CoordType')] JCoordType = interface(JEnum) // or JObject // SuperSignature: java/lang/Enum ['{E5150E18-2A84-4DC2-B27A-5D61CC468C05}'] { Property Methods } { methods } { Property } end; TJCoordType = class(TJavaGenericImport<JCoordTypeClass, JCoordType>) end; JOpenLogUtilClass = interface(JObjectClass) ['{DF528496-713C-439F-A144-31796C17EE8E}'] { static Property Methods } { static Methods } { class } function init: JOpenLogUtil; cdecl; // ()V { class } procedure setModuleLogEnable(P1: JModuleName; P2: Boolean); cdecl; // (Lcom/baidu/mapapi/ModuleName;Z)V { static Property } end; [JavaSignature('com/baidu/mapapi/OpenLogUtil')] JOpenLogUtil = interface(JObject) ['{10EB569C-CE7E-4C32-970D-558F359268AF}'] { Property Methods } { methods } { Property } end; TJOpenLogUtil = class(TJavaGenericImport<JOpenLogUtilClass, JOpenLogUtil>) end; JSDKInitializerClass = interface(JObjectClass) ['{DFDA0430-82FB-479C-A3C9-D0C41599A584}'] { static Property Methods } { class } function _GetSDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK : JString; // Ljava/lang/String; { class } function _GetSDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR : JString; // Ljava/lang/String; { class } function _GetSDK_BROADCAST_ACTION_STRING_NETWORK_ERROR: JString; // Ljava/lang/String; { class } function _GetSDK_BROADTCAST_INTENT_EXTRA_INFO_KEY_ERROR_CODE : JString; // Ljava/lang/String; { static Methods } { class } procedure initialize(P1: JString; P2: JContext); cdecl; overload; // (Ljava/lang/String;Landroid/content/Context;)V { class } procedure initialize(P1: JContext); cdecl; overload; // (Landroid/content/Context;)V { class } procedure setCoordType(P1: JCoordType); cdecl; // (Lcom/baidu/mapapi/CoordType;)V { class } function getCoordType: JCoordType; cdecl; // ()Lcom/baidu/mapapi/CoordType; { static Property } { class } property SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK: JString read _GetSDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK; { class } property SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR : JString read _GetSDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR; { class } property SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR: JString read _GetSDK_BROADCAST_ACTION_STRING_NETWORK_ERROR; { class } property SDK_BROADTCAST_INTENT_EXTRA_INFO_KEY_ERROR_CODE: JString read _GetSDK_BROADTCAST_INTENT_EXTRA_INFO_KEY_ERROR_CODE; end; [JavaSignature('com/baidu/mapapi/SDKInitializer')] JSDKInitializer = interface(JObject) ['{923EE9EC-8263-4B37-BA23-A133CD5AD160}'] { Property Methods } { methods } { Property } end; TJSDKInitializer = class(TJavaGenericImport<JSDKInitializerClass, JSDKInitializer>) end; JVersionInfoClass = interface(JObjectClass) ['{B972F96C-B230-481E-BFD2-EE44BF51764B}'] { static Property Methods } { class } function _GetVERSION_DESC: JString; // Ljava/lang/String; { class } function _GetKIT_NAME: JString; // Ljava/lang/String; { static Methods } { class } function init: JVersionInfo; cdecl; // ()V { class } function getApiVersion: JString; cdecl; // ()Ljava/lang/String; { class } function getVersionDesc: JString; cdecl; // ()Ljava/lang/String; { class } function getKitName: JString; cdecl; // ()Ljava/lang/String; { static Property } { class } property VERSION_DESC: JString read _GetVERSION_DESC; { class } property KIT_NAME: JString read _GetKIT_NAME; end; [JavaSignature('com/baidu/mapapi/VersionInfo')] JVersionInfo = interface(JObject) ['{F6A60A24-D42D-4924-9F1A-483F0DA9BBAE}'] { Property Methods } { methods } { Property } end; TJVersionInfo = class(TJavaGenericImport<JVersionInfoClass, JVersionInfo>) end; implementation procedure RegisterTypes; begin TRegTypes.RegisterType('Androidapi.JNI.baidu.mapapi.ModuleName', TypeInfo(Androidapi.JNI.baidu.mapapi.JModuleName)); TRegTypes.RegisterType('Androidapi.JNI.baidu.mapapi.CoordType', TypeInfo(Androidapi.JNI.baidu.mapapi.JCoordType)); TRegTypes.RegisterType('Androidapi.JNI.baidu.mapapi.OpenLogUtil', TypeInfo(Androidapi.JNI.baidu.mapapi.JOpenLogUtil)); TRegTypes.RegisterType('Androidapi.JNI.baidu.mapapi.SDKInitializer', TypeInfo(Androidapi.JNI.baidu.mapapi.JSDKInitializer)); TRegTypes.RegisterType('Androidapi.JNI.baidu.mapapi.VersionInfo', TypeInfo(Androidapi.JNI.baidu.mapapi.JVersionInfo)); end; initialization RegisterTypes; end.
unit landscapeMainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Forms3D, FMX.Types3D, FMX.Objects3D, FMX.Layers3D, FMX.StdCtrls, FMX.Controls3D, FMX.MaterialSources; type TAddable = (aTree, aHouse); TMain = class(TForm3D) sun: TLight; tree: TCone; house: TModel3D; Layer3D1: TLayer3D; BtnTree: TButton; BtnHouse: TButton; Label1: TLabel; BtnSun: TButton; Label2: TLabel; BtnUndo: TButton; houseMat01: TLightMaterialSource; land: TPlane; landimage: TTextureMaterialSource; procedure landMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); procedure landMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); procedure landMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); procedure Form3DCreate(Sender: TObject); procedure BtnTreeClick(Sender: TObject); procedure BtnHouseClick(Sender: TObject); procedure BtnSunClick(Sender: TObject); procedure BtnUndoClick(Sender: TObject); private FMouseDown: Boolean; FAddable : TAddable; FLastX, FLastZ : Double; FSeparation: Double; FHouseAngle: Integer; FSunAngle: Integer; public end; var Main: TMain; implementation {$R *.fmx} procedure TMain.Form3DCreate(Sender: TObject); begin FMouseDown := False; FAddable := aTree; FHouseAngle := 30; FSunAngle := -45; FSeparation := 0.3; end; procedure TMain.landMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); begin FMouseDown := True; FLastX := -99; FLastZ := -99; end; procedure TMain.landMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); var newObj: TProxyObject; HitPos: TVector3D; begin if FMouseDown then begin land.RayCastIntersect(RayPos, RayDir, HitPos); // if moved far enough if (Abs(HitPos.X - FLastX) > FSeparation) or (Abs(HitPos.Z - FLastZ) > FSeparation) then begin // add new object as a proxy object newObj := TProxyObject.Create(self); land.AddObject(newObj); case FAddable of aTree: begin newObj.SourceObject := tree; newObj.Scale.Assign(tree.Scale); newObj.RotationAngle.X := 90;//tree.RotationAngle.X; newObj.RotationAngle.Y := 0;//tree.RotationAngle.Y; newObj.RotationAngle.Z := 0;//tree.RotationAngle.Z; FSeparation := 0.6; end; aHouse: begin //newObj.SourceObject := wall; // need to point at material !!! // this use to point to the walls in the original but the object got mangled somehow newObj.SourceObject := house; // need to point at material !!! newObj.Scale.Assign(house.Scale); newObj.RotationAngle.X := 90; newObj.RotationAngle.Y := 356.8679;//house.RotationAngle.Y; newObj.RotationAngle.Z := FHouseAngle; newObj.Scale.X := 0.02; newObj.Scale.Y := 0.02; newObj.Scale.Z := 0.02; FSeparation := 1.0; end; end; newObj.Position.Z := newObj.SourceObject.Position.Z; //newObj.Position.X := HitPos.X; //newObj.Position.Y := -HitPos.Z; // Z -> Y // added +2 offet to get under the mouse cursor on my machine newObj.Position.X := HitPos.X+2; newObj.Position.Y := -HitPos.Z+2; // Z -> Y newObj.HitTest := False; FLastX := HitPos.X; FLastZ := HitPos.Z; end; end; end; procedure TMain.landMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); begin FMouseDown := False; end; procedure TMain.BtnHouseClick(Sender: TObject); begin FAddable := aHouse; FHouseAngle := (FHouseAngle + 45) mod 360; Label1.Text := IntToStr(FHouseAngle); end; procedure TMain.BtnTreeClick(Sender: TObject); begin FAddable := aTree; end; procedure TMain.BtnUndoClick(Sender: TObject); begin if land.ChildrenCount > 2 then land.RemoveObject(land.ChildrenCount-1); end; procedure TMain.BtnSunClick(Sender: TObject); begin FSunAngle := (FSunAngle + 10) mod 360; sun.RotationAngle.Y := FSunAngle; Label2.Text := IntToStr(FSunAngle); end; end.
unit uUser; interface uses uModel, System.Generics.Collections,System.SysUtils; type TUserMenuItem = class; TUser = class(TAppObject) private FPassword: string; FUserMenuItems: TObjectList<TUserMenuItem>; FUserName: string; function GetUserMenuItems: TObjectList<TUserMenuItem>; public destructor Destroy; override; published property Password: string read FPassword write FPassword; property UserMenuItems: TObjectList<TUserMenuItem> read GetUserMenuItems write FUserMenuItems; property UserName: string read FUserName write FUserName; end; TMenu = class(TAppObject) private FMenuCaption: string; FMenuName: string; published property MenuCaption: string read FMenuCaption write FMenuCaption; property MenuName: string read FMenuName write FMenuName; end; TUserMenuItem = class(TAppObjectItem) private FMenu: TMenu; FUseraPP: TUser; public function GetHeaderField: string; override; procedure SetHeaderProperty(AHeaderProperty : TAppObject); override; published property Menu: TMenu read FMenu write FMenu; property UseraPP: TUser read FUseraPP write FUseraPP; end; implementation destructor TUser.Destroy; begin inherited; FreeAndNil(FUserMenuItems); end; function TUser.GetUserMenuItems: TObjectList<TUserMenuItem>; begin if FUserMenuItems = nil then FUserMenuItems := TObjectList<TUserMenuItem>.Create; Result := FUserMenuItems; end; function TUserMenuItem.GetHeaderField: string; begin Result := 'UseraPP'; end; procedure TUserMenuItem.SetHeaderProperty(AHeaderProperty : TAppObject); begin UseraPP := TUser(AHeaderProperty); end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpDerObjectIdentifier; {$I ..\Include\CryptoLib.inc} interface uses Classes, SysUtils, StrUtils, SyncObjs, ClpBits, ClpArrayUtils, ClpStringUtils, ClpStreamHelper, ClpBigInteger, ClpCryptoLibTypes, ClpAsn1Tags, ClpOidTokenizer, ClpIOidTokenizer, ClpDerOutputStream, ClpAsn1Object, ClpAsn1OctetString, ClpIAsn1TaggedObject, ClpIProxiedInterface, ClpIDerObjectIdentifier; resourcestring SIllegalObject = 'Illegal Object in GetInstance: %s'; SIdentifierNil = 'Identifier Cannot be Empty'; SInvalidOID = '"String " %s is " not an OID"'; SInvalidBranchId = '"String " %s " not a valid OID branch", "branchID"'; type TDerObjectIdentifier = class(TAsn1Object, IDerObjectIdentifier) strict private const LONG_LIMIT = Int64((Int64($7FFFFFFFFFFFFFFF) shr 7) - $7F); class var FIsBooted: Boolean; FLock: TCriticalSection; Fcache: TCryptoLibGenericArray<IDerObjectIdentifier>; var Fidentifier: String; Fbody: TCryptoLibByteArray; class constructor CreateDerObjectIdentifier(); class destructor DestroyDerObjectIdentifier(); constructor Create(const oid: IDerObjectIdentifier; const branchID: String); overload; constructor Create(const bytes: TCryptoLibByteArray); overload; function GetID: String; inline; procedure WriteField(const outputStream: TStream; fieldValue: Int64); overload; procedure WriteField(const outputStream: TStream; const fieldValue: TBigInteger); overload; procedure DoOutput(const bOut: TMemoryStream); overload; function GetBody(): TCryptoLibByteArray; class function IsValidBranchID(const branchID: String; start: Int32) : Boolean; static; class function IsValidIdentifier(const identifier: String): Boolean; static; class function MakeOidStringFromBytes(const bytes: TCryptoLibByteArray) : String; static; strict protected function Asn1GetHashCode(): Int32; override; function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override; public // /** // * return an Oid from the passed in object // * // * @exception ArgumentException if the object cannot be converted. // */ class function GetInstance(const obj: TObject): IDerObjectIdentifier; overload; static; // /** // * return an Oid from the passed in byte array // */ class function GetInstance(const obj: TCryptoLibByteArray) : IDerObjectIdentifier; overload; static; inline; // /** // * return an object Identifier from a tagged object. // * // * @param obj the tagged object holding the object we want // * @param explicitly true if the object is meant to be explicitly // * tagged false otherwise. // * @exception ArgumentException if the tagged object cannot // * be converted. // */ class function GetInstance(const obj: IAsn1TaggedObject; explicitly: Boolean): IDerObjectIdentifier; overload; static; inline; class function FromOctetString(const enc: TCryptoLibByteArray) : IDerObjectIdentifier; static; class procedure Boot(); static; constructor Create(const identifier: String); overload; property ID: String read GetID; function Branch(const branchID: String): IDerObjectIdentifier; virtual; // /** // * Return true if this oid is an extension of the passed in branch, stem. // * @param stem the arc or branch that is a possible parent. // * @return true if the branch is on the passed in stem, false otherwise. // */ function &On(const stem: IDerObjectIdentifier): Boolean; virtual; procedure Encode(const derOut: TStream); override; function ToString(): String; override; end; implementation { TDerObjectIdentifier } function TDerObjectIdentifier.GetID: String; begin result := Fidentifier; end; function TDerObjectIdentifier.Asn1Equals(const asn1Object: IAsn1Object) : Boolean; var other: IDerObjectIdentifier; begin if (not Supports(asn1Object, IDerObjectIdentifier, other)) then begin result := false; Exit; end; result := ID = other.ID; end; function TDerObjectIdentifier.Asn1GetHashCode: Int32; begin result := TStringUtils.GetStringHashCode(Fidentifier); end; class procedure TDerObjectIdentifier.Boot; begin if not FIsBooted then begin FLock := TCriticalSection.Create; System.SetLength(Fcache, 1024); FIsBooted := True; end; end; function TDerObjectIdentifier.Branch(const branchID: String) : IDerObjectIdentifier; begin result := TDerObjectIdentifier.Create(Self as IDerObjectIdentifier, branchID); end; constructor TDerObjectIdentifier.Create(const oid: IDerObjectIdentifier; const branchID: String); begin Inherited Create(); if (not(IsValidBranchID(branchID, 1))) then begin raise EArgumentCryptoLibException.CreateResFmt(@SInvalidBranchId, [branchID]); end; Fidentifier := oid.ID + '.' + branchID; end; constructor TDerObjectIdentifier.Create(const identifier: String); begin Inherited Create(); if (identifier = '') then begin raise EArgumentNilCryptoLibException.CreateRes(@SIdentifierNil); end; if (not(IsValidIdentifier(identifier))) then begin raise EFormatCryptoLibException.CreateResFmt(@SInvalidOID, [identifier]); end; Fidentifier := identifier; end; constructor TDerObjectIdentifier.Create(const bytes: TCryptoLibByteArray); begin Inherited Create(); Fidentifier := MakeOidStringFromBytes(bytes); Fbody := System.Copy(bytes); end; function TDerObjectIdentifier.&On(const stem: IDerObjectIdentifier): Boolean; var LocalId, stemId: String; begin LocalId := ID; stemId := stem.ID; result := (System.Length(LocalId) > System.Length(stemId)) and (LocalId[System.Length(stemId) + 1] = '.') and (AnsiStartsStr(stemId, LocalId)); end; class constructor TDerObjectIdentifier.CreateDerObjectIdentifier; begin TDerObjectIdentifier.Boot; end; class destructor TDerObjectIdentifier.DestroyDerObjectIdentifier; begin FLock.Free; end; procedure TDerObjectIdentifier.DoOutput(const bOut: TMemoryStream); var tok: IOidTokenizer; token: String; first: Int32; begin tok := TOidTokenizer.Create(Fidentifier); token := tok.NextToken(); first := StrToInt(token) * 40; token := tok.NextToken(); if (System.Length(token) <= 18) then begin WriteField(bOut, Int64(first + StrToInt64(token))); end else begin WriteField(bOut, TBigInteger.Create(token).Add(TBigInteger.ValueOf(first))); end; while (tok.HasMoreTokens) do begin token := tok.NextToken(); if (System.Length(token) <= 18) then begin WriteField(bOut, StrToInt64(token)); end else begin WriteField(bOut, TBigInteger.Create(token)); end; end; end; procedure TDerObjectIdentifier.Encode(const derOut: TStream); begin (derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.ObjectIdentifier, GetBody()); end; class function TDerObjectIdentifier.FromOctetString (const enc: TCryptoLibByteArray): IDerObjectIdentifier; var HashCode, first: Int32; entry: IDerObjectIdentifier; begin HashCode := TArrayUtils.GetArrayHashCode(enc); first := HashCode and 1023; TDerObjectIdentifier.Boot; FLock.Acquire; try entry := Fcache[first]; if ((entry <> Nil) and (TArrayUtils.AreEqual(enc, entry.GetBody()))) then begin result := entry; Exit; end; Fcache[first] := TDerObjectIdentifier.Create(enc); result := Fcache[first]; finally FLock.Release; end; end; function TDerObjectIdentifier.GetBody: TCryptoLibByteArray; var bOut: TMemoryStream; begin TDerObjectIdentifier.Boot; FLock.Acquire; try if (Fbody = Nil) then begin bOut := TMemoryStream.Create(); try DoOutput(bOut); System.SetLength(Fbody, bOut.Size); bOut.Position := 0; bOut.Read(Fbody[0], System.Length(Fbody)); finally bOut.Free; end; end; finally FLock.Release; end; result := Fbody; end; class function TDerObjectIdentifier.GetInstance(const obj: IAsn1TaggedObject; explicitly: Boolean): IDerObjectIdentifier; var o: IAsn1Object; begin o := obj.GetObject(); if ((explicitly) or (Supports(o, IDerObjectIdentifier))) then begin result := GetInstance(o as TAsn1Object); Exit; end; result := FromOctetString(TAsn1OctetString.GetInstance(o as TAsn1Object) .GetOctets()); end; class function TDerObjectIdentifier.GetInstance(const obj: TObject) : IDerObjectIdentifier; begin if ((obj = Nil) or (obj is TDerObjectIdentifier)) then begin result := obj as TDerObjectIdentifier; Exit; end; raise EArgumentCryptoLibException.CreateResFmt(@SIllegalObject, [obj.ClassName]); end; class function TDerObjectIdentifier.GetInstance(const obj: TCryptoLibByteArray) : IDerObjectIdentifier; begin result := FromOctetString(obj); end; class function TDerObjectIdentifier.IsValidBranchID(const branchID: String; start: Int32): Boolean; var periodAllowed: Boolean; pos: Int32; ch: Char; begin periodAllowed := false; pos := System.Length(branchID) + 1; System.Dec(pos); while (pos >= start) do begin ch := branchID[pos]; // TODO Leading zeroes? // if (('0' <= ch) and (ch <= '9')) then // begin // periodAllowed := true; // continue; // end; // TODO Leading zeroes? if (CharInSet(ch, ['0' .. '9'])) then begin periodAllowed := True; System.Dec(pos); continue; end; if (ch = '.') then begin if (not(periodAllowed)) then begin result := false; Exit; end; periodAllowed := false; System.Dec(pos); continue; end; result := false; Exit; end; result := periodAllowed; end; class function TDerObjectIdentifier.IsValidIdentifier(const identifier : String): Boolean; var first: Char; begin if ((System.Length(identifier) < 3) or (identifier[2] <> '.')) then begin result := false; Exit; end; first := identifier[1]; // if ((first < '0') or (first > '2')) then // begin // result := false; // Exit; // end; if (not CharInSet(first, ['0' .. '2'])) then begin result := false; Exit; end; result := IsValidBranchID(identifier, 3); end; class function TDerObjectIdentifier.MakeOidStringFromBytes (const bytes: TCryptoLibByteArray): String; var objId: TStringList; value: Int64; bigValue: TBigInteger; first: Boolean; i, b: Int32; begin value := 0; bigValue := Default (TBigInteger); first := True; objId := TStringList.Create(); objId.LineBreak := ''; try i := 0; while i <> System.Length(bytes) do begin b := Int32(bytes[i]); if (value <= LONG_LIMIT) then begin value := value + (b and $7F); if ((b and $80) = 0) then // end of number reached begin if (first) then begin if (value < 40) then begin objId.Add('0'); end else if (value < 80) then begin objId.Add('1'); value := value - 40; end else begin objId.Add('2'); value := value - 80; end; first := false; end; objId.Add('.'); objId.Add(IntToStr(value)); value := 0; end else begin value := value shl 7; end; end else begin if (not bigValue.IsInitialized) then begin bigValue := TBigInteger.ValueOf(value); end; bigValue := bigValue.&Or(TBigInteger.ValueOf(b and $7F)); if ((b and $80) = 0) then begin if (first) then begin objId.Add('2'); bigValue := bigValue.Subtract(TBigInteger.ValueOf(80)); first := false; end; objId.Add('.'); objId.Add(bigValue.ToString()); bigValue := Default (TBigInteger); value := 0; end else begin bigValue := bigValue.ShiftLeft(7); end end; System.Inc(i); end; result := objId.Text; finally objId.Free; end; end; function TDerObjectIdentifier.ToString: String; begin result := ID; end; procedure TDerObjectIdentifier.WriteField(const outputStream: TStream; const fieldValue: TBigInteger); var byteCount, i: Int32; tmpValue: TBigInteger; tmp: TCryptoLibByteArray; begin byteCount := (fieldValue.BitLength + 6) div 7; if (byteCount = 0) then begin outputStream.WriteByte(0); end else begin tmpValue := fieldValue; System.SetLength(tmp, byteCount); i := byteCount - 1; while i >= 0 do begin tmp[i] := Byte((tmpValue.Int32Value and $7F) or $80); tmpValue := tmpValue.ShiftRight(7); System.Dec(i); end; tmp[byteCount - 1] := tmp[byteCount - 1] and $7F; outputStream.Write(tmp[0], System.Length(tmp)); end; end; procedure TDerObjectIdentifier.WriteField(const outputStream: TStream; fieldValue: Int64); var tempRes: TCryptoLibByteArray; pos: Int32; begin System.SetLength(tempRes, 9); pos := 8; tempRes[pos] := Byte(fieldValue and $7F); while (fieldValue >= (Int64(1) shl 7)) do begin fieldValue := TBits.Asr64(fieldValue, 7); System.Dec(pos); tempRes[pos] := Byte((fieldValue and $7F) or $80); end; outputStream.Write(tempRes[pos], 9 - pos); end; end.
// -------------------------------------------------------------------------- // Archivo del Proyecto Ventas // Página del proyecto: http://sourceforge.net/projects/ventas // -------------------------------------------------------------------------- // Este archivo puede ser distribuido y/o modificado bajo lo terminos de la // Licencia Pública General versión 2 como es publicada por la Free Software // Fundation, Inc. // -------------------------------------------------------------------------- unit Gastos; interface uses SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs, QMenus, QTypes, QExtCtrls, QDBGrids, QStdCtrls, QButtons, QGrids, QcurrEdit, QComCtrls, IniFiles, Qt; type TfrmGastos = class(TForm) pgeGeneral: TPageControl; tabDatos: TTabSheet; grpArticulo: TGroupBox; Label1: TLabel; Label3: TLabel; Label4: TLabel; Label12: TLabel; txtDescripLarga: TEdit; txtDescripCorta: TEdit; txtCodigo: TEdit; txtFechaCap: TEdit; pgeDatos: TPageControl; tabOrganiza: TTabSheet; grpOrganiza: TGroupBox; Label5: TLabel; cmbCategorias: TComboBox; grpProveedores: TGroupBox; txtProvNum1: TcurrEdit; Label6: TLabel; txtProveedor1: TEdit; btnInsertar: TBitBtn; btnEliminar: TBitBtn; btnModificar: TBitBtn; btnGuardar: TBitBtn; btnCancelar: TBitBtn; MainMenu1: TMainMenu; Archivo1: TMenuItem; mnuInsertar: TMenuItem; mnuEliminar: TMenuItem; mnuModificar: TMenuItem; N3: TMenuItem; mnuGuardar: TMenuItem; mnuCancelar: TMenuItem; N2: TMenuItem; Salir1: TMenuItem; mnuConsulta: TMenuItem; mnuAvanza: TMenuItem; mnuRetrocede: TMenuItem; N1: TMenuItem; mnuBuscar: TMenuItem; N4: TMenuItem; mnuLimpiar: TMenuItem; mnuSeleccionar: TMenuItem; mnuFichas: TMenuItem; mnuProved: TMenuItem; mnuBusqueda: TMenuItem; N5: TMenuItem; mnuOrganizacion: TMenuItem; tabBusqueda: TTabSheet; grdListado: TDBGrid; rdgBuscar: TRadioGroup; rdgOrden: TRadioGroup; Label26: TLabel; txtRegistros: TcurrEdit; btnBuscar: TBitBtn; btnSeleccionar: TBitBtn; btnLimpiar: TBitBtn; pnlCodigo: TPanel; Label27: TLabel; txtCodigoBusq: TEdit; pnlDescCorta: TPanel; Label29: TLabel; txtDescCortaBusq: TEdit; tabMov: TTabSheet; grpUltCompra: TGroupBox; Label20: TLabel; Label21: TLabel; txtProv: TEdit; txtFechComp: TEdit; cmbEstatus: TComboBox; Buscarproveedor1: TMenuItem; N6: TMenuItem; Label33: TLabel; pnlProveedor: TPanel; Label37: TLabel; txtProvClave: TcurrEdit; txtProvDesc: TEdit; mnuMovimientos: TMenuItem; grpImpuesto: TGroupBox; Label16: TLabel; txtIva: TcurrEdit; grpCostos: TGroupBox; Label14: TLabel; txtUltimoCos: TcurrEdit; procedure btnInsertarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure btnGuardarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure txtProvNum1Change(Sender: TObject); procedure txtProvNum2Change(Sender: TObject); procedure btnBuscarClick(Sender: TObject); procedure rdgBuscarClick(Sender: TObject); procedure btnModificarClick(Sender: TObject); procedure btnLimpiarClick(Sender: TObject); procedure grdJuegoDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure mnuOrganizacionClick(Sender: TObject); procedure mnuProvedClick(Sender: TObject); procedure mnuBusquedaClick(Sender: TObject); procedure mnuAvanzaClick(Sender: TObject); procedure mnuRetrocedeClick(Sender: TObject); procedure btnEliminarClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure grdListadoDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure Buscarproveedor1Click(Sender: TObject); procedure grdListadoDblClick(Sender: TObject); procedure grdListadoEnter(Sender: TObject); procedure grdListadoExit(Sender: TObject); procedure btnSeleccionarClick(Sender: TObject); procedure Salir1Click(Sender: TObject); procedure Salta(Sender: TObject; var Key: Word; Shift: TShiftState); procedure txtCodigoKeyPress(Sender: TObject; var Key: Char); procedure pgeGeneralPageChanging(Sender: TObject; NewPage: TTabSheet; var AllowChange: Boolean); procedure pgeGeneralChange(Sender: TObject); procedure CargaMovimientos; procedure mnuMovimientosClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure txtProvClaveChange(Sender: TObject); function VerificaCodigo:boolean; private sModo: String; iClave: Integer; bLetras: Boolean; procedure LimpiaDatos; procedure ActivaControles; procedure Colores(clColor : TColor); procedure RecuperaDatos; procedure GuardaDatos; function VerificaDatos:boolean; function ClaveCarga(sBusqueda:String ; sConsulta:String):Integer; procedure BuscaProveedor(Sender: TObject); procedure RecuperaDatosBusq; procedure ActivaBuscar; // procedure BuscaArticulo; procedure RecuperaConfig; procedure VerificaCategs; procedure VerificaDeptos; function BuscaNombre(iValor:Integer; sTabla:string):String; public end; var frmGastos: TfrmGastos; implementation uses dm, ProveedBusq, ArticuloBusq; {$R *.xfm} procedure TfrmGastos.btnInsertarClick(Sender: TObject); begin pgeGeneral.ActivePage := tabDatos; sModo := 'Insertar'; ActivaControles; LimpiaDatos; txtCodigo.SetFocus; txtFechaCap.Text := FormatDateTime('dd/mm/yyyy',Date); pgeGeneral.ActivePage := tabDatos; cmbEstatus.ItemIndex := 0 ; //Estatus Activo if(cmbCategorias.ItemIndex = -1) then cmbCategorias.ItemIndex := 0; end; procedure TfrmGastos.LimpiaDatos; begin txtCodigo.Clear; txtDescripCorta.Clear; txtDescripLarga.Clear; txtFechaCap.Clear; txtProvNum1.Value := 0; txtProveedor1.Clear; txtUltimoCos.Value := 0; txtIva.Value:=0; end; procedure TfrmGastos.ActivaControles; begin if( (sModo = 'Insertar') or (sModo = 'Modificar') ) then begin tabBusqueda.TabVisible := false; Colores(clWindowText); btnInsertar.Enabled := false; btnModificar.Enabled := false; btnEliminar.Enabled := false; mnuInsertar.Enabled := false; mnuModificar.Enabled := false; mnuEliminar.Enabled := false; btnGuardar.Enabled := true; btnCancelar.Enabled := true; mnuGuardar.Enabled := true; mnuCancelar.Enabled := true; mnuConsulta.Enabled := false; mnuBusqueda.Enabled := false; tabBusqueda.Enabled := false; tabBusqueda.TabVisible := false; txtCodigo.ReadOnly := false; txtDescripCorta.ReadOnly := false; txtDescripLarga.ReadOnly := false; txtFechaCap.ReadOnly := true; txtFechComp.ReadOnly := true; txtRegistros.ReadOnly := false; txtProvNum1.ReadOnly := false; txtUltimoCos.ReadOnly := false; txtIva.ReadOnly:=false; txtCodigo.TabStop := true; txtDescripCorta.TabStop := true; txtDescripLarga.TabStop := true; txtFechaCap.TabStop := false; txtFechComp.TabStop := false; txtIva.TabStop:=True; txtRegistros.TabStop := false; txtProvNum1.TabStop := true; txtUltimoCos.TabStop := true; cmbCategorias.Enabled:=true; cmbEstatus.Enabled:=True; end; if(sModo = 'Consulta') then begin tabBusqueda.TabVisible := True; Colores(clBlue); btnInsertar.Enabled := True; btnModificar.Enabled := True;; btnEliminar.Enabled := True; mnuInsertar.Enabled := True; mnuModificar.Enabled :=True; mnuEliminar.Enabled := True; btnGuardar.Enabled := false; btnCancelar.Enabled := false; mnuGuardar.Enabled := false; mnuCancelar.Enabled := false; mnuConsulta.Enabled := True; mnuBusqueda.Enabled := True; tabBusqueda.Enabled := True; if(Length(txtCodigo.Text) > 0) then begin btnModificar.Enabled := true; btnEliminar.Enabled := true; mnuModificar.Enabled := true; mnuEliminar.Enabled := true; end; txtCodigo.ReadOnly := True; txtDescripCorta.ReadOnly := True; txtDescripLarga.ReadOnly := True; txtRegistros.ReadOnly := True; txtFechaCap.ReadOnly := True; txtFechComp.ReadOnly := True; txtProvNum1.ReadOnly := True; txtUltimoCos.ReadOnly := True; txtIva.ReadOnly:=True; txtCodigo.TabStop := False; txtDescripCorta.TabStop :=False; txtDescripLarga.TabStop := False; txtRegistros.TabStop :=False; txtFechaCap.TabStop := False; txtFechComp.TabStop := False; txtProvNum1.TabStop := False; txtUltimoCos.TabStop := False; txtIva.TabStop:=False; cmbCategorias.Enabled:=False; cmbEstatus.Enabled:=False; end; end; procedure TfrmGastos.Colores(clColor : TColor); begin txtCodigo.Font.Color := clColor; txtDescripCorta.Font.Color := clColor; txtDescripLarga.Font.Color := clColor; txtRegistros.Font.Color := clColor; txtFechComp.Font.Color := clColor; txtProvNum1.Font.Color := clColor; txtUltimoCos.Font.Color := clColor; txtIva.Font.Color:=clColor; end; procedure TfrmGastos.btnCancelarClick(Sender: TObject); begin sModo := 'Consulta'; LimpiaDatos; ActivaControles; pgeGeneral.ActivePage := tabBusqueda; end; procedure TfrmGastos.btnGuardarClick(Sender: TObject); begin btnGuardar.SetFocus; if(VerificaDatos) then begin GuardaDatos; sModo := 'Consulta'; ActivaControles; btnBuscar.Click; btnInsertar.SetFocus; end; end; procedure TfrmGastos.GuardaDatos; var sDescAuto, sFecha,sCateg, sDeptos, sTipo, sProv1, sProv2, sEstatus: String; begin sFecha := FormatDateTime('mm/dd/yyyy hh:nn:ss',Now); sDescAuto:='N'; sDeptos := 'null'; if(cmbCategorias.ItemIndex <> -1) then sCateg := IntToStr(Clavecarga(cmbCategorias.Items.Strings[cmbCategorias.ItemIndex],'C')) else sCateg := 'null'; if(txtProvNum1.value <> 0) then sProv1 := FloatToStr(txtProvNum1.value) else sProv1 := 'null'; sProv2 :='null'; sTipo := '4'; if (cmbEstatus.ItemIndex = 0)then sEstatus := 'A' else sEstatus := 'I'; with dmDatos.qryModifica do begin if(sModo = 'Insertar') then begin Close; SQL.Clear; SQL.Add('INSERT INTO articulos (desc_corta,desc_larga, precio1,'); SQL.Add('precio2, precio3, precio4, ult_costo, costoprom, desc_auto,'); SQL.Add('existencia, minimo, maximo, categoria, departamento, tipo,'); SQL.Add('proveedor1, proveedor2, iva, fecha_cap, fecha_umov,'); SQL.Add('estatus) VALUES('); SQL.Add('''' + txtDescripCorta.Text + ''',''' + txtDescripLarga.text + ''',' + '0,'); SQL.Add('0,0,0,'+ FloatToStr(txtUltimoCos.value) + ',0,' +'''' + sDescAuto+''','); SQL.Add('0,0,0,'+ sCateg + ',' + sDeptos + ',' + sTipo + ','); SQL.Add(sProv1 + ',' + sProv2 + ',' + FloatToStr(txtIva.Value) + ','); SQL.Add('''' + sFecha + ''',''' + sFecha + ''',''' + sEstatus + ''')'); ExecSQL; Close; SQL.Clear; SQL.Add('SELECT clave FROM articulos WHERE desc_larga = ''' + txtDescripLarga.Text + ''''); Open; iClave := FieldByName('clave').AsInteger; Close; end else begin Close; SQL.Clear; SQL.Add('UPDATE articulos SET '); SQL.Add('DESC_CORTA = ''' + txtDescripCorta.Text + ''','); SQL.Add('DESC_LARGA = ''' + txtDescripLarga.Text + ''','); SQL.Add('ULT_COSTO = ' + FloatToStr(txtUltimoCos.Value) + ','); SQL.Add('CATEGORIA = ' + sCateg + ','); SQL.Add('TIPO = '+ sTipo + ','); SQL.Add('PROVEEDOR1 = ' + sProv1 + ','); SQL.Add('IVA = ' + FloatToStr(txtIva.Value)+','); SQL.Add('ESTATUS = ''' + sEstatus+''''); SQL.Add('WHERE clave = ' + IntToStr(iClave)); ExecSQL; // Elimina los codigos por si existe alguna modificación en alguno de ellos Close; SQL.Clear; SQL.Add('DELETE FROM codigos WHERE articulo = ' + IntToStr(iClave)); ExecSQL; end; // Inserta el codigo principal Close; SQL.Clear; SQL.Add('INSERT INTO codigos (articulo, codigo, tipo) VALUES('); SQL.Add(IntToStr(iClave) + ',''' + txtCodigo.Text + ''',''P'')'); ExecSQL; end; end; function TfrmGastos.VerificaDatos:boolean; var bVerifica : Boolean; begin bVerifica := True; if(Length(Trim(txtCodigo.Text)) = 0) then begin Application.MessageBox('Introduce el código del gasto','Error',[smbOK],smsCritical); txtCodigo.SetFocus; bVerifica := False; end else if(not VerificaCodigo) then begin Application.MessageBox('El código especificado ya existe','Error',[smbOK],smsCritical); txtCodigo.SetFocus; bVerifica := False; end else if(Length(txtDescripCorta.Text) = 0) then begin Application.MessageBox('Introduce la descripción corta','Error',[smbOK],smsCritical); txtDescripCorta.SetFocus; bVerifica := False; end else if(Length(txtDescripLarga.Text) = 0) then begin Application.MessageBox('Introduce la descripción larga','Error',[smbOK],smsCritical); txtDescripLarga.SetFocus; bVerifica := False; end else if (txtProvNum1.Value > 0) and (Length(txtProveedor1.Text) = 0) then begin Application.MessageBox('Introduce un proveedor válido','Error',[smbOK],smsCritical); pgeDatos.ActivePage := tabOrganiza; txtProvNum1.SetFocus; bVerifica := False; end; Result := bVerifica; end; procedure TfrmGastos.RecuperaDatos; begin with dmDatos.qryConsulta do begin Close; SQL.Clear; SQL.Add('SELECT nombre FROM categorias WHERE tipo = ''G'' ORDER BY nombre'); Open; cmbCategorias.Items.Clear; while (not Eof) do begin cmbCategorias.Items.Add(Trim(FieldByName('nombre').AsString)); Next; end; Close; end; end; function TfrmGastos.ClaveCarga(sBusqueda:string; sConsulta:string):Integer; begin with dmDatos.qryModifica do begin Close; SQL.Clear; if (sConsulta = 'C') then Begin SQL.Add('SELECT clave FROM categorias WHERE nombre = ''' + sBusqueda + ''''); SQL.Add('AND tipo = ''G'''); Open; end; Result := FieldByName('clave').AsInteger; Close; end; end; procedure TfrmGastos.BuscaProveedor(Sender: TObject); begin with dmDatos.qryModifica do begin if(Length((Sender as TEdit).Text) > 0) then begin Close; SQL.Clear; SQL.Add('SELECT nombre FROM proveedores WHERE clave = ' + (Sender as TEdit).Text); Open; if((Sender as TEdit).Name = 'txtProvNum1') then txtProveedor1.Text := Trim(FieldByName('nombre').AsString) else if((Sender as TEdit).Name = 'txtProvClave') then txtProvDesc.Text := Trim(FieldByName('nombre').AsString); Close; end; end; end; procedure TfrmGastos.FormShow(Sender: TObject); begin rdgBuscarClick(rdgBuscar); VerificaCategs; VerificaDeptos; LimpiaDatos; sModo := 'Consulta'; ActivaControles; ActivaBuscar; pgeGeneral.ActivePage := tabBusqueda; RecuperaDatos; cmbCategorias.ItemIndex := 0; btnBuscarClick(Sender); end; procedure TfrmGastos.txtProvNum1Change(Sender: TObject); begin BuscaProveedor(Sender); end; procedure TfrmGastos.txtProvNum2Change(Sender: TObject); begin BuscaProveedor(Sender); end; procedure TfrmGastos.btnBuscarClick(Sender: TObject); var sBM : String; begin if(pgeGeneral.ActivePage = tabBusqueda) then btnBuscar.SetFocus; with dmDatos.qryArticulos do begin sBM := dmDatos.cdsArticulos.Bookmark; Close; SQL.Clear; dmDatos.cdsArticulos.Active := false; SQL.Add('SELECT a.clave, a.tipo, o.codigo, a.desc_larga, a.desc_corta'); SQL.Add('FROM articulos a LEFT JOIN codigos o'); SQL.Add('ON (a.clave = o.articulo AND o.tipo = ''P'') WHERE 1 = 1 and a.tipo=4'); case rdgBuscar.ItemIndex of 0: SQL.Add('AND a.clave IN (SELECT articulo FROM codigos WHERE codigo STARTING ''' + txtCodigoBusq.Text + ''')'); 1: SQL.Add('AND a.desc_larga LIKE ''%' + txtDescCortaBusq.Text + '%'''); 2: if(txtProvClave.Value > 0) then SQL.Add('AND (a.proveedor1 = ' + FloatToStr(txtProvClave.Value) + ' OR a.proveedor2 = ' + FloatToStr(txtProvClave.Value) + ')'); end; case rdgOrden.ItemIndex of 0: SQL.Add('ORDER BY o.codigo'); 1: SQL.Add('ORDER BY a.desc_larga'); 2: SQL.Add('ORDER BY a.proveedor1, a.proveedor2, o.codigo'); end; Open; dmDatos.cdsArticulos.Active := true; dmDatos.cdsArticulos.FieldByName('clave').Visible := False; dmDatos.cdsArticulos.FieldByName('tipo').Visible := False; dmDatos.cdsArticulos.FieldByName('codigo').DisplayLabel := 'Código'; dmDatos.cdsArticulos.FieldByName('desc_corta').DisplayWidth := 25; dmDatos.cdsArticulos.FieldByName('desc_larga').DisplayWidth := 35; dmDatos.cdsArticulos.FieldByName('desc_corta').DisplayLabel := 'Descripción corta'; dmDatos.cdsArticulos.FieldByName('desc_larga').DisplayLabel := 'Descripción larga'; txtRegistros.Value := dmDatos.cdsArticulos.RecordCount; try dmDatos.cdsArticulos.Bookmark := sBM; except txtRegistros.Value := txtRegistros.Value; end; if(pgeGeneral.ActivePage = tabBusqueda) then grdListado.SetFocus; end; end; procedure TfrmGastos.rdgBuscarClick(Sender: TObject); begin pnlCodigo.Visible := false; pnlCodigo.Enabled := false; pnlDescCorta.Visible := false; pnlDescCorta.Enabled := false; pnlProveedor.Visible := false; pnlProveedor.Enabled := false; case rdgBuscar.ItemIndex of 0: begin pnlCodigo.Visible := true; pnlCodigo.Enabled := true; if(pgeGeneral.ActivePage = tabBusqueda) then txtCodigoBusq.SetFocus; end; 1: begin pnlDescCorta.Visible := true; pnlDescCorta.Enabled := true; if(pgeGeneral.ActivePage = tabBusqueda) then txtDescCortaBusq.SetFocus; end; 2: begin pnlProveedor.Visible := true; pnlProveedor.Enabled := true; if(pgeGeneral.ActivePage = tabBusqueda) then txtProvClave.SetFocus; end; end; end; procedure TfrmGastos.RecuperaDatosBusq; var sCateg, sDeptos: String; begin iClave := dmDatos.cdsArticulos.FieldByName('Clave').AsInteger; with dmDatos.qryConsulta do begin Close; SQL.Clear; SQL.Add('SELECT o.codigo, a.desc_corta, a.desc_larga, a.precio1,'); SQL.Add('a.existencia, a.clave, a.precio2, a.precio3, a.precio4, a.ult_costo,'); SQL.Add('a.desc_auto, a.minimo, a.maximo, a.categoria, a.departamento,'); SQL.Add('a.tipo, a.proveedor1, a.proveedor2, a.iva, a.fecha_cap, a.fecha_umov,'); SQL.Add('a.ultcompra, a.ultventa, a.estatus, c.nombre AS categorias,'); SQL.Add('d.nombre AS departamentos FROM articulos a '); SQL.Add('LEFT JOIN codigos o ON a.clave = o.articulo AND o.tipo = ''P'''); SQL.Add('LEFT JOIN categorias c ON a.categoria = c.clave '); SQL.Add('LEFT JOIN departamentos d ON a.departamento = d.clave '); SQL.Add('WHERE a.clave = ' + IntToStr(iClave)); Open; if(not Eof) then begin pgeGeneral.ActivePage := tabDatos; txtCodigo.Text := Trim(FieldByName('codigo').AsString); txtDescripCorta.Text := Trim(FieldByName('desc_corta').AsString); txtDescripLarga.Text := Trim(FieldByName('desc_larga').AsString); txtFechaCap.Text := FormatDateTime('dd/mm/yyyy',FieldByName('fecha_cap').AsDateTime); txtProvNum1.Value := FieldByName('proveedor1').AsInteger; txtUltimoCos.Value := FieldByName('ult_costo').AsFloat; txtIva.Value := FieldByName('iva').AsFloat; if FieldByName('estatus').AsString ='A' then cmbEstatus.ItemIndex := 0 else cmbEstatus.ItemIndex := 1; sDeptos := BuscaNombre(FieldByName('departamento').AsInteger, 'departamentos'); sCateg := BuscaNombre(FieldByName('categoria').AsInteger, 'categorias'); cmbCategorias.ItemIndex := cmbCategorias.Items.IndexOf(Trim(sCateg)); end; end; end; procedure TfrmGastos.btnModificarClick(Sender: TObject); begin sModo := 'Modificar'; if (pgeGeneral.ActivePage = tabBusqueda) then RecuperaDatosBusq; ActivaControles; txtCodigo.SetFocus; end; procedure TfrmGastos.btnLimpiarClick(Sender: TObject); begin txtCodigoBusq.Clear; txtDescCortaBusq.Clear; txtProvClave.Value:=0; end; procedure TfrmGastos.ActivaBuscar; begin if(pgeGeneral.ActivePage <> tabBusqueda) then begin mnuBuscar.Enabled := false; mnuLimpiar.Enabled := false; mnuSeleccionar.Enabled := false; end else begin mnuBuscar.Enabled := true; mnuLimpiar.Enabled := true; mnuSeleccionar.Enabled := true; end; end; procedure TfrmGastos.grdJuegoDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var sCad : String; i : real; begin sCad := (Sender as TStringGrid).Cells[ACol,ARow]; if(Length(sCad) > 0) then begin if(ARow = 0) then begin i := Rect.Left + (Rect.Right - Rect.Left) / 2 - (Sender as TStringGrid).Canvas.TextWidth(sCad) / 2; (Sender as TStringGrid).Canvas.FillRect(Rect); (Sender as TStringGrid).Canvas.TextOut(Round(i),Rect.Top+2,sCad); end; if(ACol = 2) and (ARow > 0) then begin sCad := FormatFloat('#,##0.000',StrToFloat(sCad)); i := Rect.Right-(Sender as TStringGrid).Canvas.TextWidth(sCad+' '); (Sender as TStringGrid).Canvas.FillRect(Rect); (Sender as TStringGrid).Canvas.TextOut(Round(i),Rect.Top+2,sCad); end; if(ACol = 3) and (ARow > 0) then begin sCad := FormatFloat('#,##0.00',StrToFloat(sCad)); i := Rect.Right-(Sender as TStringGrid).Canvas.TextWidth(sCad+' '); (Sender as TStringGrid).Canvas.FillRect(Rect); (Sender as TStringGrid).Canvas.TextOut(Round(i),Rect.Top+2,sCad); end; end; end; procedure TfrmGastos.mnuOrganizacionClick(Sender: TObject); begin pgeDatos.ActivePage := tabOrganiza; ActivaBuscar; end; procedure TfrmGastos.mnuProvedClick(Sender: TObject); begin pgeGeneral.ActivePage := tabDatos; ActivaBuscar; end; procedure TfrmGastos.mnuBusquedaClick(Sender: TObject); begin pgeGeneral.ActivePage := tabBusqueda; ActivaBuscar; end; procedure TfrmGastos.mnuAvanzaClick(Sender: TObject); begin with dmDatos.cdsArticulos do begin if(Active) then begin Next; if(pgeGeneral.ActivePage <> tabBusqueda) then begin RecuperaDatosBusq; ActivaControles; end; end; end; end; procedure TfrmGastos.mnuRetrocedeClick(Sender: TObject); begin with dmDatos.cdsArticulos do begin if(Active) then begin Prior; if(pgeGeneral.ActivePage <> tabBusqueda) then begin RecuperaDatosBusq; ActivaControles; end; end; end; end; procedure TfrmGastos.btnEliminarClick(Sender: TObject); begin if (pgeGeneral.ActivePage = tabBusqueda) then RecuperaDatosBusq; pgeGeneral.ActivePage := tabDatos; if(Application.MessageBox('Se eliminará el registro seleccionado','Eliminar',[smbOK]+[smbCancel],smsWarning) = smbOK) then begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM articulos WHERE clave = ' + IntToStr(iClave)); ExecSQL; Close; LimpiaDatos; sModo := 'Consulta'; ActivaControles; btnBuscar.Click; pgeGeneral.ActivePage := tabBusqueda; ActivaBuscar; end; end; end; procedure TfrmGastos.RecuperaConfig; var iniArchivo : TIniFile; sIzq, sArriba, sValor : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); with iniArchivo do begin //Recupera la posición Y de la ventana sArriba := ReadString('Gastos', 'Posy', ''); //Recupera la posición X de la ventana sIzq := ReadString('Gastos', 'Posx', ''); if (Length(sIzq) > 0) and (Length(sArriba) > 0) then begin Left := StrToInt(sIzq); Top := StrToInt(sArriba); end; //Recupera el valor de los botones de radio de buscar sValor := ReadString('Gastos', 'Buscar', ''); if (Length(sValor) > 0) then rdgBuscar.ItemIndex := StrToInt(sValor); //Recupera el valor de los botones de radio de orden sValor := ReadString('Gastos', 'Orden', ''); if (Length(sValor) > 0) then rdgOrden.ItemIndex := StrToInt(sValor); //Recupera la {ultima ficha que se seleccionó sValor := ReadString('Gastos', 'Ficha', ''); if (Length(sValor) > 0) then pgeDatos.ActivePageIndex := StrToInt(sValor); sValor := ReadString('Gastos', 'Ficha2', ''); if (Length(sValor) > 0) then pgeGeneral.ActivePageIndex := StrToInt(sValor); Free; end; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT letraencodigo FROM config'); Open; if( FieldByName('letraencodigo').AsString = 'S' ) then bLetras := true else bLetras := false; Close; end; end; procedure TfrmGastos.FormClose(Sender: TObject; var Action: TCloseAction); var iniArchivo : TIniFile; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); with iniArchivo do begin // Registra la posición y de la ventana WriteString('Gastos', 'Posy', IntToStr(Top)); // Registra la posición X de la ventana WriteString('Gastos', 'Posx', IntToStr(Left)); //Registra el valor de los botones de radio de buscar WriteString('Gastos', 'Buscar', IntToStr(rdgBuscar.ItemIndex)); //Registra el valor de los botones de radio de orden WriteString('Gastos', 'Orden', IntToStr(rdgOrden.ItemIndex)); //Registra la ultima ficha que se seleccionó WriteString('Gastos', 'Ficha', IntToStr(pgeDatos.ActivePageIndex)); //Registra la ultima ficha que se seleccionó WriteString('Gastos', 'Ficha2', IntToStr(pgeGeneral.ActivePageIndex)); Free; end; dmDatos.qryArticulos.Close; dmDatos.cdsArticulos.Active := false; end; procedure TfrmGastos.grdListadoDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin case dmDatos.cdsArticulos.FieldByName('tipo').AsInteger of 0:grdListado.Canvas.Brush.Color := $0094E7ED; 1:grdListado.Canvas.Brush.Color := $0099A7F7; 2:grdListado.Canvas.Brush.Color := $00DCBFA5; 3:grdListado.Canvas.Brush.Color := $00BFCAB7; end; grdListado.Canvas.FillRect(Rect); grdListado.DefaultDrawColumnCell(Rect,DataCol,Column,State); end; procedure TfrmGastos.Buscarproveedor1Click(Sender: TObject); begin with TFrmProveedBusq.Create(Self) do try if(txtProvNum1.Focused)and (txtProvNum1.Font.Color=clWindowText) then begin if(ShowModal = mrOk) then txtProvNum1.Text := sClave; txtProvNum1.SetFocus; end else if(txtProvClave.Focused) then begin if(ShowModal = mrOk) then txtProvClave.Text := sClave; txtProvClave.SetFocus; end; finally Free; end; end; procedure TfrmGastos.VerificaCategs; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT * FROM categorias WHERE tipo = ''A'''); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO categorias (nombre, tipo, cuenta, fecha_umov) VALUES'); SQL.Add('(''DEFAULT'',''G'','''',''' + FormatDateTime('mm/dd/yyyy',Date) + ''')'); ExecSQL; end; Close; end; end; procedure TfrmGastos.VerificaDeptos; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT * FROM departamentos'); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO departamentos (clave, nombre, fecha_umov) VALUES'); SQL.Add('(1,''DEFAULT'',''' + FormatDateTime('mm/dd/yyyy',Date) + ''')'); ExecSQL; end; Close; end; end; procedure TfrmGastos.grdListadoDblClick(Sender: TObject); begin pgeGeneral.ActivePage := tabDatos; LimpiaDatos; RecuperaDatosBusq; ActivaBuscar; ActivaControles; end; procedure TfrmGastos.grdListadoEnter(Sender: TObject); begin btnSeleccionar.Default := true; btnBuscar.Default := false; end; procedure TfrmGastos.grdListadoExit(Sender: TObject); begin btnBuscar.Default := true; btnSeleccionar.Default := false; end; procedure TfrmGastos.btnSeleccionarClick(Sender: TObject); begin if (txtRegistros.Value > 0) then begin RecuperaDatosBusq; ActivaBuscar; ActivaControles; end; end; procedure TfrmGastos.Salir1Click(Sender: TObject); begin Close; end; procedure TfrmGastos.Salta(Sender: TObject; var Key: Word; Shift: TShiftState); begin {Inicio (36), Fin (35), Izquierda (37), derecha (39), arriba (38), abajo (40)} if(Key >= 30) and (Key <= 122) and (Key <> 35) and (Key <> 36) and not ((Key >= 37) and (Key <= 40)) then if( Length((Sender as TEdit).Text) = (Sender as TEdit).MaxLength) then SelectNext(Sender as TWidgetControl, true, true); end; procedure TfrmGastos.txtCodigoKeyPress(Sender: TObject; var Key: Char); begin if(not bLetras) then if not (Key in ['0'..'9',#8,#9,#13,#46]) then Key := #0; end; procedure TfrmGastos.pgeGeneralPageChanging(Sender: TObject; NewPage: TTabSheet; var AllowChange: Boolean); begin ActivaBuscar; end; procedure TfrmGastos.pgeGeneralChange(Sender: TObject); begin ActivaBuscar; end; procedure TfrmGastos.CargaMovimientos; begin with dmDatos.qryConsulta do begin Close; SQL.Clear; SQL.Add('SELECT a.ultcompra, a.ultventa, a.estatus, '); SQL.Add('c.fecha AS cfecha, c.proveedor, p.nombre AS nomproveedor,'); SQL.Add('v.fecha AS vfecha, v.hora, v.cliente, cli.nombre AS nomcliente'); SQL.Add('FROM articulos a '); SQL.Add('LEFT JOIN compras c ON a.ultcompra = c.clave '); SQL.Add('LEFT JOIN ventas v ON a.ultventa = v.clave '); SQL.Add('LEFT JOIN proveedores p ON c.proveedor = p.clave '); SQL.Add('LEFT JOIN clientes cli ON v.cliente = cli.clave '); SQL.Add('WHERE a.clave = ' + IntToStr(iClave)); Open; if(not Eof) then begin if(Length(FieldByName('cfecha').AsString) > 0) then txtFechComp.Text := FormatDateTime('dd/mm/yyyy',FieldByName('cfecha').AsDateTime) else txtFechComp.Clear; end; Close; end; end; function TfrmGastos.BuscaNombre(iValor:Integer; sTabla:string):String; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT nombre FROM ' + sTabla + ' WHERE clave = ' + IntToStr(iValor)); Open; Result := FieldByName('nombre').AsString; Close; end; end; procedure TfrmGastos.mnuMovimientosClick(Sender: TObject); begin pgeDatos.ActivePage := tabMov; ActivaBuscar; end; procedure TfrmGastos.FormCreate(Sender: TObject); begin RecuperaConfig; end; procedure TfrmGastos.txtProvClaveChange(Sender: TObject); begin BuscaProveedor(Sender); end; function TfrmGastos.VerificaCodigo:boolean; begin Result := true; if(Length(txtCodigo.Text) > 0) then begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT articulo FROM codigos WHERE codigo = ''' + txtCodigo.Text + ''''); Open; if(not Eof) and ((sModo = 'Insertar') or ((FieldByName('articulo').AsInteger <> iClave) and (sModo = 'Modificar'))) then begin Result := false; end; Close; end; end; end; end.
unit QuickExportSetup; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,save_isilo_dialog; type TQuickExportSetupForm = class(TForm) SkipImages: TCheckBox; Button1: TButton; Button2: TButton; Label1: TLabel; TOCDepthEdit: TEdit; Label2: TLabel; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure WidthEditChange(Sender: TObject); private { Private declarations } ParentHandle:THandle; Key:String; public { Public declarations } constructor CreateWithForeighnParent(AParent:THandle;AKey:String); procedure CreateParams(var Params: TCreateParams); override; end; var QuickExportSetupForm: TQuickExportSetupForm; const QuickSetupKey=RegistryKey+'\quick\'; implementation uses Registry; {$R *.dfm} constructor TQuickExportSetupForm.CreateWithForeighnParent; Begin ParentHandle:=AParent; Key:=QuickSetupKey+AKey; create(Nil); end; procedure TQuickExportSetupForm.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.WndParent := ParentHandle; end; procedure TQuickExportSetupForm.FormCreate(Sender: TObject); Var Reg:TRegistry; begin Reg:=TRegistry.Create(KEY_READ); Try Try if Reg.OpenKeyReadOnly(Key) then Begin SkipImages.Checked:=Reg.ReadBool('Skip images'); TOCDepthEdit.Text:=IntToStr(Reg.ReadInteger('TOC deepness')); end; Finally Reg.Free; end; Except end; end; procedure TQuickExportSetupForm.Button1Click(Sender: TObject); Var Reg:TRegistry; begin Reg:=TRegistry.Create(KEY_ALL_ACCESS); Try if Reg.OpenKey(Key,True) then Begin Reg.WriteBool('Skip images',SkipImages.Checked); Reg.WriteInteger('TOC deepness',StrToInt(TOCDepthEdit.Text)); end; Finally Reg.Free; end; end; procedure TQuickExportSetupForm.WidthEditChange(Sender: TObject); begin try StrToInt(TOCDepthEdit.Text); except TOCDepthEdit.Text:='4'; end; end; end.
unit crazyclimber_hw_dac; interface uses {$IFDEF WINDOWS}windows,{$ENDIF}sound_engine,timer_engine; type tcclimber_audio=class constructor create; destructor free; public procedure reset; procedure change_sample(valor:byte); procedure change_freq(valor:byte); procedure change_volume(valor:byte); procedure trigger_w; function get_rom_addr:pbyte; procedure update; private sample_freq:single; sample_volume:single; tsample_num:byte; timer_num:byte; start,pos:word; rom:array[0..$1fff] of byte; out_:smallint; up_down:boolean; end; var cclimber_audio:tcclimber_audio; implementation const AMP=4; procedure cclimer_update_internal; var sample:byte; pos:word; begin pos:=cclimber_audio.start+cclimber_audio.pos; if ((pos>$1fff) or (cclimber_audio.rom[pos]=$70)) then begin timers.enabled(cclimber_audio.timer_num,false); cclimber_audio.out_:=0; exit; end; if not(cclimber_audio.up_down) then begin sample:=(cclimber_audio.rom[pos] and $f0) shr 4; cclimber_audio.up_down:=true; end else begin sample:=cclimber_audio.rom[pos] and $f; cclimber_audio.pos:=cclimber_audio.pos+1; cclimber_audio.up_down:=false; end; cclimber_audio.out_:=trunc((($1111*sample)-$8000)*cclimber_audio.sample_volume); end; function tcclimber_audio.get_rom_addr:pbyte; begin get_rom_addr:=@self.rom[0]; end; constructor tcclimber_audio.create; begin self.tsample_num:=init_channel; timer_num:=timers.init(sound_status.cpu_num,1,cclimer_update_internal,nil,false); self.reset; end; destructor tcclimber_audio.free; begin end; procedure tcclimber_audio.reset; begin timers.enabled(self.timer_num,false); end; procedure tcclimber_audio.change_sample(valor:byte); begin self.start:=valor*32; end; procedure tcclimber_audio.change_freq(valor:byte); begin self.sample_freq:=3072000/4/(256-valor); timers.timer[self.timer_num].time_final:=3072000/self.sample_freq; end; procedure tcclimber_audio.change_volume(valor:byte); begin cclimber_audio.sample_volume:=(valor and $1f)/(31*AMP); end; procedure tcclimber_audio.trigger_w; begin timers.enabled(self.timer_num,true); self.pos:=0; up_down:=false; end; procedure tcclimber_audio.update; begin tsample[self.tsample_num,sound_status.posicion_sonido]:=self.out_; if sound_status.stereo then tsample[self.tsample_num,sound_status.posicion_sonido+1]:=self.out_; end; end.
unit UDemo; interface uses SysUtils, Types, UITypes, Classes, Variants, UIConsts, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSBaseControl, FMX.TMSGridOptions, FMX.TMSGridData, FMX.TMSGrid, FMX.GridExcelIO, FMX.TMSBitmapContainer, FMX.TMSGridCell, FMX.TMSGridRTF, FMX.TMSXUtil, FMX.TMSCustomGrid, FMX.StdCtrls; type TForm719 = class(TForm) TMSFMXGrid1: TTMSFMXGrid; Panel1: TPanel; Button1: TButton; TMSFMXBitmapContainer1: TTMSFMXBitmapContainer; TMSFMXGridRTFIO1: TTMSFMXGridRTFIO; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure TMSFMXGrid1GetCellLayout(Sender: TObject; ACol, ARow: Integer; ALayout: TTMSFMXGridCellLayout; ACellState: TCellState); private { Private declarations } public { Public declarations } procedure InitGrid; end; var Form719: TForm719; implementation {$R *.fmx} { TForm719 } procedure TForm719.Button1Click(Sender: TObject); begin TMSFMXGridRTFIO1.ExportRTF('..\..\gridexport.rtf'); XOpenFile('open', '..\..\gridexport.rtf', '', ''); end; procedure TForm719.FormCreate(Sender: TObject); begin TMSFMXGridRTFIO1.Options.ExportOverwrite := omAlways; TMSFMXGridRTFIO1.Options.ExportImages := true; TMSFMXGridRTFIO1.Options.ExportBackground := true; InitGrid; end; procedure TForm719.InitGrid; begin TMSFMXGrid1.ColumnCount := 6; TMSFMXGrid1.RandomFill; TMSFMXGrid1.AutoNumberCol(0); TMSFMXGrid1.Colors[2,2] := claRed; TMSFMXGrid1.Colors[3,3] := claLime; TMSFMXGrid1.Colors[4,4] := claYellow; TMSFMXGrid1.HorzAlignments[2,3] := TTextAlign.taCenter; TMSFMXGrid1.HorzAlignments[3,4] := TTextAlign.taTrailing; TMSFMXGrid1.FontStyles[1,1] := [TFontStyle.fsBold]; TMSFMXGrid1.FontStyles[1,2] := [TFontStyle.fsItalic]; TMSFMXGrid1.MergeCells(1,4,2,2); TMSFMXGrid1.MergeCells(1,7,2,1); TMSFMXGrid1.AddBitmap(1,7,'1'); TMSFMXGrid1.AddBitmap(1,8,'2'); TMSFMXGrid1.AddBitmap(1,9,'3'); end; procedure TForm719.TMSFMXGrid1GetCellLayout(Sender: TObject; ACol, ARow: Integer; ALayout: TTMSFMXGridCellLayout; ACellState: TCellState); begin if (ACol = 5) then begin ALayout.FontFill.Color := claRed; ALayout.TextAlign := TTextAlign.taTrailing; end; end; end.
unit App; { Based on 025_recursive_texture.cpp example from oglplus (http://oglplus.org/) } {$INCLUDE 'Sample.inc'} interface uses System.Classes, Neslib.Ooogles, Neslib.FastMath, Sample.App, Sample.Geometry; type TRecursiveTextureApp = class(TApplication) private const TEXTURE_SIZE = 512; private FProgram: TGLProgram; FVerts: TGLBuffer; FNormals: TGLBuffer; FTexCoords: TGLBuffer; FIndices: TGLBuffer; FUniTexUnit: TGLUniform; FUniProjectionMatrix: TGLUniform; FUniCameraMatrix: TGLUniform; FUniModelMatrix: TGLUniform; FDefaultFramebuffer: TGLFramebuffer; FFramebuffers: array [0..1] of TGLFramebuffer; FRenderbuffers: array [0..1] of TGLRenderbuffer; FTextures: array [0..1] of TGLTexture; FCurrentTextureIndex: Integer; FCube: TCubeGeometry; public procedure Initialize; override; procedure Render(const ADeltaTimeSec, ATotalTimeSec: Double); override; procedure Shutdown; override; procedure KeyDown(const AKey: Integer; const AShift: TShiftState); override; end; implementation uses {$INCLUDE 'OpenGL.inc'} System.UITypes, Sample.Math; { TRecursiveTextureApp } procedure TRecursiveTextureApp.Initialize; var VertexShader, FragmentShader: TGLShader; VertAttr: TGLVertexAttrib; Uniform: TGLUniform; I: Integer; begin VertexShader.New(TGLShaderType.Vertex, 'uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;'#10+ 'attribute vec3 Position;'#10+ 'attribute vec3 Normal;'#10+ 'attribute vec2 TexCoord;'#10+ 'varying vec3 vertNormal;'#10+ 'varying vec3 vertLight;'#10+ 'varying vec2 vertTexCoord;'#10+ 'uniform vec3 LightPos;'#10+ 'void main(void)'#10+ '{'#10+ ' vertNormal = mat3(ModelMatrix) * Normal;'#10+ ' gl_Position = ModelMatrix * vec4(Position, 1.0);'#10+ ' vertLight = LightPos - gl_Position.xyz;'#10+ ' vertTexCoord = TexCoord;'#10+ ' gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;'#10+ '}'); VertexShader.Compile; FragmentShader.New(TGLShaderType.Fragment, 'precision mediump float;'#10+ 'uniform sampler2D TexUnit;'#10+ 'varying vec3 vertNormal;'#10+ 'varying vec3 vertLight;'#10+ 'varying vec2 vertTexCoord;'#10+ 'void main(void)'#10+ '{'#10+ ' float l = sqrt(length(vertLight));'#10+ ' float d = (l > 0.0) ? dot(vertNormal, normalize(vertLight)) / l : 0.0;'#10+ ' float i = 0.6 + max(d, 0.0);'#10+ ' gl_FragColor = texture2D(TexUnit, vertTexCoord) * i;'#10+ '}'); FragmentShader.Compile; FProgram.New(VertexShader, FragmentShader); FProgram.Link; VertexShader.Delete; FragmentShader.Delete; FProgram.Use; FCube.Generate; { Positions } FVerts.New(TGLBufferType.Vertex); FVerts.Bind; FVerts.Data<TVector3>(FCube.Positions); VertAttr.Init(FProgram, 'Position'); VertAttr.SetConfig<TVector3>; VertAttr.Enable; { Normals } FNormals.New(TGLBufferType.Vertex); FNormals.Bind; FNormals.Data<TVector3>(FCube.Normals); VertAttr.Init(FProgram, 'Normal'); VertAttr.SetConfig<TVector3>; VertAttr.Enable; { Texture coordinates } FNormals.New(TGLBufferType.Vertex); FNormals.Bind; FNormals.Data<TVector2>(FCube.TexCoords); VertAttr.Init(FProgram, 'TexCoord'); VertAttr.SetConfig<TVector2>; VertAttr.Enable; { Indices } FIndices.New(TGLBufferType.Index); FIndices.Bind; FIndices.Data<UInt16>(FCube.Indices); { Don't need data anymore } FCube.Clear; { Textures, renderbuffers and framebuffers } FDefaultFramebuffer := TGLFramebuffer.GetCurrent; for I := 0 to 1 do begin FTextures[I].New; FTextures[I].BindToTextureUnit(I); FTextures[I].MinFilter(TGLMinFilter.Linear); FTextures[I].MagFilter(TGLMagFilter.Linear); FTextures[I].WrapS(TGLWrapMode.NormalRepeat); FTextures[I].WrapT(TGLWrapMode.NormalRepeat); FTextures[I].Upload(TGLPixelFormat.RGBA, TEXTURE_SIZE, TEXTURE_SIZE, nil); FRenderbuffers[I].New; FRenderbuffers[I].Bind; FRenderbuffers[I].Storage(TEXTURE_SIZE, TEXTURE_SIZE, TGLRenderbufferFormat.Depth16); FFramebuffers[I].New; FFramebuffers[I].Bind; FFramebuffers[I].AttachTexture(TGLFramebufferAttachment.Color, FTextures[I]); FFramebuffers[I].AttachRenderbuffer(TGLFramebufferAttachment.Depth, FRenderbuffers[I]); Assert(FFramebuffers[I].Status = TGLFramebufferStatus.Complete); end; { Uniforms } Uniform.Init(FProgram, 'LightPos'); Uniform.SetValue(4.0, 4.0, -8.0); FUniTexUnit.Init(FProgram, 'TexUnit'); FUniProjectionMatrix.Init(FProgram, 'ProjectionMatrix'); FUniCameraMatrix.Init(FProgram, 'CameraMatrix'); FUniModelMatrix.Init(FProgram, 'ModelMatrix'); gl.ClearColor(1.0, 1.0, 1.0, 0); gl.ClearDepth(1); gl.Enable(TGLCapability.DepthTest); gl.Enable(TGLCapability.CullFace); gl.FrontFace(TGLFaceOrientation.CounterClockwise); gl.CullFace(TGLFace.Back); end; procedure TRecursiveTextureApp.KeyDown(const AKey: Integer; const AShift: TShiftState); begin { Terminate app when Esc key is pressed } if (AKey = vkEscape) then Terminate; end; procedure TRecursiveTextureApp.Render(const ADeltaTimeSec, ATotalTimeSec: Double); var FrontIndex, BackIndex: Integer; CameraMatrix, ModelMatrix, ProjectionMatrix: TMatrix4; Time: Single; begin FrontIndex := FCurrentTextureIndex; BackIndex := 1 - FCurrentTextureIndex; FCurrentTextureIndex := BackIndex; { Use the program } FProgram.Use; { Render into texture } FUniTexUnit.SetValue(FrontIndex); { Set the matrix for camera orbiting the origin } OrbitCameraMatrix(TVector3.Zero, 3.0, Radians(ATotalTimeSec * 35), Radians(FastSin(Pi * ATotalTimeSec / 10) * 60), CameraMatrix); FUniCameraMatrix.SetValue(CameraMatrix); { Set model matrix } ModelMatrix.InitRotationX(Pi * ATotalTimeSec * 0.5); FUniModelMatrix.SetValue(ModelMatrix); { Set projection matrix } ProjectionMatrix.InitPerspectiveFovRH(Radians(40), 1, 1, 40); FUniProjectionMatrix.SetValue(ProjectionMatrix); { Render to framebuffer } FFramebuffers[BackIndex].Bind; gl.Viewport(TEXTURE_SIZE, TEXTURE_SIZE); gl.Clear([TGLClear.Color, TGLClear.Depth]); FCube.DrawWithBoundIndexBuffer; { Render textured cube to default framebuffer } FDefaultFramebuffer.Bind; gl.Viewport(Width, Height); gl.Clear([TGLClear.Color, TGLClear.Depth]); Time := ATotalTimeSec + 0.3; { Set the matrix for camera orbiting the origin } OrbitCameraMatrix(TVector3.Zero, 3.0, Radians(Time * 35), Radians(FastSin(Pi * Time / 10) * 60), CameraMatrix); FUniCameraMatrix.SetValue(CameraMatrix); { Set projection matrix } ProjectionMatrix.InitPerspectiveFovRH(Radians(60), Width / Height, 1, 40); FUniProjectionMatrix.SetValue(ProjectionMatrix); { Render } FCube.DrawWithBoundIndexBuffer; end; procedure TRecursiveTextureApp.Shutdown; var I: Integer; begin { Release resources } for I := 0 to 1 do begin FFramebuffers[I].Delete; FRenderbuffers[I].Delete; FTextures[I].Delete; end; FIndices.Delete; FTexCoords.Delete; FNormals.Delete; FVerts.Delete; FProgram.Delete; end; end.
unit TcpQuoteAgent; interface uses Windows, BaseWinProcess, ThostFtdcBaseDataType, ThostFtdcMdApiDataType, define_price, define_ctp_quote; type TTcpAgentQuoteConsoleData = record IsMDConnected: Boolean; IsMDLogined: Boolean; //TCPAgentProcess: TExProcessA; SrvWND: HWND; TCPAgentQuoteProcess: TOwnProcess; QuoteInstrumentIds: array[0..QuoteArraySize - 1] of AnsiString; QuoteArray: array[0..QuoteArraySize - 1] of TRT_QuoteData; end; TQuoteConsole = class protected fTcpAgentQuoteConsoleData: TTcpAgentQuoteConsoleData; public constructor Create; virtual; destructor Destroy; override; //================================ function FindSrvWindow: Boolean; procedure StartAgentProcess; //================================ procedure InitMD; procedure ConnectMD(Addr: AnsiString); procedure LoginMD(ABrokerId, Account, APassword: AnsiString); procedure MDSubscribe(AInstrumentId: AnsiString); procedure MDSaveAllQuote; //================================ function CheckOutQuoteData(AInstrumentId: AnsiString): PRT_QuoteData; //================================ property SrvWND: HWND read fTcpAgentQuoteConsoleData.SrvWND; property IsMDConnected: Boolean read fTcpAgentQuoteConsoleData.IsMDConnected write fTcpAgentQuoteConsoleData.IsMDConnected; property IsMDLogined: Boolean read fTcpAgentQuoteConsoleData.IsMDLogined write fTcpAgentQuoteConsoleData.IsMDLogined; end; function CheckOutQuoteDataRecords(ART_QuoteData: PRT_QuoteData): PRT_QuoteDataRecords; procedure FtdcPrice2RTPricePack(APricePack: PRT_PricePack; APrice: TThostFtdcPriceType); procedure MarketData2QuoteData(AMarketData: PhostFtdcDepthMarketDataField; ART_QuoteDataRecord: PRT_QuoteDataRecord); implementation uses Messages, Sysutils, UtilsApplication, TcpAgentConsole, define_app_msg; { TQuoteConsole } function CheckOutQuoteDataRecords(ART_QuoteData: PRT_QuoteData): PRT_QuoteDataRecords; begin Result := System.New(PRT_QuoteDataRecords); FillChar(Result^, SizeOf(TRT_QuoteDataRecords), 0); Windows.EnterCriticalSection(ART_QuoteData.PageLock); try if ART_QuoteData.FirstRecords = nil then ART_QuoteData.FirstRecords := Result; if ART_QuoteData.LastRecords <> nil then begin Result.PrevSibling := ART_QuoteData.LastRecords; ART_QuoteData.LastRecords.NextSibling := Result; end; ART_QuoteData.LastRecords := Result; finally Windows.LeaveCriticalSection(ART_QuoteData.PageLock); end; end; procedure FtdcPrice2RTPricePack(APricePack: PRT_PricePack; APrice: TThostFtdcPriceType); begin try APricePack.Value := Trunc(APrice * 1000); except APricePack.Value := 0; end; end; procedure MarketData2QuoteData(AMarketData: PhostFtdcDepthMarketDataField; ART_QuoteDataRecord: PRT_QuoteDataRecord); begin // 最新价 FtdcPrice2RTPricePack(@ART_QuoteDataRecord.LastPrice, AMarketData.LastPrice); ///数量 ART_QuoteDataRecord.Volume := AMarketData.Volume; // 4 - 12 ///成交金额 ART_QuoteDataRecord.Turnover := AMarketData.Turnover; // 8 - 20 // 持仓量 ART_QuoteDataRecord.OpenInterest := AMarketData.OpenInterest; // 8 - 20 ///申买价一 FtdcPrice2RTPricePack(@ART_QuoteDataRecord.BidPrice1, AMarketData.BidPrice1); /// ///申买量一 ART_QuoteDataRecord.BidVolume1 := AMarketData.BidVolume1; // 4 - 32 ///申卖价一 FtdcPrice2RTPricePack(@ART_QuoteDataRecord.AskPrice1, AMarketData.AskPrice1); // 8 - 40 ///申卖量一 ART_QuoteDataRecord.AskVolume1 := AMarketData.AskVolume1; // 4 - 44 // 时间 ??? ART_QuoteDataRecord.UpdateTime := 0; // 8 - 52 ///最后修改毫秒 ART_QuoteDataRecord.UpdateMillisec := AMarketData.UpdateMillisec; // 4 - 56 // 程序记录时间 ART_QuoteDataRecord.RecordTime := Now(); // 8 - 64 ART_QuoteDataRecord.UpdateTime2 := AMarketData.UpdateTime; // 9 - 81 ART_QuoteDataRecord.Status := 1; // 1 -- 82 end; constructor TQuoteConsole.Create; begin FillChar(fTcpAgentQuoteConsoleData, SizeOf(fTcpAgentQuoteConsoleData), 0); end; destructor TQuoteConsole.Destroy; begin inherited; end; function TQuoteConsole.FindSrvWindow: Boolean; begin if 0 <> fTcpAgentQuoteConsoleData.SrvWND then begin if not IsWindow(fTcpAgentQuoteConsoleData.SrvWND) then begin fTcpAgentQuoteConsoleData.SrvWND := 0; end else begin Result := true; exit; end; end; fTcpAgentQuoteConsoleData.SrvWND := FindWindow('Tftdc_api_srv', 'tcpagent'); Result := (fTcpAgentQuoteConsoleData.SrvWND <> 0) and (fTcpAgentQuoteConsoleData.SrvWND <> INVALID_HANDLE_VALUE); end; procedure TQuoteConsole.StartAgentProcess; var tmpProcessFileUrl: AnsiString; begin if not FindSrvWindow then begin //CloseExProcess(@fTcpAgentConsoleData.TCPAgentProcess); //fTcpAgentConsoleData.TCPAgentProcess.FilePath := ExtractFilePath(ParamStr(0)); //fTcpAgentConsoleData.TCPAgentProcess.FileUrl := fTcpAgentConsoleData.TCPAgentProcess.FilePath + 'tcpagent.exe'; tmpProcessFileUrl := ExtractFilePath(ParamStr(0)) + 'tcpagent.exe'; if FileExists(tmpProcessFileUrl) then begin RunProcessA(@fTcpAgentQuoteConsoleData.TCPAgentQuoteProcess, tmpProcessFileUrl, nil); end; //RunExProcess(@fTcpAgentConsoleData.TCPAgentProcess); end; SleepWait(200); end; procedure TQuoteConsole.InitMD; begin StartAgentProcess(); if FindSrvWindow then begin SleepWait(50); PostMessage(SrvWND, WM_C2S_MD_RequestInitialize, 0, 0); end; end; procedure TQuoteConsole.ConnectMD(Addr: AnsiString); var tmpCopyData: TCopyDataCommand; begin if FindSrvWindow then begin //PostMessage(SrvWND, WM_C2S_RequestConnectFront, 0, 0); FillChar(tmpCopyData, SizeOf(tmpCopyData), 0); tmpCopyData.Base.dwData := WM_C2S_MD_RequestConnectFront; tmpCopyData.Base.cbData := SizeOf(tmpCopyData.CommonCommand); tmpCopyData.Base.lpData := @tmpCopyData.CommonCommand; CopyMemory(@tmpCopyData.CommonCommand.scmd1[0], @Addr[1], Length(Addr)); SendMessage(SrvWND, WM_COPYDATA, 0, LongWord(@tmpCopyData)); end; end; procedure TQuoteConsole.LoginMD(ABrokerId, Account, APassword: AnsiString); var tmpCopyData: TCopyDataCommand; tmpAnsi: AnsiString; begin if FindSrvWindow then begin //PostMessage(SrvWND, WM_C2S_RequestUserLogin, 0, 0); FillChar(tmpCopyData, SizeOf(tmpCopyData), 0); tmpCopyData.Base.dwData := WM_C2S_MD_RequestUserLogin; tmpCopyData.Base.cbData := SizeOf(tmpCopyData.CommonCommand); tmpCopyData.Base.lpData := @tmpCopyData.CommonCommand; tmpAnsi := ABrokerId; CopyMemory(@tmpCopyData.CommonCommand.scmd3[0], @tmpAnsi[1], Length(tmpAnsi)); tmpAnsi := Account; CopyMemory(@tmpCopyData.CommonCommand.scmd1[0], @tmpAnsi[1], Length(tmpAnsi)); tmpAnsi := APassword; CopyMemory(@tmpCopyData.CommonCommand.scmd2[0], @tmpAnsi[1], Length(tmpAnsi)); tmpCopyData.CommonCommand.icmd1 := GTcpAgentConsole.CheckOutRequestId; SendMessage(SrvWND, WM_COPYDATA, 0, LongWord(@tmpCopyData)); SleepWait(1000); if GTcpAgentConsole.Deal.IsDealLogined then begin GTcpAgentConsole.Deal.ConfirmSettlementInfo; end; end; end; procedure TQuoteConsole.MDSaveAllQuote; //var // i: integer; // tmpFileUrl: string; begin // for i := 0 to Quote.QuoteCount - 1 do // begin // if Quote.QuoteCode[i] <> '' then // begin // tmpFileUrl := ExtractFilePath(ParamStr(0)) + 'q'+ Quote.QuoteCode[i] + '_' + FormatDateTime('yyyymmdd_hh', now) + '.ptc'; // SaveQuoteData(Quote.QuoteData[i], tmpFileUrl); // end; // end; end; procedure TQuoteConsole.MDSubscribe(AInstrumentId: AnsiString); var tmpCopyData: TCopyDataCommand; tmpAnsi: AnsiString; begin if FindSrvWindow then begin //PostMessage(SrvWND, WM_C2S_SubscribeMarketData, 0, 0); FillChar(tmpCopyData, SizeOf(TCopyDataCommand), 0); tmpCopyData.Base.dwData := WM_C2S_SubscribeMarketData; tmpCopyData.Base.cbData := SizeOf(tmpCopyData.CommonCommand); tmpCopyData.Base.lpData := @tmpCopyData.CommonCommand; tmpAnsi := AInstrumentId; CopyMemory(@tmpCopyData.CommonCommand.scmd1[0], @tmpAnsi[1], Length(tmpAnsi)); SendMessage(SrvWND, WM_COPYDATA, 0, LongWord(@tmpCopyData)); end; end; function TQuoteConsole.CheckOutQuoteData(AInstrumentId: AnsiString): PRT_QuoteData; var i: integer; begin Result := nil; for i := Low(fTcpAgentQuoteConsoleData.QuoteInstrumentIds) to High(fTcpAgentQuoteConsoleData.QuoteInstrumentIds) do begin if fTcpAgentQuoteConsoleData.QuoteInstrumentIds[i] <> '' then begin if fTcpAgentQuoteConsoleData.QuoteInstrumentIds[i] = AInstrumentId then begin Result := @fTcpAgentQuoteConsoleData.QuoteArray[i]; Break; end; end else begin fTcpAgentQuoteConsoleData.QuoteInstrumentIds[i] := AInstrumentId; Result := @fTcpAgentQuoteConsoleData.QuoteArray[i]; Break; end; end; end; end.
unit evdTopicFileSplitter; { $Id: evdTopicFileSplitter.pas,v 1.1 2014/07/16 10:39:23 fireton Exp $ } interface uses k2TagGen, k2FileGenerator, k2TagFilter, l3Variant; type TevdTopicFileSplitter = class(Tk2TagFilter) private f_FileGenerator: Tk2CustomFileGenerator; f_Index : Integer; f_BaseFilename : AnsiString; private function GetNextFilename: AnsiString; public constructor Create(const aFileGenerator : Tk2CustomFileGenerator; aBaseFileName : AnsiString); class function SetTo(var theGenerator : Tk2TagGenerator; const aFileGenerator : Tk2CustomFileGenerator; aBaseFileName : AnsiString): Pointer; procedure StartChild(TypeID: Tl3VariantDef); override; end; implementation uses SysUtils, l3Base, l3Filer, Document_Const; constructor TevdTopicFileSplitter.Create(const aFileGenerator : Tk2CustomFileGenerator; aBaseFileName : AnsiString); begin inherited Create; f_BaseFilename := aBaseFilename; f_FileGenerator := aFileGenerator; end; function TevdTopicFileSplitter.GetNextFilename: AnsiString; var l_Ext: AnsiString; begin Inc(f_Index); l_Ext := ExtractFileExt(f_BaseFilename); Result := ChangeFileExt(f_BaseFilename, '_' + IntToStr(f_Index) + l_Ext); end; class function TevdTopicFileSplitter.SetTo(var theGenerator : Tk2TagGenerator; const aFileGenerator : Tk2CustomFileGenerator; aBaseFileName : AnsiString): Pointer; var l_Filter: TevdTopicFileSplitter; begin l_Filter := Create(aFileGenerator, aBaseFilename); try l_Filter.Generator := theGenerator; l3Set(theGenerator, l_Filter); finally FreeAndNil(l_Filter); end; Result := theGenerator; end; procedure TevdTopicFileSplitter.StartChild(TypeID: Tl3VariantDef); begin if TypeID = k2_typDocument then begin if f_FileGenerator.Filer.Opened then f_FileGenerator.Filer.Close; Tl3CustomDOSFiler(f_FileGenerator.Filer).FileName := GetNextFilename; f_FileGenerator.Filer.Open; end; inherited; end; end.
unit xn.grid.common; interface type TxnGridLinkNotifyData = record type TKind = (gekAdd, gekDel, gekEdit, gekMove); private fRow: Integer; fCol: Integer; fKind: TKind; public constructor Create(aCol, aRow: Integer; aKind: TKind); property Row: Integer read fRow; property Col: Integer read fCol; property Kind: TKind read fKind; end; TxnGridColNotify = procedure(fData: TxnGridLinkNotifyData) of object; TxnGridLinkNotify = procedure(fData: TxnGridLinkNotifyData) of object; IxnGridData = interface ['{D88DE50E-5A96-4955-B8C3-DD321FB97458}'] function RowCountGet: Integer; function ValueString(aCol, aRow: Integer): String; function ValueFloat(aCol, aRow: Integer): Double; end; IxnGridLink = interface(IxnGridData) ['{6CDF8790-F13F-4507-9DB3-E173799CEAD4}'] procedure RecNoSet(aIndex: Integer); function RecNoGet: Integer; procedure NotifySet(aRowEvent: TxnGridLinkNotify); end; function xnGridEventKindDes(aGridEventKind: TxnGridLinkNotifyData.TKind): string; function xnGridNotifyDataCreateColEvent(aCol: Integer; aKind: TxnGridLinkNotifyData.TKind): TxnGridLinkNotifyData; function xnGridNotifyDataCreateLinkEvent(aRow: Integer; aKind: TxnGridLinkNotifyData.TKind): TxnGridLinkNotifyData; implementation uses System.Math, System.TypInfo; function xnGridEventKindDes(aGridEventKind: TxnGridLinkNotifyData.TKind): string; begin Result := GetEnumName(TypeInfo(TxnGridLinkNotifyData.TKind), Ord(aGridEventKind)); end; { TxnGridNotifyData } constructor TxnGridLinkNotifyData.Create(aCol, aRow: Integer; aKind: TKind); begin fCol := aCol; fRow := aRow; fKind := aKind; end; function xnGridNotifyDataCreateColEvent(aCol: Integer; aKind: TxnGridLinkNotifyData.TKind): TxnGridLinkNotifyData; begin Result.Create(aCol, -1, aKind); end; function xnGridNotifyDataCreateLinkEvent(aRow: Integer; aKind: TxnGridLinkNotifyData.TKind): TxnGridLinkNotifyData; begin Result.Create(-1, aRow, aKind); end; end.
unit UGeRemessaBoletos; interface uses UGrPadrao, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, DB, IBCustomDataSet, IBTable, ComCtrls, IBSQL, DBClient, Provider, IBUpdateSQL, IBQuery, Buttons, ToolWin, Grids, DBGrids, ComObj, frxClass, frxDBSet, ACBrBoleto, ACBrBoletoFCFR, ACBrBase, Mask, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, cxButtons, JvExMask, JvToolEdit, dxSkinsCore, dxSkinMcSkin, dxSkinOffice2007Green, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White; type TfrmGeRemessaBoleto = class(TfrmGrPadrao) pnlFiltro: TPanel; GroupBox1: TGroupBox; lblBanco: TLabel; edBanco: TComboBox; lblInicio: TLabel; lblFinal: TLabel; edArquivoRemessa: TEdit; lblArquivoRemessa: TLabel; IbQryTitulos: TIBQuery; IbUpdTitulos: TIBUpdateSQL; DspTitulos: TDataSetProvider; CdsTitulos: TClientDataSet; CdsTitulosPARCELA: TSmallintField; CdsTitulosCODBANCO: TIntegerField; CdsTitulosDTEMISS: TDateField; CdsTitulosDTVENC: TDateField; CdsTitulosVALORREC: TBCDField; CdsTitulosPERCENTJUROS: TBCDField; CdsTitulosPERCENTMULTA: TBCDField; CdsTitulosPERCENTDESCONTO: TBCDField; CdsTitulosVALORRECTOT: TBCDField; CdsTitulosVALORSALDO: TBCDField; CdsTitulosDATAPROCESSOBOLETO: TDateField; DtsTitulos: TDataSource; UpdateLanc: TIBSQL; pnlTitulos: TPanel; Shape1: TShape; Bevel2: TBevel; Bevel1: TBevel; Bevel5: TBevel; dbgTitulos: TDBGrid; Label5: TLabel; frrRemessa: TfrxReport; frdRemessa: TfrxDBDataset; CdsTitulosANOLANC: TSmallintField; CdsTitulosANOVENDA: TSmallintField; CdsTitulosNUMVENDA: TIntegerField; CdsTitulosNUMLANC: TIntegerField; ACBrBoleto: TACBrBoleto; ACBrBoletoFCFR: TACBrBoletoFCFR; CdsTitulosNFE: TLargeintField; IbQryBancos: TIBQuery; IbQryBancosBCO_COD: TSmallintField; IbQryBancosEMPRESA: TIBStringField; IbQryBancosBCO_CARTEIRA: TIBStringField; IbQryBancosBCO_NOME: TIBStringField; IbQryBancosBCO_AGENCIA: TIBStringField; IbQryBancosBCO_CC: TIBStringField; IbQryBancosBCO_CODIGO_CEDENTE: TIBStringField; IbQryBancosBCO_CHAVE: TIBStringField; IbQryBancosBCO_GERAR_BOLETO: TSmallintField; IbQryBancosBCO_NOSSO_NUM_INICIO: TIBStringField; IbQryBancosBCO_NOSSO_NUM_FINAL: TIBStringField; IbQryBancosBCO_NOSSO_NUM_PROXIMO: TIBStringField; IbQryBancosBCO_CONFG_1: TIBStringField; IbQryBancosBCO_CONFG_2: TIBStringField; IbQryBancosBCO_SEQUENCIAL_REM: TIntegerField; IbQryBancosBCO_DIRETORIO_REMESSA: TIBStringField; IbQryBancosBCO_DIRETORIO_RETORNO: TIBStringField; IbQryBancosBCO_PERCENTUAL_JUROS: TIBBCDField; IbQryBancosBCO_PERCENTUAL_MORA: TIBBCDField; IbQryBancosBCO_DIA_PROTESTO: TSmallintField; IbQryBancosBCO_MSG_INSTRUCAO: TIBStringField; IbQryBancosBCO_LAYOUT_REMESSA: TSmallintField; IbQryBancosBCO_LAYOUT_RETORNO: TSmallintField; IbQryBancosRZSOC: TIBStringField; IbQryBancosNMFANT: TIBStringField; IbQryBancosIE: TIBStringField; IbQryBancosIM: TIBStringField; IbQryBancosENDER: TIBStringField; IbQryBancosCOMPLEMENTO: TIBStringField; IbQryBancosNUMERO_END: TIBStringField; IbQryBancosBAIRRO: TIBStringField; IbQryBancosCEP: TIBStringField; IbQryBancosCIDADE: TIBStringField; IbQryBancosUF: TIBStringField; IbQryBancosEMAIL: TIBStringField; IbUpdBancos: TIBUpdateSQL; CdsTitulosPARCELA_MAXIMA: TSmallintField; CdsTitulosSITUACAO: TSmallintField; edInicio: TJvDateEdit; edFinal: TJvDateEdit; tlbBotoes: TPanel; Bevel3: TBevel; btnFechar: TcxButton; Bevel4: TBevel; btnGerarRemessa: TcxButton; Bevel6: TBevel; chkEnviarCancelados: TCheckBox; Bevel7: TBevel; btnHistorico: TcxButton; CdsTitulosNOSSONUMERO: TWideStringField; CdsTitulosCNPJ: TWideStringField; CdsTitulosTIPPAG: TWideStringField; CdsTitulosINSCEST: TWideStringField; CdsTitulosNOME: TWideStringField; CdsTitulosFONE: TWideStringField; CdsTitulosSERIE: TWideStringField; CdsTitulosNumeroDocumento: TStringField; CdsTitulosENDER: TWideStringField; CdsTitulosENDER_DESC: TWideStringField; CdsTitulosENDER_NUM: TWideStringField; CdsTitulosBAIRRO: TWideStringField; CdsTitulosCIDADE: TWideStringField; CdsTitulosUF: TWideStringField; CdsTitulosCEP: TWideStringField; CdsTitulosEMAIL: TWideStringField; procedure FormShow(Sender: TObject); procedure edBancoChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnFecharClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure btnGerarRemessaClick(Sender: TObject); procedure edInicioChange(Sender: TObject); procedure dbgTitulosDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure frrRemessaGetValue(const VarName: String; var Value: Variant); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure CdsTitulosCalcFields(DataSet: TDataSet); private { Private declarations } {$IFNDEF ACBR} CobreBemX : Variant; {$ENDIF} procedure CarregarBancos; procedure DefinirNomeArquivo( iBanco : Integer ); procedure CarregarTitulos( iBanco : Integer; DataInicial, DataFinal : TDate); procedure GravarHistoricoRemessa; function GetAgenciaNumero : String; function GetAgenciaDigito : String; function GetContaNumero : String; function GetContaDigito : String; function GetNossoNumeroRepetido : Boolean; {$IFDEF ACBR} function DefinirCedenteACBr(iBanco : Integer; sCarteira : String) : Boolean; function InserirBoletoACBr : Boolean; {$ELSE} function DefinirCedente( Banco, Carteira : Integer; var Objeto : Variant ) : Boolean; function InserirBoleto( var Objeto : Variant ) : Boolean; {$ENDIF} public { Public declarations } procedure RegistrarRotinaSistema; override; end; (* Tabelas: - TBEMPRESA - TBBANCO_BOLETO - TBCONTREC - TBVENDAS - TBCLIENTE Views: - VW_EMPRESA Procedures: *) var frmGeRemessaBoleto: TfrmGeRemessaBoleto; {$IFNDEF ACBR} const feeSMTPBoletoHTML = $00000000; feeSMTPMensagemBoletoHTMLAnexo = $00000001; feeSMTPMensagemBoletoPDFAnexo = $00000002; feeSMTPMensagemLinhaDigitavelURLCobreBemECommerce = $00000003; feeSMTPMensagemURLCobreBemECommerce = $00000004; feeSMTPMensagemLinhaDigitavel = $00000005; feeOutlookBoletoHTML = $00000006; feeOutlookMensagemBoletoHTMLAnexo = $00000007; feeOutlookMensagemBoletoPDFAnexo = $00000008; feeOutlookMensagemLinhaDigitavelURLCobreBemECommerce = $00000009; feeOutlookMensagemURLCobreBemECommerce = $0000000A; feeOutlookMensagemLinhaDigitavel = $0000000B; scpExecutar = $00000000; scpOK = $00000001; scpInvalido = $00000002; scpErro = $00000003; {$ENDIF} procedure GerarArquivoRemessa(const AOwer : TComponent); implementation uses UDMBusiness, UConstantesDGE, UFuncoes, UDMRecursos; {$R *.dfm} { TfrmGrRemessaBoleto } procedure GerarArquivoRemessa(const AOwer : TComponent); var f : TfrmGeRemessaBoleto; begin try f := TfrmGeRemessaBoleto.Create(AOwer); f.ShowModal; finally f.Free; end; end; procedure TfrmGeRemessaBoleto.CarregarBancos; begin with IbQryBancos, edBanco do begin Close; ParamByName('empresa').AsString := gUsuarioLogado.Empresa; Open; if ( not IsEmpty ) then Clear; while not Eof do begin Items.Add( FormatFloat('000', IbQryBancosBCO_COD.AsInteger) + ' - ' + IbQryBancosBCO_NOME.AsString ); Next; end; First; edBanco.Tag := IbQryBancosBCO_COD.AsInteger; edBanco.ItemIndex := 0; end; end; procedure TfrmGeRemessaBoleto.FormShow(Sender: TObject); begin Self.Caption := Self.Caption + ' - (' + GetNomeFantasiaEmpresa(gUsuarioLogado.Empresa) + ')'; CarregarBancos; edBancoChange(edBanco); end; procedure TfrmGeRemessaBoleto.edBancoChange(Sender: TObject); begin if ( not IbQryBancos.Active ) then IbQryBancos.Open; if ( IbQryBancos.Locate('BCO_COD', StrToIntDef(Copy(edBanco.Text, 1, 3), 0), []) ) then edBanco.Tag := IbQryBancosBCO_COD.AsInteger; DefinirNomeArquivo( edBanco.Tag ); CarregarTitulos( edBanco.Tag, edInicio.Date, edFinal.Date ); end; procedure TfrmGeRemessaBoleto.FormCreate(Sender: TObject); begin inherited; edInicio.Date := Date; edFinal.Date := Date; {$IFNDEF ACBR} CobreBemX := CreateOleObject('CobreBemX.ContaCorrente'); {$ENDIF} end; procedure TfrmGeRemessaBoleto.DefinirNomeArquivo(iBanco: Integer); begin try ForceDirectories(Trim(IbQryBancosBCO_DIRETORIO_REMESSA.AsString)); except end; if ( DirectoryExists(Trim(IbQryBancosBCO_DIRETORIO_REMESSA.AsString)) ) then edArquivoRemessa.Text := Trim(IbQryBancosBCO_DIRETORIO_REMESSA.AsString) + FormatFloat('000', iBanco) + '\' + FormatFloat('000', iBanco) + '_' + FormatDateTime('yyyymmdd-hhmmss', Now) + '.rem' else edArquivoRemessa.Text := ExtractFilePath(ParamStr(0)) + 'Remessa\' + FormatFloat('000', iBanco) + '\' + FormatFloat('000', iBanco) + '_' + FormatDateTime('yyyymmdd-hhmmss', Now) + '.rem'; edArquivoRemessa.Text := StringReplace(edArquivoRemessa.Text, '\\', '\', [rfReplaceAll]); ForceDirectories( ExtractFilePath(edArquivoRemessa.Text) ); end; procedure TfrmGeRemessaBoleto.btnFecharClick(Sender: TObject); begin Close; end; procedure TfrmGeRemessaBoleto.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin // CanClose := ( Application.MessageBox('Deseja abandonar processo de geração de remessas?','Fechar', MB_YESNO + MB_ICONQUESTION + MB_DEFBUTTON2) = ID_YES ); ; end; procedure TfrmGeRemessaBoleto.btnGerarRemessaClick(Sender: TObject); var IBanco , ICarteira : Integer; sBanco , sCarteira : String; begin try if ( CdsTitulos.IsEmpty ) then begin Application.MessageBox('Não existe relação de boletos para gerar arquivo de remessa.','Alerta', MB_ICONEXCLAMATION); Exit; end; if ( Application.MessageBox('Confirma a geração de arquivo de remessa?','Gerar Remessa', MB_YESNO + MB_ICONQUESTION + MB_DEFBUTTON2) <> ID_YES ) then Exit; if ( edBanco.ItemIndex < 0 ) then begin Application.MessageBox(PChar('Favor selecionar a entidade financeira para geração dos boletos.'), 'Alerta', MB_ICONWARNING); Exit; end; IBanco := StrToIntDef( Copy(edBanco.Text, 1, 3), 0 ); ICarteira := IbQryBancosBCO_CARTEIRA.AsInteger; sBanco := Copy(edBanco.Text, 1, 3); sCarteira := IbQryBancosBCO_CARTEIRA.AsString; if GetNossoNumeroRepetido then Exit; {$IFDEF ACBR} if DefinirCedenteACBr( IBanco, sCarteira ) then {$ELSE} if DefinirCedente( IBanco, ICarteira, CobreBemX ) then {$ENDIF} begin CdsTitulos.First; {$IFDEF ACBR} if ( InserirBoletoACbr ) then begin edArquivoRemessa.Text := StringReplace(ACBrBoleto.GerarRemessa(IbQryBancosBCO_SEQUENCIAL_REM.AsInteger), '\\', '\', [rfReplaceAll]); {$ELSE} if ( InserirBoleto( CobreBemX ) ) then begin CobreBemX.GravaArquivoRemessa; {$ENDIF} GravarHistoricoRemessa; ShowInformation('Remessa', 'Arquivo de remessa gerado com sucesso.'{$IFDEF ACBR} + #13#13 + QuotedStr(edArquivoRemessa.Text){$ENDIF}); frrRemessa.ShowReport; CarregarTitulos( edBanco.Tag, edInicio.Date, edFinal.Date ); end; end; except On E : Exception do Application.MessageBox(PChar('Erro na tentativa de gerar o arquivo de remessa.' + #13 + E.Message), 'Erro', MB_ICONERROR); end; end; procedure TfrmGeRemessaBoleto.CarregarTitulos(iBanco: Integer; DataInicial, DataFinal: TDate); begin with CdsTitulos, Params do begin Close; ParamByName('empresa').AsString := gUsuarioLogado.Empresa; ParamByName('banco').Value := iBanco; ParamByName('dataInicial').AsDate := DataInicial; ParamByName('dataFinal').AsDate := DataFinal; Open; btnGerarRemessa.Enabled := not IsEmpty; end; end; procedure TfrmGeRemessaBoleto.edInicioChange(Sender: TObject); begin CarregarTitulos( edBanco.Tag, edInicio.Date, edFinal.Date ); end; procedure TfrmGeRemessaBoleto.dbgTitulosDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin TDbGrid(Sender).Canvas.font.Color := clBlack; if gdSelected in State then with (Sender as TDBGrid).Canvas do begin Brush.Color := clMoneyGreen; FillRect(Rect); Font.Style := [fsbold] end; if ( CdsTitulosSITUACAO.AsInteger = 0 ) then TDbGrid(Sender).Canvas.Font.Color := clRed; TDbGrid(Sender).DefaultDrawDataCell(Rect, TDbGrid(Sender).columns[datacol].field, State); end; {$IFNDEF ACBR} function TfrmGeRemessaBoleto.DefinirCedente(Banco, Carteira: Integer; var Objeto: Variant): Boolean; var sAppPath , sFileLisence : String; begin try sAppPath := ExtractFilePath(ParamStr(0)); sFileLisence := sAppPath + BOLETO_LICENCAS + FormatFloat('000', Banco) + '-' + FormatFloat('00', Carteira) + '.conf'; if ( not FileExists(sFileLisence) ) then raise Exception.Create('Arquivo de licença ' + QuotedStr(sFileLisence) + ' não encontrado'); // Parâmetros obrigatórios da conta corrente do Cedente Objeto.ArquivoLicenca := sFileLisence; Objeto.CodigoAgencia := IbQryBancosBCO_AGENCIA.AsString; Objeto.NumeroContaCorrente := IbQryBancosBCO_CC.AsString; Objeto.CodigoCedente := IbQryBancosBCO_CHAVE.AsString; Objeto.InicioNossoNumero := IbQryBancosBCO_NOSSO_NUM_INICIO.AsString; Objeto.FimNossoNumero := IbQryBancosBCO_NOSSO_NUM_FINAL.AsString; Objeto.OutroDadoConfiguracao1 := Trim(IbQryBancosBCO_CONFG_1.AsString); Objeto.OutroDadoConfiguracao2 := Trim(IbQryBancosBCO_CONFG_2.AsString); if ( Trim(IbQryBancosBCO_NOSSO_NUM_PROXIMO.AsString) = EmptyStr ) then Objeto.ProximoNossoNumero := '1' else Objeto.ProximoNossoNumero := IbQryBancosBCO_NOSSO_NUM_PROXIMO.AsString; // Parâmetros obrigatórios para a geração de arquivos de remessa Objeto.ArquivoRemessa.Arquivo := ExtractFileName(edArquivoRemessa.Text); Objeto.ArquivoRemessa.Diretorio := ExtractFilePath(edArquivoRemessa.Text); Objeto.ArquivoRemessa.Sequencia := IbQryBancosBCO_SEQUENCIAL_REM.AsInteger; Objeto.ArquivoRemessa.DataGravacao := FormatDateTime('dd/mm/yyyy', Date); Objeto.PadroesBoleto.PadroesBoletoImpresso.ArquivoLogotipo := sAppPath + BOLETO_ARQUIVO_LOGOTIPO; Objeto.PadroesBoleto.PadroesBoletoImpresso.CaminhoImagensCodigoBarras := sAppPath + BOLETO_IMAGENS; Result := True; except On E : Exception do begin Application.MessageBox(PChar('Erro ao tentar iniciar processo de geração de arquivo de remessa.' + #13 + E.Message), 'Erro', MB_ICONERROR); Result := False; end; end; end; function TfrmGeRemessaBoleto.InserirBoleto(var Objeto: Variant): Boolean; var sDocumento : String; Boleto , EmailSacado : Variant; begin try Objeto.DocumentosCobranca.Clear; CdsTitulos.First; while not CdsTitulos.Eof do begin Boleto := Objeto.DocumentosCobranca.Add; sDocumento := Copy(CdsTitulosANOLANC.AsString, 3, 2) + FormatFloat('00000000', CdsTitulosNUMLANC.AsInteger) + FormatFloat('000', CdsTitulosPARCELA.AsInteger); Boleto.NumeroDocumento := sDocumento; Boleto.NomeSacado := Trim(CdsTitulosNOME.AsString); if Length(Trim(CdsTitulosCNPJ.AsString)) > 11 then Boleto.CNPJSacado := Trim(CdsTitulosCNPJ.AsString) else Boleto.CPFSacado := Trim(CdsTitulosCNPJ.AsString); Boleto.EnderecoSacado := Trim(CdsTitulosENDER.AsString); Boleto.BairroSacado := Trim(CdsTitulosBAIRRO.AsString); Boleto.CidadeSacado := Trim(CdsTitulosCIDADE.AsString); Boleto.EstadoSacado := Trim(CdsTitulosUF.AsString); Boleto.CepSacado := Trim(CdsTitulosCEP.AsString); Boleto.DataDocumento := FormatDateTime('dd/mm/yyyy', CdsTitulosDATAPROCESSOBOLETO.AsDateTime); if not CdsTitulosDTVENC.IsNull then Boleto.DataVencimento := FormatDateTime('dd/mm/yyyy', CdsTitulosDTVENC.AsDateTime); Boleto.DataProcessamento := FormatDateTime('dd/mm/yyyy', CdsTitulosDATAPROCESSOBOLETO.AsDateTime); Boleto.ValorDocumento := CdsTitulosVALORREC.AsFloat; Boleto.PercentualJurosDiaAtraso := CdsTitulosPERCENTJUROS.AsFloat; Boleto.PercentualMultaAtraso := CdsTitulosPERCENTMULTA.AsFloat; Boleto.PercentualDesconto := CdsTitulosPERCENTDESCONTO.AsFloat; Boleto.ValorOutrosAcrescimos := 0; Boleto.PadroesBoleto.Demonstrativo := 'Referente a compra de produtos <br>e/ou a contratação de serviços' + '<br><br>Venda No. ' + FormatFloat('0000', CdsTitulosANOLANC.AsInteger) + '/' + FormatFloat('##00000000', CdsTitulosNUMVENDA.AsInteger);; Boleto.PadroesBoleto.InstrucoesCaixa := '<br>' + IbQryBancosBCO_MSG_INSTRUCAO.AsString; EmailSacado := Boleto.EnderecosEmailSacado.Add; EmailSacado.Nome := Boleto.NomeSacado; EmailSacado.Endereco := Trim(CdsTitulosEMAIL.AsString); Boleto.ControleProcessamentoDocumento.Imprime := scpExecutar; Boleto.ControleProcessamentoDocumento.EnviaEmail := scpExecutar; Boleto.ControleProcessamentoDocumento.GravaRemessa := scpExecutar; Boleto.NossoNumero := CdsTitulosNOSSONUMERO.AsString; CdsTitulos.Next; end; Result := True; except On E : Exception do begin Application.MessageBox(PChar('Erro ao tentar inserir boleto no arquivo de remessa.' + #13 + E.Message), 'Erro', MB_ICONERROR); Result := False; end; end; end; {$ENDIF} procedure TfrmGeRemessaBoleto.GravarHistoricoRemessa; var sSQL : TStringList; begin try sSQL := TStringList.Create; if ( FileExists(edArquivoRemessa.Text) ) then begin sSQL.BeginUpdate; sSQL.Clear; sSQL.Add( ' Update TBCONTREC Set ' ); sSQL.Add( ' enviado = 1, remessa = ' + IbQryBancosBCO_SEQUENCIAL_REM.AsString ); sSQL.Add( ' where codbanco = ' + IntToStr(edBanco.Tag) ); sSQL.Add( ' and baixado = 0' ); sSQL.Add( ' and enviado = 0' ); sSQL.Add( ' and dataprocessoboleto between ' + QuotedStr(FormatDateTime('yyyy-mm-dd', edInicio.Date)) + ' and ' + QuotedStr(FormatDateTime('yyyy-mm-dd', edFinal.Date))) ; sSQL.EndUpdate; with UpdateLanc, SQL do begin Clear; AddStrings( sSQL ); ExecQuery; end; IbQryBancos.Edit; IbQryBancosBCO_SEQUENCIAL_REM.Value := IbQryBancosBCO_SEQUENCIAL_REM.AsInteger + 1; IbQryBancos.Post; CommitTransaction; end; finally sSQL.Free; end; end; procedure TfrmGeRemessaBoleto.frrRemessaGetValue(const VarName: String; var Value: Variant); begin if ( VarName = 'Banco' ) then Value := edBanco.Text; if ( VarName = 'Arquivo' ) then Value := ExtractFileName(edArquivoRemessa.Text); end; procedure TfrmGeRemessaBoleto.FormDestroy(Sender: TObject); begin {$IFNDEF ACBR} CobreBemX := Unassigned; {$ENDIF} end; procedure TfrmGeRemessaBoleto.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if ( Key = VK_ESCAPE ) then btnFechar.Click else inherited; end; procedure TfrmGeRemessaBoleto.CdsTitulosCalcFields(DataSet: TDataSet); begin if ( CdsTitulosNFE.AsLargeInt > 0 ) then CdsTitulosNumeroDocumento.AsString := FormatFloat('###0000000', CdsTitulosNFE.AsLargeInt) + '-' + FormatFloat('00', CdsTitulosPARCELA.AsInteger) else CdsTitulosNumeroDocumento.AsString := Copy(CdsTitulosANOLANC.AsString, 3, 2) + FormatFloat('00000000', CdsTitulosNUMLANC.AsInteger) + FormatFloat('000', CdsTitulosPARCELA.AsInteger); end; function TfrmGeRemessaBoleto.DefinirCedenteACBr(iBanco: Integer; sCarteira: String): Boolean; var sAppLogo , sAppBoleto, sAppPath : String; begin // Esta função deverá ser replicada em: TfrmGeRemessaBoleto.DefinirCedenteACBr() try sAppPath := ExtractFilePath(ParamStr(0)); sAppBoleto := sAppPath + LAYOUT_BOLETO_ENTREGA; sAppLogo := sAppPath + BOLETO_IMAGENS + 'Colorido\' + FormatFloat('000".bmp"', iBanco); if not FileExists(sAppBoleto) then raise Exception.Create(Format('Arquivo de layout %s não encontrado!', [QuotedStr(sAppBoleto)])); if not FileExists(sAppLogo) then sAppLogo := sAppPath + BOLETO_IMAGENS + 'PretoBranco\' + FormatFloat('000".bmp"', iBanco); if not FileExists(sAppLogo) then sAppLogo := EmptyStr; // Parâmetros obrigatórios da conta corrente do Cedente with ACBrBoleto, Banco do begin Case iBanco of CODIGO_BANCO_BRASIL: begin TipoCobranca := cobBancoDoBrasil; TamanhoMaximoNossoNum := 17; Cedente.Modalidade := EmptyStr; end; CODIGO_BANCO_BRADESCO: begin TipoCobranca := cobBradesco; TamanhoMaximoNossoNum := 11; Cedente.Modalidade := EmptyStr; end; CODIGO_BANCO_CAIXA: begin TipoCobranca := cobCaixaEconomica; TamanhoMaximoNossoNum := 15; Cedente.Modalidade := EmptyStr; end; CODIGO_BANCO_HSBC: begin TipoCobranca := cobHSBC; TamanhoMaximoNossoNum := 16; Cedente.Modalidade := EmptyStr; end; CODIGO_BANCO_ITAU: begin TipoCobranca := cobItau; TamanhoMaximoNossoNum := 8; Cedente.Modalidade := EmptyStr; end; CODIGO_BANCO_SANTANDER: begin TipoCobranca := cobSantander; TamanhoMaximoNossoNum := 12; Cedente.Modalidade := '101'; end; else raise Exception.Create('Sistema não adapitado para gerar boletos para o banco ' + IbQryBancosBCO_NOME.AsString); end; Case IbQryBancosBCO_LAYOUT_REMESSA.AsInteger of 240: LayoutRemessa := c240; 400: LayoutRemessa := c400; end; ACBrBoleto.NomeArqRemessa := ExtractFileName(edArquivoRemessa.Text); ACBrBoleto.DirArqRemessa := ExtractFilePath(edArquivoRemessa.Text); ACBrBoletoFCFR.DirLogo := ExtractFilePath(sAppLogo); ACBrBoletoFCFR.FastReportFile := sAppBoleto; ACBrBoletoFCFR.SoftwareHouse := GetCompanyName; // Dados Conta Cedente.Agencia := GetAgenciaNumero; Cedente.AgenciaDigito := GetAgenciaDigito; Cedente.Conta := GetContaNumero; Cedente.ContaDigito := GetContaDigito; Cedente.Convenio := IbQryBancosBCO_CHAVE.AsString; // Dados Cedente if StrIsCPF(IbQryBancosEMPRESA.AsString) then Cedente.TipoInscricao := pFisica else if StrIsCNPJ(IbQryBancosEMPRESA.AsString) then Cedente.TipoInscricao := pJuridica; Cedente.CNPJCPF := IbQryBancosEMPRESA.AsString; Cedente.Nome := IbQryBancosRZSOC.AsString; Cedente.Logradouro := IbQryBancosENDER.AsString; Cedente.NumeroRes := IbQryBancosNUMERO_END.AsString; Cedente.Complemento := IbQryBancosCOMPLEMENTO.AsString; Cedente.Bairro := IbQryBancosBAIRRO.AsString; Cedente.CEP := IbQryBancosCEP.AsString; Cedente.Cidade := IbQryBancosCIDADE.AsString; Cedente.UF := IbQryBancosUF.AsString; // Dados Convênio Cedente.CodigoCedente := Trim(IbQryBancosBCO_CODIGO_CEDENTE.AsString); Cedente.Convenio := IbQryBancosBCO_CHAVE.AsString; Cedente.CodigoTransmissao := EmptyStr; end; Result := True; except On E : Exception do begin Application.MessageBox(PChar('Erro ao tentar iniciar processo de geração de boletos (ACBr).' + #13 + E.Message), 'Erro', MB_ICONERROR); Result := False; end; end; end; function TfrmGeRemessaBoleto.GetAgenciaDigito: String; var S : String; begin S := Trim(IbQryBancosBCO_AGENCIA.AsString); if Pos('-', S) > 0 then S := Copy(S, Pos('-', S) + 1, Length(S)) else S := EmptyStr; Result := S; end; function TfrmGeRemessaBoleto.GetAgenciaNumero: String; var S : String; begin S := Trim(IbQryBancosBCO_AGENCIA.AsString); if Pos('-', S) > 0 then S := Copy(S, 1, Pos('-', S) - 1); Result := S; end; function TfrmGeRemessaBoleto.GetContaDigito: String; var S : String; begin S := Trim(IbQryBancosBCO_CC.AsString); if Pos('-', S) > 0 then S := Copy(S, Pos('-', S) + 1, Length(S)) else S := EmptyStr; Result := S; end; function TfrmGeRemessaBoleto.GetContaNumero: String; var S : String; begin S := Trim(IbQryBancosBCO_CC.AsString); if Pos('-', S) > 0 then S := Copy(S, 1, Pos('-', S) - 1); Result := S; end; function TfrmGeRemessaBoleto.GetNossoNumeroRepetido : Boolean; var bReturn : Boolean; sNossoNumeroOLD : String; begin bReturn := False; try sNossoNumeroOLD := EmptyStr; CdsTitulos.IndexFieldNames := 'NOSSONUMERO'; CdsTitulos.Close; CdsTitulos.Open; CdsTitulos.First; CdsTitulos.DisableControls; while not CdsTitulos.Eof do begin if (CdsTitulosNOSSONUMERO.AsString = sNossoNumeroOLD) then begin bReturn := True; Break; end; sNossoNumeroOLD := CdsTitulosNOSSONUMERO.AsString; CdsTitulos.Next; end; finally CdsTitulos.First; CdsTitulos.EnableControls; Result := bReturn; if Result then ShowWarning(Format('O identificador ''%s'' utilizado como NOSSO NÚMERO está repetido!' + #13#13 + 'Favor comunicar ao suporte.', [sNossoNumeroOLD])); end; end; function TfrmGeRemessaBoleto.InserirBoletoACBr: Boolean; var sDocumento , sMensagem : String; Boleto : TACBrTitulo; const MSG_REF_NFE = 'Referente a NF-e %s, parcela %s/%s'; MSG_REF_DOC = 'Referente ao título %s, parcela %s/%s'; begin // Esta função deverá ser replicada em: TfrmGeRemessaBoleto.InserirBoletoACBr() try ACBrBoleto.ListadeBoletos.Clear; CdsTitulos.First; CdsTitulos.DisableControls; while not CdsTitulos.Eof do begin // Não enviar na remessa boletos cancelados if ( not chkEnviarCancelados.Checked ) then if ( CdsTitulosSITUACAO.AsInteger = 0 ) then begin CdsTitulos.Next; Continue; end; Boleto := ACBrBoleto.CriarTituloNaLista; if ( CdsTitulosNFE.AsLargeInt > 0 ) then begin sMensagem := Format(MSG_REF_NFE, [FormatFloat('###0000000', CdsTitulosNFE.AsLargeInt), FormatFloat('00', CdsTitulosPARCELA.AsInteger), FormatFloat('00', CdsTitulosPARCELA_MAXIMA.AsInteger)]); sDocumento := FormatFloat('###0000000', CdsTitulosNFE.AsLargeInt) + '-' + FormatFloat('00', CdsTitulosPARCELA.AsInteger); end else begin sMensagem := Format(MSG_REF_DOC, [Copy(CdsTitulosANOLANC.AsString, 3, 2) + FormatFloat('00000000', CdsTitulosNUMLANC.AsInteger), FormatFloat('00', CdsTitulosPARCELA.AsInteger), FormatFloat('00', CdsTitulosPARCELA_MAXIMA.AsInteger)]); sDocumento := Copy(CdsTitulosANOLANC.AsString, 3, 2) + FormatFloat('00000000', CdsTitulosNUMLANC.AsInteger) + FormatFloat('000', CdsTitulosPARCELA.AsInteger); end; with Boleto do begin // Dados do Sacado if StrIsCPF(CdsTitulosCNPJ.AsString) then Sacado.Pessoa := pFisica else if StrIsCNPJ(CdsTitulosCNPJ.AsString) then Sacado.Pessoa := pJuridica else Sacado.Pessoa := pOutras; Sacado.CNPJCPF := CdsTitulosCNPJ.AsString; Sacado.NomeSacado := CdsTitulosNOME.AsString; Sacado.Logradouro := CdsTitulosENDER_DESC.AsString; Sacado.Numero := CdsTitulosENDER_NUM.AsString; Sacado.Bairro := CdsTitulosBAIRRO.AsString; Sacado.Cidade := CdsTitulosCIDADE.AsString; Sacado.UF := CdsTitulosUF.AsString; Sacado.CEP := StrOnlyNumbers(CdsTitulosCEP.AsString); Sacado.Email := AnsiLowerCase(Trim(CdsTitulosEMAIL.AsString)); Sacado.Fone := StrOnlyNumbers(Trim(CdsTitulosFONE.AsString)); // Dados do Documento LocalPagamento := 'Pagar preferêncialmente nas agências do(a) ' + ACBrBoleto.Banco.Nome; if not CdsTitulosDTVENC.IsNull then Vencimento := CdsTitulosDTVENC.AsDateTime else Vencimento := GetProximoDiaUtil(Date); (* O campo Aceite indica se o Sacado (quem recebe o boleto) aceitou o boleto, ou seja, se ele assinou o documento de cobrança que originou o boleto. O padrão é usar "Não" no aceite, pois nesse caso não é necessário a autorização do Sacado para protestar o título. Se escolher "Sim", o Cedente (quem emite o boleto) precisará de algum documento onde o Sacado reconhece a dívida para poder protestar o título. *) Aceite := atNao; DataDocumento := CdsTitulosDTEMISS.AsDateTime; NumeroDocumento := sDocumento; Parcela := CdsTitulosPARCELA.AsInteger; EspecieDoc := 'DM'; // Duplicata Mercantil EspecieMod := 'R$'; DataProcessamento := CdsTitulosDATAPROCESSOBOLETO.AsDateTime; Carteira := IbQryBancosBCO_CARTEIRA.AsString; NossoNumero := CdsTitulosNOSSONUMERO.AsString; // Dados de Cobrança ValorDocumento := CdsTitulosVALORREC.AsCurrency; ValorAbatimento := 0.0; ValorMoraJuros := (CdsTitulosVALORREC.AsCurrency * IbQryBancosBCO_PERCENTUAL_MORA.AsCurrency / 100) / 30; ValorDesconto := CdsTitulosVALORREC.AsCurrency * CdsTitulosPERCENTDESCONTO.AsCurrency / 100; DataMoraJuros := GetProximoDiaUtil(Vencimento); DataAbatimento := StrToCurrDef(EmptyStr, 0); if ( CdsTitulosPERCENTDESCONTO.AsCurrency = 0 ) then DataDesconto := StrToCurrDef(EmptyStr, 0) else DataDesconto := CdsTitulosDTVENC.AsDateTime; if ( IbQryBancosBCO_DIA_PROTESTO.AsInteger = 0 ) then DataProtesto := StrToCurrDef(EmptyStr, 0) else DataProtesto := (Vencimento + IbQryBancosBCO_DIA_PROTESTO.AsInteger); PercentualMulta := IbQryBancosBCO_PERCENTUAL_JUROS.AsCurrency; // Percentual de multa por dia de atraso. if ( CdsTitulosSITUACAO.AsInteger = 0 ) then // Cancelado OcorrenciaOriginal.Tipo := toRemessaBaixar else if ( CdsTitulosSITUACAO.AsInteger = 1 ) then // Ativo OcorrenciaOriginal.Tipo := toRemessaRegistrar; Instrucao1 := '00'; Instrucao2 := '00'; Mensagem.Text := sMensagem + #13 + StringReplace(IbQryBancosBCO_MSG_INSTRUCAO.AsString, '<br>', '', [rfReplaceAll]); end; CdsTitulos.Next; end; Result := True; except On E : Exception do begin CdsTitulos.EnableControls; Application.MessageBox(PChar('Erro ao tentar gerar boletos (ACBr).' + #13 + E.Message), 'Erro', MB_ICONERROR); Result := False; end; end; CdsTitulos.EnableControls; end; procedure TfrmGeRemessaBoleto.RegistrarRotinaSistema; begin ; end; initialization FormFunction.RegisterForm('frmGeRemessaBoleto', TfrmGeRemessaBoleto); end.
{ Subroutine SST_W_C_SCOPE_PUSH (SCOPE,SCOPE_TYPE) * * Set the current scope to SCOPE. The state for the old scope will be pushed * onto the stack. The old scope state can be recovered with SST_W_C_SCOPE_POP. * SCOPE_TYPE is the type of the new scope. This must be one of the constants * SCOPE_TYPE_xxx_K. } module sst_w_c_SCOPE_PUSH; define sst_w_c_scope_push; %include 'sst_w_c.ins.pas'; procedure sst_w_c_scope_push ( {set a new scope as current} in scope: sst_scope_t; {scope to set current} in scope_type: scope_type_k_t); {the type of the new scope} const max_msg_parms = 1; {max parameters we can pass to a message} var fold_p: frame_scope_p_t; {pointer to previous scope stack frame} global_only: boolean; {declare only global symbols first if true} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin %debug; write (sst_stack^.last_p^.curr_adr, ' '); %debug; writeln ('SCOPE PUSH'); frame_scope_p^.scope_p := sst_scope_p; {save pnt to old scope on old stack frame} fold_p := frame_scope_p; {save pointer to old scope stack frame} util_stack_push ( {create new stack frame} sst_stack, sizeof(frame_scope_p^), frame_scope_p); frame_scope_p^.prev_p := fold_p; frame_scope_p^.pos_decll := sst_out.dyn_p^; frame_scope_p^.pos_exec := sst_out.dyn_p^; frame_scope_p^.scope_p := addr(scope); frame_scope_p^.funcval_sym_p := nil; {init to no function return val var exists} frame_scope_p^.const_p := nil; {init to no implicit const var created yet} frame_scope_p^.scope_type := scope_type; {set what kind of scope this is} case scope_type of scope_type_global_k, scope_type_module_k: begin {scope is always global} frame_scope_p^.sment_type := sment_type_declg_k; sst_out.dyn_p := addr(pos_declg); global_only := false; end; scope_type_prog_k: begin {scope will start out as global} frame_scope_p^.sment_type := sment_type_declg_k; sst_out.dyn_p := addr(pos_declg); global_only := true; end; scope_type_rout_k: begin {scope is always local} global_only := false; {declare all symbols for this scope} if {already within executable scope ?} (fold_p^.scope_type = scope_type_prog_k) or (fold_p^.scope_type = scope_type_rout_k) then begin {this is a nested executable scope} frame_scope_p^.funcval_sym_p := fold_p^.funcval_sym_p; {propagate state} frame_scope_p^.const_p := fold_p^.const_p; frame_scope_p^.sment_type := sment_type_exec_k; {curr in executable sments} sst_out.dyn_p := addr(frame_scope_p^.pos_exec); {use pos for exec sments} end else begin {this is executable scope of new routine} frame_scope_p^.sment_type := sment_type_decll_k; {assume local scope} sst_out.dyn_p := addr(frame_scope_p^.pos_decll); if {scope belongs to function with return val ?} (scope.symbol_p <> nil) and then scope.symbol_p^.symtype = sst_symtype_proc_k then begin frame_scope_p^.funcval_sym_p := {save pointer to function value variable} scope.symbol_p^.proc_funcvar_p; end; end ; end; otherwise sys_msg_parm_int (msg_parm[1], ord(scope_type)); sys_message_bomb ('sst_c_write', 'scope_type_bad', msg_parm, 1); end; sst_scope_p := addr(scope); {set the new scope as current} sst_names_p := sst_scope_p; sst_w_c_symbols (global_only); {declare symbols in this new scope} end;
{******************************************************************************} { } { Delphi FB4D Library } { Copyright (c) 2018-2023 Christoph Schneider } { Schneider Infosystems AG, Switzerland } { https://github.com/SchneiderInfosystems/FB4D } { } {******************************************************************************} { } { 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 ChatMainFmx; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.ImageList, System.Generics.Collections, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.Controls.Presentation, FMX.Edit, FMX.TabControl,FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.Layouts, FMX.ListView, FMX.StdCtrls, FMX.MultiResBitmap, FMX.ImgList, FMX.TextLayout, FMX.ListBox, FB4D.Interfaces, FB4D.Configuration, FB4D.SelfRegistrationFra; type TfmxChatMain = class(TForm) TabControl: TTabControl; tabChat: TTabItem; tabLogin: TTabItem; edtKey: TEdit; Text2: TText; edtProjectID: TEdit; Text3: TText; lsvChat: TListView; layPushMessage: TLayout; edtMessage: TEdit; btnPushMessage: TButton; lblVersionInfo: TLabel; layUserInfo: TLayout; btnSignOut: TButton; lblUserInfo: TLabel; FraSelfRegistration: TFraSelfRegistration; txtUpdate: TText; txtError: TText; btnDeleteMessage: TButton; btnEditMessage: TButton; layFBConfig: TLayout; edtBucket: TEdit; Text1: TText; shpProfile: TCircle; ImageList: TImageList; imgCloudOff: TImage; layVirtualKeyboardSpace: TLayout; rctBack: TRectangle; tmrWatchdog: TTimer; txtWatchdog: TText; tmrTesting: TTimer; chbTesting: TCheckBox; cboFilterMessages: TComboBox; procedure FormCreate(Sender: TObject); procedure btnSignOutClick(Sender: TObject); procedure btnPushMessageClick(Sender: TObject); procedure edtMessageKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure lsvChatItemClick(const Sender: TObject; const AItem: TListViewItem); procedure btnEditMessageClick(Sender: TObject); procedure btnDeleteMessageClick(Sender: TObject); procedure FraSelfRegistrationbtnCheckEMailClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure lsvChatUpdateObjects(const Sender: TObject; const AItem: TListViewItem); procedure FormVirtualKeyboard(Sender: TObject; KeyboardVisible: Boolean; const Bounds: TRect); procedure tmrWatchdogTimer(Sender: TObject); procedure chbTestingChange(Sender: TObject); procedure tmrTestingTimer(Sender: TObject); procedure cboFilterMessagesChange(Sender: TObject); private type TPendingProfile = class Items: TList<TListViewItem>; Stream: TStream; constructor Create(FirstItem: TListViewItem); destructor Destroy; override; end; private type TMsgType = (myMsg, foreignMsg); private fConfig: TFirebaseConfiguration; fUID: string; fUserName: string; fMyImgIndex: integer; fEditDocID: string; fLastCreated: TDateTime; fPendingProfiles: TDictionary<string {UID}, TPendingProfile>; fStressTestCounter: cardinal; function GetAuth: IFirebaseAuthentication; function GetStorage: IFirebaseStorage; function GetSettingFilename: string; function GetCacheFolder: string; procedure SaveSettings; procedure OnTokenRefresh(TokenRefreshed: boolean); procedure OnUserLogin(const Info: string; User: IFirebaseUser); procedure StartChat; procedure StartListener; procedure WipeToTab(ActiveTab: TTabItem); procedure EnterEditMode(const DocPath: string); procedure ExitEditMode(ClearEditBox: boolean); function GetMsgTextName(MsgType: TMsgType): string; function GetDetailTextName(MsgType: TMsgType): string; function GetProfileImgName(MsgType: TMsgType): string; procedure OnAuthRevoked(TokenRenewPassed: boolean); procedure OnChangedColDocument(Document: IFirestoreDocument); procedure OnDeletedColDocument(const DeleteDocumentPath: string; TimeStamp: TDateTime); procedure OnListenerError(const RequestID, ErrMsg: string); procedure OnStopListening(Sender: TObject); procedure OnConnectionStateChange(ListenerConnected: boolean); function SearchItem(const DocId: string): TListViewItem; procedure OnDocWrite(const Info: string; Document: IFirestoreDocument); procedure OnDocWriteError(const RequestID, ErrMsg: string); procedure OnDocDelete(const RequestID: string; Response: IFirebaseResponse); procedure OnDocDeleteError(const RequestID, ErrMsg: string); function AddProfileImgToImageList(const UID: string; Img: TBitmap): integer; procedure DownloadProfileImgAndAddToImageList(const UID: string; Item: TListViewItem); procedure OnStorageDownload(Obj: IStorageObject); procedure OnGetStorageError(const ObjectName: TObjectName; const ErrMsg: string); end; var fmxChatMain: TfmxChatMain; implementation uses System.IniFiles, System.IOUtils, System.JSON, System.Math, FB4D.Helpers, FB4D.Firestore, FB4D.Document, FB4D.Storage; {$R *.fmx} {$R *.LgXhdpiPh.fmx ANDROID} const cCollectionID = 'Chat'; // Install the following Firestore Rule: // rules_version = '2'; // service cloud.firestore { // match /databases/{database}/documents { // match /Chat/{document=**} { // allow read, write: if request.auth != null;}} { TfmxChatMain } procedure TfmxChatMain.FormCreate(Sender: TObject); var IniFile: TIniFile; LastEMail: string; LastToken: string; begin Caption := Caption + ' - ' + TFirebaseHelpers.GetConfigAndPlatform + ' [' + TFirebaseConfiguration.GetLibVersionInfo + ']'; IniFile := TIniFile.Create(GetSettingFilename); try edtKey.Text := IniFile.ReadString('FBProjectSettings', 'APIKey', ''); edtProjectID.Text := IniFile.ReadString('FBProjectSettings', 'ProjectID', ''); edtBucket.Text := IniFile.ReadString('FBProjectSettings', 'Bucket', ''); LastEMail := IniFile.ReadString('Authentication', 'User', ''); LastToken := IniFile.ReadString('Authentication', 'Token', ''); finally IniFile.Free; end; fPendingProfiles := TDictionary<string, TPendingProfile>.Create; TabControl.ActiveTab := tabLogin; FraSelfRegistration.InitializeAuthOnDemand(GetAuth, OnUserLogin, LastToken, LastEMail, true, false, true); FraSelfRegistration.RequestProfileImg(GetStorage); if edtProjectID.Text.IsEmpty then edtProjectID.SetFocus; end; procedure TfmxChatMain.FormDestroy(Sender: TObject); begin fPendingProfiles.Free; FreeAndNil(fConfig); end; procedure TfmxChatMain.FraSelfRegistrationbtnCheckEMailClick(Sender: TObject); begin FraSelfRegistration.btnCheckEMailClick(Sender); end; procedure TfmxChatMain.SaveSettings; var IniFile: TIniFile; begin IniFile := TIniFile.Create(GetSettingFilename); try IniFile.WriteString('FBProjectSettings', 'APIKey', edtKey.Text); IniFile.WriteString('FBProjectSettings', 'ProjectID', edtProjectID.Text); IniFile.WriteString('FBProjectSettings', 'Bucket', edtBucket.Text); IniFile.WriteString('Authentication', 'User', FraSelfRegistration.GetEMail); if assigned(fConfig) and fConfig.Auth.Authenticated then IniFile.WriteString('Authentication', 'Token', fConfig.Auth.GetRefreshToken) else IniFile.DeleteKey('Authentication', 'Token'); finally IniFile.Free; end; end; procedure TfmxChatMain.OnTokenRefresh(TokenRefreshed: boolean); begin SaveSettings; end; function TfmxChatMain.GetAuth: IFirebaseAuthentication; begin fConfig := TFirebaseConfiguration.Create(edtKey.Text, edtProjectID.Text); result := fConfig.Auth; result.InstallTokenRefreshNotification(OnTokenRefresh); edtKey.Enabled := false; edtProjectID.Enabled := false; end; function TfmxChatMain.GetStorage: IFirebaseStorage; begin Assert(assigned(fConfig), 'FirebaseConfiguration not initialized'); if not edtBucket.Text.IsEmpty and edtBucket.Enabled then begin edtBucket.Enabled := false; fConfig.SetBucket(edtBucket.Text); fConfig.Storage.SetupCacheFolder(GetCacheFolder); end; result := fConfig.Storage; end; function TfmxChatMain.GetSettingFilename: string; var FileName: string; begin FileName := ChangeFileExt(ExtractFileName(ParamStr(0)), ''); result := IncludeTrailingPathDelimiter( {$IFDEF IOS} TPath.GetDocumentsPath {$ELSE} TPath.GetHomePath {$ENDIF} ) + FileName + TFirebaseHelpers.GetPlatform + '.ini'; end; function TfmxChatMain.GetCacheFolder: string; var FileName: string; begin FileName := ChangeFileExt(ExtractFileName(ParamStr(0)), ''); result := IncludeTrailingPathDelimiter( {$IFDEF IOS} TPath.GetDocumentsPath {$ELSE} TPath.GetHomePath {$ENDIF} ) + IncludeTrailingPathDelimiter(FileName); end; procedure TfmxChatMain.OnUserLogin(const Info: string; User: IFirebaseUser); begin fUID := User.UID; fUserName := User.DisplayName; if assigned(FraSelfRegistration.ProfileImg) then shpProfile.Fill.Bitmap.Bitmap.Assign(FraSelfRegistration.ProfileImg); SaveSettings; StartChat; end; procedure TfmxChatMain.btnSignOutClick(Sender: TObject); begin fConfig.Database.StopListener; fConfig.Auth.SignOut; fUID := ''; fUserName := ''; FraSelfRegistration.StartEMailEntering; WipeToTab(tabLogin); end; procedure TfmxChatMain.WipeToTab(ActiveTab: TTabItem); var c: integer; begin if TabControl.ActiveTab <> ActiveTab then begin ActiveTab.Visible := true; {$IFDEF ANDROID} TabControl.ActiveTab := ActiveTab; {$ELSE} TabControl.GotoVisibleTab(ActiveTab.Index, TTabTransition.Slide, TTabTransitionDirection.Normal); {$ENDIF} for c := 0 to TabControl.TabCount - 1 do TabControl.Tabs[c].Visible := TabControl.Tabs[c] = ActiveTab; end; end; procedure TfmxChatMain.StartChat; begin GetStorage; while not fConfig.Storage.IsCacheScanFinished do begin FraSelfRegistration.InformDelayedStart('starting...'); if Application.Terminated then exit else TFirebaseHelpers.SleepAndMessageLoop(1); end; FraSelfRegistration.StopDelayedStart; lblUserInfo.Text := fUserName + ' logged in'; edtMessage.Text := ''; btnEditMessage.Visible := false; btnDeleteMessage.Visible := false; btnPushMessage.Visible := true; fEditDocID := ''; fMyImgIndex := AddProfileImgToImageList(fUID, FraSelfRegistration.ProfileImg); StartListener; {$IFDEF DEBUG} tmrWatchdog.Enabled := true; chbTesting.Visible := true; {$ENDIF} WipeToTab(tabChat); end; procedure TfmxChatMain.StartListener; function ExtractIntInStr(const str: string): integer; var c: char; begin result := 0; for c in str do if CharInSet(c, ['0'..'9']) then result := result * 10 + ord(c) - ord('0'); end; var Query: IStructuredQuery; FilterMsgs: string; begin Assert(cboFilterMessages.ItemIndex >= 0, 'No filter is selected'); lsvChat.Items.Clear; fLastCreated := 0; FilterMsgs := cboFilterMessages.Items[cboFilterMessages.ItemIndex]; Query := TStructuredQuery.CreateForCollection(cCollectionID). OrderBy('DateTime', odDescending); if FilterMsgs.Contains('newest') then Query.Limit(ExtractIntInStr(FilterMsgs)) else if FilterMsgs.Contains('week') then Query.QueryForFieldFilter( TQueryFilter.TimestampFieldFilter('DateTime', TWhereOperator.woGreaterThan, now - 7)) else if FilterMsgs.Contains('month') then Query.QueryForFieldFilter( TQueryFilter.TimestampFieldFilter('DateTime', TWhereOperator.woGreaterThan, now - 31)) else if FilterMsgs.Contains('year') then Query.QueryForFieldFilter( TQueryFilter.TimestampFieldFilter('DateTime', TWhereOperator.woGreaterThan, now - 365)); fConfig.Database.SubscribeQuery(Query, OnChangedColDocument, OnDeletedColDocument); fConfig.Database.StartListener(OnStopListening, OnListenerError, OnAuthRevoked, OnConnectionStateChange); end; procedure TfmxChatMain.cboFilterMessagesChange(Sender: TObject); begin fConfig.Database.StopListener(true); ExitEditMode(not fEditDocID.IsEmpty); StartListener; end; function TfmxChatMain.SearchItem(const DocId: string): TListViewItem; var c: integer; begin result := nil; for c := 0 to lsvChat.ItemCount - 1 do if lsvChat.Items[c].Purpose = TListItemPurpose.None then if lsvChat.Items[c].TagString = DocId then exit(lsvChat.Items[c]); end; function TfmxChatMain.GetMsgTextName(MsgType: TMsgType): string; begin if MsgType = myMsg then result := 'Text3' else result := 'Text5'; end; function TfmxChatMain.GetDetailTextName(MsgType: TMsgType): string; begin if MsgType = myMsg then result := 'Text4' else result := 'Text6'; end; function TfmxChatMain.GetProfileImgName(MsgType: TMsgType): string; begin if MsgType = myMsg then result := 'Image1' else result := 'Image2'; end; procedure TfmxChatMain.OnChangedColDocument(Document: IFirestoreDocument); var Item: TListViewItem; Created, Edited: TDateTime; UID: string; DetailInfo: string; ImgInd: integer; MsgType, InvType: TMsgType; begin Item := SearchItem(Document.DocumentName(true)); lsvChat.BeginUpdate; try Created := TFirebaseHelpers.ConvertToLocalDateTime( Document.GetTimeStampValueDef('DateTime', now)); Edited := Document.GetTimeStampValueDef('Edited', 0); if not assigned(Item) then begin if Created > fLastCreated then Item := lsvChat.Items.AddItem(lsvChat.ItemCount) // add new item to bottom else Item := lsvChat.Items.AddItem(0); // While initial scan add all on top fLastCreated := Created; Item.TagString := Document.DocumentName(true); end; Item.Text := Document.GetStringValueDef('Message', '?'); DetailInfo := Document.GetStringValueDef('Sender', '?') + ' at ' + DateTimeToStr(Created); if Edited > 0 then DetailInfo := DetailInfo + ' (edited ' + DateTimeToStr(TFirebaseHelpers.ConvertToLocalDateTime(Edited)) + ')'; UID := Document.GetStringValueDef('UID', '?'); if UID = fUID then begin MsgType := myMsg; InvType := foreignMsg; ImgInd := fMyImgIndex; end else begin MsgType := foreignMsg; InvType := myMsg; ImgInd := ImageList.Source.IndexOf(UID); if ImgInd < 0 then begin DownloadProfileImgAndAddToImageList(UID, Item); ImgInd := 0; // set to default avatar end else dec(ImgInd); end; Item.Tag := ord(MsgType); Item.Data[GetMsgTextName(MsgType)] := Item.Text; Item.Data[GetDetailTextName(MsgType)] := DetailInfo; Item.Data[GetProfileImgName(MsgType)] := ImgInd; Item.Data[GetMsgTextName(InvType)] := ''; // After re-login with other Item.Data[GetDetailTextName(InvType)] := ''; // other user the former Item.Data[GetProfileImgName(InvType)] := -1; // MsgType must removed finally lsvChat.EndUpdate; end; lsvChat.ScrollTo(Item.Index); txtUpdate.Text := 'Last message written at ' + FormatDateTime('HH:NN:SS.ZZZ', Document.UpdateTime); end; procedure TfmxChatMain.OnConnectionStateChange(ListenerConnected: boolean); begin if ListenerConnected then begin txtUpdate.Text := 'Server reconnected at ' + TimeToStr(now); imgCloudOff.Visible := false; shpProfile.Visible := true; end else begin txtUpdate.Text := 'Server disconnected at ' + TimeToStr(fConfig.Database.GetTimeStampOfLastAccess); imgCloudOff.Visible := true; shpProfile.Visible := false; end; end; procedure TfmxChatMain.lsvChatItemClick(const Sender: TObject; const AItem: TListViewItem); begin if AItem.Tag = ord(myMsg) then begin edtMessage.Text := AItem.Text; EnterEditMode(AItem.TagString); end else ExitEditMode(not fEditDocID.IsEmpty); end; procedure TfmxChatMain.EnterEditMode(const DocPath: string); begin fEditDocID := copy(DocPath, DocPath.LastDelimiter('/') + 2); btnEditMessage.Visible := true; btnDeleteMessage.Visible := true; btnPushMessage.Visible := false; btnEditMessage.Enabled := true; btnDeleteMessage.Enabled := true; end; procedure TfmxChatMain.ExitEditMode(ClearEditBox: boolean); begin if ClearEditBox then edtMessage.Text := ''; fEditDocID := ''; btnEditMessage.Visible := false; btnDeleteMessage.Visible := false; btnPushMessage.Visible := true; btnPushMessage.Enabled := true; end; procedure TfmxChatMain.OnDeletedColDocument(const DeleteDocumentPath: string; TimeStamp: TDateTime); var Item: TListViewItem; begin Item := SearchItem(DeleteDocumentPath); if assigned(Item) then lsvChat.Items.Delete(Item.Index); lsvChat.Selected := nil; txtUpdate.Text := 'Last message deleted at ' + FormatDateTime('HH:NN:SS.ZZZ', TimeStamp); end; procedure TfmxChatMain.btnPushMessageClick(Sender: TObject); var Doc: IFirestoreDocument; begin Doc := TFirestoreDocument.Create( [cCollectionID, TFirebaseHelpers.CreateAutoID], fConfig.ProjectID); Doc.AddOrUpdateField(TJSONObject.SetString('Message', edtMessage.Text)); Doc.AddOrUpdateField(TJSONObject.SetString('Sender', fUserName)); Doc.AddOrUpdateField(TJSONObject.SetString('UID', fUID)); Doc.AddOrUpdateField(TJSONObject.SetTimeStamp('DateTime', now)); {$IFDEF DEBUG} TFirebaseHelpers.Log('Doc: ' + Doc.AsJSON.ToJSON); {$ENDIF} fConfig.Database.InsertOrUpdateDocument( [cCollectionID, Doc.DocumentName(false)], Doc, nil, OnDocWrite, OnDocWriteError); btnPushMessage.Enabled := false; end; procedure TfmxChatMain.btnEditMessageClick(Sender: TObject); var Doc: IFirestoreDocument; begin Assert(not fEditDocID.IsEmpty, 'No doc ID to patch'); Doc := TFirestoreDocument.Create([cCollectionID, fEditDocID], fConfig.ProjectID); Doc.AddOrUpdateField(TJSONObject.SetString('Message', edtMessage.Text)); Doc.AddOrUpdateField(TJSONObject.SetTimeStamp('Edited', now)); fConfig.Database.PatchDocument([cCollectionID, fEditDocID], Doc, ['Message', 'Edited'], OnDocWrite, OnDocWriteError); btnEditMessage.Enabled := false; btnDeleteMessage.Enabled := false; end; procedure TfmxChatMain.btnDeleteMessageClick(Sender: TObject); begin Assert(not fEditDocID.IsEmpty, 'No doc ID to patch'); fConfig.Database.Delete([cCollectionID, fEditDocID], nil, OnDocDelete, OnDocDeleteError); btnEditMessage.Enabled := false; btnDeleteMessage.Enabled := false; end; procedure TfmxChatMain.edtMessageKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if Key = vkReturn then if fEditDocID.IsEmpty then btnPushMessageClick(Sender) else btnEditMessageClick(Sender); end; procedure TfmxChatMain.OnDocWriteError(const RequestID, ErrMsg: string); begin if btnPushMessage.Visible then begin txtError.Text := 'Failure while write message: ' + ErrMsg; btnPushMessage.Enabled := true end else begin txtError.Text := 'Failure while update message: ' + ErrMsg; btnEditMessage.Enabled := true; btnDeleteMessage.Enabled := true; end; {$IFDEF DEBUG} TFirebaseHelpers.Log('DocWriteError ' + txtError.Text); {$ENDIF} end; procedure TfmxChatMain.OnDocWrite(const Info: string; Document: IFirestoreDocument); begin if btnPushMessage.Visible then txtUpdate.Text := 'Last message sent on ' + DateTimeToStr(Document.UpdateTime) else txtUpdate.Text := 'Last message update on ' + DateTimeToStr(Document.UpdateTime); {$IFDEF DEBUG} TFirebaseHelpers.Log('Written ID: ' + Document.DocumentName(false)); {$ENDIF} ExitEditMode(true); end; procedure TfmxChatMain.OnDocDelete(const RequestID: string; Response: IFirebaseResponse); begin txtUpdate.Text := 'Last message deleted on ' + DateTimeToStr(now); ExitEditMode(true); end; procedure TfmxChatMain.OnDocDeleteError(const RequestID, ErrMsg: string); begin txtError.Text := 'Failure while deleted message ' + ErrMsg; {$IFDEF DEBUG} TFirebaseHelpers.Log('DocDeleteError ' + txtError.Text); {$ENDIF} end; procedure TfmxChatMain.OnStopListening(Sender: TObject); begin txtUpdate.Text := 'Chat listener stopped'; {$IFDEF DEBUG} TFirebaseHelpers.Log('UNEXPECTED StopListener'); {$ENDIF} end; procedure TfmxChatMain.OnAuthRevoked(TokenRenewPassed: boolean); begin if TokenRenewPassed then txtUpdate.Text := 'Chat authorization renewed' else txtError.Text := 'Chat authorization renew failed'; end; procedure TfmxChatMain.OnListenerError(const RequestID, ErrMsg: string); begin txtError.Text := 'Error in listener: ' + ErrMsg; {$IFDEF DEBUG} TFirebaseHelpers.Log('ListenerError ' + txtError.Text); {$ENDIF} end; procedure TfmxChatMain.lsvChatUpdateObjects(const Sender: TObject; const AItem: TListViewItem); function CalcHeight(MsgText: TListItemText; const Text: string): Integer; const cMinItemHeight = 60; var Layout: TTextLayout; begin Layout := TTextLayoutManager.DefaultTextLayout.Create; try Layout.BeginUpdate; try Layout.Font.Assign(MsgText.Font); Layout.VerticalAlign := MsgText.TextVertAlign; Layout.HorizontalAlign := MsgText.TextAlign; Layout.WordWrap := MsgText.WordWrap; Layout.Trimming := MsgText.Trimming; Layout.MaxSize := TPointF.Create(MsgText.Width, TTextLayout.MaxLayoutSize.Y); Layout.Text := Text; finally Layout.EndUpdate; end; result := round(Layout.Height); Layout.Text := 'm'; result := max(cMinItemHeight, result + round(Layout.Height)); finally Layout.Free; end; end; const cOffsetMsg = 60 - 40; cOffsetDetail = 60 - 42; var MsgType: TMsgType; MsgTxt, DetTxt: TListItemText; AvailableWidth: single; begin MsgType := TMsgType(AItem.Tag); MsgTxt := TListItemText(AItem.View.FindDrawable(GetMsgTextName(MsgType))); DetTxt := TListItemText(AItem.View.FindDrawable(GetDetailTextName(MsgType))); AvailableWidth := lsvChat.Width - lsvChat.ItemSpaces.Left - lsvChat.ItemSpaces.Right - abs(MsgTxt.PlaceOffset.X); lsvChat.BeginUpdate; try MsgTxt.Width := AvailableWidth; AItem.Height := CalcHeight(MsgTxt, AItem.Text); MsgTxt.Width := AvailableWidth; MsgTxt.Height := AItem.Height; DetTxt.PlaceOffset.Y := AItem.Height - cOffsetDetail; finally lsvChat.EndUpdate; end; end; function TfmxChatMain.AddProfileImgToImageList(const UID: string; Img: TBitmap): integer; var SrcItem: TCustomSourceItem; DstItem: TCustomDestinationItem; BmpItem: TCustomBitmapItem; begin result := ImageList.Source.IndexOf(UID); if result < 0 then // Profile already stored in case ro re-login? begin SrcItem := ImageList.Source.Add; SrcItem.Name := UID; BmpItem := SrcItem.MultiResBitmap.Add; BmpItem.Scale := 1; BmpItem.Bitmap.Assign(Img); DstItem := ImageList.Destination.Add; with DstItem.Layers.Add do begin Name := UID; SourceRect.Rect := RectF(0, 0, BmpItem.Width, BmpItem.Height); end; with DstItem.Layers.Add do begin Name := 'ProfileMask'; SourceRect.Rect := RectF(0, 0, BmpItem.Width, BmpItem.Height); end; result := DstItem.Index; end else dec(result); end; procedure TfmxChatMain.DownloadProfileImgAndAddToImageList(const UID: string; Item: TListViewItem); var Profile: TPendingProfile; begin if fPendingProfiles.TryGetValue(UID, Profile) then Profile.Items.Add(Item) else begin Profile := TPendingProfile.Create(Item); fPendingProfiles.Add(UID, Profile); GetStorage; // Ensure that Bucket is sent to Config fConfig.Storage.GetAndDownload( TFraSelfRegistration.cDefaultStoragePathForProfileImg + '/' + UID, Profile.Stream, OnStorageDownload, OnGetStorageError); end; end; procedure TfmxChatMain.OnStorageDownload(Obj: IStorageObject); var Profile: TPendingProfile; Bmp: TBitmap; Ind: integer; Item: TListViewItem; UID: string; begin UID := Obj.ObjectName(false); Profile := fPendingProfiles.Items[UID]; Assert(assigned(Profile), 'Invalid profile'); Profile.Stream.Position := 0; Bmp := TBitmap.Create; try Bmp.LoadFromStream(Profile.Stream); Ind := AddProfileImgToImageList(UID, Bmp); finally Bmp.Free; end; lsvChat.BeginUpdate; try for Item in Profile.Items do Item.Data['Image2'] := Ind; finally lsvChat.EndUpdate; end; fPendingProfiles.Remove(UID); Profile.Free; end; procedure TfmxChatMain.OnGetStorageError(const ObjectName: TObjectName; const ErrMsg: string); begin // Do not remove the assoziated profile from fPendingProfiles to prevent retry end; procedure TfmxChatMain.FormVirtualKeyboard(Sender: TObject; KeyboardVisible: Boolean; const Bounds: TRect); begin {$IFDEF ANDROID} // Simple workaround for problem with covered controls from virtual keyboard layVirtualKeyboardSpace.Height := Bounds.Height; layVirtualKeyboardSpace.Visible := KeyboardVisible; if TabControl.ActiveTab = tabChat then lsvChat.ScrollTo(lsvChat.ItemCount - 1); {$ENDIF} end; {$REGION 'DEBUG Version Only'} procedure TfmxChatMain.tmrWatchdogTimer(Sender: TObject); begin txtWatchdog.Text := TimeToStr(fConfig.Database.GetTimeStampOfLastAccess) + ': ' + lsvChat.ItemCount.ToString + ' docs'; end; procedure TfmxChatMain.chbTestingChange(Sender: TObject); begin fStressTestCounter := 0; tmrTesting.Enabled := chbTesting.IsChecked; end; procedure TfmxChatMain.tmrTestingTimer(Sender: TObject); var c: integer; Item: TListViewItem; begin inc(fStressTestCounter); edtMessage.Text := 'Stress Test at ' + DateTimeToStr(now) + ': ' + fStressTestCounter.ToString + ' sent messages from ' + TFirebaseHelpers.GetConfigAndPlatform; btnPushMessageClick(Sender); if lsvChat.ItemCount > 10 then begin c := 0; while c < lsvChat.ItemCount do begin Item := lsvChat.Items[c]; if Item.Purpose = TListItemPurpose.None then if Item.Tag = ord(myMsg) then begin if Item.Text.StartsWith('Stress Test at ') then begin fEditDocID := copy(Item.TagString, Item.TagString.LastDelimiter('/') + 2); btnDeleteMessageClick(Sender); exit; end; end; inc(c); end; end; end; {$ENDREGION} { TfmxChatMain.TPendingProfile } constructor TfmxChatMain.TPendingProfile.Create(FirstItem: TListViewItem); begin Items := TList<TListViewItem>.Create; Items.Add(FirstItem); Stream := TMemoryStream.Create; end; destructor TfmxChatMain.TPendingProfile.Destroy; begin Stream.Free; Items.Free; inherited; end; end.
program Fakultaet (input,output); { berechnet die Fakultaet einer einzulesenden natuerlichen Zahl } type tNatZahl = 0..maxint; var i : tNatZahl; { Laufvariable } Zahl, { einzulesende Zahl } Ergebnis : integer; begin write ('Fuer welche Zahl soll die Fakultaet ', 'berechnet werden? '); readln (Zahl); if Zahl < 0 then writeln ('Fuer negative Zahlen ist die Fakultaet nicht definiert.') else begin Ergebnis := 1; { Initialisierung } for i := 1 to Zahl do Ergebnis := Ergebnis * i; writeln ('Die Fakultaet von ', Zahl, ' lautet ', Ergebnis, '.') end end. {Fakultaet}
unit MFichas.Model.Impressao.Caixa.Fechamento; interface uses System.SysUtils, System.Classes, MFichas.Model.Impressao.Interfaces, MFichas.Model.Conexao.Interfaces, MFichas.Model.Conexao.Factory, MFichas.Model.Impressao.Constantes, MFichas.Controller.Types, FireDAC.Comp.Client; const _2CIFROES = 4; _1CIFRAO = 2; type TModelImpressaoCaixaMetodosFechamento = class(TInterfacedObject, iModelImpressaoCaixaFechamento) private [weak] FParent : iModelImpressaoCaixa; FConexaoSQL : iModelConexaoSQL; FBluetooth : iModelConexaoBluetooth; FTitulo : String; FGUUIDCaixa : String; FAbertura : Currency; FSuprimento : Currency; FSangria : Currency; FTotalVendidoEmDinheiro : Currency; FTotalDevolvidoEmDinheiro : Currency; FTotalDinheiro : Currency; FCartaoCredito : Currency; FCartaoDebito : Currency; FTotalQtdeItensVendidos : Integer; FTotalQtdeItensDevolvidos : Integer; FValorTotalItensVendidos : Currency; FSQL : String; FWhere : String; FGroupBy : String; FStringListQtdeItensVendidos : TStrings; FStringListQtdeItensDevolvidos : TStrings; FStringListValorTotalItensVendidos : TStrings; FStringListValorTotalItensDevolvidos: TStrings; constructor Create(AParent: iModelImpressaoCaixa); procedure RecuperarValores; procedure Imprimir; procedure Abertura; procedure Suprimento; procedure Sangria; procedure TotalVendido; procedure TotalDevolvido; procedure SomarTotalDinheiro; procedure SomarTotalCartaoCredito; procedure SomarTotalCartaoDebito; procedure SomarQuantidadeDeItensVendidos; procedure SomarQuantidadeDeItensDevolvidos; procedure SomarValorTotalDeItensVendidos; procedure BuildSQL(AFDQuery: TFDQuery; ASQL: String); overload; procedure BuildSQL(AFDQuery: TFDQuery; ASQL: String; AFilter: String); overload; procedure RelacaoDeItensVendidos; procedure TotalGeralDeItensVendidos; procedure RelacaoDeItensDevolvidos; procedure TotalGeralDeItensDevolvidos; public destructor Destroy; override; class function New(AParent: iModelImpressaoCaixa): iModelImpressaoCaixaFechamento; function TituloDaImpressao(ATitulo: String): iModelImpressaoCaixaFechamento; function CodigoDoCaixa(AGUUID: String) : iModelImpressaoCaixaFechamento; function ExecutarImpressao : iModelImpressaoCaixaFechamento; function &End : iModelImpressaoCaixa; end; implementation uses System.Bluetooth; { TModelImpressaoCaixaMetodosFechamento } procedure TModelImpressaoCaixaMetodosFechamento.BuildSQL(AFDQuery: TFDQuery; ASQL: String); begin AFDQuery.Active := False; AFDQuery.Filtered := False; AFDQuery.SQL.Text := ''; AFDQuery.SQL.Text := ASQL; AFDQuery.Active := True; AFDQuery.Open; AFDQuery.First; end; procedure TModelImpressaoCaixaMetodosFechamento.Abertura; begin FSQL := ' SELECT * FROM CAIXA '; FWhere := ' GUUID = ' + QuotedStr(FGUUIDCaixa); BuildSQL(FConexaoSQL.Query, FSQL, FWhere); FAbertura := 0; FAbertura := FConexaoSQL.Query.FieldByName('VALORABERTURA').AsCurrency; end; procedure TModelImpressaoCaixaMetodosFechamento.BuildSQL(AFDQuery: TFDQuery; ASQL, AFilter: String); begin AFDQuery.Active := False; AFDQuery.SQL.Text := ''; AFDQuery.SQL.Text := ASQL; AFDQuery.Filtered := False; AFDQuery.Filter := AFilter; AFDQuery.Filtered := True; AFDQuery.Active := True; AFDQuery.Open; AFDQuery.First; end; function TModelImpressaoCaixaMetodosFechamento.CodigoDoCaixa( AGUUID: String): iModelImpressaoCaixaFechamento; begin Result := Self; FGUUIDCaixa := AGUUID; end; function TModelImpressaoCaixaMetodosFechamento.&End: iModelImpressaoCaixa; begin Result := FParent; end; function TModelImpressaoCaixaMetodosFechamento.ExecutarImpressao: iModelImpressaoCaixaFechamento; begin Result := Self; RecuperarValores; Imprimir; end; procedure TModelImpressaoCaixaMetodosFechamento.Imprimir; var LSocket: TBluetoothSocket; begin FBluetooth.ConectarDispositivo(LSocket); //CABEÇALHO LSocket.SendData(TEncoding.UTF8.GetBytes(FONTE_14PX)); LSocket.SendData(TEncoding.UTF8.GetBytes(ALINHAR_CENTRO)); LSocket.SendData(TEncoding.UTF8.GetBytes(FTitulo + QUEBRADELINHA)); LSocket.SendData(TEncoding.UTF8.GetBytes(FONTE_12PX)); LSocket.SendData(TEncoding.UTF8.GetBytes(ALINHAR_CENTRO)); LSocket.SendData(TEncoding.UTF8.GetBytes(DateTimeToStr(Now) + QUEBRADELINHA)); LSocket.SendData(TEncoding.UTF8.GetBytes(PULAR_1LINHA_ANTESDOPROXIMOTEXTO)); LSocket.SendData(TEncoding.UTF8.GetBytes(FONTE_12PX)); LSocket.SendData(TEncoding.UTF8.GetBytes('(+)ABERTURA: ' + FormatCurr('#,##0.00', FAbertura) + QUEBRADELINHA)); LSocket.SendData(TEncoding.UTF8.GetBytes('(+)SUPRIMENTO: ' + FormatCurr('#,##0.00', FSuprimento) + QUEBRADELINHA)); LSocket.SendData(TEncoding.UTF8.GetBytes('(-)SANGRIA: ' + FormatCurr('#,##0.00', FSangria) + QUEBRADELINHA)); LSocket.SendData(TEncoding.UTF8.GetBytes('(+)DINHEIRO: ' + FormatCurr('#,##0.00', FTotalVendidoEmDinheiro) + QUEBRADELINHA)); LSocket.SendData(TEncoding.UTF8.GetBytes(FONTE_14PX)); LSocket.SendData(TEncoding.UTF8.GetBytes('------------------------' + QUEBRADELINHA)); LSocket.SendData(TEncoding.UTF8.GetBytes(PULAR_1LINHA_ANTESDOPROXIMOTEXTO)); LSocket.SendData(TEncoding.UTF8.GetBytes(FONTE_12PX)); LSocket.SendData(TEncoding.UTF8.GetBytes('(=)TOTAL DINHEIRO: ' + FormatCurr('#,##0.00', FTotalDinheiro) + QUEBRADELINHA)); LSocket.SendData(TEncoding.UTF8.GetBytes('(=)CARTAO CREDITO: ' + FormatCurr('#,##0.00', FCartaoCredito) + QUEBRADELINHA)); LSocket.SendData(TEncoding.UTF8.GetBytes('(=)CARTAO DEBITO: ' + FormatCurr('#,##0.00', FCartaoDebito) + QUEBRADELINHA)); LSocket.SendData(TEncoding.UTF8.GetBytes(QUEBRADELINHA)); //RELAÇÃO DE ITENS VENDIDOS LSocket.SendData(TEncoding.UTF8.GetBytes(FONTE_14PX)); LSocket.SendData(TEncoding.UTF8.GetBytes(ALINHAR_CENTRO)); LSocket.SendData(TEncoding.UTF8.GetBytes('RELACAO DE ITENS VENDIDOS' + QUEBRADELINHA)); LSocket.SendData(TEncoding.UTF8.GetBytes(PULAR_1LINHA_ANTESDOPROXIMOTEXTO)); LSocket.SendData(TEncoding.UTF8.GetBytes(FONTE_12PX)); LSocket.SendData(TEncoding.UTF8.GetBytes(FStringListQtdeItensVendidos.Text + QUEBRADELINHA)); //TOTALGERAL DE ITENS VENDIDOS LSocket.SendData(TEncoding.UTF8.GetBytes(PULAR_1LINHA_ANTESDOPROXIMOTEXTO)); LSocket.SendData(TEncoding.UTF8.GetBytes(FONTE_14PX)); LSocket.SendData(TEncoding.UTF8.GetBytes('------------------------' + QUEBRADELINHA)); LSocket.SendData(TEncoding.UTF8.GetBytes(FONTE_12PX)); LSocket.SendData(TEncoding.UTF8.GetBytes(FStringListValorTotalItensVendidos.Text + QUEBRADELINHA)); LSocket.SendData(TEncoding.UTF8.GetBytes(FONTE_14PX)); LSocket.SendData(TEncoding.UTF8.GetBytes('------------------------' + QUEBRADELINHA)); //RELACAO DE ITENS DEVOLVIDOS LSocket.SendData(TEncoding.UTF8.GetBytes(PULAR_1LINHA_ANTESDOPROXIMOTEXTO)); LSocket.SendData(TEncoding.UTF8.GetBytes('RELACAO DE ITENS DEVOLVIDOS' + QUEBRADELINHA)); LSocket.SendData(TEncoding.UTF8.GetBytes(PULAR_1LINHA_ANTESDOPROXIMOTEXTO)); LSocket.SendData(TEncoding.UTF8.GetBytes(FONTE_12PX)); LSocket.SendData(TEncoding.UTF8.GetBytes(FStringListQtdeItensDevolvidos.Text + QUEBRADELINHA)); //TOTALGERAL DE ITENS DEVOLVIDOS LSocket.SendData(TEncoding.UTF8.GetBytes(PULAR_1LINHA_ANTESDOPROXIMOTEXTO)); LSocket.SendData(TEncoding.UTF8.GetBytes(FONTE_14PX)); LSocket.SendData(TEncoding.UTF8.GetBytes('------------------------' + QUEBRADELINHA)); LSocket.SendData(TEncoding.UTF8.GetBytes(FONTE_12PX)); LSocket.SendData(TEncoding.UTF8.GetBytes(FStringListValorTotalItensDevolvidos.Text + QUEBRADELINHA)); LSocket.SendData(TEncoding.UTF8.GetBytes(FONTE_14PX)); LSocket.SendData(TEncoding.UTF8.GetBytes('------------------------' + QUEBRADELINHA)); LSocket.SendData(TEncoding.UTF8.GetBytes(QUEBRADELINHA)); LSocket.SendData(TEncoding.UTF8.GetBytes(QUEBRADELINHA)); end; constructor TModelImpressaoCaixaMetodosFechamento.Create(AParent: iModelImpressaoCaixa); begin FParent := AParent; FConexaoSQL := TModelConexaoFactory.New.ConexaoSQL; FBluetooth := TModelConexaoFactory.New.ConexaoBluetooth; FStringListQtdeItensVendidos := TStringList.Create; FStringListQtdeItensDevolvidos := TStringList.Create; FStringListValorTotalItensVendidos := TStringList.Create; FStringListValorTotalItensDevolvidos := TStringList.Create; end; destructor TModelImpressaoCaixaMetodosFechamento.Destroy; begin {$IFDEF MSWINDOWS} FreeAndNil(FStringListQtdeItensVendidos); FreeAndNil(FStringListQtdeItensDevolvidos); FreeAndNil(FStringListValorTotalItensVendidos); FreeAndNil(FStringListValorTotalItensDevolvidos); {$ELSE} FStringListQtdeItensVendidos.Free; FStringListQtdeItensVendidos.DisposeOf; FStringListQtdeItensDevolvidos.Free; FStringListQtdeItensDevolvidos.DisposeOf; FStringListValorTotalItensVendidos.Free; FStringListValorTotalItensVendidos.DisposeOf; FStringListValorTotalItensDevolvidos.Free; FStringListValorTotalItensDevolvidos.DisposeOf; {$ENDIF} inherited; end; class function TModelImpressaoCaixaMetodosFechamento.New(AParent: iModelImpressaoCaixa): iModelImpressaoCaixaFechamento; begin Result := Self.Create(AParent); end; function TModelImpressaoCaixaMetodosFechamento.TituloDaImpressao( ATitulo: String): iModelImpressaoCaixaFechamento; begin Result := Self; FTitulo := ATitulo; end; procedure TModelImpressaoCaixaMetodosFechamento.TotalDevolvido; var I: Integer; begin FSQL := ' SELECT C.GUUID as GUUIDCAIXA, A.TIPO AS TIPOPAGAMENTO, A.VALOR AS VALORDOPAGAMENTO, A.STATUS AS STATUSPAGAMENTO FROM VENDAPAGAMENTOS A ' + ' INNER JOIN VENDA B ON B.GUUID = A.VENDA ' + ' INNER JOIN CAIXA C ON C.GUUID = B.CAIXA '; FWhere := ' GUUIDCAIXA = ' + QuotedStr(FGUUIDCaixa) + ' AND ' + ' TIPOPAGAMENTO = ' + Integer(tpDinheiro).ToString + ' AND ' + ' STATUSPAGAMENTO = ' + Integer(spEstornado).ToString; BuildSQL(FConexaoSQL.Query, FSQL, FWhere); FTotalDevolvidoEmDinheiro := 0; while not FConexaoSQL.Query.Eof do begin FTotalDevolvidoEmDinheiro := FTotalDevolvidoEmDinheiro + (FConexaoSQL.Query.FieldByName('VALORDOPAGAMENTO').AsCurrency); FConexaoSQL.Query.Next; end; end; procedure TModelImpressaoCaixaMetodosFechamento.TotalGeralDeItensDevolvidos; var I : Integer; LCalculoEspaco : Integer; LEspaco : String; LTotalLenght : Integer; LTotalQtdeItensDevolvidos : String; LValorTotalItensDevolvidos: String; LTotalGeral : String; begin LEspaco := ''; LTotalGeral := 'TOTAL GERAL:'; LTotalQtdeItensDevolvidos := FormatCurr('###', FTotalQtdeItensDevolvidos); LValorTotalItensDevolvidos := FormatCurr('#,##0.00', FTotalDevolvidoEmDinheiro); LTotalLenght := ( LTotalGeral.Length + LTotalQtdeItensDevolvidos.Length + LValorTotalItensDevolvidos.Length + _1CIFRAO ); LCalculoEspaco := Trunc((32 - LTotalLenght)/2); for I := 0 to Pred(LCalculoEspaco) do LEspaco := LEspaco + ' '; FStringListValorTotalItensDevolvidos.Add( LTotalGeral + LEspaco + LTotalQtdeItensDevolvidos + LEspaco + 'R$' + LValorTotalItensDevolvidos ); end; procedure TModelImpressaoCaixaMetodosFechamento.TotalGeralDeItensVendidos; var I : Integer; LCalculoEspaco : Integer; LEspaco : String; LTotalLenght : Integer; LTotalQtdeItensVendidos : String; LValorTotalItensVendidos: String; LTotalGeral : String; begin LEspaco := ''; LTotalGeral := 'TOTAL GERAL:'; LTotalQtdeItensVendidos := FormatCurr('###', FTotalQtdeItensVendidos); LValorTotalItensVendidos := FormatCurr('#,##0.00', FValorTotalItensVendidos); LTotalLenght := ( LTotalGeral.Length + LTotalQtdeItensVendidos.Length + LValorTotalItensVendidos.Length + _1CIFRAO ); LCalculoEspaco := Trunc((32 - LTotalLenght)/2); for I := 0 to Pred(LCalculoEspaco) do LEspaco := LEspaco + ' '; FStringListValorTotalItensVendidos.Add( LTotalGeral + LEspaco + LTotalQtdeItensVendidos + LEspaco + 'R$' + LValorTotalItensVendidos ); end; procedure TModelImpressaoCaixaMetodosFechamento.TotalVendido; var I: Integer; begin FSQL := ' SELECT C.GUUID as GUUIDCAIXA, A.TIPO AS TIPOPAGAMENTO, A.VALOR AS VALORDOPAGAMENTO, A.STATUS AS STATUSPAGAMENTO FROM VENDAPAGAMENTOS A ' + ' INNER JOIN VENDA B ON B.GUUID = A.VENDA ' + ' INNER JOIN CAIXA C ON C.GUUID = B.CAIXA '; FWhere := ' GUUIDCAIXA = ' + QuotedStr(FGUUIDCaixa) + ' AND ' + ' TIPOPAGAMENTO = ' + Integer(tpDinheiro).ToString + ' AND ' + ' STATUSPAGAMENTO = ' + Integer(spProcessado).ToString; BuildSQL(FConexaoSQL.Query, FSQL, FWhere); FTotalVendidoEmDinheiro := 0; while not FConexaoSQL.Query.Eof do begin FTotalVendidoEmDinheiro := FTotalVendidoEmDinheiro + (FConexaoSQL.Query.FieldByName('VALORDOPAGAMENTO').AsCurrency); FConexaoSQL.Query.Next; end; end; procedure TModelImpressaoCaixaMetodosFechamento.RecuperarValores; begin Abertura; Suprimento; Sangria; TotalVendido; TotalDevolvido; SomarTotalDinheiro; SomarTotalCartaoCredito; SomarTotalCartaoDebito; RelacaoDeItensVendidos; SomarValorTotalDeItensVendidos; TotalGeralDeItensVendidos; RelacaoDeItensDevolvidos; TotalGeralDeItensDevolvidos; end; procedure TModelImpressaoCaixaMetodosFechamento.RelacaoDeItensDevolvidos; var I : Integer; LCountEspacos : Integer; LDescricaoProduto: String; LValorProduto : Currency; LQuantidade : Currency; LTotal : Currency; LCalculoEspaco : Integer; LEspaco : String; LTotalLenght : Integer; begin FSQL := ' SELECT D.DESCRICAO as DESCRICAOPRODUTO, COUNT(DISTINCT C.PRODUTO), SUM(C.QUANTIDADE) as QUANTIDADEPRODUTO, C.PRECO as PRECOPRODUTO, C.TIPO as TIPOVENDAITEM, A.GUUID as GUUIDCAIXA FROM CAIXA A ' + ' INNER JOIN VENDA B ON B.CAIXA = A.GUUID ' + ' INNER JOIN VENDAITENS C ON C.VENDA = B.GUUID ' + ' INNER JOIN PRODUTO D ON D.GUUID = C.PRODUTO '; FWhere := ' WHERE ' + ' A.GUUID = ' + QuotedStr(FGUUIDCaixa) + ' AND ' + ' C.TIPO = ' + Integer(tvDevolucao).ToString; FGroupBy := ' GROUP BY C.PRODUTO '; BuildSQL(FConexaoSQL.Query, FSQL + FWhere + FGroupBy); FTotalQtdeItensDevolvidos := 0; FConexaoSQL.Query.First; while not FConexaoSQL.Query.Eof do begin SomarQuantidadeDeItensDevolvidos; LEspaco := ''; LDescricaoProduto := FConexaoSQL.Query.FieldByName('DESCRICAOPRODUTO').AsString; LValorProduto := FConexaoSQL.Query.FieldByName('PRECOPRODUTO').AsCurrency; LQuantidade := FConexaoSQL.Query.FieldByName('QUANTIDADEPRODUTO').AsCurrency; LTotal := (LValorProduto * LQuantidade); LTotalLenght := ( FormatCurr('', LValorProduto).Length + FormatCurr('', LQuantidade).Length + FormatCurr('', LTotal).Length + _2CIFROES ); LCalculoEspaco := Trunc((32 - LTotalLenght)/2); for LCountEspacos := 0 to Pred(LCalculoEspaco) do LEspaco := LEspaco + ' '; FStringListQtdeItensDevolvidos.Add( LDescricaoProduto + QUEBRADELINHA + FormatCurr('', LQuantidade) + LEspaco + 'R$' + FormatCurr('', LValorProduto) + LEspaco + 'R$' + FormatCurr('', LTotal) ); FConexaoSQL.Query.Next; end; end; procedure TModelImpressaoCaixaMetodosFechamento.RelacaoDeItensVendidos; var I : Integer; LCountEspacos : Integer; LDescricaoProduto: String; LValorProduto : Currency; LQuantidade : Currency; LTotal : Currency; LCalculoEspaco : Integer; LEspaco : String; LTotalLenght : Integer; begin FSQL := ' SELECT D.DESCRICAO as DESCRICAOPRODUTO, COUNT(DISTINCT C.PRODUTO), SUM(C.QUANTIDADE) as QUANTIDADEPRODUTO, C.PRECO as PRECOPRODUTO, C.TIPO as TIPOVENDAITEM, A.GUUID as GUUIDCAIXA FROM CAIXA A ' + ' INNER JOIN VENDA B ON B.CAIXA = A.GUUID ' + ' INNER JOIN VENDAITENS C ON C.VENDA = B.GUUID ' + ' INNER JOIN PRODUTO D ON D.GUUID = C.PRODUTO '; FWhere := ' WHERE ' + ' A.GUUID = ' + QuotedStr(FGUUIDCaixa) + ' AND ' + ' C.TIPO = ' + Integer(tvVenda).ToString; FGroupBy := ' GROUP BY C.PRODUTO '; BuildSQL(FConexaoSQL.Query, FSQL + FWhere + FGroupBy); FTotalQtdeItensVendidos := 0; FConexaoSQL.Query.First; while not FConexaoSQL.Query.Eof do begin SomarQuantidadeDeItensVendidos; LEspaco := ''; LDescricaoProduto := FConexaoSQL.Query.FieldByName('DESCRICAOPRODUTO').AsString; LValorProduto := FConexaoSQL.Query.FieldByName('PRECOPRODUTO').AsCurrency; LQuantidade := FConexaoSQL.Query.FieldByName('QUANTIDADEPRODUTO').AsCurrency; LTotal := (LValorProduto * LQuantidade); LTotalLenght := ( FormatCurr('###', LValorProduto).Length + FormatCurr('#,##0.00', LQuantidade).Length + FormatCurr('#,##0.00', LTotal).Length + _2CIFROES ); LCalculoEspaco := Trunc((32 - LTotalLenght)/2); for LCountEspacos := 0 to Pred(LCalculoEspaco) do LEspaco := LEspaco + ' '; FStringListQtdeItensVendidos.Add( LDescricaoProduto + QUEBRADELINHA + FormatCurr('###', LQuantidade) + LEspaco + 'R$' + FormatCurr('#,##0.00', LValorProduto) + LEspaco + 'R$' + FormatCurr('#,##0.00', LTotal) ); FConexaoSQL.Query.Next; end; end; procedure TModelImpressaoCaixaMetodosFechamento.Sangria; var I: Integer; begin FSQL := ' SELECT * FROM CAIXAOPERACOES '; FWhere := ' CAIXA = ' + QuotedStr(FGUUIDCaixa) + ' AND ' + ' TIPO = ' + Integer(ocSangria).ToString; BuildSQL(FConexaoSQL.Query, FSQL, FWhere); FSangria := 0; while not FConexaoSQL.Query.Eof do begin FSangria := FSangria + FConexaoSQL.Query.FieldByName('VALOR').AsCurrency; FConexaoSQL.Query.Next; end; end; procedure TModelImpressaoCaixaMetodosFechamento.SomarQuantidadeDeItensDevolvidos; begin FTotalQtdeItensDevolvidos := FTotalQtdeItensDevolvidos + Trunc(FConexaoSQL.Query.FieldByName('QUANTIDADEPRODUTO').AsCurrency); end; procedure TModelImpressaoCaixaMetodosFechamento.SomarQuantidadeDeItensVendidos; begin FTotalQtdeItensVendidos := FTotalQtdeItensVendidos + Trunc(FConexaoSQL.Query.FieldByName('QUANTIDADEPRODUTO').AsCurrency); end; procedure TModelImpressaoCaixaMetodosFechamento.SomarTotalCartaoCredito; var I: Integer; begin FSQL := ' SELECT C.GUUID as GUUIDCAIXA, A.TIPO AS TIPOPAGAMENTO, A.VALOR AS VALORDOPAGAMENTO, A.STATUS AS STATUSPAGAMENTO FROM VENDAPAGAMENTOS A ' + ' INNER JOIN VENDA B ON B.GUUID = A.VENDA ' + ' INNER JOIN CAIXA C ON C.GUUID = B.CAIXA '; FWhere := ' GUUIDCAIXA = ' + QuotedStr(FGUUIDCaixa) + ' AND ' + ' TIPOPAGAMENTO = ' + Integer(tpCartaoCredito).ToString + ' AND ' + ' STATUSPAGAMENTO = ' + Integer(spProcessado).ToString; BuildSQL(FConexaoSQL.Query, FSQL, FWhere); FCartaoCredito := 0; while not FConexaoSQL.Query.Eof do begin FCartaoCredito := FCartaoCredito + (FConexaoSQL.Query.FieldByName('VALORDOPAGAMENTO').AsCurrency); FConexaoSQL.Query.Next; end; end; procedure TModelImpressaoCaixaMetodosFechamento.SomarTotalCartaoDebito; var I: Integer; begin FSQL := ' SELECT C.GUUID as GUUIDCAIXA, A.TIPO AS TIPOPAGAMENTO, A.VALOR AS VALORDOPAGAMENTO, A.STATUS AS STATUSPAGAMENTO FROM VENDAPAGAMENTOS A ' + ' INNER JOIN VENDA B ON B.GUUID = A.VENDA ' + ' INNER JOIN CAIXA C ON C.GUUID = B.CAIXA '; FWhere := ' GUUIDCAIXA = ' + QuotedStr(FGUUIDCaixa) + ' AND ' + ' TIPOPAGAMENTO = ' + Integer(tpCartaoDebito).ToString + ' AND ' + ' STATUSPAGAMENTO = ' + Integer(spProcessado).ToString; BuildSQL(FConexaoSQL.Query, FSQL, FWhere); FCartaoDebito := 0; while not FConexaoSQL.Query.Eof do begin FCartaoDebito := FCartaoDebito + (FConexaoSQL.Query.FieldByName('VALORDOPAGAMENTO').AsCurrency); FConexaoSQL.Query.Next; end; end; procedure TModelImpressaoCaixaMetodosFechamento.SomarTotalDinheiro; begin FTotalDinheiro := ((FTotalVendidoEmDinheiro + FSuprimento + FAbertura) - FSangria - FTotalDevolvidoEmDinheiro); end; procedure TModelImpressaoCaixaMetodosFechamento.SomarValorTotalDeItensVendidos; begin FValorTotalItensVendidos := 0; FValorTotalItensVendidos := FTotalVendidoEmDinheiro + FCartaoCredito + FCartaoDebito; end; procedure TModelImpressaoCaixaMetodosFechamento.Suprimento; var I: Integer; begin FSQL := ' SELECT * FROM CAIXAOPERACOES '; FWhere := ' CAIXA = ' + QuotedStr(FGUUIDCaixa) + ' AND ' + ' TIPO = ' + Integer(ocSuprimento).ToString; BuildSQL(FConexaoSQL.Query, FSQL, FWhere); FSuprimento := 0; while not FConexaoSQL.Query.Eof do begin FSuprimento := FSuprimento + FConexaoSQL.Query.FieldByName('VALOR').AsCurrency; FConexaoSQL.Query.Next; end; end; end.
unit View.CadastroPadrao; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinsDefaultPainters, cxClasses, dxLayoutContainer, dxLayoutControl, cxContainer, cxEdit, dxLayoutcxEditAdapters, cxLabel, cxTextEdit, cxMaskEdit, cxDropDownEdit, Vcl.ComCtrls, dxCore, cxDateUtils, cxCalendar, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxDBEdit, cxCheckBox, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, cxNavigator, cxDBNavigator, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, dxDateRanges, cxDataControllerConditionalFormattingRulesManagerDialog, cxDBData, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, System.Actions, Vcl.ActnList, dxBar, cxMemo; type Tview_CadastroPadrao = class(TForm) layoutControlPadraoGroup_Root: TdxLayoutGroup; layoutControlPadrao: TdxLayoutControl; maskEditID: TcxMaskEdit; layoutItemMaskID: TdxLayoutItem; comboBoxTipoPessoa: TcxComboBox; layoutItemComboBoxTipoPessoa: TdxLayoutItem; dxLayoutAutoCreatedGroup1: TdxLayoutAutoCreatedGroup; maskEditCPCNPJ: TcxMaskEdit; layoutItemCPFCNPJ: TdxLayoutItem; textEditNome: TcxTextEdit; layoutItemTextEditNome: TdxLayoutItem; layoutControlDadosGroup_Root: TdxLayoutGroup; layoutControlDados: TdxLayoutControl; layoutItemDadosGeral: TdxLayoutItem; layoutGroupPessoaFisica: TdxLayoutGroup; textEditRG: TcxTextEdit; layoutItemRG: TdxLayoutItem; textEditExpedidor: TcxTextEdit; layoutItemExpedidorRG: TdxLayoutItem; dateEditDataRG: TcxDateEdit; layoutItemDataRG: TdxLayoutItem; lookupComboBoxUFRG: TcxLookupComboBox; layoutItemUFRG: TdxLayoutItem; dateEditNascimento: TcxDateEdit; layoutItemNascimento: TdxLayoutItem; layoutGroupFisica1: TdxLayoutGroup; layoutGroupFisica2: TdxLayoutGroup; textEditNomePai: TcxTextEdit; layoutItemNomePai: TdxLayoutItem; textEditNomeMae: TcxTextEdit; layoutItemNomeMae: TdxLayoutItem; layoutGroupFisica3: TdxLayoutGroup; textEditNaturalidade: TcxTextEdit; layoutItemNaturalidade: TdxLayoutItem; lookupComboBoxNaturalidade: TcxLookupComboBox; layoutItemUFNaturalidade: TdxLayoutItem; layoutGroupFisica4: TdxLayoutGroup; textEditSegurancaCNH: TcxTextEdit; layoutItemCodigoSeguranca: TdxLayoutItem; textEditNumeroCNH: TcxTextEdit; layoutItemNumeroCNH: TdxLayoutItem; textEditRegistroCNH: TcxTextEdit; layoutItemRegistroCNH: TdxLayoutItem; textEditCategoriaCNH: TcxTextEdit; layoutItemCategoriaCNH: TdxLayoutItem; layoutGroupFisica5: TdxLayoutGroup; dateEditEmissaoCNH: TcxDateEdit; layoutItemDataEmissao: TdxLayoutItem; dateEditValidadeCNH: TcxDateEdit; layoutItemValidadeCNH: TdxLayoutItem; dateEditPrimeiraCNH: TcxDateEdit; layoutItemPrimeiraCNH: TdxLayoutItem; lookupComboBoxUFCNH: TcxLookupComboBox; layoutItemUFCNH: TdxLayoutItem; layoutGroupPessoaJuridica: TdxLayoutGroup; layoutGroupJuridica1: TdxLayoutGroup; textEditNomeFantasia: TcxTextEdit; layoutItemNomeFantasia: TdxLayoutItem; layoutGroupJuridica2: TdxLayoutGroup; textEditIE: TcxTextEdit; layoutItemIE: TdxLayoutItem; textEditIEST: TcxTextEdit; layoutItemIEST: TdxLayoutItem; textEditIM: TcxTextEdit; layoutItemIM: TdxLayoutItem; textEditCNAE: TcxTextEdit; layoutItemCNAE: TdxLayoutItem; comboBoxCRT: TcxComboBox; layoutItemCRT: TdxLayoutItem; layoutControlComplementoGroup_Root: TdxLayoutGroup; layoutControlComplemento: TdxLayoutControl; layoutItemComplemento: TdxLayoutItem; layoutGroupEnderecos: TdxLayoutGroup; layoutGroupContatos: TdxLayoutGroup; layoutGroupDadosBancarios: TdxLayoutGroup; memTableEnderecos: TFDMemTable; memTableEnderecosid_cadastro: TIntegerField; memTableEnderecosdes_tipo_endereco: TStringField; memTableEnderecosnum_cep: TStringField; memTableEnderecosdes_logradouro: TStringField; memTableEnderecosnum_logradouro: TStringField; memTableEnderecosdes_complemento: TStringField; memTableEnderecosnom_bairro: TStringField; memTableEnderecosnom_cidade: TStringField; memTableEnderecosuf_estado: TStringField; dsEnderecos: TDataSource; layoutGroupEndereco1: TdxLayoutGroup; dbComboBoxTipoEndereco: TcxDBComboBox; layoutItemTipoEndereco: TdxLayoutItem; LayoutGroupEndereco2: TdxLayoutGroup; dbMaskEditCEP: TcxDBMaskEdit; layoutItemCEP: TdxLayoutItem; dbTextEditEndereco: TcxDBTextEdit; layoutItemEndereco: TdxLayoutItem; dbTextEditNumero: TcxDBTextEdit; layoutItemNumero: TdxLayoutItem; dbTextEditComplemento: TcxDBTextEdit; layoutItemComplementoEndewreco: TdxLayoutItem; layoutGroupEndereco3: TdxLayoutGroup; dbTextEditBairro: TcxDBTextEdit; layoutItemBairro: TdxLayoutItem; dbTextEditCidade: TcxDBTextEdit; layoutItemCidade: TdxLayoutItem; dbLookupComboBoxUFEndereco: TcxDBLookupComboBox; layoutItemUFEndereco: TdxLayoutItem; memTableEnderecosseq_endereco: TIntegerField; memTableEnderecosdom_correspondencia: TIntegerField; memTableEnderecosdes_referencia: TStringField; CheckBoxCorrespondencia: TcxCheckBox; layoutItemCorrespondencia: TdxLayoutItem; layoutGroupEndereco4: TdxLayoutGroup; dbTextEditReferencia: TcxDBTextEdit; layoutItemReferencia: TdxLayoutItem; dbNavigatorEnderecos: TcxDBNavigator; layoutItemNavegadorEndereco: TdxLayoutItem; gridContatosDBTableView1: TcxGridDBTableView; gridContatosLevel1: TcxGridLevel; gridContatos: TcxGrid; layoutItemContatos: TdxLayoutItem; memTableContatos: TFDMemTable; memTableContatosid: TIntegerField; memTableContatosseq_contato: TIntegerField; memTableContatosdes_contato: TStringField; memTableContatosnum_telefone: TStringField; memTableContatosdes_email: TStringField; dsContatos: TDataSource; gridContatosDBTableView1id: TcxGridDBColumn; gridContatosDBTableView1seq_contato: TcxGridDBColumn; gridContatosDBTableView1des_contato: TcxGridDBColumn; gridContatosDBTableView1num_telefone: TcxGridDBColumn; gridContatosDBTableView1des_email: TcxGridDBColumn; LayoutGroupDadosBancarios1: TdxLayoutGroup; comboBoxFormaPagamento: TcxComboBox; layoutItemFormaPagamento: TdxLayoutItem; comboBoxTipoConta: TcxComboBox; layoutItemTipoConta: TdxLayoutItem; layoutGroupDadosBancarios2: TdxLayoutGroup; lookupComboBoxBanco: TcxLookupComboBox; layoutItemBanco: TdxLayoutItem; textEditAgencia: TcxTextEdit; layoutItemAgencia: TdxLayoutItem; textEditConta: TcxTextEdit; layoutItemConta: TdxLayoutItem; layoutGroupDadosBancarios3: TdxLayoutGroup; textEditFavorecido: TcxTextEdit; layoutItemFavorecido: TdxLayoutItem; maskEditCPFCNPJFavorecido: TcxMaskEdit; layoutItemCPFCNPJFavorecido: TdxLayoutItem; LayoutGrouPDadosBancarios4: TdxLayoutGroup; textEditChavePIX: TcxTextEdit; layoutItemChavePIX: TdxLayoutItem; actionListCadastro: TActionList; actionIncluir: TAction; actionEditar: TAction; actionLocalizar: TAction; actionCancelar: TAction; actionGravar: TAction; actionDocumentosVencidos: TAction; actionVencimentoGR: TAction; actionFechar: TAction; layoutGroupMaster: TdxLayoutGroup; layoutGroupCadastro: TdxLayoutGroup; actionFichaDIRECT: TAction; actionSolicitarGR: TAction; actionContrato: TAction; barManagerCadastro: TdxBarManager; barManagerCadastroBar1: TdxBar; dxBarButton1: TdxBarButton; dxBarButton2: TdxBarButton; dxBarButton3: TdxBarButton; dxBarButton4: TdxBarButton; dxBarButton5: TdxBarButton; dxBarSubItem1: TdxBarSubItem; dxBarSubItem2: TdxBarSubItem; dxBarButton6: TdxBarButton; dxBarButton7: TdxBarButton; dxBarButton8: TdxBarButton; dxBarButton9: TdxBarButton; dxBarButton10: TdxBarButton; dxBarButton11: TdxBarButton; dxBarButton12: TdxBarButton; dxBarButton13: TdxBarButton; layoutGroupComplementos: TdxLayoutGroup; layoutGroupGR: TdxLayoutGroup; checkBoxStatusGR: TcxCheckBox; layoutItemStatusGR: TdxLayoutItem; textEditEmpresaGR: TcxTextEdit; layoutItemEmpresaGR: TdxLayoutItem; dateEditValidadeGR: TcxDateEdit; layoutItemValidadeGR: TdxLayoutItem; textEditNumeroConsultaGR: TcxTextEdit; layoutItemNumeroConsultaGR: TdxLayoutItem; layoutGroupMEI: TdxLayoutGroup; textEditCodigoIMEI: TcxTextEdit; layoutItemCodigoIMEI: TdxLayoutItem; maskEditCNPJIMEI: TcxMaskEdit; layoutItemCNPJIMEI: TdxLayoutItem; textEditNomeMEI: TcxTextEdit; layoutItemNomeMEI: TdxLayoutItem; textEditNomeFantasiaMEI: TcxTextEdit; layoutItemFantasiaMEI: TdxLayoutItem; layoutGroupObs: TdxLayoutGroup; memoObservacoes: TcxMemo; layoutItemObservacoes: TdxLayoutItem; procedure comboBoxTipoPessoaPropertiesChange(Sender: TObject); private { Private declarations } public { Public declarations } end; var view_CadastroPadrao: Tview_CadastroPadrao; implementation {$R *.dfm} procedure Tview_CadastroPadrao.comboBoxTipoPessoaPropertiesChange(Sender: TObject); begin if comboBoxTipoPessoa.ItemIndex = 1 then begin layoutGroupPessoaFisica.MakeVisible; end else if comboBoxTipoPessoa.ItemIndex = 2 then begin layoutGroupPessoaJuridica.MakeVisible; end else begin layoutGroupPessoaFisica.MakeVisible; end; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpX9Curve; {$I ..\..\Include\CryptoLib.inc} interface uses ClpCryptoLibTypes, ClpBigInteger, ClpIDerSequence, ClpIDerInteger, ClpIDerObjectIdentifier, ClpDerBitString, ClpIDerBitString, ClpDerSequence, ClpX9FieldElement, ClpIX9FieldID, ClpIX9FieldElement, ClpIAsn1OctetString, ClpECAlgorithms, ClpAsn1OctetString, ClpAsn1EncodableVector, ClpIAsn1EncodableVector, ClpX9ObjectIdentifiers, ClpIProxiedInterface, ClpIAsn1Sequence, ClpIX9Curve, ClpECCurve, ClpIECInterface, ClpAsn1Encodable; resourcestring SCurveNil = 'Curve'; SNotImplementedECCurve = 'This Type of ECCurve is not Implemented'; SFieldIDNil = 'FieldID'; SSeqNil = 'Seq'; type /// <summary> /// ASN.1 def for Elliptic-Curve Curve structure. See X9.62, for further /// details. /// </summary> TX9Curve = class(TAsn1Encodable, IX9Curve) strict private var FSeed: TCryptoLibByteArray; FfieldIdentifier: IDerObjectIdentifier; Fcurve: IECCurve; function GetCurve: IECCurve; inline; public constructor Create(const curve: IECCurve); overload; constructor Create(const curve: IECCurve; const seed: TCryptoLibByteArray); overload; constructor Create(const fieldID: IX9FieldID; const seq: IAsn1Sequence); overload; deprecated 'Use constructor including order/cofactor'; constructor Create(const fieldID: IX9FieldID; const order, cofactor: TBigInteger; const seq: IAsn1Sequence); overload; function GetSeed(): TCryptoLibByteArray; inline; property curve: IECCurve read GetCurve; /// <summary> /// <para> /// Produce an object suitable for an Asn1OutputStream. <br /> /// &lt;pre&gt; /// </para> /// <para> /// Curve ::= Sequence { a FieldElement, b FieldElement, seed BIT /// STRING OPTIONAL } /// </para> /// <para> /// <br />&lt;/pre&gt; /// </para> /// </summary> function ToAsn1Object(): IAsn1Object; override; end; implementation { TX9Curve } constructor TX9Curve.Create(const curve: IECCurve; const seed: TCryptoLibByteArray); begin Inherited Create(); if (curve = Nil) then begin raise EArgumentNilCryptoLibException.CreateRes(@SCurveNil); end; Fcurve := curve; FSeed := System.Copy(seed); if (TECAlgorithms.IsFpCurve(curve)) then begin FfieldIdentifier := TX9ObjectIdentifiers.PrimeField; end else if (TECAlgorithms.IsF2mCurve(curve)) then begin FfieldIdentifier := TX9ObjectIdentifiers.CharacteristicTwoField; end else begin raise EArgumentCryptoLibException.CreateRes(@SNotImplementedECCurve); end; end; constructor TX9Curve.Create(const curve: IECCurve); begin Create(curve, Nil); end; constructor TX9Curve.Create(const fieldID: IX9FieldID; const seq: IAsn1Sequence); begin Create(fieldID, Default (TBigInteger), Default (TBigInteger), seq); end; constructor TX9Curve.Create(const fieldID: IX9FieldID; const order, cofactor: TBigInteger; const seq: IAsn1Sequence); var p, A, B: TBigInteger; parameters: IDerSequence; representation: IDerObjectIdentifier; pentanomial: IDerSequence; m, k1, k2, k3: Int32; begin Inherited Create(); if (fieldID = Nil) then begin raise EArgumentNilCryptoLibException.CreateRes(@SFieldIDNil); end; if (seq = Nil) then begin raise EArgumentNilCryptoLibException.CreateRes(@SSeqNil); end; FfieldIdentifier := fieldID.Identifier; if (FfieldIdentifier.Equals(TX9ObjectIdentifiers.PrimeField)) then begin p := (fieldID.parameters as IDerInteger).Value; A := TBigInteger.Create(1, TAsn1OctetString.GetInstance(seq[0] as TAsn1Encodable).GetOctets()); B := TBigInteger.Create(1, TAsn1OctetString.GetInstance(seq[1] as TAsn1Encodable).GetOctets()); Fcurve := TFpCurve.Create(p, A, B, order, cofactor); end else if (FfieldIdentifier.Equals(TX9ObjectIdentifiers.CharacteristicTwoField)) then begin // Characteristic two field parameters := fieldID.parameters as IDerSequence; m := (parameters[0] as IDerInteger).Value.Int32Value; representation := parameters[1] as IDerObjectIdentifier; k2 := 0; k3 := 0; if (representation.Equals(TX9ObjectIdentifiers.TPBasis)) then begin // Trinomial basis representation k1 := (parameters[2] as IDerInteger).Value.Int32Value; end else begin // Pentanomial basis representation pentanomial := parameters[2] as IDerSequence; k1 := (pentanomial[0] as IDerInteger).Value.Int32Value; k2 := (pentanomial[1] as IDerInteger).Value.Int32Value; k3 := (pentanomial[2] as IDerInteger).Value.Int32Value; end; A := TBigInteger.Create(1, TAsn1OctetString.GetInstance(seq[0] as TAsn1Encodable).GetOctets()); B := TBigInteger.Create(1, TAsn1OctetString.GetInstance(seq[1] as TAsn1Encodable).GetOctets()); Fcurve := TF2mCurve.Create(m, k1, k2, k3, A, B, order, cofactor); end else begin raise EArgumentCryptoLibException.CreateRes(@SNotImplementedECCurve); end; if (seq.Count = 3) then begin FSeed := (seq[2] as IDerBitString).GetBytes(); end; end; function TX9Curve.GetCurve: IECCurve; begin result := Fcurve; end; function TX9Curve.GetSeed: TCryptoLibByteArray; begin result := System.Copy(FSeed); end; function TX9Curve.ToAsn1Object: IAsn1Object; var v: IAsn1EncodableVector; begin v := TAsn1EncodableVector.Create(); if (FfieldIdentifier.Equals(TX9ObjectIdentifiers.PrimeField) or FfieldIdentifier.Equals(TX9ObjectIdentifiers.CharacteristicTwoField)) then begin v.Add([(TX9FieldElement.Create(Fcurve.A) as IX9FieldElement) .ToAsn1Object()]); v.Add([(TX9FieldElement.Create(Fcurve.B) as IX9FieldElement) .ToAsn1Object()]); end; if (FSeed <> Nil) then begin v.Add([TDerBitString.Create(FSeed) as IDerBitString]); end; result := TDerSequence.Create(v); end; end.
unit GX_NTAEditServiceNotifier; {$I GX_CondDefine.inc} interface uses Classes, ToolsAPI, DockForm; {$IFDEF GX_VER160_up} type ///<summary> /// This is a dummy implementation of INTAEditServicesNotifier that does nothing. /// Descendants override some methods to get the notifications they are interested in. </summary> TGxNTAEditServiceNotifier = class(TNotifierObject) protected // INTAEditServicesNotifier procedure WindowShow(const EditWindow: INTAEditWindow; Show, LoadedFromDesktop: Boolean); virtual; procedure WindowNotification(const EditWindow: INTAEditWindow; Operation: TOperation); virtual; procedure WindowActivated(const EditWindow: INTAEditWindow); virtual; procedure WindowCommand(const EditWindow: INTAEditWindow; Command, Param: Integer; var Handled: Boolean); virtual; procedure EditorViewActivated(const EditWindow: INTAEditWindow; const EditView: IOTAEditView); virtual; procedure EditorViewModified(const EditWindow: INTAEditWindow; const EditView: IOTAEditView); virtual; procedure DockFormVisibleChanged(const EditWindow: INTAEditWindow; DockForm: TDockableForm); virtual; procedure DockFormUpdated(const EditWindow: INTAEditWindow; DockForm: TDockableForm); virtual; procedure DockFormRefresh(const EditWindow: INTAEditWindow; DockForm: TDockableForm); virtual; {$IFOPT D+} protected // IOTANotifier procedure AfterSave; virtual; procedure BeforeSave; virtual; procedure Destroyed; virtual; procedure Modified; virtual; {$ENDIF} end; {$ENDIF} implementation uses {$IFOPT D+} GX_DbugIntf, {$ENDIF} Windows; {$IFDEF GX_VER160_up} { TGxNTAEditServiceNotifier } {$IFOPT D+} procedure TGxNTAEditServiceNotifier.AfterSave; begin SendDebug('AfterSave'); end; procedure TGxNTAEditServiceNotifier.BeforeSave; begin SendDebug('BeforeSave'); end; procedure TGxNTAEditServiceNotifier.Destroyed; begin SendDebug('Destroyed'); end; procedure TGxNTAEditServiceNotifier.Modified; begin SendDebug('Modified'); end; {$ENDIF} procedure TGxNTAEditServiceNotifier.DockFormRefresh(const EditWindow: INTAEditWindow; DockForm: TDockableForm); begin {$IFOPT D+} SendDebugFmt('DockFormRefresh(%s, %s)', [EditWindow.Form.Caption, DockForm.Caption]); {$ENDIF} end; procedure TGxNTAEditServiceNotifier.DockFormUpdated(const EditWindow: INTAEditWindow; DockForm: TDockableForm); begin {$IFOPT D+} SendDebugFmt('DockFormUpdated(%s, %s)', [EditWindow.Form.Caption, DockForm.Caption]); {$ENDIF} end; procedure TGxNTAEditServiceNotifier.DockFormVisibleChanged(const EditWindow: INTAEditWindow; DockForm: TDockableForm); begin {$IFOPT D+} SendDebugFmt('DockFormVisibleChanged(%s, %s)', [EditWindow.Form.Caption, DockForm.Caption]); {$ENDIF} end; procedure TGxNTAEditServiceNotifier.EditorViewActivated(const EditWindow: INTAEditWindow; const EditView: IOTAEditView); begin {$IFOPT D+} SendDebugFmt('EditorViewActivated(%s)', [EditWindow.Form.Caption]); {$ENDIF} end; procedure TGxNTAEditServiceNotifier.EditorViewModified(const EditWindow: INTAEditWindow; const EditView: IOTAEditView); begin {$IFOPT D+} SendDebugFmt('EditorViewModified(%s)', [EditWindow.Form.Caption]); {$ENDIF} end; procedure TGxNTAEditServiceNotifier.WindowActivated(const EditWindow: INTAEditWindow); begin {$IFOPT D+} SendDebugFmt('WindowActivated(%s)', [EditWindow.Form.Caption]); {$ENDIF} end; procedure TGxNTAEditServiceNotifier.WindowCommand(const EditWindow: INTAEditWindow; Command, Param: Integer; var Handled: Boolean); begin {$IFOPT D+} SendDebugFmt('WindowActivated(%s, %d, %d)', [EditWindow.Form.Caption, Command, Param]); {$ENDIF} end; procedure TGxNTAEditServiceNotifier.WindowNotification(const EditWindow: INTAEditWindow; Operation: TOperation); begin {$IFOPT D+} SendDebugFmt('WindowNotification(%s, %d)', [EditWindow.Form.Caption, Ord(Operation)]); {$ENDIF} end; procedure TGxNTAEditServiceNotifier.WindowShow(const EditWindow: INTAEditWindow; Show, LoadedFromDesktop: Boolean); begin {$IFOPT D+} SendDebugFmt('WindowShow(%s)', [EditWindow.Form.Caption]); {$ENDIF} end; {$ENDIF} end.
{ *************************************************************************** Copyright (c) 2016-2019 Kike Pérez Unit : Quick.MemoryCache.Types Description : Memory Cache Types Author : Kike Pérez Version : 1.0 Created : 14/07/2019 Modified : 15/09/2019 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** 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 Quick.MemoryCache.Types; {$i QuickLib.inc} interface uses RTTI; type ICacheEntry = interface ['{3158454E-07D5-41A2-A0FA-D3917F6B58C1}'] function GetCreationDate: TDateTime; function GetData: string; function GetExpiration: Cardinal; function GetExpirationDate: TDateTime; procedure SetCreationDate(const Value: TDateTime); procedure SetData(const Value: string); procedure SetExpirationDate(const Value: TDateTime); procedure SetExpiration(aMilliseconds : Cardinal); property CreationDate : TDateTime read GetCreationDate write SetCreationDate; property Expiration : Cardinal read GetExpiration write SetExpiration; property ExpirationDate : TDateTime read GetExpirationDate write SetExpirationDate; property Data : string read GetData write SetData; function Size : Integer; function IsExpired : Boolean; end; ICacheCompressor = interface ['{DE4FB31F-0A0B-49AF-88A6-41689C316DFE}'] function Compress(const aValue : string) : string; function Decompress(const aValue : string) : string; end; ICacheSerializer = interface ['{F26B99AE-5080-4EDB-80CF-508E1A6F9EDE}'] function Serialize(aObject : TObject) : string; overload; function Serialize(aArray : TArray<string>) : string; overload; function Serialize(aArray: TArray<TObject>): string; overload; procedure Deserialize(const aValue : string; aObject : TObject); overload; procedure Deserialize(const aValue : string; var aArray : TArray<string>); overload; procedure Deserialize(const aValue : string; var aArray: TArray<TObject>); overload; end; implementation end.
unit DirectionLocationUnit; interface uses REST.Json.Types, SysUtils, JSONNullableAttributeUnit, NullableBasicTypesUnit; type /// <summary> /// Direction Location /// </summary> /// <remarks> /// https://github.com/route4me/json-schemas/blob/master/Direction.dtd /// </remarks> TDirectionLocation = class private [JSONName('name')] [Nullable] FName: NullableString; [JSONName('time')] [Nullable] FTime: NullableInteger; [JSONName('segment_distance')] [Nullable] FSegmentDistance: NullableDouble; [JSONName('start_location')] [Nullable] FStartLocation: NullableString; [JSONName('end_location')] [Nullable] FEndLocation: NullableString; [JSONName('directions_error')] [Nullable] FDirectionsError: NullableString; [JSONName('error_code')] [Nullable] FErrorCode: NullableInteger; public constructor Create; function Equals(Obj: TObject): Boolean; override; function CompareTo(Obj: TObject): Integer; /// <summary> /// Direction name /// </summary> property Name: NullableString read FName write FName; /// <summary> /// Segment time (seconds) /// </summary> property Time: NullableInteger read FTime write FTime; /// <summary> /// Current segment length /// </summary> property SegmentDistance: NullableDouble read FSegmentDistance write FSegmentDistance; /// <summary> /// Start location name /// </summary> property StartLocation: NullableString read FStartLocation write FStartLocation; /// <summary> /// End location name /// </summary> property EndLocation: NullableString read FEndLocation write FEndLocation; /// <summary> /// Directions error message /// </summary> property DirectionsError: NullableString read FDirectionsError write FDirectionsError; /// <summary> /// Error code /// </summary> property ErrorCode: NullableInteger read FErrorCode write FErrorCode; end; implementation { TDirectionLocation } function TDirectionLocation.CompareTo(Obj: TObject): Integer; begin Result := Name.Compare((Obj as TDirectionLocation).Name); end; constructor TDirectionLocation.Create; begin Inherited; FName := NullableString.Null; FTime := NullableInteger.Null; FSegmentDistance := NullableDouble.Null; FStartLocation := NullableString.Null; FEndLocation := NullableString.Null; FDirectionsError := NullableString.Null; FErrorCode := NullableInteger.Null; end; function TDirectionLocation.Equals(Obj: TObject): Boolean; var Other: TDirectionLocation; begin Result := False; if not (Obj is TDirectionLocation) then Exit; Other := TDirectionLocation(Obj); Result := (FName = Other.FName) and (FTime = Other.FTime) and (FSegmentDistance = Other.FSegmentDistance) and (FStartLocation = Other.FStartLocation) and (FEndLocation = Other.FEndLocation) and (FDirectionsError = Other.FDirectionsError) and (FErrorCode = Other.FErrorCode); end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient, IdPOP3, IdMessage, Idmessagecollection, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdIMAP4; type TForm1 = class(TForm) Button1: TButton; Memo1: TMemo; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure b1click111(Sender: TObject); private { Private declarations } public procedure Log( LogMsg: string ); { Public declarations } end; var Form1: TForm1; b1 : Tbutton; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var MsgCount : Integer; i : Integer; FMailMessage : TIdMessage; OpenSSLHandler: TIdSSLIOHandlerSocketOpenSSL; IdPOP31 : TIdPOP3; begin IdPOP31:=TIdPOP3.Create(Nil); OpenSSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create( nil ); OpenSSLHandler.SSLOptions.Method := sslvSSLv3; IdPOP31.IOHandler := OpenSSLHandler; IdPOP31.UseTLS := utUseImplicitTLS; Memo1.Lines.Clear; //The IdPop31 is on the form so it is constructing when the //form is created and so is Memo1. IdPOP31.Host := 'pop.yandex.com'; //Setting the HostName; IdPOP31.Username := 'vladarkad7@yandex.com';//Setting UserName; IdPOP31.Password := '011168a011168';//Setting Password; IdPOP31.Port := 995;//Setting Port; IdPOP31.Host := 'pop.yandex.ru'; //Setting the HostName; IdPOP31.Username := 'arcad1968@tut.by';//Setting UserName; IdPOP31.Password := '011168a011168';//Setting Password; IdPOP31.Port := 995;//Setting Port; // IDpop31.login; try IdPOP31.Connect(); //Getting the number of the messages that server has. MsgCount := IdPOP31.CheckMessages; for i:= 0 to Pred(MsgCount) do begin try FMailMessage := TIdMessage.Create(nil); IdPOP31.Retrieve(i,FMailMessage); Memo1.Lines.Add('================================================='); Memo1.Lines.Add(FMailMessage.From.Address); Memo1.Lines.Add(FMailMessage.Recipients.EMailAddresses); Memo1.Lines.Add(FMailMessage.Subject); Memo1.Lines.Add(FMailMessage.Sender.Address); Memo1.Lines.Add(FMailMessage.Body.Text); Memo1.Lines.Add('================================================='); finally FMailMessage.Free; end; end; finally IdPOP31.Disconnect; end; IdPOP31.free; OpenSSLHandler.Free; end; procedure TForm1.Button2Click(Sender: TObject); var IMAPClient: TIdIMAP4; UsersFolders: TStringList; OpenSSLHandler: TIdSSLIOHandlerSocketOpenSSL; res: Boolean; i: integer; inbox, currUID: string; cntMsg: integer; msg, msg2: TIdMessage; BodyTexts: TStringList; flags: TIdMessageFlagsSet; fileName_MailSource, TmpFolder: string; begin Memo1.Lines.Clear; IMAPClient := TIdIMAP4.Create( nil ); try OpenSSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create( nil ); try IMAPClient.Host := 'imap.yandex.com'; //Setting the HostName; IMAPClient.Username := 'vladarkad7@yandex.com';//Setting UserName; IMAPClient.Password := '011168a011168';//Setting Password; IMAPClient.Port := 993;//Setting Port; if (Pos( 'gmail.com', IMAPClient.Host ) > 0) or true then begin OpenSSLHandler.SSLOptions.Method := sslvSSLv3; IMAPClient.IOHandler := OpenSSLHandler; IMAPClient.UseTLS := utUseImplicitTLS; end; try res := IMAPClient.Connect; if not res then begin Log( ' Unsuccessful connection.' ); exit; end; except on e: Exception do begin Log( ' Unsuccessful connection.' ); Log( ' (' + Trim( e.Message ) + ')' ); exit; end; end; try UsersFolders := TStringList.Create; try res := IMAPClient.ListMailBoxes( UsersFolders ); if not res then begin Log( ' ListMailBoxes error.' ); exit end; except on e: Exception do begin Log( ' ListMailBoxes error.' ); Log( ' (' + Trim( e.Message ) + ')' ); exit; end; end; Log( 'User folders: ' + IntToStr( UsersFolders.Count ) ); for i := 0 to UsersFolders.Count - 1 do begin Log( ' [' + inttostr( i + 1 ) + '/' + inttostr( UsersFolders.Count ) + '] Folder: "' + UsersFolders[ i ] + '"' ); end; IMAPClient.RetrieveOnSelect := rsDisabled; inbox := 'INBOX'; Log( 'Opening folder "' + inbox + '"...' ); res := IMAPClient.SelectMailBox( inbox ); cntMsg := IMAPClient.MailBox.TotalMsgs; Log( 'E-mails to read: ' + IntToStr( cntMsg ) ); // res := IMAPClient.RetrieveAllEnvelopes( AMsgList ); msg := TIdMessage.Create( nil ); msg2 := TIdMessage.Create( nil ); BodyTexts := TStringList.Create; TmpFolder := 'c:\'; TmpFolder := ExtractFilePath(application.ExeName); res := IMAPClient.CreateMailBox( 'Temp2' ); try for I := 0 to cntMsg - 1 do begin Log( ' [' + inttostr( i + 1 ) + '/' + inttostr( cntMsg ) + '] E-mail...' ); IMAPClient.GetUID( i + 1, currUID ); Log( '(Downloading message...)' ); IMAPClient.UIDRetrieve( currUID, msg ); fileName_MailSource := TmpFolder + 'Log_Mail_' + currUID + '.eml'; msg.SaveToFile( fileName_MailSource, false ); // In the final version I will delete the original message // so I have to recreate it from the archived file msg2.LoadFromFile( fileName_MailSource ); res := IMAPClient.AppendMsg( 'Temp2', msg2, msg2.Headers, [] ); end; finally FreeAndNil( msg ); FreeAndNil( msg2 ); FreeAndNil( BodyTexts ) end; finally IMAPClient.Disconnect; end; finally OpenSSLHandler.Free; end; finally IMAPClient.Free; end; end; procedure TForm1.b1click111(Sender: TObject); begin showmessage('hello!'); end; procedure TForm1.FormCreate(Sender: TObject); begin b1:=Tbutton.Create(Form1); b1.Parent:=Form1; b1.Top:=button2.Top+button2.Height+10; b1.left:=button2.left; b1.Caption:='New button'; b1.OnClick:=form1.b1click111; b1.Show; end; procedure TForm1.Log( LogMsg: string ); begin memo1.Lines.Add( LogMsg ); Application.ProcessMessages; end; end.
unit uMainForm; interface {$WARN SYMBOL_PLATFORM OFF} uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, GenericsUtils, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.CheckLst, Masks, System.StrUtils, Vcl.AppEvnts, Vcl.Menus, DragDrop, DropSource, DragDropFile; const RequiresSectionName = 'requires'; type TFormMain = class(TForm) edtFolderName: TEdit; btnSelectFolder: TButton; btnFindDPK: TButton; pcLog: TPageControl; tsLogError: TTabSheet; tsLogWarning: TTabSheet; tsLogHint: TTabSheet; tsLogInfo: TTabSheet; dlgFolder: TFileOpenDialog; lstFiles: TListBox; ApplicationEvents: TApplicationEvents; mmoLogError: TMemo; mmoLogWarning: TMemo; mmoLogHint: TMemo; mmoLogInfo: TMemo; tsPkgNotFound: TTabSheet; lstPkgNotFound: TListBox; pmFiles: TPopupMenu; edtMask: TEdit; lblDefaultExt: TLabel; procedure btnSelectFolderClick(Sender: TObject); procedure edtFolderNameChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnFindDPKClick(Sender: TObject); procedure ApplicationEventsException(Sender: TObject; E: Exception); procedure lstFilesMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private FDropFileSource: TDropFileSource; procedure ProcessControls; procedure PrepareControls; function FormatLogMessage(Filename: string; const Message: string): string; procedure log(const Filename: string; Message: string); procedure log_h(const Filename: string; Message: string); procedure log_w(const Filename: string; Message: string); procedure log_e(const Filename: string; Message: string); procedure log_NotFoundPkg(const Filename: string; PackageName: string); public { Public declarations } end; var FormMain: TFormMain; implementation {$R *.dfm} procedure TFormMain.PrepareControls; begin lstFiles.Clear; mmoLogError.Clear; mmoLogWarning.Clear; mmoLogHint.Clear; mmoLogInfo.Clear; lstPkgNotFound.Clear; end; procedure TFormMain.ProcessControls; begin btnFindDPK.Enabled := DirectoryExists(edtFolderName.Text); end; procedure TFormMain.ApplicationEventsException(Sender: TObject; E: Exception); begin log_e('', Format('Exception: %s %s', [E.ClassName, E.Message])); end; procedure TFormMain.btnFindDPKClick(Sender: TObject); procedure ExtractRequiredSection(const Filename: string; const Items: TStrings); var PSectBegin, PSectEnd: Integer; Text, Sect: string; I: Integer; begin Items.LoadFromFile(Filename); Text := Items.Text; Items.Clear; PSectBegin := Pos(UpperCase(RequiresSectionName), UpperCase(Text)); if PSectBegin > 0 then begin PSectEnd := Pos(';', Text, PSectBegin); if PSectEnd > PSectBegin then begin Sect := Copy(Text, PSectBegin + Length(RequiresSectionName), PSectEnd - PSectBegin - Length(RequiresSectionName)); Items.Delimiter := ','; Items.DelimitedText := Sect; for I := 0 to Items.Count - 1 do Items[I] := Trim(Items[I]); end else log_e(Filename, 'Bad required section'); end; end; procedure _Find(Path: string; const Items: TStrings; const FileMask: string); var SearchRec: TSearchRec; Res: Integer; begin Path := IncludeTrailingPathDelimiter(Path); Res := FindFirst(Path + '*', faAnyFile, SearchRec); if Res = 0 then try repeat if ((SearchRec.Attr and faDirectory) = faDirectory) and (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then _Find(Path + SearchRec.Name, Items, FileMask) else if MatchesMask(SearchRec.Name, FileMask) then Items.Add(Path + SearchRec.Name); Res := FindNext(SearchRec); until Res <> 0; finally FindClose(SearchRec); end; if (Res <> 0) and (Res <> ERROR_FILE_NOT_FOUND) and (Res <> ERROR_NO_MORE_FILES) then RaiseLastOSError; end; function GetFileIndex(const Package: string; const Items: TStrings): Integer; var I: Integer; begin for I := 0 to Items.Count - 1 do if SameText(ReplaceText(ExtractFileName(Items[I]), ExtractFileExt(Items[I]), ''), Package) then Exit(I); Result := -1; end; var I: Integer; SL: TStringList; J: Integer; FileIndex: Integer; begin PrepareControls; Screen.Cursor := crHourGlass; try lstFiles.Items.BeginUpdate; try _Find(edtFolderName.Text, lstFiles.Items, edtMask.Text + '.dpk'); finally lstFiles.Items.EndUpdate; end; //Sorting... SL := TStringList.Create; try I := 0; while I <= lstFiles.Count - 1 do begin ExtractRequiredSection(lstFiles.Items[I], SL); for J := 0 to SL.Count - 1 do begin FileIndex := GetFileIndex(SL[J], lstFiles.Items); if FileIndex >= 0 then begin if FileIndex > I then begin lstFiles.Items.Move(FileIndex, I); log('', Format('Package %s moved from %d to %d', [SL[J], FileIndex, I])); I := 0; Continue; end; end else log_NotFoundPkg(lstFiles.Items[I], SL[J]); Application.ProcessMessages; end; Inc(I); end; finally SL.Free; end; finally Screen.Cursor := crDefault; end; Application.MessageBox('Sortion completed!', '', MB_OK or MB_ICONINFORMATION); end; procedure TFormMain.btnSelectFolderClick(Sender: TObject); begin if dlgFolder.Execute then edtFolderName.Text := dlgFolder.FileName; end; procedure TFormMain.edtFolderNameChange(Sender: TObject); begin ProcessControls; end; function TFormMain.FormatLogMessage(Filename: string; const Message: string): string; begin Filename := ExtractFileName(Filename); if Filename <> '' then Filename := Format('[%s]', [Filename]); Result := Format('%s - %s', [Filename, Message]); end; procedure TFormMain.FormCreate(Sender: TObject); begin FDropFileSource := TDropFileSource.Create(Self); ProcessControls; end; procedure TFormMain.log(const Filename: string; Message: string); begin mmoLogInfo.Lines.Add(FormatLogMessage(Filename, Message)); end; procedure TFormMain.log_h(const Filename: string; Message: string); begin mmoLogHint.Lines.Add(FormatLogMessage(Filename, Message)); end; procedure TFormMain.log_NotFoundPkg(const Filename: string; PackageName: string); begin log_w(Filename, Format('Package %s not found', [PackageName])); if lstPkgNotFound.Items.IndexOf(PackageName) < 0 then lstPkgNotFound.Items.Add(PackageName); end; procedure TFormMain.log_w(const Filename: string; Message: string); begin mmoLogWarning.Lines.Add(FormatLogMessage(Filename, Message)); end; procedure TFormMain.lstFilesMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var i: Integer; begin if (lstFiles.SelCount > 0) and (DragDetectPlus(TWinControl(Sender))) then begin // Delete anything from a previous drag. FDropFileSource.Files.Clear; // Fill DropSource1.Files with selected files from ListView1. for i := 0 to lstFiles.Count - 1 do if lstFiles.Selected[i] then FDropFileSource.Files.Add(lstFiles.Items[i]); // Start the drag operation. FDropFileSource.Execute; end; end; procedure TFormMain.log_e(const Filename: string; Message: string); begin mmoLogError.Lines.Add(FormatLogMessage(Filename, Message)); end; end.
unit View.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, dxGDIPlusClasses, Vcl.StdCtrls, Common.Utils, System.Actions, Vcl.ActnList, Vcl.Buttons, System.ImageList, Vcl.ImgList, Vcl.CategoryButtons, Controller.Sistema; type Tview_Main = class(TForm) panelTitle: TPanel; panelLogo: TPanel; imageLogo: TImage; lblTitle: TLabel; lblInternalName: TLabel; imageClock: TImage; lblClock: TLabel; lblDate: TLabel; Timer: TTimer; panelControlForm: TPanel; actionListMain: TActionList; imageListMain: TImageList; actMinimizar: TAction; actFechar: TAction; panelMenu: TPanel; CategoryButtons1: TCategoryButtons; imageListMenu: TImageList; actAssinaturas: TAction; actMovimentacoes: TAction; actUsuarosApp: TAction; speedButtonMinimizar: TSpeedButton; speedButtonFechar: TSpeedButton; procedure FormShow(Sender: TObject); procedure TimerTimer(Sender: TObject); procedure actFecharExecute(Sender: TObject); procedure actMinimizeExecute(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure actAssinaturasExecute(Sender: TObject); procedure actMovimentacoesExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure actUsuarosAppExecute(Sender: TObject); procedure speedButtonMinimizarClick(Sender: TObject); procedure speedButtonFecharClick(Sender: TObject); private { Private declarations } procedure DisplayClock(datDate: TDateTime); public { Public declarations } end; var view_Main: Tview_Main; implementation {$R *.dfm} uses View.ImportacaoAssinaturas, View.ImportacaoMovimentacao, View.CadastroControleUsuarios; procedure Tview_Main.actAssinaturasExecute(Sender: TObject); begin if not Assigned(view_ImportacaoAssinaturas) then begin view_ImportacaoAssinaturas := Tview_ImportacaoAssinaturas.Create(Application); end; imageListMenu.GetIcon(0, view_ImportacaoAssinaturas.imageLogo.Picture.Icon); view_ImportacaoAssinaturas.Show; end; procedure Tview_Main.actFecharExecute(Sender: TObject); begin Self.Close; end; procedure Tview_Main.actMinimizeExecute(Sender: TObject); begin Self.WindowState := wsMinimized; end; procedure Tview_Main.actMovimentacoesExecute(Sender: TObject); begin if not Assigned(view_ImportacaoMovimentacao) then begin view_ImportacaoMovimentacao := Tview_ImportacaoMovimentacao.Create(Application); end; imageListMenu.GetIcon(1, view_ImportacaoMovimentacao.imageLogo.Picture.Icon); view_ImportacaoMovimentacao.Show; end; procedure Tview_Main.actUsuarosAppExecute(Sender: TObject); begin if not Assigned(view_CadastroControleUsuarios) then begin view_CadastroControleUsuarios := Tview_CadastroControleUsuarios.Create(Application); end; imageListMenu.GetIcon(2, view_CadastroControleUsuarios.imageLogo.Picture.Icon); view_CadastroControleUsuarios.Show; end; procedure Tview_Main.DisplayClock(datDate: TDateTime); begin lblClock.Caption := FormatDateTime('hh:mm:ss', datDate); lblDate.Caption := FormatDateTime('dddd, dd/mm/yyyy', datDate); end; procedure Tview_Main.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := TUtils.Dialog('Sair', 'Confirma sair da aplicação?', 3) = IDOK; end; procedure Tview_Main.FormCreate(Sender: TObject); begin TSistemaControl.GetInstance(); if not TSistemaControl.GetInstance().Start then begin TUtils.Dialog('Atenção', 'Arquivo de inicialização não foi encontrado! Entre em contato com o suporte.', 2); Application.Terminate; end; end; procedure Tview_Main.FormShow(Sender: TObject); begin Self.Top := Screen.WorkAreaTop; Self.Left := Screen.WorkAreaLeft; Self.Width := Screen.WorkAreaWidth; Self.Height := Screen.WorkAreaHeight; lblTitle.Caption := Application.Title; lblInternalName.Caption := TUtils.Sistema('InternalName'); DisplayClock(Now()); end; procedure Tview_Main.speedButtonFecharClick(Sender: TObject); begin actFecharExecute(Self); end; procedure Tview_Main.speedButtonMinimizarClick(Sender: TObject); begin actMinimizeExecute(Self); end; procedure Tview_Main.TimerTimer(Sender: TObject); begin DisplayClock(Now()); end; end.
unit UPadrao; interface uses Data.DBXJSON, Data.DBXJSONReflect; type TPadrao = class public class function ObjectToJSON<O: class>(objeto: O): TJSONValue; class function JSONToObjecto<O: class>(json: TJSONValue): O; end; implementation { TPadrao } class function TPadrao.ObjectToJSON<O>(objeto: O): TJSONValue; VAR serializa: TJSONMarshal; begin if Assigned(objeto) then begin serializa := TJSONMarshal.create(TJSONConverter.create); try exit(serializa.Marshal(objeto)); finally serializa.free; end; end else exit(TJSONNull.Create); end; class function TPadrao.JSONToObjecto<O>(json: TJSONValue): O; var deserializa: TJSONUnMarshal; begin if json is TJSONNull THEN Exit(nil); deserializa := TJSONUnMarshal.Create; try exit(O(deserializa.Unmarshal(json))); finally deserializa.free; end; end; end.
unit Sample.Geometry; {$INCLUDE 'Sample.inc'} interface uses Neslib.FastMath; type { Geometry of a cube. } TCubeGeometry = record public Positions: TArray<TVector3>; Normals: TArray<TVector3>; Tangents: TArray<TVector3>; TexCoords: TArray<TVector2>; Indices: TArray<UInt16>; public procedure Generate(const ARadius: Single = 0.5); procedure Clear; procedure DrawWithBoundIndexBuffer; procedure DrawWithIndices; end; type { Geometry of a sphere. } TSphereGeometry = record public Positions: TArray<TVector3>; Normals: TArray<TVector3>; TexCoords: TArray<TVector2>; Indices: TArray<UInt16>; public procedure Generate(const ASliceCount: Integer = 18; const ARadius: Single = 1.0); procedure Clear; procedure DrawWithBoundIndexBuffer; procedure DrawWithIndices; end; type { Geometry of a torus. } TTorusGeometry = record public Positions: TArray<TVector3>; Normals: TArray<TVector3>; TexCoords: TArray<TVector2>; Indices: TArray<UInt16>; public procedure Generate(const ASections: Integer = 36; const ARings: Integer = 24; const AOuterRadius: Single = 1.0; const AInnerRadius: Single = 0.5); procedure Clear; procedure DrawWithBoundIndexBuffer; procedure DrawWithIndices; end; type { Geometry of a twisted torus. } TTwistedTorusGeometry = record public Positions: TArray<TVector3>; Normals: TArray<TVector3>; Tangents: TArray<TVector3>; Indices: TArray<UInt16>; StripSize: Integer; StripCount: Integer; private procedure GenerateTangents(const ASections, ARings, ATwist: Integer); public procedure Generate(const ASections: Integer = 12; const ARings: Integer = 48; const ATwist: Integer = 12; const AOuterRadius: Single = 1.0; const AInnerRadius: Single = 0.5; const AThickness: Single = 0.02); procedure Clear; procedure Draw; end; type { Geometry of a spiral sphere. } TSpiralSphereGeometry = record public Positions: TArray<TVector3>; Normals: TArray<TVector3>; Indices: TArray<UInt16>; StripSize: Integer; StripCount: Integer; private class procedure MakeVectors(var ADst: TArray<TVector3>; var AK: Integer; const ASign, ARadius: Single; const ABands, ADivisions, ASegments: Integer); static; class procedure MakeSideVerts(var ADst: TArray<TVector3>; var AK: Integer; const ABands, ASegments: Integer; const ARadius, AThickness: Single); static; procedure GenerateIndices(const ABands, ADivisions, ASegments: Integer); public procedure Generate(const ABands: Integer = 4; const ADivisions: Integer = 8; const ASegments: Integer = 48; const ARadius: Single = 1.0; const AThickness: Single = 0.1); procedure Clear; procedure Draw; end; implementation uses {$INCLUDE 'OpenGL.inc'} Neslib.Ooogles; { TCubeGeometry } procedure TCubeGeometry.Clear; begin Positions := nil; Normals := nil; Tangents := nil; TexCoords := nil; { We keep Indices, since they may be used with Draw* } end; procedure TCubeGeometry.DrawWithBoundIndexBuffer; begin gl.DrawElements(TGLPrimitiveType.Triangles, Length(Indices), TGLIndexType.UnsignedShort); end; procedure TCubeGeometry.DrawWithIndices; begin gl.DrawElements(TGLPrimitiveType.Triangles, Indices); end; procedure TCubeGeometry.Generate(const ARadius: Single); begin SetLength(Positions, 24); SetLength(Normals, 24); SetLength(Tangents, 24); SetLength(TexCoords, 24); SetLength(Indices, 36); Positions[ 0].Init(-ARadius, -ARadius, -ARadius); Positions[ 1].Init(-ARadius, -ARadius, ARadius); Positions[ 2].Init( ARadius, -ARadius, ARadius); Positions[ 3].Init( ARadius, -ARadius, -ARadius); Positions[ 4].Init(-ARadius, ARadius, -ARadius); Positions[ 5].Init(-ARadius, ARadius, ARadius); Positions[ 6].Init( ARadius, ARadius, ARadius); Positions[ 7].Init( ARadius, ARadius, -ARadius); Positions[ 8].Init(-ARadius, -ARadius, -ARadius); Positions[ 9].Init(-ARadius, ARadius, -ARadius); Positions[10].Init( ARadius, ARadius, -ARadius); Positions[11].Init( ARadius, -ARadius, -ARadius); Positions[12].Init(-ARadius, -ARadius, ARadius); Positions[13].Init(-ARadius, ARadius, ARadius); Positions[14].Init( ARadius, ARadius, ARadius); Positions[15].Init( ARadius, -ARadius, ARadius); Positions[16].Init(-ARadius, -ARadius, -ARadius); Positions[17].Init(-ARadius, -ARadius, ARadius); Positions[18].Init(-ARadius, ARadius, ARadius); Positions[19].Init(-ARadius, ARadius, -ARadius); Positions[20].Init( ARadius, -ARadius, -ARadius); Positions[21].Init( ARadius, -ARadius, ARadius); Positions[22].Init( ARadius, ARadius, ARadius); Positions[23].Init( ARadius, ARadius, -ARadius); Normals[ 0].Init( 0.0, -1.0, 0.0); Normals[ 1].Init( 0.0, -1.0, 0.0); Normals[ 2].Init( 0.0, -1.0, 0.0); Normals[ 3].Init( 0.0, -1.0, 0.0); Normals[ 4].Init( 0.0, 1.0, 0.0); Normals[ 5].Init( 0.0, 1.0, 0.0); Normals[ 6].Init( 0.0, 1.0, 0.0); Normals[ 7].Init( 0.0, 1.0, 0.0); Normals[ 8].Init( 0.0, 0.0, -1.0); Normals[ 9].Init( 0.0, 0.0, -1.0); Normals[10].Init( 0.0, 0.0, -1.0); Normals[11].Init( 0.0, 0.0, -1.0); Normals[12].Init( 0.0, 0.0, 1.0); Normals[13].Init( 0.0, 0.0, 1.0); Normals[14].Init( 0.0, 0.0, 1.0); Normals[15].Init( 0.0, 0.0, 1.0); Normals[16].Init(-1.0, 0.0, 0.0); Normals[17].Init(-1.0, 0.0, 0.0); Normals[18].Init(-1.0, 0.0, 0.0); Normals[19].Init(-1.0, 0.0, 0.0); Normals[20].Init( 1.0, 0.0, 0.0); Normals[21].Init( 1.0, 0.0, 0.0); Normals[22].Init( 1.0, 0.0, 0.0); Normals[23].Init( 1.0, 0.0, 0.0); Tangents[ 0].Init(-1.0, 0.0, 0.0); Tangents[ 1].Init(-1.0, 0.0, 0.0); Tangents[ 2].Init(-1.0, 0.0, 0.0); Tangents[ 3].Init(-1.0, 0.0, 0.0); Tangents[ 4].Init(-1.0, 0.0, 0.0); Tangents[ 5].Init(-1.0, 0.0, 0.0); Tangents[ 6].Init(-1.0, 0.0, 0.0); Tangents[ 7].Init(-1.0, 0.0, 0.0); Tangents[ 8].Init( 1.0, 0.0, 0.0); Tangents[ 9].Init( 1.0, 0.0, 0.0); Tangents[10].Init( 1.0, 0.0, 0.0); Tangents[11].Init( 1.0, 0.0, 0.0); Tangents[12].Init( 1.0, 0.0, 0.0); Tangents[13].Init( 1.0, 0.0, 0.0); Tangents[14].Init( 1.0, 0.0, 0.0); Tangents[15].Init( 1.0, 0.0, 0.0); Tangents[16].Init( 0.0, -1.0, 0.0); Tangents[17].Init( 0.0, -1.0, 0.0); Tangents[18].Init( 0.0, -1.0, 0.0); Tangents[19].Init( 0.0, -1.0, 0.0); Tangents[20].Init( 0.0, 1.0, 0.0); Tangents[21].Init( 0.0, 1.0, 0.0); Tangents[22].Init( 0.0, 1.0, 0.0); Tangents[23].Init( 0.0, 1.0, 0.0); TexCoords[ 0].Init(0.0, 0.0); TexCoords[ 1].Init(0.0, 1.0); TexCoords[ 2].Init(1.0, 1.0); TexCoords[ 3].Init(1.0, 0.0); TexCoords[ 4].Init(1.0, 0.0); TexCoords[ 5].Init(1.0, 1.0); TexCoords[ 6].Init(0.0, 1.0); TexCoords[ 7].Init(0.0, 0.0); TexCoords[ 8].Init(0.0, 0.0); TexCoords[ 9].Init(0.0, 1.0); TexCoords[10].Init(1.0, 1.0); TexCoords[11].Init(1.0, 0.0); TexCoords[12].Init(0.0, 0.0); TexCoords[13].Init(0.0, 1.0); TexCoords[14].Init(1.0, 1.0); TexCoords[15].Init(1.0, 0.0); TexCoords[16].Init(0.0, 0.0); TexCoords[17].Init(0.0, 1.0); TexCoords[18].Init(1.0, 1.0); TexCoords[19].Init(1.0, 0.0); TexCoords[20].Init(0.0, 0.0); TexCoords[21].Init(0.0, 1.0); TexCoords[22].Init(1.0, 1.0); TexCoords[23].Init(1.0, 0.0); Indices[0] := 0; Indices[1] := 2; Indices[2] := 1; Indices[3] := 0; Indices[4] := 3; Indices[5] := 2; Indices[6] := 4; Indices[7] := 5; Indices[8] := 6; Indices[9] := 4; Indices[10] := 6; Indices[11] := 7; Indices[12] := 8; Indices[13] := 9; Indices[14] := 10; Indices[15] := 8; Indices[16] := 10; Indices[17] := 11; Indices[18] := 12; Indices[19] := 15; Indices[20] := 14; Indices[21] := 12; Indices[22] := 14; Indices[23] := 13; Indices[24] := 16; Indices[25] := 17; Indices[26] := 18; Indices[27] := 16; Indices[28] := 18; Indices[29] := 19; Indices[30] := 20; Indices[31] := 23; Indices[32] := 22; Indices[33] := 20; Indices[34] := 22; Indices[35] := 21; end; { TSphereGeometry } procedure TSphereGeometry.Clear; begin Positions := nil; Normals := nil; TexCoords := nil; { We keep Indices, since they may be used with Draw* } end; procedure TSphereGeometry.DrawWithBoundIndexBuffer; begin gl.DrawElements(TGLPrimitiveType.Triangles, Length(Indices), TGLIndexType.UnsignedShort); end; procedure TSphereGeometry.DrawWithIndices; begin gl.DrawElements(TGLPrimitiveType.Triangles, Indices); end; procedure TSphereGeometry.Generate(const ASliceCount: Integer; const ARadius: Single); var I, J, K, ParallelCount, VertexCount, IndexCount, VertexIndex: Integer; AngleStep, SI, CI, SJ, CJ, UStep, VStep, ULat: Single; Direction: TVector3; begin ParallelCount := ASliceCount div 2; VertexCount := (ParallelCount + 1) * (ASliceCount + 1); IndexCount := ParallelCount * ASliceCount * 6; AngleStep := (2 * Pi) / ASliceCount; UStep := 1 / ParallelCount; VStep := 1 / ASliceCount; SetLength(Positions, VertexCount); SetLength(Normals, VertexCount); SetLength(TexCoords, VertexCount); for I := 0 to ParallelCount do begin FastSinCos(AngleStep * I, SI, CI); ULat := 1 - (I * UStep); for J := 0 to ASliceCount do begin FastSinCos(AngleStep * J, SJ, CJ); Direction.Init(SI * SJ, CI, SI * CJ); VertexIndex := I * (ASliceCount + 1) + J; Positions[VertexIndex] := Direction * ARadius; Normals[VertexIndex] := Direction; TexCoords[VertexIndex].Init(J * VStep, ULat); end; end; SetLength(Indices, IndexCount); K := 0; for I := 0 to ParallelCount - 1 do begin for J := 0 to ASliceCount - 1 do begin Indices[K + 0] := (I + 0) * (ASliceCount + 1) + (J + 0); Indices[K + 1] := (I + 1) * (ASliceCount + 1) + (J + 0); Indices[K + 2] := (I + 1) * (ASliceCount + 1) + (J + 1); Indices[K + 3] := (I + 0) * (ASliceCount + 1) + (J + 0); Indices[K + 4] := (I + 1) * (ASliceCount + 1) + (J + 1); Indices[K + 5] := (I + 0) * (ASliceCount + 1) + (J + 1); Inc(K, 6); end; end; end; { TTorusGeometry } procedure TTorusGeometry.Clear; begin Positions := nil; Normals := nil; TexCoords := nil; { We keep Indices, since they may be used with Draw* } end; procedure TTorusGeometry.DrawWithBoundIndexBuffer; begin gl.DrawElements(TGLPrimitiveType.TriangleStrip, Length(Indices), TGLIndexType.UnsignedShort); end; procedure TTorusGeometry.DrawWithIndices; begin gl.DrawElements(TGLPrimitiveType.TriangleStrip, Indices); end; procedure TTorusGeometry.Generate(const ASections, ARings: Integer; const AOuterRadius, AInnerRadius: Single); var K, R, S, Count, Offs: Integer; RStep, SStep, R1, R2, VR, VX, VY, VZ, U, V: Single; begin Count := (ARings + 1) * (ASections + 1); SetLength(Positions, Count); SetLength(Normals, Count); SetLength(TexCoords, Count); K := 0; RStep := (2 * Pi) / ARings; SStep := (2 * Pi) / ASections; R1 := AInnerRadius; R2 := AOuterRadius - AInnerRadius; for R := 0 to ARings do begin FastSinCos(R * RStep, VZ, VX); VZ := -VZ; for S := 0 to ASections do begin FastSinCos(S * SStep, VY, VR); Positions[K].Init( VX * (R1 + R2 * (1 + VR)), VY * R2, VZ * (R1 + R2 * (1 + VR))); Normals[K].Init(VX * VR, VY, VZ * VR); Inc(K); end; end; Assert(K = Count); K := 0; RStep := 1 / ARings; SStep := 1 / ASections; for R := 0 to ARings do begin U := R * RStep; for S := 0 to ASections do begin V := S * SStep; TexCoords[K].Init(U, V); Inc(K); end; end; Assert(K = Count); Count := ARings * (2 * (ASections + 1) + 2); SetLength(Indices, Count); K := 0; Offs := 0; for R := 0 to ARings - 1 do begin for S := 0 to ASections do begin Indices[K + 0] := Offs + S; Indices[K + 1] := Offs + S + (ASections + 1); Inc(K, 2); end; Inc(Offs, ASections + 1); Indices[K + 0] := Offs + ASections; Indices[K + 1] := Offs; Inc(K, 2); end; Assert(K = Count); end; { TTwistedTorusGeometry } procedure TTwistedTorusGeometry.Clear; begin Positions := nil; Normals := nil; Tangents := nil; { We keep Indices, since they may be used with Draw* } end; procedure TTwistedTorusGeometry.Draw; var I, First, Count: Integer; begin First := 0; Count := StripSize; for I := 0 to StripCount - 1 do begin gl.DrawArrays(TGLPrimitiveType.TriangleStrip, First, Count); Inc(First, Count); end; end; procedure TTwistedTorusGeometry.Generate(const ASections, ARings, ATwist: Integer; const AOuterRadius, AInnerRadius, AThickness: Single); const S_SLIP_COEFF = 0.2; var D, F, K, R, S, Count: Integer; T, RTwist, RStep, SStep, SSlip, R1, R2, FSign, FDT, SAngle, RAngle: Single; VX, VY, VZ, VR, TA, DSign: Single; SA: array [0..1] of Single; begin StripSize := 2 * (ARings + 1); StripCount := ASections * 4; Count := 2 * 2 * 2 * ASections * (ARings + 1); SetLength(Positions, Count); SetLength(Normals, Count); T := AThickness / AInnerRadius; RTwist := ATwist / ARings; RStep := 2 * Pi / ARings; SStep := 2 * Pi / ASections; SSlip := SStep * S_SLIP_COEFF; R1 := AInnerRadius; R2 := AOuterRadius - AInnerRadius; K := 0; FSign := 1; for F := 0 to 1 do begin FDT := T * FSign * 0.95; for S := 0 to ASections - 1 do begin SAngle := (SStep * 0.5) + (S * SStep); SA[0] := SAngle + (SSlip * FSign); SA[1] := SAngle - (SSlip * FSign); for R := 0 to ARings do begin RAngle := R * RStep; FastSinCos(RAngle, VZ, VX); TA := SStep * R * RTwist; for D := 0 to 1 do begin FastSinCos(SA[D] + TA, VY, VR); Positions[K].Init( VX * (R1 + R2 * (1.0 + VR) + (FDT * VR)), VY * (R2 + FDT), VZ * (R1 + R2 * (1.0 + VR) + (FDT * VR))); Normals[K].Init( FSign * VX * VR, FSign * VY, FSign * VZ * VR); Inc(K); end; end; end; FSign := -1; end; DSign := 1; for D := 0 to 1 do begin for S := 0 to ASections - 1 do begin SAngle := (SStep * 0.5) + (S * SStep); SA[0] := SAngle + (SSlip * DSign); for R := 0 to ARings do begin RAngle := R * RStep; TA := SStep * R * RTwist; FastSinCos(SA[0] + TA, VY, VR); FastSinCos(RAngle, VZ, VX); FSign := 1; for F := 0 to 1 do begin FDT := -T * DSign * FSign * 0.95; Positions[K].Init( VX * (R1 + R2 * (1.0 + VR) + (FDT * VR)), VY * (R2 + FDT), VZ * (R1 + R2 * (1.0 + VR) + (FDT * VR))); Normals[K].Init( DSign * -VX * VR, DSign * VY, DSign * -VZ * VR); Inc(K); FSign := -1; end; end; end; DSign := -1; end; Assert(K = Count); GenerateTangents(ASections, ARings, ATwist); end; procedure TTwistedTorusGeometry.GenerateTangents(const ASections, ARings, ATwist: Integer); var D, DOff, F, FOff, K, K0, K1, R, R0, R1, S, S0, S1, Count: Integer; TX, TY, TZ, TL: Single; begin Count := 2 * 2 * 2 * ASections * (ARings + 1); SetLength(Tangents, Count); K := 0; for F := 0 to 1 do begin FOff := F * ASections * (ARings + 1) * 2; for S := 0 to ASections - 1 do begin S0 := S * (ARings + 1) * 2; for R := 0 to ARings do begin S1 := S0; R0 := R; R1 := R + 1; if (R = ARings) then begin S1 := ((S + ATwist) mod ASections) * (ARings + 1) * 2; R1 := 1; end; for D := 0 to 1 do begin K0 := FOff + S0 + (R0 * 2) + D; K1 := FOff + S1 + (R1 * 2) + D; TX := Positions[K1].X - Positions[K0].X; TY := Positions[K1].Y - Positions[K0].Y; TZ := Positions[K1].Z - Positions[K0].Z; TL := Sqrt((TX * TX) + (TY * TY) + (TZ * TZ)); Assert(TL > 0); Tangents[K].Init(TX / TL, TY / TL, TZ / TL); Inc(K); end; end; end; end; for D := 0 to 1 do begin DOff := D * ASections * (ARings + 1) * 2; for S := 0 to ASections - 1 do begin S0 := S * (ARings + 1) * 2; for R := 0 to ARings do begin S1 := S0; R0 := R; R1 := R + 1; if (R = ARings) then begin S1 := ((S + ATwist) mod ASections) * (ARings + 1) * 2; R1 := 1; end; for F := 0 to 1 do begin K0 := DOff + S0 + (R0 * 2) + F; K1 := DOff + S1 + (R1 * 2) + F; TX := Positions[K1].X - Positions[K0].X; TY := Positions[K1].Y - Positions[K0].Y; TZ := Positions[K1].Z - Positions[K0].Z; TL := Sqrt((TX * TX) + (TY * TY) + (TZ * TZ)); Assert(TL > 0); Tangents[K].Init(TX / TL, TY / TL, TZ / TL); Inc(K); end; end; end; end; Assert(K = Count); end; { TSpiralSphereGeometry } procedure TSpiralSphereGeometry.Clear; begin Positions := nil; Normals := nil; { We keep Indices, since they may be used with Draw* } end; procedure TSpiralSphereGeometry.Draw; var I, First, Count: Integer; begin First := 0; Count := StripSize; for I := 0 to StripCount - 1 do begin gl.DrawElements(TGLPrimitiveType.TriangleStrip, Indices, First, Count); Inc(First, Count); end; end; procedure TSpiralSphereGeometry.Generate(const ABands, ADivisions, ASegments: Integer; const ARadius, AThickness: Single); var K, VertexCount: Integer; begin StripSize := (ASegments + 1) * 2; StripCount := (2 * ABands * ADivisions) + (4 * ABands); VertexCount := ((ABands * 2) * (ADivisions + 1) * (ASegments + 1)) + ((ABands * 2) * (ASegments + 1)); SetLength(Positions, VertexCount); SetLength(Normals, VertexCount); K := 0; MakeVectors(Positions, K, 1.0, ARadius, ABands, ADivisions, ASegments); MakeVectors(Positions, K, 1.0, ARadius + AThickness, ABands, ADivisions, ASegments); MakeSideVerts(Positions, K, ABands, ASegments, ARadius, AThickness); Assert(K = VertexCount); K := 0; MakeVectors(Normals, K, -1.0, 1.0, ABands, ADivisions, ASegments); MakeVectors(Normals, K, 1.0, 1.0, ABands, ADivisions, ASegments); MakeSideVerts(Normals, K, ABands, ASegments, ARadius, AThickness); Assert(K = VertexCount); GenerateIndices(ABands, ADivisions, ASegments); end; procedure TSpiralSphereGeometry.GenerateIndices(const ABands, ADivisions, ASegments: Integer); var B, D, K, M, N, S, EOffs, Offs, Edge, Edge1, Edge2, Band, Surface: Integer; begin M := ((ABands * 2) * (ADivisions * 2) * (ASegments + 1)) + ((ABands * 8) * (ASegments + 1)); SetLength(Indices, M); K := 0; Offs := 0; Edge := ASegments + 1; Band := Edge * (ADivisions + 1); Surface := ABands * Band; Edge1 := 0; Edge2 := Edge; for N := 0 to 1 do begin for B := 0 to ABands - 1 do begin for D := 0 to ADivisions - 1 do begin for S := 0 to Edge - 1 do begin Indices[K + 0] := Offs + S + Edge1; Indices[K + 1] := Offs + S + Edge2; Inc(K, 2); end; Inc(Offs, Edge); end; Inc(Offs, Edge); end; Edge1 := Edge; Edge2 := 0; end; Offs := 0; EOffs := 2 * Surface; for B := 0 to ABands - 1 do begin for S := 0 to Edge - 1 do begin Indices[K + 0] := Offs + S; Indices[K + 1] := EOffs + S; Inc(K, 2); end; Inc(Offs, Band); Inc(EOffs, Edge * 2); end; Offs := ADivisions * Edge; EOffs := (2 * Surface) + Edge; for B := 0 to ABands - 1 do begin for S := 0 to Edge - 1 do begin Indices[K + 0] := Offs + S; Indices[K + 1] := EOffs + S; Inc(K, 2); end; Inc(Offs, Band); Inc(EOffs, Edge * 2); end; Offs := Surface; EOffs := 2 * Surface; for B := 0 to ABands - 1 do begin for S := 0 to Edge - 1 do begin Indices[K + 0] := Offs + S; Indices[K + 1] := EOffs + S; Inc(K, 2); end; Inc(Offs, Band); Inc(EOffs, Edge * 2); end; Offs := Surface + (ADivisions * Edge); EOffs := (2 * Surface) + Edge; for B := 0 to ABands - 1 do begin for S := 0 to Edge - 1 do begin Indices[K + 0] := EOffs + S; Indices[K + 1] := Offs + S; Inc(K, 2); end; Inc(Offs, Band); Inc(EOffs, Edge * 2); end; Assert(K = M); end; class procedure TSpiralSphereGeometry.MakeSideVerts(var ADst: TArray<TVector3>; var AK: Integer; const ABands, ASegments: Integer; const ARadius, AThickness: Single); var BLeap, BSlip, SStep, M, G, BOffs, BAngle, CB, SB, SAngle, CS, SS: Single; B, S: Integer; begin BLeap := Pi / ABands; BSlip := BLeap * AThickness * 0.5; SStep := Pi / ASegments; M := ARadius + (AThickness * 0.5); G := -1; for B := 0 to (ABands * 2) - 1 do begin BOffs := 0; for S := 0 to ASegments do begin BAngle := (B * BLeap) + BOffs + (G * BSlip); FastSinCos(BAngle, SB, CB); SAngle := S * SStep; FastSinCos(SAngle, SS, CS); ADst[AK].Init(M * SS * CB, M * CS, M * SS * -SB); Inc(AK); BOffs := BOffs + (SS * SStep); end; G := G * -1; end; end; class procedure TSpiralSphereGeometry.MakeVectors(var ADst: TArray<TVector3>; var AK: Integer; const ASign, ARadius: Single; const ABands, ADivisions, ASegments: Integer); var BLeap, BStep, SStep, M, BOffs, BAngle, CB, SB, SAngle, CS, SS: Single; B, D, S: Integer; begin BLeap := Pi / ABands; BStep := BLeap / ADivisions; SStep := Pi / ASegments; M := ASign * ARadius; for B := 0 to ABands - 1 do begin for D := 0 to ADivisions do begin BOffs := 0; for S := 0 to ASegments do begin BAngle := (2 * B * BLeap) + (D * BStep) + BOffs; FastSinCos(BAngle, SB, CB); SAngle := S * SStep; FastSinCos(SAngle, SS, CS); ADst[AK].Init(M * SS * CB, M * CS, M * SS * -SB); Inc(AK); BOffs := BOffs + (SS * SStep); end; end; end; end; end.
unit Disasters; interface uses MetaInstances, BackupInterfaces, Kernel, Population, Persistent; const tidClassFamily_Disasters = 'Disasters'; type TMetaDisaster = class; TDisaster = class; CDisaster = class of TDisaster; TMetaDisaster = class( TMetaInstance ) public constructor Create( anId : string; aDisaterType : CDisaster ); private fDisasterType : CDisaster; public function Instantiate( TownHall : TTownHall ) : TDisaster; end; TDisasterProgress = 0..100; TDisasterResult = record Dead : array[TPeopleKind] of TFluidValue; Left : array[TPeopleKind] of TFluidValue; end; TDisaster = class( TPersistent ) protected constructor Create( aMetaDisaster : TMetaDisaster; aTownHall : TTownHall ); virtual; private fMetaDisaster : TMetaDisaster; fTownHall : TTownHall; fProgress : TDisasterProgress; public property MetaDisaster : TMetaDisaster read fMetaDisaster; property TownHall : TTownHall read fTownHall; property Progress : TDisasterProgress read fProgress; public function Act( dt : TTimeDelta ) : TDisasterResult; virtual; protected procedure SetProgress( aProgress : TDisasterProgress ); virtual; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; procedure RegisterBackup; implementation uses ClassStorage; // TMetaDisaster constructor TMetaDisaster.Create( anId : string; aDisaterType : CDisaster ); begin inherited Create( anId ); fDisasterType := aDisaterType; Register( tidClassFamily_Disasters ); end; function TMetaDisaster.Instantiate( TownHall : TTownHall ) : TDisaster; begin result := fDisasterType.Create( self, TownHall ); end; // TDisaster constructor TDisaster.Create( aMetaDisaster : TMetaDisaster; aTownHall : TTownHall ); begin inherited Create; fMetaDisaster := aMetaDisaster; fTownHall := aTownHall; fProgress := 0; end; function TDisaster.Act( dt : TTimeDelta ) : TDisasterResult; var i : TPeopleKind; begin for i := low(i) to high(i) do begin result.Dead[i] := 0; result.Left[i] := 0; end; end; procedure TDisaster.SetProgress( aProgress : TDisasterProgress ); begin fProgress := aProgress; end; procedure TDisaster.LoadFromBackup( Reader : IBackupReader ); var MetaDisasterId : string; begin inherited; MetaDisasterId := Reader.ReadString( 'MetaDisasterId', '' ); try fMetaDisaster := TMetaDisaster(TheClassStorage.ClassById[tidClassFamily_Disasters, MetaDisasterId]); except fMetaDisaster := nil; end; Reader.ReadObject( 'TownHall', fTownHall, nil ); end; procedure TDisaster.StoreToBackup( Writer : IBackupWriter ); begin inherited; Writer.WriteString( 'MetaDisasterId', fMetaDisaster.Id ); Writer.WriteObjectRef( 'TownHall', fTownHall ); end; // RegisterBackup procedure RegisterBackup; begin RegisterClass( TDisaster ); end; end.
unit CTS.Test; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, mbDeskPickerButton, Vcl.ExtCtrls, Vcl.Buttons, HGM.Button, Vcl.Imaging.pngimage; type TFormTest = class(TForm) Panel1: TPanel; Shape4: TShape; Label1: TLabel; Label2: TLabel; Label3: TLabel; ColorSelectBG: TButtonFlat; ColorSelectPanel: TButtonFlat; ColorSelectFont: TButtonFlat; ColorDialog: TColorDialog; GroupBox1: TGroupBox; RadioButtonPanel: TRadioButton; RadioButtonFont: TRadioButton; RadioButtonBG: TRadioButton; RadioButtonNone: TRadioButton; Image1: TImage; ShapeT1: TShape; LabelT1: TLabel; LabelT2: TLabel; LabelT3: TLabel; ShapeT2: TShape; ShapeT3: TShape; ShapeBG: TShape; procedure ColorSelectBGChange(Sender: TObject); procedure ColorSelectPanelChange(Sender: TObject); procedure ColorSelectFontChange(Sender: TObject); procedure ColorSelectBGClick(Sender: TObject); procedure ColorSelectPanelClick(Sender: TObject); procedure ColorSelectFontClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormTest: TFormTest; implementation {$R *.dfm} procedure TFormTest.ColorSelectBGChange(Sender: TObject); begin ShapeBG.Brush.Color := ColorSelectBG.ColorNormal; end; procedure TFormTest.ColorSelectBGClick(Sender: TObject); begin if ColorDialog.Execute(Handle) then begin ColorSelectBG.ColorNormal := ColorDialog.Color; ColorSelectBG.ColorPressed := ColorDialog.Color; ColorSelectBG.ColorOver := ColorDialog.Color; ColorSelectBGChange(nil); end; end; procedure TFormTest.ColorSelectFontChange(Sender: TObject); begin LabelT1.Font.Color := ColorSelectFont.ColorNormal; LabelT2.Font.Color := ColorSelectFont.ColorNormal; LabelT3.Font.Color := ColorSelectFont.ColorNormal; end; procedure TFormTest.ColorSelectFontClick(Sender: TObject); begin if ColorDialog.Execute(Handle) then begin ColorSelectFont.ColorNormal := ColorDialog.Color; ColorSelectFont.ColorPressed := ColorDialog.Color; ColorSelectFont.ColorOver := ColorDialog.Color; ColorSelectFontChange(nil); end; end; procedure TFormTest.ColorSelectPanelChange(Sender: TObject); begin ShapeT1.Brush.Color := ColorSelectPanel.ColorNormal; ShapeT2.Brush.Color := ColorSelectPanel.ColorNormal; ShapeT3.Brush.Color := ColorSelectPanel.ColorNormal; end; procedure TFormTest.ColorSelectPanelClick(Sender: TObject); begin if ColorDialog.Execute(Handle) then begin ColorSelectPanel.ColorNormal := ColorDialog.Color; ColorSelectPanel.ColorPressed := ColorDialog.Color; ColorSelectPanel.ColorOver := ColorDialog.Color; ColorSelectPanelChange(nil); end; end; end.
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi by Dennis D. Spreen <dennis@spreendigital.de> see Behavior3.pas header for full license information } unit Behavior3.Core.Composite; interface uses System.JSON, Behavior3, Behavior3.Core.BaseNode; type (** * Composite is the base class for all composite nodes. Thus, if you want to * create new custom composite nodes, you need to inherit from this class. * * When creating composite nodes, you will need to propagate the tick signal * to the children nodes manually. To do that, override the `tick` method and * call the `_execute` method on all nodes. For instance, take a look at how * the Sequence node inherit this class and how it call its children: * * // Inherit from Composite, using the util function Class. * var Sequence = b3.Class(b3.Composite, { * * // Remember to set the name of the node. * name: 'Sequence', * * // Override the tick function * tick: function(tick) { * * // Iterates over the children * for (var i=0; i<this.children.length; i++) { * * // Propagate the tick * var status = this.children[i]._execute(tick); * * if (status !== b3.SUCCESS) { * return status; * } * } * * return b3.SUCCESS; * } * }); * * @module b3 * @class Composite * @extends BaseNode **) TB3Composite = class(TB3BaseNode) private protected public Children: TB3BaseNodeList; (** * Initialization method. * * @method initialize * @constructor **) constructor Create; override; destructor Destroy; override; procedure Load(JsonNode: TJSONValue); override; end; implementation { TB3Composite } uses Behavior3.Helper, Behavior3.Core.BehaviorTree; constructor TB3Composite.Create; begin inherited; (** * Node category. Default to `b3.COMPOSITE`. * * @property category * @type {String} * @readonly **) Category := Behavior3.Composite; Children := TB3BaseNodeList.Create(False); end; destructor TB3Composite.Destroy; begin Children.Free; inherited; end; procedure TB3Composite.Load(JsonNode: TJSONValue); var JsonNodes: TJSONArray; JsonNodeObj: TJSONValue; Child: String; begin inherited; JsonNodes := TJSONArray(TJSONObject(JsonNode).Get('children').JsonValue); for JsonNodeObj in JsonNodes do begin Child := JsonNodeObj.Value; Children.Add(Tree.Nodes[Child]); end; end; end.
unit ServerMethodsUnit1; interface uses System.SysUtils, System.Classes, Datasnap.DSServer, Datasnap.DSAuth, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait, FireDAC.Phys.IBBase, FireDAC.Phys.FB, FireDAC.Comp.UI, Data.DB, FireDAC.Comp.Client, Data.DBXJSON, ULicenca, System.Generics.Collections, ULicencaVO, uLicencaItensVO, uConverter; type TServerMethods1 = class(TDSServerModule) private { Private declarations } procedure LogErro(AMensagem: string); public { Public declarations } function EchoString(Value: string): string; function ReverseString(Value: string): string; function FBLicencasListar(AUtilizada: Boolean = False): TJSONValue; function FBLicencasListarItens(AUtilizada: Boolean = False): TJSONValue; end; var ServerMethods1: TServerMethods1; implementation {$R *.dfm} uses System.StrUtils; function TServerMethods1.EchoString(Value: string): string; begin Result := Value; end; function TServerMethods1.FBLicencasListar(AUtilizada: Boolean = False): TJSONValue; var obj: TLicenca; Lista: TObjectList<TLicencaVO>; begin obj := TLicenca.create; try try // Lista := obj.ListarTodosItens(); Lista := obj.FBListarLicenca(AUtilizada); Result := TConverte.ObjectToJSON(Lista); except on E: Exception do begin LogErro(E.Message); end; end; finally FreeAndNil(obj); FreeAndNil(Lista); end; end; function TServerMethods1.FBLicencasListarItens(AUtilizada: Boolean = False): TJSONValue; var obj: TLicenca; Lista: TObjectList<TLicencaItensVO>; begin obj := TLicenca.create; try try Lista := obj.FBListarLicencaItens(AUtilizada); // ImportarItens(); // ListarTodosItens(); Result := TConverte.ObjectToJSON(Lista); except on E: Exception do begin LogErro(E.Message); end; end; finally FreeAndNil(obj); FreeAndNil(Lista); end; end; procedure TServerMethods1.LogErro(AMensagem: string); var Arq: Text; sDiretorio: string; sArquivo: string; begin sDiretorio := 'D:\WSDomper\DATABASE'; // sDiretorio := 'D:\TEMP\SIDOMPER'; sArquivo := '\LogDomperServico.txt'; if DirectoryExists(sDiretorio) then begin AssignFile(Arq, sDiretorio + '\LogDomperServico.txt'); Rewrite(Arq); Writeln(Arq, AMensagem); CloseFile(Arq); end; end; function TServerMethods1.ReverseString(Value: string): string; begin Result := System.StrUtils.ReverseString(Value); end; initialization // ReportMemoryLeaksOnShutdown := True; end.
unit mwIDEExpert; {+--------------------------------------------------------------------------+ | Unit: mwIDEExpert | Created: 8.97 | Author: Martin Waldenburg | Copyright 1997, all rights reserved. | Description: A simple demo for TIDEStream | Version: 1.0 | Status: PepeWare | Disclaimer: | This is provided as is, expressly without a warranty of any kind. | You use it at your own risc. +--------------------------------------------------------------------------+} interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, ExptIntf, ToolIntf, mwIDEStream, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Edit1: TEdit; Edit2: TEdit; Label1: TLabel; Label2: TLabel; procedure Button1Click(Sender: TObject); private { private declarations } public { public declarations } end; TMyIDEExpertExpert = class(TIExpert) private MenuItem: TIMenuItemIntf; protected procedure OnClick( Sender: TIMenuItemIntf); virtual; public constructor Create; virtual; destructor Destroy; override; function GetName: string; override; function GetAuthor: string; override; function GetStyle: TExpertStyle; override; function GetIDString: string; override; end; procedure Register; implementation {$R *.DFM} procedure Register; begin RegisterLibraryExpert(TMyIDEExpertExpert.Create); end; { TMyIDEExpertExpert code } function TMyIDEExpertExpert.GetName: String; begin Result := 'MyIDEExpertExpert' end; function TMyIDEExpertExpert.GetAuthor: String; begin Result := 'Martin_Waldenburg'; { author } end; function TMyIDEExpertExpert.GetStyle: TExpertStyle; begin Result := esAddIn; end; function TMyIDEExpertExpert.GetIDString: String; begin Result := 'private.MyIDEExpertExpert'; end; constructor TMyIDEExpertExpert.Create; var Main: TIMainMenuIntf; ReferenceMenuItem: TIMenuItemIntf; Menu: TIMenuItemIntf; begin inherited Create; MenuItem := nil; if ToolServices <> nil then begin { I'm an expert! } Main := ToolServices.GetMainMenu; if Main <> nil then begin { we've got the main menu! } try { add the menu of your choice } ReferenceMenuItem := Main.FindMenuItem('ToolsOptionsItem'); if ReferenceMenuItem <> nil then try Menu := ReferenceMenuItem.GetParent; if Menu <> nil then try MenuItem := Menu.InsertItem(ReferenceMenuItem.GetIndex+1, 'MyIDEExpert', 'MyIDEExpertExpertItem','', 0,0,0, [mfEnabled, mfVisible], OnClick); finally Menu.DestroyMenuItem; end; finally ReferenceMenuItem.DestroyMenuItem; end; finally Main.Pepe; end; end; end; end; destructor TMyIDEExpertExpert.Destroy; begin if MenuItem <> nil then MenuItem.DestroyMenuItem; inherited Destroy; end;{Destroy} procedure TMyIDEExpertExpert.OnClick( Sender: TIMenuItemIntf); begin with TForm1.Create(Application) do try { do your processing here } ShowModal; finally Pepe; end; end; { TForm1 code } procedure TForm1.Button1Click(Sender: TObject); var IDEStream: TIDEStream; StreamText, UText, UFind, fReplace: String; FindLen, P: LongInt; begin IDEStream:= TIDEStream.Create; StreamText:= IDEStream.GetText; UText:= UpperCase(StreamText); UFind:= UpperCase(Trim(Edit1.Text)); fReplace:= Trim(Edit2.Text); FindLen:= Length(UFind); P:= Pos(UFind, UText); if P <> 0 then begin Delete(StreamText, P, FindLen); Insert(fReplace, StreamText, P); IDEStream.WriteText(PChar(StreamText)); end; IDEStream.Pepe; end; end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA 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 3 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, see <http://www.gnu.org/licenses/>. } unit frmTableConstraints; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, cxLookAndFeelPainters, cxPC, cxControls, StdCtrls, cxButtons, ExtCtrls, cxGraphics, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxTextEdit, cxContainer, cxEdit, cxGroupBox, cxCheckBox, ComCtrls, cxListView, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, Buttons, cxImageComboBox, cxMemo, cxRichEdit, cxRadioGroup, Ora, jpeg, VirtualTable, MemDS, DBAccess, GenelDM, OraConstraint, OraStorage; type TTableConstraintsFrm = class(TForm) pc: TcxPageControl; tsKey: TcxTabSheet; tsCheck: TcxTabSheet; tsForeignKey: TcxTabSheet; tsOptions: TcxTabSheet; tsDDL: TcxTabSheet; edtDDL: TcxRichEdit; qTableColumns: TOraQuery; qTableColumnsCOLUMN_NAME: TStringField; qTableColumnsDATA_TYPE: TStringField; qTableColumnsCOLUMN_ID: TFloatField; dTableColumns: TDataSource; qKeyColumns: TVirtualTable; qKeyColumnsCOLUMN_NAME: TStringField; qKeyColumnsDATA_TYPE: TStringField; qKeyColumnsORDER: TStringField; qKeyColumnsSORT: TFloatField; dsKeyColumns: TDataSource; qTable: TOraQuery; StringField3: TStringField; tsStorage: TcxTabSheet; dsTable: TDataSource; qRefTable: TOraQuery; StringField1: TStringField; dsRefTable: TDataSource; qRefTableColumns: TOraQuery; StringField2: TStringField; StringField4: TStringField; FloatField1: TFloatField; dsRefTableColumns: TDataSource; qRefTableKeyColumns: TVirtualTable; StringField5: TStringField; StringField6: TStringField; StringField7: TStringField; FloatField2: TFloatField; dsRefTableKeyColumns: TDataSource; qExceptionTable: TOraQuery; StringField8: TStringField; dsExceptionTable: TDataSource; cxGroupBox4: TcxGroupBox; Label2: TLabel; Label3: TLabel; Label4: TLabel; sbtnAddKey: TSpeedButton; sbtnAddAllKey: TSpeedButton; sbtnRemoveKey: TSpeedButton; sbtnRemoveAllKey: TSpeedButton; edtKeyName: TcxTextEdit; lcKeyTableSchema: TcxLookupComboBox; lcKeyTable: TcxLookupComboBox; cbKeySystemName: TcxCheckBox; rgrpKeyType: TcxRadioGroup; gridKeyTableColums: TcxGrid; gridKeyTableColumsDBTableView1: TcxGridDBTableView; gridKeyTableColumsDBTableView1COLUMN_NAME: TcxGridDBColumn; gridKeyTableColumsDBTableView1Column1: TcxGridDBColumn; gridKeyTableColumsLevel1: TcxGridLevel; gridKeyIndexColums: TcxGrid; cxGridDBTableView1: TcxGridDBTableView; cxGridDBColumn1: TcxGridDBColumn; cxGridDBTableView4Column1: TcxGridDBColumn; cxGridLevel1: TcxGridLevel; cxGroupBox6: TcxGroupBox; Label17: TLabel; Label18: TLabel; Label19: TLabel; cxGroupBox2: TcxGroupBox; edtCheckConditions: TcxRichEdit; edtCheckName: TcxTextEdit; lcCheckTableSchema: TcxLookupComboBox; lcCheckTable: TcxLookupComboBox; cbCheckSystemName: TcxCheckBox; cxGroupBox1: TcxGroupBox; Label23: TLabel; Label24: TLabel; Label25: TLabel; cxGroupBox5: TcxGroupBox; sbtnAddFKey: TSpeedButton; sbtnAddAllFKey: TSpeedButton; sbtnRemoveFKey: TSpeedButton; sbtnRemoveAllFKey: TSpeedButton; cxGrid1: TcxGrid; cxGridDBTableView2: TcxGridDBTableView; cxGridDBColumn2: TcxGridDBColumn; cxGridDBColumn3: TcxGridDBColumn; cxGridLevel2: TcxGridLevel; cxGrid2: TcxGrid; cxGridDBTableView3: TcxGridDBTableView; cxGridDBColumn4: TcxGridDBColumn; cxGridDBColumn5: TcxGridDBColumn; cxGridLevel3: TcxGridLevel; edtForeignKeyName: TcxTextEdit; lcForeignTableSchema: TcxLookupComboBox; lcForeignTable: TcxLookupComboBox; cbForeignKeySystemName: TcxCheckBox; cxGroupBox7: TcxGroupBox; sbtnAddRKey: TSpeedButton; sbtnAddAllRKey: TSpeedButton; sbtnRemoveRKey: TSpeedButton; sbtnRemoveAllRKey: TSpeedButton; Label6: TLabel; Label8: TLabel; cxGrid3: TcxGrid; cxGridDBTableView4: TcxGridDBTableView; cxGridDBColumn6: TcxGridDBColumn; cxGridDBColumn7: TcxGridDBColumn; cxGridLevel4: TcxGridLevel; cxGrid4: TcxGrid; cxGridDBTableView5: TcxGridDBTableView; cxGridDBColumn8: TcxGridDBColumn; cxGridDBColumn9: TcxGridDBColumn; cxGridLevel5: TcxGridLevel; lcRefTableSchema: TcxLookupComboBox; lcRefTable: TcxLookupComboBox; cxGroupBox8: TcxGroupBox; Label7: TLabel; Label15: TLabel; edtPercentFree: TcxMaskEdit; cxGroupBox3: TcxGroupBox; Label11: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; Label29: TLabel; Label30: TLabel; Label31: TLabel; Label32: TLabel; edtInitialExtend: TcxMaskEdit; edtNextExtend: TcxMaskEdit; edtMinExtents: TcxMaskEdit; edtMaxExtents: TcxMaskEdit; edtPctIncrease: TcxMaskEdit; edtFreeList: TcxMaskEdit; edtFreeGroup: TcxMaskEdit; cbBufferPool: TcxImageComboBox; lcTablespace: TcxLookupComboBox; cbUIA: TcxCheckBox; cxGroupBox9: TcxGroupBox; rgrpStatus: TcxRadioGroup; rgrpValidation: TcxRadioGroup; rgrpDeferrable: TcxRadioGroup; rgrpRely: TcxRadioGroup; grpExceptions: TcxGroupBox; Label1: TLabel; Label5: TLabel; lcbExceptionSchema: TcxLookupComboBox; lcbExceptionTable: TcxLookupComboBox; cbDeferrable: TcxCheckBox; rgrpDeleteRule: TcxRadioGroup; cxGroupBox10: TcxGroupBox; btnCancel: TcxButton; btnExecute: TcxButton; Bevel1: TBevel; Bevel2: TBevel; Bevel3: TBevel; procedure lcKeyTableSchemaPropertiesEditValueChanged(Sender: TObject); procedure lcKeyTablePropertiesEditValueChanged(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure sbtnAddKeyClick(Sender: TObject); procedure sbtnAddAllKeyClick(Sender: TObject); procedure sbtnRemoveKeyClick(Sender: TObject); procedure sbtnRemoveAllKeyClick(Sender: TObject); procedure lcCheckTableSchemaPropertiesEditValueChanged( Sender: TObject); procedure lcForeignTableSchemaPropertiesEditValueChanged( Sender: TObject); procedure lcForeignTablePropertiesEditValueChanged(Sender: TObject); procedure sbtnAddFKeyClick(Sender: TObject); procedure sbtnAddAllFKeyClick(Sender: TObject); procedure sbtnRemoveFKeyClick(Sender: TObject); procedure sbtnRemoveAllFKeyClick(Sender: TObject); procedure lcRefTableSchemaPropertiesEditValueChanged(Sender: TObject); procedure lcRefTablePropertiesEditValueChanged(Sender: TObject); procedure sbtnAddRKeyClick(Sender: TObject); procedure sbtnAddAllRKeyClick(Sender: TObject); procedure sbtnRemoveRKeyClick(Sender: TObject); procedure sbtnRemoveAllRKeyClick(Sender: TObject); procedure cbDeferrablePropertiesChange(Sender: TObject); procedure btnExecuteClick(Sender: TObject); procedure pcPageChanging(Sender: TObject; NewPage: TcxTabSheet; var AllowChange: Boolean); procedure rgrpValidationPropertiesChange(Sender: TObject); procedure cxLookupComboBox1PropertiesEditValueChanged(Sender: TObject); private { Private declarations } FConstraint: TConstraint; procedure GetConstraintDetail; function SetConstraintDetail: boolean; public { Public declarations } function Init(Constraint: TConstraint): boolean; end; var TableConstraintsFrm: TTableConstraintsFrm; implementation {$R *.dfm} uses frmSchemaBrowser, OraScripts, Util, OraTable, VisualOptions; function TTableConstraintsFrm.Init(Constraint: TConstraint): boolean; begin TableConstraintsFrm := TTableConstraintsFrm.Create(Application); Self := TableConstraintsFrm; DMGenel.ChangeLanguage(self); ChangeVisualGUI(self); FConstraint := Constraint; dmGenel.ReLoad(FConstraint.OraSession); qTable.Session := FConstraint.OraSession; qTableColumns.Session := FConstraint.OraSession; tsKey.TabVisible := false; tsCheck.TabVisible := false; tsForeignKey.TabVisible := false; GetConstraintDetail; ShowModal; result := ModalResult = mrOk; Free; end; procedure TTableConstraintsFrm.btnCancelClick(Sender: TObject); begin close; end; procedure TTableConstraintsFrm.GetConstraintDetail; begin if FConstraint.ConstraintType in [ctPrimary, ctUniqe] then begin if FConstraint.ConstraintName = '' then caption := 'Create Key' else caption := 'Alter Key '+FConstraint.ConstraintName; tsKey.TabVisible := true; pc.ActivePage := tsKey; edtKeyName.Text := FConstraint.ConstraintName; lcKeyTableSchema.EditValue := FConstraint.Owner; qTable.SQL.Text := GetTables(FConstraint.Owner); qTable.Open; lcKeyTable.EditValue := FConstraint.TableName; end; if FConstraint.ConstraintType = ctCheck then begin if FConstraint.ConstraintName = '' then caption := 'Create Check' else caption := 'Alter Check '+FConstraint.ConstraintName; tsCheck.TabVisible := true; pc.ActivePage := tsCheck; edtCheckName.Text := FConstraint.ConstraintName; lcCheckTableSchema.EditValue := FConstraint.Owner; qTable.SQL.Text := GetTables(FConstraint.Owner); qTable.Open; lcCheckTable.EditValue := FConstraint.TableName; end; if FConstraint.ConstraintType = ctForeignKey then begin if FConstraint.ConstraintName = '' then caption := 'Create Foreign Key' else caption := 'Alter Foreign Key '+FConstraint.ConstraintName; tsForeignKey.TabVisible := true; pc.ActivePage := tsForeignKey; edtForeignKeyName.Text := FConstraint.ConstraintName; lcForeignTableSchema.EditValue := FConstraint.Owner; qTable.SQL.Text := GetTables(FConstraint.Owner); qTable.Open; lcForeignTable.EditValue := FConstraint.TableName; lcRefTableSchema.EditValue := FConstraint.Owner; end; rgrpDeleteRule.Visible := FConstraint.ConstraintType = ctForeignKey; end; procedure TTableConstraintsFrm.cbDeferrablePropertiesChange( Sender: TObject); begin rgrpDeferrable.Enabled := cbDeferrable.Checked; if not cbDeferrable.Checked then rgrpDeferrable.ItemIndex := 0; end; procedure TTableConstraintsFrm.rgrpValidationPropertiesChange( Sender: TObject); begin grpExceptions.Enabled := rgrpValidation.ItemIndex = 1; end; procedure TTableConstraintsFrm.cxLookupComboBox1PropertiesEditValueChanged( Sender: TObject); begin qExceptionTable.close; if lcbExceptionSchema.Text = '' then exit; qExceptionTable.SQL.Text := GetTables(lcbExceptionSchema.Text); qExceptionTable.Open; end; function TTableConstraintsFrm.SetConstraintDetail: boolean; var FColumn: TColumn; FColumnList : TColumnList; FRefColumnList : TColumnList; begin result := true; if FConstraint.ConstraintType in [ctPrimary, ctUniqe] then begin if edtKeyName.Text = '' then begin MessageDlg('Key Name must be specified', mtWarning, [mbOk], 0); result:= false; exit; end; if (qKeyColumns.RecordCount = 0) then begin MessageDlg('Key Columns must be required', mtWarning, [mbOk], 0); result:= false; exit; end; FColumnList := TColumnList.Create; qKeyColumns.first; while not qKeyColumns.Eof do begin FColumn := TColumn.Create; FColumn.ColumnName := qKeyColumns.FieldByName('COLUMN_NAME').AsString; FColumn.DataType := qKeyColumns.FieldByName('DATA_TYPE').AsString; FColumnList.Add(FColumn); FColumn.NewInstance; FColumnList.NewInstance; qKeyColumns.Next; end; with FConstraint do begin ConstraintName := edtKeyName.Text; Owner := FConstraint.Owner; if rgrpKeyType.ItemIndex = 0 then ConstraintType := ctPrimary else ConstraintType := ctUniqe; TableName := lcKeyTable.Text; ConstraitColumns := FColumnList; if cbKeySystemName.Checked then Generated := 'GENERATED NAME' else Generated := 'USER NAME'; end; //FConstraint end; //FConstraintType = ctKey if FConstraint.ConstraintType = ctCheck then begin if edtCheckName.Text = '' then begin MessageDlg('Check Constraint Name must be specified', mtWarning, [mbOk], 0); result:= false; exit; end; if (edtCheckConditions.Text = '') then begin MessageDlg('Chechk Conditions must be required', mtWarning, [mbOk], 0); result:= false; exit; end; with FConstraint do begin ConstraintName := edtCheckName.Text; Owner := FConstraint.Owner; ConstraintType := ctCheck; TableName := lcCheckTable.Text; SearchCondidion := edtCheckConditions.Text; if cbCheckSystemName.Checked then Generated := 'GENERATED NAME' else Generated := 'USER NAME'; end; //FConstraint end; //FConstraintType = ctCheck if FConstraint.ConstraintType = ctForeignKey then begin if edtForeignKeyName.Text = '' then begin MessageDlg('Foreign Key Name must be specified', mtWarning, [mbOk], 0); result:= false; exit; end; if (qKeyColumns.RecordCount = 0) then begin MessageDlg('Foreign Key Columns must be required', mtWarning, [mbOk], 0); result:= false; exit; end; if (qRefTableKeyColumns.RecordCount = 0) then begin MessageDlg('Referancel Key Columns must be required', mtWarning, [mbOk], 0); result:= false; exit; end; FColumnList := TColumnList.Create; qKeyColumns.first; while not qKeyColumns.Eof do begin FColumn := TColumn.Create; FColumn.ColumnName := qKeyColumns.FieldByName('COLUMN_NAME').AsString; FColumn.DataType := qKeyColumns.FieldByName('DATA_TYPE').AsString; FColumnList.Add(FColumn); FColumn.NewInstance; FColumnList.NewInstance; qKeyColumns.Next; end; FRefColumnList := TColumnList.Create; qRefTableKeyColumns.First; while not qRefTableKeyColumns.Eof do begin FColumn := TColumn.Create; FColumn.ColumnName := qRefTableKeyColumns.FieldByName('COLUMN_NAME').AsString; FColumn.DataType := qRefTableKeyColumns.FieldByName('DATA_TYPE').AsString; FRefColumnList.Add(FColumn); FColumn.NewInstance; FRefColumnList.NewInstance; qRefTableKeyColumns.Next; end; with FConstraint do begin ConstraintName := edtForeignKeyName.Text; Owner := FConstraint.Owner; ConstraintType := ctForeignKey; TableName := lcForeignTable.Text; ConstraitColumns := FColumnList; ReferencedColumns := FRefColumnList; ROwner := lcRefTableSchema.Text; RConstraintName := lcRefTable.Text; if cbForeignKeySystemName.Checked then Generated := 'GENERATED NAME' else Generated := 'USER NAME'; end; //FConstraint end; //FConstraintType = ctForeign FConstraint.UsingIndexAttributes := cbUIA.Checked; if cbUIA.Checked then with FConstraint do begin with PhsicalAttributes do begin PercentFree:= edtPercentFree.Text; Tablespace:= lcTablespace.Text; InitialExtent:=edtInitialExtend.Text; NextExtent:= edtNextExtend.Text; MinExtent:= edtMinExtents.Text; MaxExtent:= edtMaxExtents.Text; PctIncrease:= edtPctIncrease.Text; BufferPool:= TBufferPool(cbBufferPool.ItemIndex); FreeLists:= edtFreeList.Text; FreeGroups:= edtFreeGroup.Text; end; end; if rgrpStatus.ItemIndex = 0 then FConstraint.Status := 'DISABLE' else FConstraint.Status := 'ENABLE'; if rgrpValidation.ItemIndex = 0 then FConstraint.Validated := 'NOVALIDATE' else FConstraint.Validated := 'VALIDATE'; if cbDeferrable.Checked then FConstraint.Deferrable := 'DEFERRABLE' else FConstraint.Deferrable := 'NOT DEFERRABLE'; if rgrpDeferrable.ItemIndex = 0 then FConstraint.Deferred := 'DEFERRABLE INITIALLY IMMEDIATE' else FConstraint.Deferred := 'DEFERRABLE INITIALLY DEFERRED'; if rgrpRely.ItemIndex = 1 then FConstraint.Rely := 'RELY' else FConstraint.Rely := ''; if rgrpDeleteRule.ItemIndex = 0 then FConstraint.DeleteRule := 'NO ACTION'; if rgrpDeleteRule.ItemIndex = 1 then FConstraint.DeleteRule := 'SET NULL'; if rgrpDeleteRule.ItemIndex = 2 then FConstraint.DeleteRule := 'CASCADE'; FConstraint.Bad := ''; FConstraint.IndexOwner := ''; FConstraint.IndexName := ''; FConstraint.Invalid := ''; FConstraint.ViewRelated := ''; FConstraint.ExceptionSchema := lcbExceptionSchema.Text; FConstraint.ExceptionTable := lcbExceptionTable.Text; end; //SetConstraintDetail {************************** K E Y *********************************************} procedure TTableConstraintsFrm.lcKeyTableSchemaPropertiesEditValueChanged( Sender: TObject); begin qTable.close; qTableColumns.Close; qKeyColumns.close; if lcKeyTableSchema.Text = '' then exit; qTable.SQL.Text := GetTables(lcKeyTableSchema.Text); qTable.Open; end; procedure TTableConstraintsFrm.lcKeyTablePropertiesEditValueChanged( Sender: TObject); begin QTableColumns.Close; if qKeyColumns.Active then qKeyColumns.Clear; qKeyColumns.close; if lcKeyTable.Text = '' then exit; QTableColumns.SQL.Text := GetTableColumns(lcKeyTable.Text, lcKeyTableSchema.Text, ''); QTableColumns.Open; qKeyColumns.Open; end; procedure TTableConstraintsFrm.sbtnAddKeyClick(Sender: TObject); begin if not QTableColumns.Active then exit; if QTableColumns.RecordCount <= 0 then exit; qKeyColumns.Append; qKeyColumns.Fields[0].AsString := QTableColumns.Fields[0].AsString; qKeyColumns.Fields[1].AsString := QTableColumns.Fields[1].AsString; qKeyColumns.Post; QTableColumns.Delete; end; procedure TTableConstraintsFrm.sbtnAddAllKeyClick(Sender: TObject); begin if not QTableColumns.Active then exit; if QTableColumns.RecordCount <= 0 then exit; QTableColumns.First; while not QTableColumns.Eof do sbtnAddKey.Click; end; procedure TTableConstraintsFrm.sbtnRemoveKeyClick(Sender: TObject); begin if not QTableColumns.Active then exit; if qKeyColumns.RecordCount <= 0 then exit; QTableColumns.Append; QTableColumns.Fields[0].AsString := qKeyColumns.Fields[0].AsString; QTableColumns.Fields[1].AsString := qKeyColumns.Fields[1].AsString; QTableColumns.Post; qKeyColumns.Delete; end; procedure TTableConstraintsFrm.sbtnRemoveAllKeyClick(Sender: TObject); begin if not QTableColumns.Active then exit; if qKeyColumns.RecordCount <= 0 then exit; qKeyColumns.First; while not qKeyColumns.Eof do sbtnRemoveKey.Click; end; {************************** C H E C K ******************************************} procedure TTableConstraintsFrm.lcCheckTableSchemaPropertiesEditValueChanged( Sender: TObject); begin qTable.close; if lcCheckTableSchema.Text = '' then exit; qTable.SQL.Text := GetTables(lcCheckTableSchema.Text); qTable.Open; end; {************************** F O R E I G N *************************************} procedure TTableConstraintsFrm.lcForeignTableSchemaPropertiesEditValueChanged( Sender: TObject); begin qTable.close; qTableColumns.Close; if qKeyColumns.Active then qKeyColumns.Clear; qKeyColumns.close; if lcForeignTableSchema.Text = '' then exit; qTable.SQL.Text := GetTables(lcForeignTableSchema.Text); qTable.Open; end; procedure TTableConstraintsFrm.lcForeignTablePropertiesEditValueChanged( Sender: TObject); begin QTableColumns.Close; if qKeyColumns.Active then qKeyColumns.Clear; qKeyColumns.close; if lcForeignTable.Text = '' then exit; QTableColumns.SQL.Text := GetTableColumns(lcForeignTable.Text, lcForeignTableSchema.Text, ''); QTableColumns.Open; qKeyColumns.Open; end; procedure TTableConstraintsFrm.sbtnAddFKeyClick(Sender: TObject); begin if not QTableColumns.Active then exit; if QTableColumns.RecordCount <= 0 then exit; qKeyColumns.Append; qKeyColumns.Fields[0].AsString := QTableColumns.Fields[0].AsString; qKeyColumns.Fields[1].AsString := QTableColumns.Fields[1].AsString; qKeyColumns.Post; QTableColumns.Delete; end; procedure TTableConstraintsFrm.sbtnAddAllFKeyClick(Sender: TObject); begin if not QTableColumns.Active then exit; if QTableColumns.RecordCount <= 0 then exit; QTableColumns.First; while not QTableColumns.Eof do sbtnAddFKey.Click; end; procedure TTableConstraintsFrm.sbtnRemoveFKeyClick(Sender: TObject); begin if not QTableColumns.Active then exit; if qKeyColumns.RecordCount <= 0 then exit; QTableColumns.Append; QTableColumns.Fields[0].AsString := qKeyColumns.Fields[0].AsString; QTableColumns.Fields[1].AsString := qKeyColumns.Fields[1].AsString; QTableColumns.Post; qKeyColumns.Delete; end; procedure TTableConstraintsFrm.sbtnRemoveAllFKeyClick(Sender: TObject); begin if not QTableColumns.Active then exit; if qKeyColumns.RecordCount <= 0 then exit; qKeyColumns.First; while not qKeyColumns.Eof do sbtnRemoveFKey.Click; end; procedure TTableConstraintsFrm.lcRefTableSchemaPropertiesEditValueChanged( Sender: TObject); begin qRefTable.close; qRefTableColumns.Close; if qRefTableKeyColumns.Active then qRefTableKeyColumns.Clear; qRefTableKeyColumns.close; if lcRefTableSchema.Text = '' then exit; qRefTable.SQL.Text := GetTables(lcRefTableSchema.Text); qRefTable.Open; end; procedure TTableConstraintsFrm.lcRefTablePropertiesEditValueChanged( Sender: TObject); begin qRefTableColumns.Close; if qRefTableKeyColumns.Active then qRefTableKeyColumns.Clear; qRefTableKeyColumns.close; if lcRefTable.Text = '' then exit; qRefTableColumns.SQL.Text := GetTableColumns(lcRefTable.Text, lcRefTableSchema.Text, ''); qRefTableColumns.Open; qRefTableKeyColumns.Open; end; procedure TTableConstraintsFrm.sbtnAddRKeyClick(Sender: TObject); begin if not qRefTableColumns.Active then exit; if qRefTableColumns.RecordCount <= 0 then exit; qRefTableKeyColumns.Append; qRefTableKeyColumns.Fields[0].AsString := qRefTableColumns.Fields[0].AsString; qRefTableKeyColumns.Fields[1].AsString := qRefTableColumns.Fields[1].AsString; qRefTableKeyColumns.Post; qRefTableColumns.Delete; end; procedure TTableConstraintsFrm.sbtnAddAllRKeyClick(Sender: TObject); begin if not qRefTableColumns.Active then exit; if qRefTableColumns.RecordCount <= 0 then exit; qRefTableColumns.First; while not qRefTableColumns.Eof do sbtnAddRKey.Click; end; procedure TTableConstraintsFrm.sbtnRemoveRKeyClick(Sender: TObject); begin if not qRefTableKeyColumns.Active then exit; if qRefTableKeyColumns.RecordCount <= 0 then exit; qRefTableColumns.Append; qRefTableColumns.Fields[0].AsString := qRefTableKeyColumns.Fields[0].AsString; qRefTableColumns.Fields[1].AsString := qRefTableKeyColumns.Fields[1].AsString; qRefTableColumns.Post; qRefTableKeyColumns.Delete; end; procedure TTableConstraintsFrm.sbtnRemoveAllRKeyClick(Sender: TObject); begin if not qRefTableKeyColumns.Active then exit; if qRefTableKeyColumns.RecordCount <= 0 then exit; qRefTableKeyColumns.First; while not qRefTableKeyColumns.Eof do sbtnRemoveRKey.Click; end; procedure TTableConstraintsFrm.btnExecuteClick(Sender: TObject); begin if not SetConstraintDetail then exit; edtDDL.Text := FConstraint.GetDDL; if FConstraint.CreateConstraint(edtDDL.Text) then ModalResult := mrOK; end; procedure TTableConstraintsFrm.pcPageChanging(Sender: TObject; NewPage: TcxTabSheet; var AllowChange: Boolean); begin if NewPage = tsDDL then begin if not SetConstraintDetail then AllowChange := false else edtDDL.Text := FConstraint.GetDDL; CodeColors(self, 'Default', edtDDL, false); end; end; end.
unit ParamsForms; {$mode objfpc}{$H+} {** * This file is part of the "Mini Library" * * @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html) * See the file COPYING.MLGPL, included in this distribution, * @author Zaher Dirkey <zaher, zaherdirkey> *} interface uses LCLProc, LCLIntf, LCLType, Classes, SysUtils, FileUtil, StdCtrls, LResources, Forms, Controls, Graphics, Dialogs, mncConnections, mncSQL; type { TParamsForm } TParamsForm = class(TForm) CancelBtn: TButton; OkBtn: TButton; procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); private public end; function ShowSQLParams(Command: TmncCommand): Boolean; implementation {$R *.lfm} type TsqlvParamEdit = class(TCustomEdit) protected procedure Change; override; public CheckBox: TCheckBox; Param: TmncCustomField; end; function ShowSQLParams(Command: TmncCommand): Boolean; var y: Integer; r: TRect; i: Integer; aForm: TParamsForm; aEdit: TsqlvParamEdit; aCheckList: TList; aEditList: TList; aCheckBox: TCheckBox; const xStart = 6; yStart = 4; begin if Command.Params.Count = 0 then Result := True else begin aForm := TParamsForm.Create(Application); with aForm do begin aEditList := TList.Create; aCheckList := TList.Create; try y := yStart; for i := 0 to Command.Params.Count - 1 do begin aCheckBox := TCheckBox.Create(aForm); aCheckBox.Parent := aForm; aCheckBox.AutoSize := True; aCheckBox.Caption := Command.Params.Items[i].Name; aCheckBox.Hint := Command.Params.Items[i].Name; //aCheckBox.Alignment := taLeftJustify; aCheckBox.Top := y; aCheckBox.Left := xStart; y := y + aCheckBox.Height + 3; aCheckList.Add(aCheckBox); end; for i := 0 to Command.Params.Count - 1 do begin aEdit := TsqlvParamEdit.Create(aForm); aEdit.Parent := aForm; aEdit.Param := Command.Params.Items[i]; aEdit.CheckBox := TCheckBox(aCheckList[i]); r := aEdit.CheckBox.BoundsRect; r.Left := r.Right + 3; r.Right := ClientWidth - 3; aEdit.BoundsRect := r; aEdit.Anchors := [akTop, akLeft, akRight]; aEditList.Add(aEdit); end; ClientHeight := y + OkBtn.Height + 3; ActiveControl := TsqlvParamEdit(aEditList[0]); Result := ShowModal = mrOK; if Result then begin for i := 0 to aEditList.Count-1 do begin if TsqlvParamEdit(aEditList[i]).CheckBox.Checked then TsqlvParamEdit(aEditList[i]).Param.AsString := TsqlvParamEdit(aEditList[i]).Text else TsqlvParamEdit(aEditList[i]).Param.Clear; end; end; finally FreeAndNil(aEditList); FreeAndNil(aCheckList); Free; end; end; end; end; procedure TParamsForm.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin CloseAction := caHide; end; procedure TParamsForm.FormCreate(Sender: TObject); begin end; { TsqlvParamEdit } procedure TsqlvParamEdit.Change; begin inherited; CheckBox.Checked := True; end; end.
unit untBlog; {$mode objfpc}{$H+} interface uses Classes, SysUtils, //unit is using HTTPDefs, RegExpr, math, sqldb, db, //also system units untDB; type { untBlog } { TuntBlog } TuntBlog = class private { private declarations } class var APPURL: string; public { public declarations } class procedure setAPPURL( url: string); class function getAPPURL(): string; class function getBlog( TagParams: TStringList; ARequest: TRequest; db:string; URL: string ): string; class function getBlogCommentCount( postid: string ): string; class function getBlogPostTags( postid: string ): string; class function getBlogComments( postid: string ): string; class function setBlogComment( Arequest: TRequest; db: string): boolean; class function getBlogCommentLast(): string; class function setBlogCommentForm( postid: string ): string; class function getBlogConfigItem( strItem: string) : string; constructor Create; destructor Destroy; override; end; implementation class procedure TuntBlog.setAPPURL(url: string); begin self.APPURL:= url; end; class function TuntBlog.getAPPURL: string; begin Result:= self.APPURL; end; class function TuntBlog.getBlog( TagParams: Tstringlist; ARequest: TRequest; db: string; URL: string ): string; var straux, straux2, strURL : string; intinicio, intlimite, inttotal: integer; //função interna para tratar a URL da paginação function geraURLpaginada( strPgNum: string ): string; var strPg: String; begin if( Pos('?', ARequest.URL) <> 0 ) then //verifica se já existe algum 'lmt' if ExecRegExpr( 'lmt=', ARequest.URL ) then begin //achou campo na URL, só substitui strPg:= 'lmt=' + strPgNum; Result:= ReplaceRegExpr('lmt=[0-9]+', ARequest.URL, strPg, false) end else Result:= ARequest.URL + '&lmt=' + strPgNum //ReplaceRegExpr('lmt=([0-9]+)', strURL, 'lmt=', False) else Result:= ARequest.URL + '?lmt=' + strPgNum; end; begin setAPPURL( URL ); if TuntDB.Connect( db ) then begin try with SQLQuery do begin //zera a query Close; //se for solicitado um post específico, mostra ele if ARequest.QueryFields.Values['pst'] <> '' then begin SQL.Add('SELECT id, title, strftime("%Y-%m-%d %H:%M:%S", datahora) AS `datahora`, message '); SQL.Add('FROM tbblogpost '); SQL.Add('WHERE id='+ ARequest.QueryFields.Values['pst'] +';'); Open; if RecordCount > 0 then begin straux := ''; straux:= straux + '<div class='''+ TagParams.Values['postbody'] +''' >'; straux:= straux + '<h1>'+ FieldByName('title').AsString +'</h1>'; straux:= straux + '<p>'+ FieldByName('message').AsString +'</p>'; //data, autor, e tags straux:= straux + '<div class='''+ TagParams.Values['postinfo'] +''' >' + FieldByName('datahora').AsString + ' '; //autor desabilitado //straux:= straux + getBlogPostAuthor( FieldByName('datahora').AsString ); //tags straux:= straux + getBlogPostTags( FieldByName('id').AsString ); //fim div straux:= straux + '</div>'; //fim do post straux:= straux + '</div>'; //prepara comentários e marca com uma âncora straux:= straux + '<div><a name="comment">Comentários:</a></div>'; //comentários completos do post straux:= straux + '<div class="'+ TagParams.Values['postcomments'] +'">' + getBlogComments( FieldByName('id').AsString ) + '</div>'; //form para envio de novo comentárip straux:= straux + setBlogCommentForm( FieldByName('id').AsString ); Result:= straux; end else begin //não há posts definidos Result:= '<b>Post não encontrado!</b>'; end; end else //se for solicitado mostrar os posts por tag... if ARequest.QueryFields.Values['tag'] <> '' then begin straux:= '<h2>Exibindo posts por assunto:</h2>'; //verifica se algum limite foi passado if( ARequest.QueryFields.Values['lmt'] <> '') then intlimite:= StrToInt( ARequest.QueryFields.Values['lmt'] ) else intlimite:= 0; //multiplica o limite passado pela quantidade por página guardada no banco intinicio:= intlimite * StrToInt( getBlogConfigItem('postlimit') ); //pega o total para trabalhar SQL.Add('SELECT COUNT(tbbp.id) AS `total` '); SQL.Add('FROM tbblogpost AS `tbbp`, tbblogtags AS `tbbt`, tbblogposttags AS `tbbpt` '); SQL.Add('WHERE tbbpt.idpost = tbbp.id AND tbbpt.idcategory = tbbt.id AND tbbpt.idcategory = '+ARequest.QueryFields.Values['tag']+' '); Open; //calcula total de páginas inttotal:= ceil( FieldByName('total').AsInteger / StrToInt( getBlogConfigItem('postlimit') ) ); //realiza consulta aos posts de acordo com a tag esperada Close; SQL.Clear; SQL.Add('SELECT tbbp.id, tbbp.title, tbbp.datahora, tbbp.message, tbbt.name '); SQL.Add('FROM tbblogpost AS `tbbp`, tbblogtags AS `tbbt`, tbblogposttags AS `tbbpt` '); SQL.Add('WHERE tbbpt.idpost = tbbp.id AND tbbpt.idcategory = tbbt.id AND tbbpt.idcategory = '+ARequest.QueryFields.Values['tag']+' '); SQL.Add('ORDER BY tbbp.datahora DESC '); SQL.Add('LIMIT '+ IntToStr( intinicio) +','+ getBlogConfigItem('postlimit') +'; '); Open; if RecordCount > 0 then begin while not EOF do begin straux:= straux + '<div class='''+ TagParams.Values['postbody'] +''' >'; straux:= straux + '<h1>'+ FieldByName('title').AsString +'</h1>'; straux:= straux + '<p>'+ FieldByName('message').AsString +'</p>'; //data, autor, e tags straux:= straux + '<div class='''+ TagParams.Values['postinfo'] +''' >' + FieldByName('datahora').AsString + ' '; //autor desabilitado //straux:= straux + getBlogPostAuthor( FieldByName('datahora').AsString ); //tags straux:= straux + getBlogPostTags( FieldByName('id').AsString ); //fim div straux:= straux + '</div>'; //pega quantidade de comentários e cria link if( Pos('?', ARequest.URL) <> 0 ) then strURL := ARequest.URL + '&' else strURL:= '?'; straux:= straux + '<a href="'+ strURL +'pst='+ FieldByName('id').AsString +'#comment">' + getBlogCommentCount( FieldByName('id').AsString ) +'</a>'; //fim do post straux:= straux + '</div>'; next; end; //cria paginação straux2:= '<div class="'+ TagParams.Values['postpages'] +'">'; //anterior if( intlimite > 0 ) then straux2:= straux2 + '<a href="'+ geraURLpaginada( IntToStr( intlimite -1 ) ) +'">'+ getBlogConfigItem('prevpoststr') +'</a> | ' else //cria link desabilitado straux2:= straux2 + '<a disabled="true">'+ getBlogConfigItem('prevpoststr') +'</a> | '; //próximo if( intlimite < (inttotal-1) ) then straux2:= straux2 + '<a href="'+ geraURLpaginada( IntToStr( intlimite + 1 ) ) +'">'+ getBlogConfigItem('nextpoststr') +'</a>' else //cria link desabilitado straux2:= straux2 + '<a disabled="true">'+ getBlogConfigItem('nextpoststr') +'</a>'; straux2:= straux2 + '</div>'; Result:= straux + straux2; end else begin //não há posts definidos Result:= '<b>Sem posts nesta categoria!</b>'; end; end else begin //se não, mostra todos //de acordo com a paginação //verifica se algum limite foi passado if( ARequest.QueryFields.Values['lmt'] <> '') then intlimite:= StrToInt( ARequest.QueryFields.Values['lmt'] ) else intlimite:= 0; //multiplica o limite passado pela quantidade por página guardada no banco intinicio:= intlimite * StrToInt( getBlogConfigItem('postlimit') ); //pega o total para trabalhar Sql.Text:= 'SELECT COUNT(id) AS `total` FROM tbblogpost;'; Open; //calcula total de páginas inttotal:= ceil( FieldByName('total').AsInteger / StrToInt( getBlogConfigItem('postlimit') ) ); //monta query com o limite Close; SQL.Clear; SQL.Add('SELECT id, title, strftime("%Y-%m-%d %H:%M:%S", datahora) AS `datahora`, message '); SQL.Add('FROM tbblogpost '); SQL.Add('ORDER BY datahora DESC '); SQL.Add('LIMIT '+ IntToStr( intinicio) +','+ getBlogConfigItem('postlimit') +'; '); Open; if RecordCount > 0 then begin straux := ''; while not EOF do begin straux:= straux + '<div class='''+ TagParams.Values['postbody'] +''' >'; straux:= straux + '<h1>'+ FieldByName('title').AsString +'</h1>'; straux:= straux + '<p>'+ FieldByName('message').AsString +'</p>'; //data, autor, e tags straux:= straux + '<div class='''+ TagParams.Values['postinfo'] +''' >' + FieldByName('datahora').AsString + ' '; //autor desabilitado //straux:= straux + getBlogPostAuthor( FieldByName('datahora').AsString ); //tags straux:= straux + getBlogPostTags( FieldByName('id').AsString ); //fim div straux:= straux + '</div>'; //pega quantidade de comentários e cria link if( Pos('?', ARequest.URL) <> 0 ) then strURL := ARequest.URL + '&' else strURL:= '?'; straux:= straux + '<a href="'+ strURL +'pst='+ FieldByName('id').AsString +'#comment">' + getBlogCommentCount( FieldByName('id').AsString ) +'</a>'; //fim do post straux:= straux + '</div>'; next; end; //cria paginação straux2:= '<div class="'+ TagParams.Values['postpages'] +'">'; //anterior if( intlimite > 0 ) then straux2:= straux2 + '<a href="'+ geraURLpaginada( IntToStr( intlimite -1 ) ) +'">'+ getBlogConfigItem('prevpoststr') +'</a> | ' else //cria link desabilitado straux2:= straux2 + '<a disabled="true">'+ getBlogConfigItem('prevpoststr') +'</a> | '; //próximo if( intlimite < (inttotal-1) ) then straux2:= straux2 + '<a href="'+ geraURLpaginada( IntToStr( intlimite + 1 ) ) +'">'+ getBlogConfigItem('nextpoststr') +'</a>' else //cria link desabilitado straux2:= straux2 + '<a disabled="true">'+ getBlogConfigItem('nextpoststr') +'</a>'; straux2:= straux2 + '</div>'; Result:= straux + straux2; end else begin //não há posts definidos Result:= '<b>Sem posts por enquanto!</b>'; end; end; //end todos os posts end; //end with except on E: EDatabaseError do begin Result:= '<b>Erro na base de dados!</b> Motivo: '+ E.Message; end; end; end; //free memory TuntDB.Disconnect(); end; class function TuntBlog.getBlogCommentCount( postid: string ): string; var qryAux : TSQLQuery; begin try qryAux := TSQLQuery.Create(nil); qryAux.DataBase := SQLite3Con; qryAux.Transaction := SQLTrans; with qryAux do begin Close; SQL.Text:= 'SELECT COUNT(idpost) AS `total` FROM tbblogpostcomments WHERE idpost='+postid+';'; Open; if RecordCount > 0 then begin Result:= FieldByName('total').AsString + ' ' + getBlogConfigItem('commentstr'); end; end; qryAux.Destroy; except on E: EDatabaseError do begin Result:= '<b>Erro na base de dados!</b> Motivo: ' + E.Message; end; end; end; class function TuntBlog.getBlogPostTags( postid: string ): string; var qryAux : TSQLQuery; straux: string; begin try qryAux := TSQLQuery.Create(nil); qryAux.DataBase := SQLite3Con; qryAux.Transaction := SQLTrans; with qryAux do begin Close; SQL.Add('SELECT tbtag.id AS `tagId`, tbtag.name AS `tagName` '); SQL.Add('FROM tbblogtags AS `tbtag`, tbblogposttags AS `tbbpt` '); SQL.Add('WHERE tbbpt.idcategory = tbtag.id AND tbbpt.idpost='+ postid +' '); SQL.Add('ORDER BY tbtag.name'); Open; if RecordCount > 0 then begin straux := ''; while not EOF do begin //monsta link de cada tag (assunto) relativo ao post straux:= straux + '<a href="tag='+ FieldByName('tagId').AsString +'">'+ FieldByName('tagName').AsString + '</a> '; next; end; Result:= straux; end else begin Result:= 'Sem Assunto'; end; end; qryAux.Destroy; except Result:= '<b>Não foi possível carregar os assuntos!</b>'; end; end; class function TuntBlog.getBlogComments( postid: string ): string; var qryAux : TSQLQuery; straux: string; begin try qryAux := TSQLQuery.Create(nil); qryAux.DataBase := SQLite3Con; qryAux.Transaction := SQLTrans; with qryAux do begin Close; SQL.Add('SELECT tc.name, tc.data, tc.site, tc.message '); SQL.Add('FROM tbblogcomments AS `tc`, tbblogpostcomments AS `tbpc` '); SQL.Add('WHERE tc.id = tbpc.idcomment AND tbpc.idpost = '+ postid +' '); SQL.Add('ORDER BY tc.data DESC;'); Open; if RecordCount > 0 then begin straux := '<ol>'; while not EOF do begin straux:= straux + '<li>'; //testa se o fulano tem site para gerar o link if ( FieldByName('site').AsString <> EmptyStr ) then straux:= straux + '<i><strong><a href="'+ FieldByName('site').AsString +'" target="new">'+ FieldByName('name').AsString +'</a></strong> em ' else straux:= straux + '<i><strong>'+ FieldByName('name').AsString +'</strong> em '; straux:= straux + FieldByName('data').AsString +'</i>:'; straux:= straux + '<p>'+ FieldByName('message').AsString +'</p>'; //fim do comentário straux:= straux + '</li>'; next; end; //encerra lista de comentários straux:= straux + '</ol>'; Result:= straux; end else begin Result:= 'Ainda sem comentários, seja o primeiro!'; end; end; qryAux.Destroy; except on E: Edatabaseerror do begin Result:= '<b>Não foi possível ler os comentários!</b> Motivo: ' + E.Message; end; end; end; class function TuntBlog.setBlogComment(Arequest: TRequest; db: string): boolean; var straux : string; begin if TuntDB.Connect( db ) then begin try if Arequest.QueryFields.Values['r'] <> EmptyStr then begin straux:= Arequest.QueryFields.Values['r']; if Pos('pst=', straux) > 0 then Delete( straux, 1, Pos('pst=', straux)+3 ); end else straux:= Arequest.ContentFields.Values['postID']; with SQLQuery do begin Close; SQL.Add('INSERT INTO tbblogcomments(name, email, site, message, data) '); SQL.Add('VALUES(:name, :email, :site, :message, :data)'); ParamByName('name').AsString:= ARequest.ContentFields.Values['edtNome']; ParamByName('email').AsString:= ARequest.ContentFields.Values['edtMail']; ParamByName('site').AsString:= ARequest.ContentFields.Values['edtSite']; ParamByName('message').AsString:= ARequest.ContentFields.Values['txtMsg']; ParamByName('data').AsString:= DateToStr( Now() );//FormatDateTime( 'dd-mm-yyyy', Now() ); ExecSQL; //Liga o commentário ao post SQL.Clear; SQL.Add('INSERT INTO tbblogpostcomments(idpost, idcomment) '); SQL.Add('VALUES(:idpost, :idcomment)'); ParamByName('idpost').AsString:= straux; ParamByName('idcomment').AsString:= getBlogCommentLast(); ExecSQL; //realizou alterações, commit. SQLTrans.Commit; Result:= true; end; except //SQLTrans.Rollback; Result:= false; end; end; TuntDB.Disconnect(); end; class function TuntBlog.getBlogCommentLast: string; var qryAux: TSQLQuery; begin try qryAux := TSQLQuery.Create(nil); qryAux.DataBase := SQLite3Con; qryAux.Transaction := SQLTrans; with qryAux do begin Close; SQL.Text:= 'SELECT seq FROM sqlite_sequence WHERE name="tbblogcomments";'; Open; if RecordCount > 0 then begin Result:= FieldByName('seq').AsString; end; end; qryAux.Destroy; except Result:= '<b>Erro na base de dados!</b>'; end; end; class function TuntBlog.setBlogCommentForm( postid: string ): string; var straux : string; begin straux:= '<div>'; //cria form e monta o caminho correto do post straux:= straux + '<br/><div class="panelGreen" id="msgOk">Comentário enviado!</div>'; straux:= straux + '<div class="panelRed" id="msgEr">Erro no envio!</div>'; straux:= straux + '<form name="frmComment" action="comment?r='+ StringReplace(getAPPURL(), '&', '_', [rfReplaceAll] ) +'" enctype="multipart/form-data" method="post">'; straux:= straux + '<input type="hidden" name="postID" value="'+ postid +'"/>'; straux:= straux + '<label for="edtNome">Nome</label><br/>'; straux:= straux + '<input id="edtNome" name="edtNome" type="text" size="60" required="required"/><br/>'; straux:= straux + '<label for="edtMail">E-mail</label><br/>'; straux:= straux + '<input id="edtMail" name="edtMail" type="text" size="60" required="required" placeholder="Não será publicado"/><br/>'; straux:= straux + '<label for="edtSite">Site</label><br/>'; straux:= straux + '<input id="edtSite" name="edtSite" type="text" size="60" placeholder="www.nomedosite.com"/><br/>'; straux:= straux + '<label for="txtMsg">Comentário</label><br/>'; straux:= straux + '<textarea id="txtMsg" name="txtMsg" rows="7" cols="80" required="required"></textarea><br/>'; straux:= straux + '<input type="submit" value="comentar"/>'; straux:= straux + '</form></div>'; Result:= straux; end; class function TuntBlog.getBlogConfigItem(strItem: string) : string; var qryAux : TSQLQuery; begin try qryAux := TSQLQuery.Create(nil); qryAux.DataBase := SQLite3Con; qryAux.Transaction := SQLTrans; with qryAux do begin SQL.Text:= 'SELECT value FROM tbblogconfig WHERE option='''+ strItem +''' '; Open; if RecordCount > 0 then Result:= FieldByName('value').AsString else Result:= '#blank#'; end; except Result:= '<div class="msgError">Erro na consulta!</div>'; end; qryAux.Destroy; end; constructor TuntBlog.Create; begin end; destructor TuntBlog.Destroy; begin inherited Destroy; end; end.
unit l3BoxMemoryManagerPrim; // Модуль: "w:\common\components\rtl\Garant\L3\l3BoxMemoryManagerPrim.pas" // Стереотип: "SimpleClass" // Элемент модели: "Tl3BoxMemoryManagerPrim" MUID: (54B69FAC0256) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface uses l3IntfUses , l3BaseBoxMemoryManager ; type Tl3BoxMemoryManagerPrim = class(Tl3BaseBoxMemoryManager) private f_Freed: PAnsiChar; f_LowIndex: Integer; f_HighIndex: Integer; f_SizeSize: Cardinal; protected function SizeSize: Cardinal; override; function Size2Index(aSize: Cardinal): Integer; override; function AlignSize(aSize: Cardinal): Cardinal; override; function GetPSz(aPt: PAnsiChar): Cardinal; override; procedure SetPSz(aPt: PAnsiChar; aValue: Cardinal); override; function HasFreed: Boolean; override; procedure InitFreed; override; procedure ClearFreed; override; function IsValidIndex(anIndex: Integer): Boolean; override; function GetFreed(anIndex: Integer): Pointer; override; procedure SetFreed(anIndex: Integer; aValue: Pointer); override; public constructor Create(aBlockSize: Integer; aHighIndex: Integer = 8; aLowIndex: Integer = 0); reintroduce; end;//Tl3BoxMemoryManagerPrim implementation uses l3ImplUses , l3MinMax , l3MemUtils //#UC START# *54B69FAC0256impl_uses* //#UC END# *54B69FAC0256impl_uses* ; const cStep = 4; constructor Tl3BoxMemoryManagerPrim.Create(aBlockSize: Integer; aHighIndex: Integer = 8; aLowIndex: Integer = 0); //#UC START# *54B6A30003E2_54B69FAC0256_var* //#UC END# *54B6A30003E2_54B69FAC0256_var* begin //#UC START# *54B6A30003E2_54B69FAC0256_impl* inherited Create(aBlockSize); f_SizeSize := 1; f_LowIndex := aLowIndex; f_HighIndex := aHighIndex; //#UC END# *54B6A30003E2_54B69FAC0256_impl* end;//Tl3BoxMemoryManagerPrim.Create function Tl3BoxMemoryManagerPrim.SizeSize: Cardinal; //#UC START# *54B6A043017E_54B69FAC0256_var* //#UC END# *54B6A043017E_54B69FAC0256_var* begin //#UC START# *54B6A043017E_54B69FAC0256_impl* Result := f_SizeSize; //#UC END# *54B6A043017E_54B69FAC0256_impl* end;//Tl3BoxMemoryManagerPrim.SizeSize function Tl3BoxMemoryManagerPrim.Size2Index(aSize: Cardinal): Integer; //#UC START# *54B6A06A00AF_54B69FAC0256_var* //#UC END# *54B6A06A00AF_54B69FAC0256_var* begin //#UC START# *54B6A06A00AF_54B69FAC0256_impl* Result := ((aSize - 1) div cStep) - 1; //#UC END# *54B6A06A00AF_54B69FAC0256_impl* end;//Tl3BoxMemoryManagerPrim.Size2Index function Tl3BoxMemoryManagerPrim.AlignSize(aSize: Cardinal): Cardinal; //#UC START# *54B6A0850253_54B69FAC0256_var* //#UC END# *54B6A0850253_54B69FAC0256_var* begin //#UC START# *54B6A0850253_54B69FAC0256_impl* Result := (((aSize - 1) div cStep) + 1) * cStep; //#UC END# *54B6A0850253_54B69FAC0256_impl* end;//Tl3BoxMemoryManagerPrim.AlignSize function Tl3BoxMemoryManagerPrim.GetPSz(aPt: PAnsiChar): Cardinal; //#UC START# *54B6A0A50097_54B69FAC0256_var* //#UC END# *54B6A0A50097_54B69FAC0256_var* begin //#UC START# *54B6A0A50097_54B69FAC0256_impl* Case SizeSize of 1: Result := PByte(aPt)^; 2: Result := PWord(aPt)^; 4: Result := PInteger(aPt)^; else begin Result := 0; Assert(false); end;//else end;//Case SizeSize //#UC END# *54B6A0A50097_54B69FAC0256_impl* end;//Tl3BoxMemoryManagerPrim.GetPSz procedure Tl3BoxMemoryManagerPrim.SetPSz(aPt: PAnsiChar; aValue: Cardinal); //#UC START# *54B6A0F1005C_54B69FAC0256_var* //#UC END# *54B6A0F1005C_54B69FAC0256_var* begin //#UC START# *54B6A0F1005C_54B69FAC0256_impl* Case SizeSize of 1: PByte(aPt)^ := aValue; 2: PWord(aPt)^ := aValue; 4: PInteger(aPt)^ := aValue; else Assert(false); end;//Case SizeSize //#UC END# *54B6A0F1005C_54B69FAC0256_impl* end;//Tl3BoxMemoryManagerPrim.SetPSz function Tl3BoxMemoryManagerPrim.HasFreed: Boolean; //#UC START# *54B6A11301EC_54B69FAC0256_var* //#UC END# *54B6A11301EC_54B69FAC0256_var* begin //#UC START# *54B6A11301EC_54B69FAC0256_impl* Result := (f_Freed <> nil); //#UC END# *54B6A11301EC_54B69FAC0256_impl* end;//Tl3BoxMemoryManagerPrim.HasFreed procedure Tl3BoxMemoryManagerPrim.InitFreed; //#UC START# *54B6A1290134_54B69FAC0256_var* //#UC END# *54B6A1290134_54B69FAC0256_var* begin //#UC START# *54B6A1290134_54B69FAC0256_impl* if (f_Freed = nil) then Tl3MemUtils.GetLocalMemZ(f_Freed, (f_HighIndex - f_LowIndex + 1) * SizeOf(Pointer)); //#UC END# *54B6A1290134_54B69FAC0256_impl* end;//Tl3BoxMemoryManagerPrim.InitFreed procedure Tl3BoxMemoryManagerPrim.ClearFreed; //#UC START# *54B6A138006E_54B69FAC0256_var* //#UC END# *54B6A138006E_54B69FAC0256_var* begin //#UC START# *54B6A138006E_54B69FAC0256_impl* Tl3MemUtils.FreeLocalMem(f_Freed); //#UC END# *54B6A138006E_54B69FAC0256_impl* end;//Tl3BoxMemoryManagerPrim.ClearFreed function Tl3BoxMemoryManagerPrim.IsValidIndex(anIndex: Integer): Boolean; //#UC START# *54B6A14B000C_54B69FAC0256_var* //#UC END# *54B6A14B000C_54B69FAC0256_var* begin //#UC START# *54B6A14B000C_54B69FAC0256_impl* Result := (anIndex >= f_LowIndex) AND (anIndex <= f_HighIndex); //#UC END# *54B6A14B000C_54B69FAC0256_impl* end;//Tl3BoxMemoryManagerPrim.IsValidIndex function Tl3BoxMemoryManagerPrim.GetFreed(anIndex: Integer): Pointer; //#UC START# *54B6A16703DD_54B69FAC0256_var* //#UC END# *54B6A16703DD_54B69FAC0256_var* begin //#UC START# *54B6A16703DD_54B69FAC0256_impl* Result := PPointer(f_Freed + (anIndex - f_LowIndex) * SizeOf(Pointer))^; //#UC END# *54B6A16703DD_54B69FAC0256_impl* end;//Tl3BoxMemoryManagerPrim.GetFreed procedure Tl3BoxMemoryManagerPrim.SetFreed(anIndex: Integer; aValue: Pointer); //#UC START# *54B6A1830090_54B69FAC0256_var* //#UC END# *54B6A1830090_54B69FAC0256_var* begin //#UC START# *54B6A1830090_54B69FAC0256_impl* PPointer(f_Freed + (anIndex - f_LowIndex) * SizeOf(Pointer))^ := aValue; //#UC END# *54B6A1830090_54B69FAC0256_impl* end;//Tl3BoxMemoryManagerPrim.SetFreed end.
program ejercicio12; const dimF = 10000; type compu = record verUbuntu : Real; cantPaquetes: Integer; cantCuentas: Integer; end; vCompu = array[1..dimF] of compu; procedure leerInfo(var c:compu); begin with c do begin write('ingrese la Version de Ubuntu: '); readln(verUbuntu); write('Ingrese la cantidad de paquetes intalados: '); readln(cantPaquetes); write('Ingrese la cantidad de usuario: '); readln(cantCuentas); writeln('------------------------------'); end; end; procedure cargarVector(var v:vCompu; var dimL:Integer); var c: compu; begin leerInfo(c); while (c.verUbuntu <> 4.10) and (dimL < dimF) do begin dimL:= dimL + 1; v[dimL]:= c; leerInfo(c); end; end; procedure cantCompuVersion(v:vCompu; dimL:Integer; i:Integer; var sumaVersion:Integer); begin sumaVersion:=0; if (v[i].verUbuntu = 18.04) or (v[i].verUbuntu = 16.04) then begin sumaVersion:= sumaVersion + 1; end; end; function promedioUsuarios(TotalUsuario:Integer; dimL:Integer): Integer; begin promedioUsuarios:= TotalUsuario div dimL; end; procedure VersionMaxPaquete(v:vCompu; i:Integer; var max:Integer; var verMax:Real); begin if (v[i].cantPaquetes > max) then begin max:= v[i].cantPaquetes; verMax:= v[i].verUbuntu; end; end; procedure informar(v:vCompu; dimL:Integer); var i,sumaVersion,TotalUsuario,promedio,max: Integer; verMax: Real; begin sumaVersion:=0; TotalUsuario:=0; promedio:=0; max:= -9999; verMax:= 0; for i := 1 to dimL do begin TotalUsuario:= TotalUsuario + v[i].cantCuentas; cantCompuVersion(v,dimL,i, sumaVersion); VersionMaxPaquete(v,i,max,verMax); writeln('El promedio de usuario para esta computadora es: ', promedioUsuarios(TotalUsuario,dimL)); end; writeln('La cantidad de computadoras que utulizan las versiones 18.04 o 16.04 son: ', sumaVersion); writeln('La version de ubunu con mas paquetes intalados es: ', verMax); end; var v: vCompu; dimL: Integer; begin dimL:=0; cargarVector(v,dimL); informar(v,dimL); readln(); end.
unit UUtilComum; interface uses FireDAC.Comp.Client, UFuncoes, System.Generics.Collections, DB, System.SysUtils, System.JSON, Winapi.Windows; procedure teste(Open: boolean); procedure setDetailsID(DataSetList: TList<TDataSet>; ID: Integer); procedure geraLog(Path, Message: String); function JSONgetField(obj: TJSONArray; indice: integer; field: String; exibeMsg: Boolean): Variant; implementation uses Vcl.Dialogs; function JSONgetField(obj: TJSONArray; indice: integer; field: String; exibeMsg: Boolean): Variant; var val: TJSONValue; Begin result:=''; Try if obj.Count<=0 then Begin if exibeMsg then UFuncoes.mensagemAlerta('Registro não Encontrado','Aviso'); Exit; End; val:= TJSONObject(obj.Items[indice]).Values[field]; if val <> nil then Begin if val is TJSONString then result := TJSONString(val).Value else if val is TJSONNumber then result := TJSONNumber(val).AsDouble; End; Except on E:Exception Do Begin UFuncoes.mensagemAlerta('Problema ao ler registro'+#13+E.Message,'Aviso'); End; End; End; procedure teste(Open: boolean); Begin // End; procedure setDetailsID(DataSetList: TList<TDataSet>; ID: Integer); var I: Integer; Begin for I := 0 to DataSetList.Count-1 do Begin Try DataSetList[i].DisableControls; DataSetList[i].First; while not DataSetList[i].Eof do Begin //Showmessage('Field Value: '+DataSetList[i].Fields[0].AsString // +#13+'RecordCount: '+DataSetList[i].RecordCount.ToString() // +#13+'RecNO: '+DataSetList[i].RecNo.ToString()); if DataSetList[i].Fields[0].AsInteger<>ID then Begin DataSetList[i].Edit; DataSetList[i].Fields[0].Value:=ID; DataSetList[i].Post; End else DataSetList[i].Next; End; Finally DataSetList[i].First; DataSetList[i].EnableControls; End; End; End; procedure geraLog(Path, Message: String); var NomeDoLog: string; Arquivo: TextFile; begin NomeDoLog := Path+'LOG.txt'; Try AssignFile(Arquivo, NomeDoLog); if FileExists(NomeDoLog) then Append(arquivo) else ReWrite(arquivo); WriteLn(arquivo, DateToStr(Date)+' '+TimeToStr(Time)+' - '+Message); finally CloseFile(arquivo) end; end; end.
unit xpr.errors; { Author: Jarl K. Holta License: GNU Lesser GPL (http://www.gnu.org/licenses/lgpl.html) Error handling } {$I express.inc} interface uses SysUtils, xpr.express; type ExpressError = class(Exception) DocPos: TDocPos; constructor Create(Msg: string; ADocPos: TDocPos); overload; end; SyntaxError = class(ExpressError); RuntimeError = class(ExpressError); EExceptionType = (eGeneralError, eSyntaxError, eRuntimeError); resourcestring eExpectedButFound = 'Expected `%s` but found `%s`'; eExpectedVar = 'Expected variable'; eInvalidExpression = 'Invalid expression'; eExpectedArgCount = 'Function `%s` expected `%d` arguments'; eIndexOutOfRange = 'Index out of range (index:%d; length:%d)'; eNotImplemented = 'Not implemented yet'; eNotCompatible1 = 'Operation is not compatible with types (%s, %s)'; eNotAllowedOutsideLoop = '`%s` is not allowed outside a loop'; eUnexpected = 'An unexpected error occurred'; eUnexpectedOperation = 'Unexpected operation `%s`'; eUnexpectedKeyword = 'Unexpected keyword `%s`'; eUndefinedIdentifier = 'Identifier `%s` is not defined'; procedure RaiseException(Msg:string; DocPos: TDocPos); procedure RaiseExceptionFmt(Msg:string; Args: array of const; DocPos: TDocPos); procedure RaiseException(Typ:EExceptionType; Msg:string; DocPos: TDocPos); procedure RaiseExceptionFmt(Typ:EExceptionType; Msg:string; Args: array of const; DocPos: TDocPos); implementation constructor ExpressError.Create(Msg:string; ADocPos: TDocPos); overload; begin DocPos := ADocPos; inherited Create(Msg); end; {$IF DEFINED(Delphi) AND (CompilerVersion <= 21.00)} function ReturnAddress: Pointer; asm MOV EAX, [EBP+4] end; {$IFEND} procedure _RaiseException(e:ExpressError); inline; {$IFDEF FPC} begin raise e at get_caller_addr(get_frame); end; {$ELSE} begin raise e at ReturnAddress; end; {$ENDIF} procedure RaiseException(Msg:string; DocPos: TDocPos); begin _RaiseException(ExpressError.Create(Msg + ' at ' + DocPos.ToString, DocPos)); end; procedure RaiseExceptionFmt(Msg:string; Args: array of const; DocPos: TDocPos); begin _RaiseException(ExpressError.Create(Format(Msg, Args) + ' at ' + DocPos.ToString, DocPos)); end; procedure RaiseException(Typ:EExceptionType; Msg:string; DocPos: TDocPos); begin case typ of eGeneralError: _RaiseException(ExpressError.Create(Msg + ' at ' + DocPos.ToString, DocPos)); eRuntimeError: _RaiseException(RuntimeError.Create(Msg + ' at ' + DocPos.ToString, DocPos)); eSyntaxError: _RaiseException(SyntaxError.Create(Msg + ' at ' + DocPos.ToString, DocPos)); end; end; procedure RaiseExceptionFmt(Typ:EExceptionType; Msg:string; Args: array of const; DocPos: TDocPos); begin case typ of eGeneralError: _RaiseException(ExpressError.Create(Format(Msg, Args) + ' at ' + DocPos.ToString, DocPos)); eRuntimeError: _RaiseException(RuntimeError.Create(Format(Msg, Args) + ' at ' + DocPos.ToString, DocPos)); eSyntaxError: _RaiseException(SyntaxError.Create(Format(Msg, Args) + ' at ' + DocPos.ToString, DocPos)); end; end; end.
unit HTMLHandler; interface uses VoyagerInterfaces, Controls, CustomWebBrowser, extctrls, Graphics, PlayerGif; type TMetaHTMLHandler = class( TInterfacedObject, IMetaURLHandler ) private function getName : string; function getOptions : TURLHandlerOptions; function getCanHandleURL( URL : TURL ) : THandlingAbility; function Instantiate : IURLHandler; end; THTMLHandler = class( TInterfacedObject, IURLHandler ) public constructor Create; destructor Destroy; override; private fControl : TCustomWebBrowser; fCurrURL : TURL; fMasterURLHandler : IMasterURLHandler; fHideScrollBars : boolean; fHideBorder : boolean; fClear : boolean; fDoNotKeep : boolean; fLastTaskId : integer; fBackEnabled : boolean; fForwardEnabled : boolean; private function HandleURL( URL : TURL ) : TURLHandlingResult; function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; function getControl : TControl; procedure setMasterURLHandler(const URLHandler : IMasterURLHandler ); private procedure Navigate( URL : TURL; Target : string ); private procedure OnWebBrowserBeforeNavigate(Sender: TObject; const pDisp: IDispatch; var URL: OleVariant; var Flags: OleVariant; var TargetFrameName: OleVariant; var PostData: OleVariant; var Headers: OleVariant; var Cancel: WordBool); procedure OnWebBrowserNavigateComplete( Sender : TObject; const pDisp : IDispatch; var URL : OleVariant ); procedure OnCommandStateChange( Sender : TObject; Command : integer; Enable : WordBool ); procedure OnStatusTextChange(Sender: TObject; const Text: WideString); procedure OnWebBrowserTitleChange(Sender: TObject; const Text: WideString); private fNavigateError : boolean; fDefaultPage : string; end; const tidMetaHandlerName_Html = 'HTMLView'; HandlingAbility_Html = 100; const htmlParmName_NoScrollBars = 'frame_NoScrollBar'; htmlParmName_NoBorder = 'frame_NoBorder'; htmlParmName_ClearWhenHidden = 'frame_ClearWhenHidden'; htmlParmName_KeepContent = 'frame_KeepContent'; htmlAction_Create = 'CREATE'; htmlAction_Refresh = 'REFRESH'; implementation uses ActiveX, URLParser, Events, SysUtils, SHDocVw_TLB, ClientMLS, VCLUtils; // res://mshtml.dll/blank.htm // TMetaHTMLHandler function TMetaHTMLHandler.getName : string; begin result := tidMetaHandlerName_Html; end; function TMetaHTMLHandler.getOptions : TURLHandlerOptions; begin result := [hopCacheable]; end; function TMetaHTMLHandler.getCanHandleURL( URL : TURL ) : THandlingAbility; begin result := 0; end; function TMetaHTMLHandler.Instantiate : IURLHandler; begin result := THTMLHandler.Create; end; // THTMLHandler constructor THTMLHandler.Create; begin inherited Create; fControl := TCustomWebBrowser.Create(nil); fControl.OnBeforeNavigate2 := OnWebBrowserBeforeNavigate; fControl.OnNavigateComplete2 := OnWebBrowserNavigateComplete; fControl.OnCommandStateChange := OnCommandStateChange; end; destructor THTMLHandler.Destroy; begin try if (fControl<>nil) then fControl.Stop; RemoveComponentFreeAndNil(fControl); //.rag except end; inherited; end; function THTMLHandler.HandleURL( URL : TURL ) : TURLHandlingResult; var ParmValue : string; Action : string; Target : string; begin URL := EncodeEscSequences( URL ); ParmValue := URLParser.GetParmValue( URL, htmlParmName_NoScrollBars ); if ParmValue <> '' then fHideScrollBars := URLParser.StrToBoolean( ParmValue ); ParmValue := URLParser.GetParmValue( URL, htmlParmName_NoBorder ); if ParmValue <> '' then fHideBorder := URLParser.StrToBoolean( ParmValue ); ParmValue := URLParser.GetParmValue( URL, htmlParmName_ClearWhenHidden ); if ParmValue <> '' then fClear := URLParser.StrToBoolean( ParmValue ); Target := URLParser.GetParmValue( URL, htmlParmName_Target ); Action := URLParser.GetURLAction( URL ); if Action = '' then begin if (fCurrURL = '') or fDoNotKeep or not URLParser.StrToBoolean( URLParser.GetParmValue( URL, htmlParmName_KeepContent )) then try fControl.HideScrollBars := fHideScrollBars; fControl.HideBorders := fHideBorder; if pos( '?', URL ) = 0 then URL := URL + '?LangId=' + ActiveLanguage else URL := URL + '&LangId=' + ActiveLanguage; Navigate( URL, Target ); fDoNotKeep := false; result := urlHandled; except result := urlError; end else result := urlHandled; end else if Action = htmlAction_Refresh then begin fControl.Refresh; result := urlHandled; end else if Action = htmlAction_Create then begin fDoNotKeep := true; result := urlHandled; end else result := urlNotHandled; end; function THTMLHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; var CachePath : string; begin result := evnHandled; try case EventId of evnGoBack : fControl.GoBack; evnGoForward : fControl.GoForward; evnRefresh : begin fControl.Refresh; end; evnStop : fControl.Stop; evnHandlerExposed : begin fMasterURLHandler.HandleEvent( evnAnswerPrivateCache, CachePath ); end; evnShutDown : //.rag begin fMasterURLHandler := nil; if (fControl<>nil) then fControl.Stop; RemoveComponentFreeAndNil(fControl); end; else result := evnNotHandled; end; except result := evnError; end; end; function THTMLHandler.getControl : TControl; begin result := fControl; // fBackControl; // end; procedure THTMLHandler.setMasterURLHandler(const URLHandler : IMasterURLHandler ); begin fMasterURLHandler := URLHandler; if fMasterURLHandler<>nil then begin fMasterURLHandler.HandleEvent( evnAnswerPrivateCache, fDefaultPage); fDefaultPage := fDefaultPage+ 'misc\htmlerr'+ActiveLanguage+'.htm'; fControl.SetDefaultPage(fDefaultPage); end; end; procedure THTMLHandler.Navigate( URL : TURL; Target : string ); var variantURL : OleVariant; variantTarget : OleVariant; flags : OleVariant; useless : OleVariant; begin // fControl.Hide(); // fBusyWeb.Paused := false; fCurrURL := URL; variantURL := URL; variantTarget := Target; flags := navNoHistory; useless := VarNull; fControl.Navigate2( variantURL, flags, variantTarget, useless, useless ); fNavigateError := false; end; procedure THTMLHandler.OnWebBrowserBeforeNavigate(Sender: TObject; const pDisp: IDispatch; var URL: OleVariant; var Flags: OleVariant; var TargetFrameName: OleVariant; var PostData: OleVariant; var Headers: OleVariant; var Cancel: WordBool); var TaskStartInfo : TEvnTaskStartInfo; begin if (fMasterURLHandler<>nil) then begin if (URL <> fCurrURL) and not fMasterURLHandler.getURLIsLocal( URL ) and (pos(#1, URL) = 0) then begin fMasterURLHandler.HandleURL( URL ); Cancel := true; end else begin // if TargetFrameName='' // then fControl.Hide(); // fBusyWeb.Paused := false; Flags := navNoHistory; inc( fLastTaskId ); TaskStartInfo.Carrier := self; TaskStartInfo.TaskName := 'WebPageDownload'; TaskStartInfo.TaskDesc := URL; fMasterURLHandler.HandleEvent( evnTaskStart, TaskStartInfo ); if fBackEnabled or fForwardEnabled then fMasterURLHandler.ReportNavigation( self, URL, fBackEnabled, fForwardEnabled ); end; end; end; procedure THTMLHandler.OnWebBrowserNavigateComplete( Sender : TObject; const pDisp : IDispatch; var URL : OleVariant ); var TaskEndInfo : TEvnTaskEndInfo; // Document: OleVariant; begin // Document := fControl.Document; // Document.bgColor := 'black'; TaskEndInfo.Carrier := self; TaskEndInfo.TaskName := 'WebPageDownload'; if (fMasterURLHandler<>nil) then fMasterURLHandler.HandleEvent( evnTaskEnd, TaskEndInfo ); end; procedure THTMLHandler.OnCommandStateChange( Sender : TObject; Command : integer; Enable : WordBool ); begin case Command of CSC_NAVIGATEFORWARD : fForwardEnabled := Enable; CSC_NAVIGATEBACK : fBackEnabled := Enable; end; end; procedure THTMLHandler.OnStatusTextChange(Sender: TObject; const Text: WideString); var CachePath : string; Filename: string; temp : string; begin temp := Text; if ((pos('res://', Text)>0) or (pos('javascript:doNetDetect()', Text)>0)) and not fNavigateError and (fMasterURLHandler<>nil) then begin fMasterURLHandler.HandleEvent( evnAnswerPrivateCache, CachePath ); fControl.Stop; Filename := cachepath + 'misc\htmlerr'+ActiveLanguage+'.htm'; if not fileexists(Filename) then Filename :=cachepath + 'misc\htmlerr0.htm'; fControl.Navigate(Filename); fNavigateError := true; end; end; procedure THTMLHandler.OnWebBrowserTitleChange(Sender: TObject; const Text: WideString); var CachePath : string; Filename: string; begin if (pos('cannot be found', Text)>0) or (pos('No page to display', Text)>0) or (pos('Web page unavailable while offline', Text)>0) or (pos('About Working Offline', Text)>0) or (pos('The page cannot be displayed', text)>0) or (pos('Not Found', Text)>0) then begin fMasterURLHandler.HandleEvent( evnAnswerPrivateCache, CachePath ); fControl.Stop; Filename := cachepath + 'misc\htmlerr'+ActiveLanguage+'.htm'; if not fileexists(Filename) then Filename :=cachepath + 'misc\htmlerr0.htm'; fControl.Navigate(Filename); fNavigateError := true; end; end; end.
unit ProgressIndicatorSupportUnit; // Модуль: "w:\garant6x\implementation\Garant\tie\Garant\GblAdapterLib\ProgressIndicatorSupportUnit.pas" // Стереотип: "Interfaces" // Элемент модели: "ProgressIndicatorSupport" MUID: (45EEA87702A5) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses ; type IProgressIndicator = interface {* Интерфейс для обратной связи при длительных операциях на сервере. Должен реализовываться пользователем адаптера. } ['{885E85E3-E74C-4413-8408-2FB7533E7F8A}'] function GetMaxCount: Integer; stdcall; procedure SetCurrent(cur_count: Integer; arg: Integer {* Дополнительный параметр. }); stdcall; {* Изменение состояния длительного процесса. В качестве параметра cur_count подается либо число уже обработанных элементов, принимающих участие в длительном процессе, либо число <=100 (при индикации в %). } property MaxCount: Integer read GetMaxCount; end;//IProgressIndicator ICancelLongProcess = interface {* Интерфейс для возможности прерывания длительных операций на сервере. Используется в интерфейсе IProgressIndicator. } ['{CD915CB2-6E7A-4788-A5B0-ED90959D8399}'] procedure CancelProcess; stdcall; {* Вызывается для прерывания длительного процесса. } end;//ICancelLongProcess implementation uses l3ImplUses ; end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: Franšois PIETTE Description: Application Server Client Component (Client side) Do not confuse TClientWSocket with TAppSrvClient which is the client application side. TClientWSocket is used on the server side to handle client connections, TAppSrvClient is used on the client side to connect to the application server. Both components are talking to each other. Creation: March 3, 1998 Version: 7.00 EMail: http://www.overbyte.be francois.piette@overbyte.be Support: Use the mailing list midware@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 1998-2010 by Franšois PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@overbyte.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software and or any derived or altered versions for any purpose, excluding commercial applications. You can use this software for personal use only. You may distribute it freely untouched. The following restrictions applies: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. 2. If you use this software in a product, an acknowledgment in the product documentation and displayed on screen is required. The text must be: "This product is based on MidWare. Freeware source code is available at http://www.overbyte.be." 3. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 4. This notice may not be removed or altered from any source distribution and must be added to the product documentation. Updates: Mar 02, 1998 V1.01 Added a RequestDone event when DnsLookup or connection fails. May 08, 1998 V1.02 Corrected a one byte error in the OnDataAvailable. Thanks to Miha Remec <miha.remec@k2.net> for finding the bug. May 24, 1998 V1.03 Added comments in the source code. Jun 01, 1998 V1.04 Removed beta status. Changed "legal stuff" to prohibe commercial applications whithout an agreement. Jun 19, 1998 V1.05 Added the Connected and State properties Corrected Len variable in DataAvailable event handler. Jul 08, 1998 V1.06 Adadpted for Delphi 4 Jul 09, 1998 V1.07 Added FOnBannerRcvd event, added some missing TriggerXXX Aug 25, 1998 V1.08 Corrected a buffersize error in ProcessLine. Nov 07, 1998 V1.09 Added var parameter in TriggerBeforeProcessReply to fix a bug occuring when encryption is used (CmdLen needs to be updated). Nov 22, 1998 V2.00 Added SOCKS5 support Apr 03, 1999 V2.01 Added AppSrvClientException. Made Request property writable. Made lots of methods virtual. Apr 16, 1999 V2.02 Added var for CmdBuf in TriggerBeforeProcessReply Sep 15, 2001 V2.03 Added connection retry Feb 19, 2002 V2.04 Corrected WMRetry to use MsgRec.WParam instead of Error. Thanks to Oliver Grahl <og@o-grahl.de> for finding this bug. Mar 30, 2002 V2.05 Added SendDatagram Apr 06, 2002 V2.06 Corrected Len variable in DataAvailable event handler (This was a bug in the fix introduced in V1.05 !) Apr 09, 2002 V2.07 Added Datagram types and datagram from server to client Jan 30, 2004 V2.08 Added NOFORMS compatibility Changed property WSocket to ClientSocket to avoid conflict with the unit name wsocket. Aug 28, 2004 V2.09 Use MWDEFS.INC Jun 18, 2005 V3.00 SSL support Sep 24, 2005 V3.01 Added RcvSizeInc property. Thanks to Bj°rnar Nielsen <bjornar@sentinel.no> Oct 08, 2005 V3.02 Uwe Schuster <jedivcs@bitcommander.de> implemented dynamic buffer allocation. If you set RcvSizeInc property to 0, then the component will increase the buffer by 25% instead of a fixed value. Oct 23, 2005 V3.03 Updated for Delphi 2006 and BCB 2006 Nov 05, 2005 V3.04 Uwe Schuster <jedivcs@bitcommander.de> updated the timeout detection mechanism to avoid timeout while still transmitting Dec 08, 2005 V3.05 Fixed TAppSrvClient.SetRequest for nil value Feb 18, 2007 V3.06 Added SetName and related. Aug 01, 2008 V7.00 Update for ICS-V7 and Delphi 2009. Warning: Unicode not really supported. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteApsCli; interface {$I OverbyteMwDefs.inc} uses Windows, Messages, SysUtils, Classes, { You must define USE_SSL so that SSL code is included in the component. } { To be able to compile the component, you must have the SSL related files } { which are _NOT_ freeware. See http://www.overbyte.be for details. } {$IFDEF USE_SSL} IcsSSLEAY, IcsLIBEAY, {$ENDIF} WinSock, OverbyteIcsWSocket, OverbyteRFormat, OverbyteIcsWndControl; const AppSrvClientVersion = 700; CopyRight : String = ' TAppSrvClient (c) 1998-2008 F. Piette V7.00 '; DefaultRcvSize = 2048; // USc 08/10/2005 zero means dynamic buffer increase(+ 1/4) -> see DataAvailable DefaultRcvSizeInc = 0; DefaultRcvSizeMinInc = 2048; // WM_REQUESTDONE = WM_USER + 1; // WM_RETRY = WM_USER + 2; // WM_DATASENT = WM_USER + 3; type TErrorEvent = procedure (Sender : TObject; Error : Integer; Msg : AnsiString) of object; TRequestDone = procedure (Sender : TObject; Error : Integer) of object; TProcessReplyEvent = procedure (Sender : TObject; var CmdBuf : PAnsiChar; var CmdLen : Integer) of object; TProcessBannerEvent = procedure (Sender : TObject; CmdBuf : PAnsiChar; CmdLen : Integer; var BannerOk : Boolean) of object; TConnectionRetryEvent = procedure (Sender : TObject; Error : Integer) of object; TDatagramAvailableEvent = procedure (Sender : TObject; const DGramType : AnsiString; Data : PAnsiChar; DataLen : Integer) of object; TClientState = (cstReady, cstDnsLookup, cstConnecting, cstWaitingResponse); TApsCliSendType = (acstNone, acstRequest, acstDatagram); AppSrvClientException = class(Exception); TAppSrvClient = class(TIcsWndControl) protected FFunctionCode : String; FWSocket : TWSocket; FPort : String; FServer : String; FServerIP : String; FSocksServer : String; FSocksPort : String; FSocksUsercode : String; FSocksPassword : String; FSocksAuthentication : TSocksAuthentication; FRequest : TMWBuffer; FAnswer : TMWBuffer; FAnswerStatus : String; FState : TClientState; FRcvBuf : PAnsiChar; FRcvCnt : LongInt; FRcvSize : LongInt; FRcvSizeInc : Integer; FBannerRcvd : Boolean; // FHandle : HWND; FRequestHeader : PAnsiChar; FRequestHeaderLen : Integer; FRequestBody : PAnsiChar; FRequestBodyLen : Integer; FRetrying : Boolean; FRetryCount : Integer; FMaxRetries : Integer; FDatagramInBuffer : PAnsiChar; FDatagramInBufferSize : Integer; FDatagramOutBuffer : PAnsiChar; FDatagramOutBufferSize : Integer; FSendType : TApsCliSendType; FRequestDoneFlag : Boolean; FPSessionID : PChar; FLastReplyRXTime : TDateTime; FLastReplyTime : TDateTime; FMsg_WM_REQUESTDONE : UINT; FMsg_WM_RETRY : UINT; FMsg_WM_DATASENT : UINT; FOnError : TErrorEvent; FOnRequestDone : TRequestDone; FOnRequestSent : TNotifyEvent; FOnDatagramSent : TNotifyEvent; FOnDatagramAvailable : TDatagramAvailableEvent; FOnSessionConnected : TSessionConnected; FOnSessionClosed : TSessionClosed; FOnBeforeProcessReply : TProcessReplyEvent; FOnAfterProcessReply : TProcessReplyEvent; FOnBeforeSendRequest : TNotifyEvent; FOnAfterSendRequest : TNotifyEvent; FOnBannerRcvd : TProcessBannerEvent; FOnSocksError : TSocksErrorEvent; FOnSocksConnected : TSessionConnected; FOnSocksAuthState : TSocksAuthStateEvent; FOnConnectionRetry : TConnectionRetryEvent; procedure AllocateMsgHandlers; override; procedure FreeMsgHandlers; override; function MsgHandlersCount: Integer; override; procedure WndProc(var MsgRec: TMessage); override; procedure WMRetry(var MsgRec: TMessage); procedure WMDataSent(var MsgRec: TMessage); procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SessionConnected(Sender : TObject; Error : Word); virtual; procedure SessionClosed(Sender : TObject; Error : Word); virtual; procedure DnsLookupDone(Sender : TObject; ErrCode : Word); virtual; procedure DataAvailable(Sender : TObject; ErrCode : Word); virtual; procedure DataSent(Sender : TObject; ErrCode : Word); virtual; procedure SocksConnected(Sender : TObject; ErrCode : Word); virtual; procedure SocksError(Sender : TObject; ErrCode : Integer; Msg : String); virtual; procedure SocksAuthState(Sender : TObject; AuthState : TSocksAuthState); virtual; procedure TriggerError(Error : Word; Msg : AnsiString); virtual; procedure TriggerRequestSent; virtual; procedure TriggerDatagramSent; virtual; procedure TriggerDatagramAvailable(const DGramType : AnsiString; Data : PAnsiChar; DataLen : Integer); virtual; procedure TriggerRequestDone(Error : Word); virtual; procedure TriggerBeforeSendRequest; virtual; procedure TriggerAfterSendRequest; virtual; procedure TriggerBannerRcvd(CmdBuf : PAnsiChar; CmdLen : Integer; var BannerOk : Boolean); virtual; procedure TriggerBeforeProcessReply(var CmdBuf : PAnsiChar; var CmdLen : Integer); virtual; procedure TriggerAfterProcessReply(CmdBuf : PAnsiChar; CmdLen : Integer); virtual; procedure TriggerConnectionRetry(Error : Word); virtual; procedure ProcessLine(CmdBuf : PansiChar; CmdLen : Integer); virtual; procedure SendRequest; virtual; procedure CrackHeader(AnsBuffer : PAnsiChar; AnsLength : Integer; var AnswerStatus : String; var ParamPtr : PAnsiChar; var ParamLen : LongInt); virtual; function GetConnected : Boolean; virtual; procedure SetSocksPort(newValue : String); virtual; procedure SetRequest(NewValue : TMWBuffer); virtual; procedure SetRcvSize(const Value: LongInt); procedure DatagramIn(const DGramType : AnsiString; Data : PAnsiChar; DataLen : Integer; EscChar : AnsiChar); virtual; // function AppSrvClientAllocateHWnd(Method: TWndMethod): HWND; // procedure AppSrvClientDeallocateHWnd(WHandle: Cardinal); procedure DoBannerReceived; virtual; procedure DoConnect; virtual; procedure DoDnsLookup; virtual; procedure DoSessionConnected; virtual; procedure CreateSocket; virtual; procedure DoBeforeConnect; virtual; procedure SetName(const NewName: TComponentName); override; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; {:Send a function code and request (parmeters) to the application server. This is the main function of the component. The communication with the application server is established if needed. } procedure Send; virtual; {:SendDatagram transparently send a given data buffer. Only allowed after having sent a request and before having received an answer. } procedure SendDatagram(const DGramType : AnsiString; Data : PAnsiChar; Size : Integer); virtual; procedure SendDatagramString(const DGramType : AnsiString; const S : AnsiString); virtual; {:Close the communication with the application server. } procedure Close; virtual; {:Create a new Requet buffer, if required.} procedure CreateRequestMWBuffer; {:ClientSocket is the reference to the underlaiying TWSocket component used for communication with the application server. } property ClientSocket : TWSocket read FWSocket; {:The request property holds the parameters sent to the application server. The application server uses the function code to know which server object must be instanciated, and pass the paramters to this server object. Parameters can be anything and are consituted of records made of fields. See TMWBuffer object description for details.} property Request : TMWBuffer read FRequest write SetRequest; {:The AnswerStatus property hold the ResultStatus returned back by the application server. It plays the same role as the function code in the request. The meaning for the value is left to the application author. The server and client code does'nt use it. It is just passed from the server to the client. By default the server use numeric values like those used by the HTTP protocol. } property AnswerStatus : String read FAnswerStatus; {:The handle for the hidden window used to send and receive internal messages for component work. } // property Handle : HWND read FHandle; {:The connected property tell if conection with the server is alive } property Connected : Boolean read GetConnected; property State : TClientState read FState; property RequestHeader : PAnsiChar read FRequestHeader write FRequestHeader; property RequestHeaderLen : Integer read FRequestHeaderLen write FRequestHeaderLen; property RequestBody : PAnsiChar read FRequestBody write FRequestBody; property RequestBodyLen : Integer read FRequestBodyLen write FRequestBodyLen; property PSessionID : PChar read FPSessionID write FPSessionID; {:Gives the time of the last command reply data received. Use for timeout. } property LastReplyRXTime : TDateTime read FLastReplyRXTime; {:Gives the time of the last command reply received. Use for timeout. } property LastReplyTime : TDateTime read FLastReplyTime; published {:The function code is a string which is used by the application server to know which server object to instanciate to execute the request. It can be anything but default in the server to the server object name without the leading TServerObject. For example if you made a server object whose class name is TServerObjectGETCLIENT then the function code will be GETCLIENT. This behaviour can be overriden in the server object by overrinding the BuildFunctionCode procedure. The function code is case incensitive. } property FunctionCode : String read FFunctionCode write FFunctionCode; {:This is the IP address or hostname for the application server. It is generaly much faster to use the IP address than the hostname because it avoid name resolution each time the communication is established. Name resolution takes time, specially if there are some problem with the DNS. It's better to get the IP address from the server host name at application startup and used the IP address after. } property Server : String read FServer write FServer; {:This is the port number used by the server to listen for clients. It defaults to 2106 but can be anything. It can even be a symbolic name provided that name is in the 'services' table. } property Port : String read FPort write FPort; property SocksServer : String read FSocksServer write FSocksServer; property SocksPort : String read FSocksPort write SetSocksPort; property SocksUsercode : String read FSocksUsercode write FSocksUsercode; property SocksPassword : String read FSocksPassword write FSocksPassword; property SocksAuthentication : TSocksAuthentication read FSocksAuthentication write FSocksAuthentication; {:The Answer property holds the answer from the application server. It is organized as the request: records made of fields. See TMWBuffer description for more details. } property Answer : TMWBuffer read FAnswer write FAnswer; {:When connection fails, the component will retry automatically. Set MaxRetries to the maximum retries you wants to do. Zero means no retry at all. } property MaxRetries : Integer read FMaxRetries write FMaxRetries; {:RcvSize is the size of the receive buffer used by the component to store data from the application server. The initial value is given by the constant DefaultRcvSize. The component automatically adjust his receive buffer size using RcvSizeInc property so there is never any problem when buffer is too small: It is enlarge automatically when needed. When RcvSizeInc is set to 0, the enlargement is 25% of current buffer size. When RcvSizeInc is not 0, the enlargement is given by RcvSizeInc.} property RcvSize : LongInt read FRcvSize write SetRcvSize; property RcvSizeInc : Integer read FRcvSizeInc write FRcvSizeInc; {:When the application server sent the answer to the client, the OnRequestdone event is triggered. The corresponding event handler is the right place to test for success or failure, and to parse the answer to extract the returned info to update the user interface or do whatever needs to be done with the request's result. } property OnRequestDone : TRequestDone read FOnRequestDone write FOnRequestDone; property OnRequestSent : TNotifyEvent read FOnRequestSent write FOnRequestSent; property OnDatagramSent : TNotifyEvent read FOnDatagramSent write FOnDatagramSent; property OnDatagramAvailable : TDatagramAvailableEvent read FOnDatagramAvailable write FOnDatagramAvailable; {:The event OnSessionConnected is triggered when the connection has been established with the application server. The event handler is the right place to update some status bar to let the user know he is connected with the server. } property OnSessionConnected : TSessionConnected read FOnSessionConnected write FOnSessionConnected; property OnSocksConnected : TSessionConnected read FOnSocksConnected write FOnSocksConnected; property OnSocksError : TSocksErrorEvent read FOnSocksError write FOnSocksError; property OnSocksAuthState : TSocksAuthStateEvent read FOnSocksAuthState write FOnSocksAuthState; {:The event OnSessionConnected is triggered when the connection has been closed. The event handler is the right place to update some status bar to let the user know he is disconnected from the server. } property OnSessionClosed : TSessionClosed read FOnSessionClosed write FOnSessionClosed; {:The event OnBeforeProcessReply is triggered when a reply have been received from the server, just before it is processed for header and body extraction. This event is the right place to decrypt or decompress data sent by the server. The event handler can allocate some resource or memory and change the parameters passed. To free resource and memory, use the OnAfterProcessReply event which will pass the same arguments. } property OnBeforeProcessReply : TProcessReplyEvent read FOnBeforeProcessReply write FOnBeforeProcessReply; {:Use to cleanup allocated resources in the OnBeforeProcessReply event handler. } property OnAfterProcessReply : TProcessReplyEvent read FOnAfterProcessReply write FOnAfterProcessReply; {:The OnBeforeSendRequest event is triggered just before a request and his parameters are sent to the server. The event handler can process the header (RequestHeader, RequestHeaderLen) and the parameters (RequestBody, RequestBodyLen) to encrypt or compress them. If needed, the event handler can reallocate the data elsewhere. If needed, the OnAfterSendRequest event handler can be used to free allocated resources. } property OnBeforeSendRequest : TNotifyEvent read FOnBeforeSendRequest write FOnBeforeSendRequest; {:Use to cleanup allocated resources in the OnBeforeSendRequest event handler. } property OnAfterSendRequest : TNotifyEvent read FOnAfterSendRequest write FOnAfterSendRequest; {:This event is triggered when the banner is received from the server } property OnBannerRcvd : TProcessBannerEvent read FOnBannerRcvd write FOnBannerRcvd; {:This event is triggered each time before a retry will be started. } property OnConnectionRetry : TConnectionRetryEvent read FOnConnectionRetry write FOnConnectionRetry; end; { You must define USE_SSL so that SSL code is included in the component. } { To be able to compile the component, you must have the SSL related files } { which are _NOT_ freeware. See http://www.overbyte.be for details. } {$IFDEF USE_SSL} {$I ApsCliIntfSsl.inc} {$ENDIF} //procedure Register; implementation {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} (* procedure Register; begin RegisterComponents('FPiette', [TAppSrvClient {$IFDEF USE_SSL} , TSslAppSrvClient {$ENDIF} ]); end; *) {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFDEF NOFORMS} { This function is a callback function. It means that it is called by } { windows. This is the very low level message handler procedure setup to } { handle the message sent by windows (winsock) to handle messages. } function AppSrvClientWindowProc( ahWnd : HWND; auMsg : Integer; awParam : WPARAM; alParam : LPARAM): Integer; stdcall; var Obj : TObject; MsgRec : TMessage; begin { At window creation asked windows to store a pointer to our object } Obj := TObject(GetWindowLong(ahWnd, 0)); { If the pointer doesn't represent a TAppSrvClient, just call the default procedure} if not (Obj is TAppSrvClient) then Result := DefWindowProc(ahWnd, auMsg, awParam, alParam) else begin { Delphi use a TMessage type to pass parameter to his own kind of } { windows procedure. So we are doing the same... } MsgRec.Msg := auMsg; MsgRec.wParam := awParam; MsgRec.lParam := alParam; { May be a try/except around next line is needed. Not sure ! } TAppSrvClient(Obj).WndProc(MsgRec); Result := MsgRec.Result; end; end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} (* function TAppSrvClient.AppSrvClientAllocateHWnd(Method: TWndMethod) : HWND; begin {$IFDEF NOFORMS} Result := XSocketAllocateHWnd(Self); SetWindowLong(Result, GWL_WNDPROC, LongInt(@AppSrvClientWindowProc)); {$ELSE} { If you have AllocateHWnd undefined, then your last project was } { compiled with NOFORMS defined. Just recompile everything for } { the new project. This will recompile wsocket.pas according to } { this project settings. } Result := OverbyteIcsWSocket.AllocateHWnd(Method); {$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.AppSrvClientDeallocateHWnd(WHandle : Cardinal); begin {$IFDEF NOFORMS} XSocketDeallocateHWnd(WHandle); {$ELSE} OverbyteIcsWSocket.DeallocateHWnd(WHandle); {$ENDIF} end; *) {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TAppSrvClient.Create(AOwner : TComponent); begin inherited Create(AOwner); // FHandle := AppSrvClientAllocateHWnd(WndProc); AllocateHWnd; FState := cstReady; CreateSocket; FRcvSizeInc := DefaultRcvSizeInc; FRcvSize := DefaultRcvSize; FDatagramInBufferSize := 2048; FDatagramInBuffer := nil; FDatagramOutBufferSize := 2048; FDatagramOutBuffer := nil; GetMem(FRcvBuf, FRcvSize); CreateRequestMWBuffer; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TAppSrvClient.Destroy; begin // Destroy Request TMWBuffer if we own it } if Assigned(FRequest) and (FRequest.Owner = Self) then begin FRequest.Destroy; FRequest := nil; end; if Assigned(FWSocket) then begin FWSocket.Destroy; FWSocket := nil; end; if Assigned(FRcvBuf) then begin FreeMem(FRcvBuf, FRcvSize); FRcvBuf := nil; end; if Assigned(FDatagramOutBuffer) then begin FreeMem(FDatagramOutBuffer, FDatagramOutBufferSize); FDatagramOutBuffer := nil; end; if Assigned(FDatagramInBuffer) then begin FreeMem(FDatagramInBuffer, FDatagramInBufferSize); FDatagramInBuffer := nil; end; // AppSrvClientDeallocateHWnd(FHandle); inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.CreateSocket; begin FWSocket := TWSocket.Create(Self); FWSocket.Name := 'WSocket_AppSrvClient'; FPort := '2106'; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Create a Request TMWBuffer, if none exists. } procedure TAppSrvClient.CreateRequestMWBuffer; begin if not Assigned(FRequest) then begin FRequest := TMWBuffer.Create(Self); FRequest.DataBufferSize := 1024; FRequest.Rewrite; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.SetRequest(NewValue : TMWBuffer); begin // Destroy existing request TMWBuffer, if we own it if Assigned(FRequest) and (FRequest.Owner = Self) then begin FRequest.Destroy; FRequest := nil; end; FRequest := NewValue; if Assigned(FRequest) then FRequest.SetPSessionID(FPSessionID); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.Notification( AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, operation); if Operation = opRemove then begin if AComponent = FAnswer then FAnswer := nil else if AComponent = FRequest then FRequest := nil else if AComponent = FWSocket then FWSocket := nil; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TAppSrvClient.MsgHandlersCount : Integer; begin Result := 3 + inherited MsgHandlersCount; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.AllocateMsgHandlers; begin inherited AllocateMsgHandlers; FMsg_WM_REQUESTDONE := FWndHandler.AllocateMsgHandler(Self); FMsg_WM_RETRY := FWndHandler.AllocateMsgHandler(Self); FMsg_WM_DATASENT := FWndHandler.AllocateMsgHandler(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.FreeMsgHandlers; begin if Assigned(FWndHandler) then begin FWndHandler.UnregisterMessage(FMsg_WM_REQUESTDONE); FWndHandler.UnregisterMessage(FMsg_WM_RETRY); FWndHandler.UnregisterMessage(FMsg_WM_DATASENT); end; inherited FreeMsgHandlers; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.WndProc(var MsgRec: TMessage); begin with MsgRec do begin if Msg = FMsg_WM_REQUESTDONE then begin FState := cstReady; if not FRequestDoneFlag then begin { 15/07/02 } FRequestDoneFlag := TRUE; TriggerRequestDone(wParam); end; end else if Msg = FMsg_WM_RETRY then WMRetry(MsgRec) else if Msg = FMsg_WM_DATASENT then WMDataSent(MsgRec) else Result := DefWindowProc(Handle, Msg, wParam, lParam); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.WMRetry(var MsgRec: TMessage); begin TriggerConnectionRetry(MsgRec.WParam); { OG 19/02/02 } FWSocket.Abort; FRetrying := FALSE; if FSocksServer <> '' then FWSocket.SocksServer := FServerIP else FWSocket.Addr := FServerIP; FWSocket.Port := FPort; FWSocket.Proto := 'tcp'; FWSocket.Connect; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.SetSocksPort(newValue : String); begin if not Assigned(FWSocket) then FSocksPort := newValue else begin FSocksPort := newValue; if FSocksPort <> String(FWSocket.SocksPort) then FWSocket.SocksPort := newValue; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.TriggerConnectionRetry(Error : Word); begin if Assigned(FOnConnectionRetry) then FOnConnectionRetry(Self, Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.TriggerError(Error : Word; Msg : AnsiString); begin if Assigned(FOnError) then FOnError(Self, Error, Msg); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.TriggerRequestDone(Error : Word); begin if Assigned(FOnRequestDone) then FOnRequestDone(Self, Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.TriggerBeforeSendRequest; begin if Assigned(FOnBeforeSendRequest) then FOnBeforeSendRequest(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.TriggerAfterSendRequest; begin if Assigned(FOnAfterSendRequest) then FOnAfterSendRequest(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.TriggerRequestSent; begin if Assigned(FOnRequestSent) then FOnRequestSent(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.TriggerDatagramSent; begin if Assigned(FOnDatagramSent) then FOnDatagramSent(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.TriggerDatagramAvailable( const DGramType : AnsiString; Data : PAnsiChar; DataLen : Integer); begin if Assigned(FOnDatagramAvailable) then FOnDatagramAvailable(Self, DGramType, Data, DataLen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.TriggerBannerRcvd( CmdBuf : PAnsiChar; CmdLen : Integer; var BannerOk : Boolean); begin if Assigned(FOnBannerRcvd) then FOnBannerRcvd(Self, CmdBuf, CmdLen, BannerOk); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.TriggerBeforeProcessReply( var CmdBuf : PAnsiChar; var CmdLen : Integer); begin if Assigned(FOnBeforeProcessReply) then FOnBeforeProcessReply(Self, CmdBuf, CmdLen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.TriggerAfterProcessReply( CmdBuf : PAnsiChar; CmdLen : Integer); begin if Assigned(FOnAfterProcessReply) then FOnAfterProcessReply(Self, CmdBuf, CmdLen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.SessionConnected(Sender : TObject; Error : Word); begin if (Error <> 0) and (FMaxRetries > 0) then begin Inc(FRetryCount); if FRetryCount <= FMaxRetries then begin FRetrying := TRUE; PostMessage(FHandle, FMsg_WM_RETRY, Error, 0); Exit; end; end; if Assigned(FOnSessionConnected) then FOnSessionConnected(Self, Error); if Error <> 0 then begin TriggerError(Error, 'Connection Failed'); PostMessage(FHandle, FMsg_WM_REQUESTDONE, Error, 0); Exit; end; { We are connected, but we need to wait for the banner from the server } // SendRequest; FWSocket.OnDataAvailable := DataAvailable; FWSocket.OnSessionClosed := SessionClosed; FWSocket.OnDataSent := DataSent; DoSessionConnected; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.DoSessionConnected; begin { We are connected, but we need to wait for the banner from the server } end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.SocksConnected(Sender : TObject; ErrCode : Word); begin if Assigned(FOnSocksConnected) then FOnSocksConnected(Self, ErrCode); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.SocksError( Sender : TObject; ErrCode : Integer; Msg : String); begin if Assigned(FOnSocksError) then FOnSocksError(Self, ErrCode, Msg); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.SocksAuthState( Sender : TObject; AuthState : TSocksAuthState); begin if Assigned(FOnSocksAuthState) then FOnSocksAuthState(Self, AuthState); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.SessionClosed(Sender : TObject; Error : Word); begin if FRetrying then Exit; if Assigned(FOnSessionClosed) then FOnSessionClosed(Self, Error); if FState <> cstReady then begin TriggerError(WSAEINTR, 'Session closed prematurely'); PostMessage(FHandle, FMsg_WM_REQUESTDONE, WSAEINTR, 0); end; FState := cstReady; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.DnsLookupDone(Sender : TObject; ErrCode : Word); begin if ErrCode <> 0 then begin TriggerError(ErrCode, 'Dns Lookup Failed'); PostMessage(FHandle, FMsg_WM_REQUESTDONE, ErrCode, 0); Exit; end; FState := cstConnecting; FServerIP := String(FWSocket.DnsResult); FRetryCount := 0; FRetrying := FALSE; FWSocket.OnSessionConnected := SessionConnected; FWSocket.OnSocksConnected := SocksConnected; FWSocket.OnSocksError := SocksError; FWSocket.OnSocksAuthState := SocksAuthState; FWSocket.SocksUsercode := String(FSocksUsercode); FWSocket.SocksPassword := String(FSocksPassword); FWSocket.SocksAuthentication := FSocksAuthentication; DoConnect; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.DoBeforeConnect; begin FWSocket.Port := FPort; FWSocket.Proto := 'tcp'; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.DoConnect; begin if FSocksServer <> '' then FWSocket.SocksServer := FServerIP else FWSocket.Addr := FServerIP; DoBeforeConnect; FWSocket.Connect; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Extract the answer status and separate parameters from header } procedure TAppSrvClient.CrackHeader( AnsBuffer : PAnsiChar; { Given answer buffer } AnsLength : Integer; { Given answer length } var AnswerStatus : String; { Returned answer status } var ParamPtr : PAnsiChar; { Returned parameters start } var ParamLen : LongInt); { Returned parameters length } var I : LongInt; begin { The first word is the answer status, usually 3 characters } SetLength(AnswerStatus, 3); I := 0; while (I < AnsLength) and (AnsBuffer[I] <> ' ') do begin if I > Length(AnswerStatus) then SetLength(AnswerStatus, I + 1); AnswerStatus[I + 1] := Char(AnsBuffer[I]); Inc(I); end; if I <> Length(AnswerStatus) then SetLength(AnswerStatus, I); { Skip spaces } while (I < AnsLength) and (AnsBuffer[I] = ' ') do Inc(I); { Parameters follows } ParamPtr := AnsBuffer + I; ParamLen := AnsLength - I; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.DoBannerReceived; begin SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.ProcessLine(CmdBuf : PAnsiChar; CmdLen : Integer); var ParamStr : PAnsiChar; ParamLen : LongInt; BannerOk : Boolean; DGramType : AnsiString; I : Integer; begin if not FBannerRcvd then begin FBannerRcvd := TRUE; BannerOk := TRUE; TriggerBannerRcvd(CmdBuf, CmdLen, BannerOk); if BannerOk then DoBannerReceived else FWSocket.Abort; Exit; end; TriggerBeforeProcessReply(CmdBuf, CmdLen); { Check if OnBeforeProcessReply has canceled command } if CmdLen = 0 then begin TriggerAfterProcessReply(CmdBuf, CmdLen); Exit; end; { Check if we received a datagram or a reply } if (CmdLen >= 3) and (CmdBuf[0] = '^') then begin { We've ot a datagram } DGramType := ''; I := 1; while (CmdBuf[I] <> ' ') and (I < CmdLen) do Inc(I); DGramType := Copy(CmdBuf, 2, I - 1); DatagramIn(DGramType, CmdBuf + I + 2, CmdLen - I - 2, CmdBuf[I + 1]); end else begin { We've got a reply } CrackHeader(CmdBuf, CmdLen, FAnswerStatus, ParamStr, ParamLen); if Assigned(FAnswer) then begin {$IFNDEF NODATACOPY} { This will allocate memory because we reseted the size before } FAnswer.DataBufferSize := ParamLen + FAnswer.HeaderSize; { Warning: DataBufferSize may be greater than allocated value ! } FAnswer.DataBufferCount := ParamLen + FAnswer.HeaderSize; // 25/08/98 { Copy the data to the allocated memory } Move(ParamStr^, FAnswer.DataBuffer[FAnswer.HeaderSize], ParamLen); {$ELSE} { Do not copy data, use it where it is... } { This is dangerous because data can be moved or overwritten if } { some communication take place before data is processed. } { Use only if you know exactly what your are doing } FAnswer.DataBuffer := CmdBuf; { This will free allocated memory } FAnswer.DataBufferSize := CmdLen; FAnswer.DataBufferCount := CmdLen; FAnswer.HeaderSize := ParamStr - CmdBuf; {$ENDIF} { Those two assignations are needed to reset the record count } FAnswer.HasData := FALSE; FAnswer.HasData := TRUE; FAnswer.First; PostMessage(FHandle, FMsg_WM_REQUESTDONE, 0, 0); end else PostMessage(FHandle, FMsg_WM_REQUESTDONE, 0, 1); end; TriggerAfterProcessReply(CmdBuf, CmdLen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.DatagramIn( const DGramType : AnsiString; Data : PansiChar; DataLen : Integer; EscChar : AnsiChar); var I, J : Integer; begin // Allocate memory for the buffer if not already done if not Assigned(FDatagramInBuffer) then begin if DataLen >= FDatagramInBufferSize then FDatagramInBufferSize := DataLen + 2048; GetMem(FDatagramInBuffer, FDatagramInBufferSize); end else if FDatagramInBufferSize < DataLen then begin // Need to enlarge buffer (2KB increment) FDatagramInBufferSize := DataLen + 2048; ReallocMem(FDatagramInBuffer, FDatagramInBufferSize); end; I := 0; J := 0; while I < DataLen do begin if Data[I] <> EscChar then FDatagramInBuffer[J] := Data[I] else begin Inc(I); case Data[I] of 'C': FDatagramInBuffer[J] := #13; 'L': FDatagramInBuffer[J] := #10; 'N': FDatagramInBuffer[J] := #0; else if Data[I] = EscChar then FDatagramInBuffer[J] := EscChar else FDatagramInBuffer[J] := Data[I]; end; end; Inc(I); Inc(J); end; FDatagramInBuffer[J] := #0; // Just easier to debug when nul termintated TriggerDatagramAvailable(DGramType, FDatagramInBuffer, J); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.SetRcvSize(const Value: LongInt); begin if Value <> FRcvSize then begin if Value < FRcvCnt then FRcvSize := FRcvCnt // Never less that what we have for data ! else FRcvSize := Value; ReallocMem(FRcvBuf, FRcvSize); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.DataAvailable(Sender : TObject; ErrCode : Word); var Len : Integer; NewLen : Integer; I : Integer; {$IFDEF OLD_ALLOCATION_SCHEME} p : PChar; {$ENDIF} CurrentRcvSizeInc : Integer; begin { Check if the buffer is big enough } NewLen := FRcvCnt + FWSocket.RcvdCount; if NewLen >= FRcvSize then begin { The buffer is too small. Allocate a new one which is greater } CurrentRcvSizeInc := FRcvSizeInc; if CurrentRcvSizeInc = 0 then begin // USc 08/10/2005 dynamic buffer increase CurrentRcvSizeInc := FRcvSize div 4; if CurrentRcvSizeInc < DefaultRcvSizeMinInc then CurrentRcvSizeInc := DefaultRcvSizeMinInc; end; if NewLen < FRcvSize + CurrentRcvSizeInc then NewLen := FRcvSize + CurrentRcvSizeInc; {$IFDEF OLD_ALLOCATION_SCHEME} GetMem(p, NewLen); { Move the existing data to the new buffer } Move(FRcvBuf^, p^, FRcvCnt); { Release the old buffer } FreeMem(FRcvBuf, FRcvSize); { Makes the new buffer the effective buffer } FRcvBuf := p; FRcvSize := NewLen; {$ELSE} ReallocMem(FRcvBuf, NewLen); FRcvSize := NewLen; {$ENDIF} end; { Receive data from the TCP/IP low level buffers } Len := FWSocket.Receive(@FRcvBuf[FRcvCnt], FRcvSize - FRcvCnt - 1); FLastReplyRXTime := Now; if Len <= 0 then Exit; FRcvCnt := FRcvCnt + Len; FRcvBuf[FRcvCnt] := #0; { Parse the received data to findout complete lines (search for LF) } while TRUE do begin I := FRcvCnt - Len; while (I < FRcvCnt) and (FRcvBuf[I] <> #10) do Inc(I); if I >= FRcvCnt then Exit; FRcvBuf[I] := #0; FLastReplyTime := Now; if (I > 1) and (FRcvBuf[I - 1] = #13) then begin FRcvBuf[I - 1] := #0; ProcessLine(FRcvBuf, I - 1); FRcvBuf[I - 1] := #13; end else begin FRcvBuf[0] := #0; // May 19, 2003. Clear #13 ProcessLine(FRcvBuf, I); end; FRcvBuf[I] := #10; if I >= (FRcvCnt - 1) then begin FRcvCnt := 0; FRcvBuf[0] := #0; break; end; Move(FRcvBuf[I + 1], FRcvBuf^, FRcvCnt - I); FRcvCnt := FRcvCnt - I - 1; //Len := Len - I - 1; { FP: 980619 } Len := FRcvCnt; { FP: 20020406 } end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.DataSent(Sender : TObject; ErrCode : Word); begin PostMessage(FHandle, FMsg_WM_DATASENT, 0, ErrCode); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.WMDataSent(var MsgRec: TMessage); var OldSendType : TApsCliSendType; begin //WriteLn('TAppSrvClient.WMDataSent ' + IntToStr(Ord(FSendType))); OldSendType := FSendType; FSendType := acstNone; case OldSendType of acstRequest: TriggerRequestSent; acstDatagram: TriggerDatagramSent; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.SendDatagramString( const DGramType : AnsiString; const S : AnsiString); begin SendDatagram(DGramType, PAnsiChar(S), Length(S)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.SendDatagram( const DGramType : AnsiString; Data : PAnsiChar; Size : Integer); var Header : AnsiString; I, J : Integer; EscChar : AnsiChar; begin //WriteLn('TAppSrvClient.SendDatagram'); // Allocate memory for the buffer if not already done if not Assigned(FDatagramOutBuffer) then begin if Size > (FDatagramOutBufferSize - 3) then FDatagramOutBufferSize := Size + 3; GetMem(FDatagramOutBuffer, FDatagramOutBufferSize); end; // Escape characters in datagram (same mechanism as implemented in TMWBuffer) EscChar := FRequest.EscSep; I := 0; J := 0; while I < Size do begin // Check if we have enough place for an EscChar, a Char and a nul if (J + 3) > FDatagramOutBufferSize then begin // Need to enlarge buffer (2KB increment) FDatagramOutBufferSize := FDatagramOutBufferSize + 2048; ReallocMem(FDatagramOutBuffer, FDatagramOutBufferSize); end; if Data[I] = EscChar then begin FDatagramOutBuffer[J] := EscChar; Inc(J); FDatagramOutBuffer[J] := EscChar; end else if Data[I] = #13 then begin FDatagramOutBuffer[J] := EscChar; Inc(J); FDatagramOutBuffer[J] := 'C'; end else if Data[I] = #10 then begin FDatagramOutBuffer[J] := EscChar; Inc(J); FDatagramOutBuffer[J] := 'L'; end else if Data[I] = #0 then begin FDatagramOutBuffer[J] := EscChar; Inc(J); FDatagramOutBuffer[J] := 'N'; end else FDatagramOutBuffer[J] := Data[I]; Inc(I); Inc(J); end; FDatagramOutBuffer[J] := #0; FSendType := acstDatagram; Header := '^' + DGramType + ' ' + EscChar; FRequestHeader := @Header[1]; FRequestHeaderLen := Length(Header); FRequestBody := FDatagramOutBuffer; FRequestBodyLen := J; TriggerBeforeSendRequest; FWSocket.PutDataInSendBuffer(FRequestHeader, FRequestHeaderLen); FWSocket.PutDataInSendBuffer(FRequestBody, FRequestBodyLen); FWSocket.SendStr(#13#10); TriggerAfterSendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.SendRequest; var Header : AnsiString; begin //WriteLn('TAppSrvClient.SendRequest'); if not Assigned(FRequest) then raise AppSrvClientException.Create( 'TAppSrvClient.SendRequest: Request property not assigned'); FState := cstWaitingResponse; FSendType := acstRequest; FWSocket.OnDataAvailable := DataAvailable; FWSocket.OnSessionClosed := SessionClosed; Header := AnsiString(FFunctionCode) + ' '; FRequestHeader := @Header[1]; FRequestHeaderLen := Length(Header); FRequestBody := FRequest.DataBuffer + FRequest.HeaderSize; FRequestBodyLen := FRequest.DataBufferCount; TriggerBeforeSendRequest; FWSocket.PutDataInSendBuffer(FRequestHeader, FRequestHeaderLen); FWSocket.PutDataInSendBuffer(FRequestBody, FRequestBodyLen); FWSocket.SendStr(#13#10); TriggerAfterSendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.Send; begin //WriteLn('TAppSrvClient.Send'); if not Assigned(FAnswer) then raise AppSrvClientException.Create('TAppSrvClient.Send: Answer property not assigned'); { Empty the answer } FAnswer.DataBuffer := nil; // This will free the allocated memory FAnswer.DataBufferSize := 0; FAnswer.DataBufferCount := 0; FAnswer.HasData := FALSE; { Flag OnRequestDone not already called } FRequestDoneFlag := FALSE; if FWSocket.State = wsConnected then SendRequest else begin { Not connected. Start the event chain until send request } FBannerRcvd := FALSE; FState := cstDnsLookup; FWSocket.OnDnsLookupDone := DnsLookupDone; DoDnsLookup; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.DoDnsLookup; begin if FSocksServer = '' then FWSocket.DnsLookup(FServer) else begin FWSocket.DnsLookup(FSocksServer); FWSocket.Addr := FServer; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.Close; begin if FState = cstDnsLookup then FWSocket.CancelDnsLookup else if FWSocket.State <> wsClosed then FWSocket.Close else FState := cstReady; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TAppSrvClient.GetConnected : Boolean; begin Result := FWSocket.State = wsConnected; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppSrvClient.SetName(const NewName: TComponentName); begin inherited SetName(NewName); if Assigned(FWSocket) then FWSocket.Name := 'WSocket_' + NewName; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { You must define USE_SSL so that SSL code is included in the component. } { To be able to compile the component, you must have the SSL related files } { which are _NOT_ freeware. See http://www.overbyte.be for details. } {$IFDEF USE_SSL} {$I ApsCliImplSsl.inc} {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
unit DelphiUp.View.Components.Buttons.Attributes; interface uses DelphiUp.View.Components.Buttons.Interfaces, System.SysUtils, System.UITypes, FMX.Types; type TButtonAttributes<T : class> = class(TInterfacedObject, iComponentButtonAttributes<T>) private [weak] FParent : T; FTitle : String; FSubTitle : String; FImage : String; FOnClick : TProc<TObject>; FBackground : TAlphaColor; FDestBackground : TAlphaColor; FAlign : TAlignLayout; FFontSize : Integer; FFontSizeSubTitle : Integer; FFontColor : TAlphaColor; public constructor Create(Parent : T); destructor Destroy; override; class function New(Parent : T) : iComponentButtonAttributes<T>; function Title ( aValue : String ) : iComponentButtonAttributes<T>; overload; function Title : String; overload; function SubTitle ( aValue : String ) : iComponentButtonAttributes<T>; overload; function SubTitle : String; overload; function Image ( aValue : String ) : iComponentButtonAttributes<T>; overload; function Image : String; overload; function OnClick ( aValue : TProc<TObject> ) : iComponentButtonAttributes<T>; overload; function OnClick : TProc<TObject>; overload; function Background ( aValue : TAlphaColor ) : iComponentButtonAttributes<T>; overload; function Background : TAlphaColor; overload; function DestBackground ( aValue : TAlphaColor ) : iComponentButtonAttributes<T>; overload; function DestBackground : TAlphaColor; overload; function Align ( aValue : TAlignLayout ) : iComponentButtonAttributes<T>; overload; function Align : TAlignLayout; overload; function FontSize ( aValue : Integer ) : iComponentButtonAttributes<T>; overload; function FontSize : Integer; overload; function FontSizeSubTitle ( aValue : Integer ) : iComponentButtonAttributes<T>; overload; function FontSizeSubTitle : Integer; overload; function FontColor ( aValue : TAlphaColor ) : iComponentButtonAttributes<T>; overload; function FontColor : TAlphaColor; overload; function &End : T; end; implementation { TButtonAttributes<T> } function TButtonAttributes<T>.Align( aValue: TAlignLayout): iComponentButtonAttributes<T>; begin Result := Self; FAlign := aValue; end; function TButtonAttributes<T>.Align: TAlignLayout; begin Result := FAlign; end; function TButtonAttributes<T>.Background: TAlphaColor; begin Result := FBackground end; function TButtonAttributes<T>.Background( aValue: TAlphaColor): iComponentButtonAttributes<T>; begin Result := Self; FBackground := aValue; end; function TButtonAttributes<T>.&End: T; begin Result := FParent; end; constructor TButtonAttributes<T>.Create(Parent : T); begin FParent := Parent; end; function TButtonAttributes<T>.DestBackground: TAlphaColor; begin Result := FDestBackground; end; function TButtonAttributes<T>.DestBackground( aValue: TAlphaColor): iComponentButtonAttributes<T>; begin Result := Self; FDestBackground := aValue; end; destructor TButtonAttributes<T>.Destroy; begin inherited; end; function TButtonAttributes<T>.FontColor: TAlphaColor; begin Result := FFontColor; end; function TButtonAttributes<T>.FontColor( aValue: TAlphaColor): iComponentButtonAttributes<T>; begin Result := Self; FFontColor := aValue; end; function TButtonAttributes<T>.FontSize( aValue: Integer): iComponentButtonAttributes<T>; begin Result := Self; FFontSize := aValue; end; function TButtonAttributes<T>.FontSize: Integer; begin Result := FFontSize; end; function TButtonAttributes<T>.FontSizeSubTitle: Integer; begin Result := FFontSizeSubTitle; end; function TButtonAttributes<T>.FontSizeSubTitle( aValue: Integer): iComponentButtonAttributes<T>; begin Result := Self; FFontSizeSubTitle := aValue; end; function TButtonAttributes<T>.Image: String; begin Result := FImage; end; function TButtonAttributes<T>.Image( aValue: String): iComponentButtonAttributes<T>; begin Result := Self; FImage := aValue; end; class function TButtonAttributes<T>.New(Parent : T): iComponentButtonAttributes<T>; begin Result := Self.Create(Parent); end; function TButtonAttributes<T>.OnClick: TProc<TObject>; begin Result := FOnClick; end; function TButtonAttributes<T>.SubTitle: String; begin Result := FSubTitle; end; function TButtonAttributes<T>.SubTitle( aValue: String): iComponentButtonAttributes<T>; begin Result := Self; FSubTitle := aValue; end; function TButtonAttributes<T>.OnClick( aValue: TProc<TObject>): iComponentButtonAttributes<T>; begin Result := Self; FOnClick := aValue; end; function TButtonAttributes<T>.Title( aValue: String): iComponentButtonAttributes<T>; begin Result := Self; FTitle := aValue; end; function TButtonAttributes<T>.Title: String; begin Result := FTitle; end; end.
UNIT Queue; INTERFACE PROCEDURE EmptyQ; {Очистить очередь} PROCEDURE AddQ(VAR Elt: CHAR); {Добавить в конец очереди элемент (символ)} PROCEDURE DelQ; {Удалить 1ый элемент очереди} PROCEDURE HeadQ(VAR Elt: CHAR); {Поместить в Elt 1ый элемент очереди} PROCEDURE WriteQ; {Печать очереди} IMPLEMENTATION VAR Q: TEXT; PROCEDURE EmptyQ; {Q := < , /, R>} BEGIN {EmptyQ} REWRITE(Q); WRITELN(Q); RESET(Q) END; {EmptyQ} PROCEDURE CopyOpen(VAR F1, F2: TEXT); VAR Ch: CHAR; BEGIN {CopyOpen} WHILE NOT EOLN(F1) DO BEGIN READ(F1, Ch); WRITE(F2, Ch) END END; {CopyOpen} PROCEDURE DelQ; { Q = < , /, R> --> (Q = < ,ax/, R>, где a - символ и x - строка)| Q:= < , x/, R> } VAR Ch: CHAR; Temp: TEXT; BEGIN {DelQ} READ(Q, Ch); IF NOT EOF(Q) THEN BEGIN REWRITE(Temp); CopyOpen(Q, Temp); WRITELN(Temp); RESET(Temp); REWRITE(Q); CopyOpen(Temp, Q); WRITELN(Q) END; RESET(Q) END; {DelQ} PROCEDURE HeadQ(VAR Elt: CHAR); {(Q = < , /, R> --> Elt := '#')| (Q = < ,ax/, R>, где a - символ, а x - строка, Elt:= 'a') } BEGIN {HeadQ} IF NOT EOLN(Q) THEN READ(Q, Elt) ELSE Elt := '#'; RESET(Q) END; {HeadQ} PROCEDURE AddQ(VAR Elt: CHAR); {(Q = < , x/, R>, где x - строка, а Elt = a) --> Q = < ,xa/, R> } VAR Temp: TEXT; BEGIN {AddQ} REWRITE(Temp); CopyOpen(Q, Temp); WRITELN(Temp, Elt); REWRITE(Q); RESET(Temp); CopyOpen(Temp, Q); WRITELN(Q); RESET(Q) END; {AddQ} PROCEDURE WriteQ; {(Q = < , x/,R> и OUTPUT =<y, , W>, где y и x - строки) --> OUTPUT := <y&x/, , W> } BEGIN {WriteQ} CopyOpen(Q, OUTPUT); WRITELN('#'); RESET(Q) END;{WriteQ} BEGIN {Queue} END. {Queue}
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.19 10/01/2005 16:31:20 ANeillans Minor bug fix for Exim compatibility. Rev 1.18 11/27/04 3:03:22 AM RLebeau Bug fix for 'STARTTLS' response handling Rev 1.17 6/11/2004 9:38:44 AM DSiders Added "Do not Localize" comments. Rev 1.16 2004.02.03 5:45:46 PM czhower Name changes Rev 1.15 2004.02.03 2:12:18 PM czhower $I path change Rev 1.14 1/28/2004 8:08:10 PM JPMugaas Fixed a bug in SendGreeting. It was sending an invalid EHLO and probably an invalid HELO command. The problem is that it was getting the computer name. There's an issue in NET with that which Kudzu commented on in IdGlobal. Thus, "EHLO<space>" and probably "HELO<space>" were being sent causing a failure. The fix is to to try to get the local computer's DNS name with GStack.HostName. We only use the computer name if GStack.HostName fails. Rev 1.13 1/25/2004 3:11:48 PM JPMugaas SASL Interface reworked to make it easier for developers to use. SSL and SASL reenabled components. Rev 1.12 2004.01.22 10:29:58 PM czhower Now supports default login mechanism with just username and pw. Rev 1.11 1/21/2004 4:03:24 PM JPMugaas InitComponent Rev 1.10 22/12/2003 00:46:36 CCostelloe .NET fixes Rev 1.9 4/12/2003 10:24:08 PM GGrieve Fix to Compile Rev 1.8 25/11/2003 12:24:22 PM SGrobety various IdStream fixes with ReadLn/D6 Rev 1.7 10/17/2003 1:02:56 AM DSiders Added localization comments. Rev 1.6 2003.10.14 1:31:16 PM czhower DotNet Rev 1.5 2003.10.12 6:36:42 PM czhower Now compiles. Rev 1.4 10/11/2003 7:14:36 PM BGooijen Changed IdCompilerDefines.inc path Rev 1.3 10/10/2003 10:45:12 PM BGooijen DotNet Rev 1.2 2003.10.02 9:27:54 PM czhower DotNet Excludes Rev 1.1 6/15/2003 03:28:24 PM JPMugaas Minor class change. Rev 1.0 6/15/2003 01:06:48 PM JPMugaas TIdSMTP and TIdDirectSMTP now share common code in this base class. } unit IdSMTPBase; interface {$i IdCompilerDefines.inc} uses IdEMailAddress, IdMessage, IdMessageClient, IdReply, IdTCPClient; //default property values const DEF_SMTP_PIPELINE = False; IdDEF_UseEhlo = True; //APR: default behavior IdDEF_UseVerp = False; const CAPAPIPELINE = 'PIPELINING'; {do not localize} CAPAVERP = 'VERP'; {do not localize} XMAILER_HEADER = 'X-Mailer'; {do not localize} const RCPTTO_ACCEPT : array [0..1] of SmallInt = (250, 251); MAILFROM_ACCEPT : SmallInt = 250; DATA_ACCEPT : SmallInt = 354; DATA_PERIOD_ACCEPT : SmallInt = 250; RSET_ACCEPT : SmallInt = 250; const RSET_CMD = 'RSET'; {do not localize} MAILFROM_CMD = 'MAIL FROM:'; {do not localize} RCPTTO_CMD = 'RCPT TO:'; {do not localize} DATA_CMD = 'DATA'; {do not localize} type TIdSMTPFailedRecipient = procedure(Sender: TObject; const AAddress, ACode, AText: String; var VContinue: Boolean) of object; TIdSMTPBase = class(TIdMessageClient) protected FMailAgent: string; FHeloName : String; FPipeline : Boolean; FUseEhlo : Boolean; FUseVerp : Boolean; FVerpDelims: string; FOnFailedRecipient: TIdSMTPFailedRecipient; // function GetSupportsTLS : Boolean; override; function GetReplyClass: TIdReplyClass; override; procedure InitComponent; override; procedure SendGreeting; procedure SetUseEhlo(const AValue: Boolean); virtual; procedure SetPipeline(const AValue: Boolean); procedure StartTLS; function FailedRecipientCanContinue(const AAddress: string): Boolean; //No pipeline send methods function WriteRecipientNoPipelining(const AEmailAddress: TIdEmailAddressItem): Boolean; procedure WriteRecipientsNoPipelining(AList: TIdEmailAddressList); procedure SendNoPipelining(AMsg: TIdMessage; const AFrom: String; ARecipients: TIdEMailAddressList); //pipeline send methods procedure WriteRecipientPipeLine(const AEmailAddress: TIdEmailAddressItem); procedure WriteRecipientsPipeLine(AList: TIdEmailAddressList); procedure SendPipelining(AMsg: TIdMessage; const AFrom: String; ARecipients: TIdEMailAddressList); // procedure InternalSend(AMsg: TIdMessage; const AFrom: String; ARecipients: TIdEMailAddressList); virtual; public procedure Send(AMsg: TIdMessage); overload; virtual; procedure Send(AMsg: TIdMessage; ARecipients: TIdEMailAddressList); overload; virtual; procedure Send(AMsg: TIdMessage; const AFrom: string); overload; virtual; procedure Send(AMsg: TIdMessage; ARecipients: TIdEMailAddressList; const AFrom: string); overload; virtual; published property MailAgent: string read FMailAgent write FMailAgent; property HeloName : string read FHeloName write FHeloName; property UseEhlo: Boolean read FUseEhlo write SetUseEhlo default IdDEF_UseEhlo; property PipeLine : Boolean read FPipeLine write SetPipeline default DEF_SMTP_PIPELINE; property UseVerp: Boolean read FUseVerp write FUseVerp default IdDEF_UseVerp; property VerpDelims: string read FVerpDelims write FVerpDelims; // property OnFailedRecipient: TIdSMTPFailedRecipient read FOnFailedRecipient write FOnFailedRecipient; end; implementation uses {$IFDEF VCL_XE3_OR_ABOVE} System.Classes, {$ENDIF} IdAssignedNumbers, IdException, IdGlobal, IdExplicitTLSClientServerBase, IdGlobalProtocols, IdIOHandler, IdReplySMTP, IdSSL, IdStack, SysUtils; //required as we need to get the local computer DNS hostname. { TIdSMTPBase } function TIdSMTPBase.GetReplyClass:TIdReplyClass; begin Result := TIdReplySMTP; end; procedure TIdSMTPBase.InitComponent; begin inherited InitComponent; FImplicitTLSProtPort := IdPORT_ssmtp; FRegularProtPort := IdPORT_SMTP; FPipeLine := DEF_SMTP_PIPELINE; FUseEhlo := IdDEF_UseEhlo; FUseVerp := IdDEF_UseVerp; FMailAgent := ''; FHeloName := ''; Port := IdPORT_SMTP; end; function TIdSMTPBase.GetSupportsTLS: Boolean; begin Result := ( FCapabilities.IndexOf('STARTTLS') > -1 ); //do not localize end; procedure TIdSMTPBase.SendGreeting; var LNameToSend : String; begin Capabilities.Clear; if HeloName <> '' then begin LNameToSend := HeloName; end else begin //Note: IndyComputerName gets the computer name. //This is not always reliable in Indy because in Dot.NET, //it is done with This is available through System.Windows.Forms.SystemInformation.ComputerName //and that requires that we link to a problematic dependancy (Wystem.Windows.Forms). //Besides, I think RFC 821 was refering to the computer's Internet //DNS name. We use the Computer name only if we can't get the DNS name. LNameToSend := GStack.HostName; if LNameToSend = '' then begin LNameToSend := IndyComputerName; end; end; if UseEhlo and (SendCmd('EHLO ' + LNameToSend ) = 250) then begin //APR: user can prevent EHLO {Do not Localize} Capabilities.AddStrings(LastCmdResult.Text); if Capabilities.Count > 0 then begin //we drop the initial greeting. We only want the feature list Capabilities.Delete(0); end; end else begin SendCmd('HELO ' + LNameToSend, 250); {Do not Localize} end; end; procedure TIdSMTPBase.SetPipeline(const AValue: Boolean); begin FPipeLine := AValue; if AValue then begin FUseEhlo := True; end; end; procedure TIdSMTPBase.SetUseEhlo(const AValue: Boolean); begin FUseEhlo := AValue; if not AValue then begin FPipeLine := False; end; end; procedure TIdSMTPBase.SendNoPipelining(AMsg: TIdMessage; const AFrom: String; ARecipients: TIdEMailAddressList); var LCmd: string; begin LCmd := MAILFROM_CMD + '<' + AFrom + '>'; {Do not Localize} if FUseVerp then begin if Capabilities.IndexOf(CAPAVERP) > -1 then begin LCmd := LCmd + ' VERP'; {Do not Localize} end else begin LCmd := LCmd + ' XVERP'; {Do not Localize} end; if FVerpDelims <> '' then begin LCmd := LCmd + '=' + FVerpDelims; {Do not Localize} end; end; SendCmd(RSET_CMD); SendCmd(LCmd, MAILFROM_ACCEPT); try WriteRecipientsNoPipelining(ARecipients); SendCmd(DATA_CMD, DATA_ACCEPT); SendMsg(AMsg); SendCmd('.', DATA_PERIOD_ACCEPT); {Do not Localize} except on E: EIdSMTPReplyError do begin SendCmd(RSET_CMD); raise; end; end; end; procedure TIdSMTPBase.SendPipelining(AMsg: TIdMessage; const AFrom: String; ARecipients: TIdEMailAddressList); var LError : TIdReplySMTP; I, LFailedRecips : Integer; LCmd: string; LBufferingStarted: Boolean; function SetupErrorReply: TIdReplySMTP; begin Result := TIdReplySMTP.Create(nil); Result.Assign(LastCmdResult); end; begin LError := nil; LCmd := MAILFROM_CMD + '<' + AFrom + '>'; {Do not Localize} if FUseVerp then begin if Capabilities.IndexOf(CAPAVERP) > -1 then begin LCmd := LCmd + ' VERP'; {Do not Localize} end else begin LCmd := LCmd + ' XVERP'; {Do not Localize} end; if FVerpDelims <> '' then begin LCmd := LCmd + '=' + FVerpDelims; {Do not Localize} end; end; try LBufferingStarted := not IOHandler.WriteBufferingActive; if LBufferingStarted then begin IOHandler.WriteBufferOpen; end; try IOHandler.WriteLn(RSET_CMD); IOHandler.WriteLn(LCmd); WriteRecipientsPipeLine(ARecipients); IOHandler.WriteLn(DATA_CMD); if LBufferingStarted then begin IOHandler.WriteBufferClose; end; except if LBufferingStarted then begin IOHandler.WriteBufferCancel; end; raise; end; //RSET if PosInSmallIntArray(GetResponse, RSET_ACCEPT) = -1 then begin LError := SetupErrorReply; end; //MAIL FROM: if PosInSmallIntArray(GetResponse, MAILFROM_ACCEPT) = -1 then begin if not Assigned(LError) then begin LError := SetupErrorReply; end; end; //RCPT TO: if ARecipients.Count > 0 then begin LFailedRecips := 0; for I := 0 to ARecipients.Count - 1 do begin if PosInSmallIntArray(GetResponse, RCPTTO_ACCEPT) = -1 then begin Inc(LFailedRecips); if not FailedRecipientCanContinue(ARecipients[I].Address) then begin if not Assigned(LError) then begin LError := SetupErrorReply; end; end; end; end; if not Assigned(LError) and (LFailedRecips = ARecipients.Count) then begin LError := SetupErrorReply; end; end; //DATA - last in the batch if PosInSmallIntArray(GetResponse, DATA_ACCEPT) <> -1 then begin SendMsg(AMsg); if PosInSmallIntArray(SendCmd('.'), DATA_PERIOD_ACCEPT) = -1 then begin {Do not Localize} if not Assigned(LError) then begin LError := SetupErrorReply; end; end; end else begin if not Assigned(LError) then begin LError := SetupErrorReply; end; end; if Assigned(LError) then begin SendCmd(RSET_CMD); LError.RaiseReplyError; end; finally FreeAndNil(LError); end; end; procedure TIdSMTPBase.StartTLS; var LIO : TIdSSLIOHandlerSocketBase; begin try if (IOHandler is TIdSSLIOHandlerSocketBase) and (FUseTLS <> utNoTLSSupport) then begin LIO := TIdSSLIOHandlerSocketBase(IOHandler); //we check passthrough because we can either be using TLS currently with //implicit TLS support or because STARTLS was issued previously. if LIO.PassThrough then begin if SupportsTLS then begin if SendCmd('STARTTLS') = 220 then begin {do not localize} TLSHandshake; //send EHLO SendGreeting; end else begin ProcessTLSNegCmdFailed; end; end else begin ProcessTLSNotAvail; end; end; end; except Disconnect; Raise; end; end; function TIdSMTPBase.FailedRecipientCanContinue(const AAddress: string): Boolean; begin Result := Assigned(FOnFailedRecipient); if Result then begin FOnFailedRecipient(Self, AAddress, LastCmdResult.Code, LastCmdResult.Text.Text, Result); end; end; function TIdSMTPBase.WriteRecipientNoPipelining(const AEmailAddress: TIdEmailAddressItem): Boolean; var LReply: SmallInt; begin LReply := SendCmd(RCPTTO_CMD + '<' + AEMailAddress.Address + '>'); {do not localize} Result := PosInSmallIntArray(LReply, RCPTTO_ACCEPT) <> -1; end; procedure TIdSMTPBase.WriteRecipientPipeLine(const AEmailAddress: TIdEmailAddressItem); begin //we'll read the reply - LATER IOHandler.WriteLn(RCPTTO_CMD + '<' + AEMailAddress.Address + '>'); end; procedure TIdSMTPBase.WriteRecipientsNoPipelining(AList: TIdEmailAddressList); var I, LFailedRecips: Integer; LContinue: Boolean; begin if AList.Count > 0 then begin LFailedRecips := 0; LContinue := True; for I := 0 to AList.Count - 1 do begin if not WriteRecipientNoPipelining(AList[I]) then begin Inc(LFailedRecips); if not FailedRecipientCanContinue(AList[I].Address) then begin LContinue := False; Break; end; end; end; if (not LContinue) or (LFailedRecips = AList.Count) then begin LastCmdResult.RaiseReplyError; end; end; end; procedure TIdSMTPBase.WriteRecipientsPipeLine(AList: TIdEmailAddressList); var I: integer; begin for I := 0 to AList.Count - 1 do begin WriteRecipientPipeLine(AList[I]); end; end; procedure TIdSMTPBase.InternalSend(AMsg: TIdMessage; const AFrom: String; ARecipients: TIdEMailAddressList); begin if Pipeline and (Capabilities.IndexOf(CAPAPIPELINE) > -1) then begin SendPipelining(AMsg, AFrom, ARecipients); end else begin SendNoPipelining(AMsg, AFrom, ARecipients); end; end; // this version of Send() uses the TIdMessage to determine both the // sender and the recipients... procedure TIdSMTPBase.Send(AMsg: TIdMessage); var LRecipients: TIdEMailAddressList; begin LRecipients := TIdEMailAddressList.Create(Self); try LRecipients.AddItems(AMsg.Recipients); LRecipients.AddItems(AMsg.CCList); LRecipients.AddItems(AMsg.BccList); Send(AMsg, LRecipients); finally FreeAndNil(LRecipients); end; end; // this version of Send() uses the TIdMessage to determine the // sender, but sends to the caller's specified recipients procedure TIdSMTPBase.Send(AMsg: TIdMessage; ARecipients: TIdEMailAddressList); var LSender: string; begin LSender := Trim(AMsg.Sender.Address); if LSender = '' then begin LSender := Trim(AMsg.From.Address); end; InternalSend(AMsg, LSender, ARecipients); end; // this version of Send() uses the TIdMessage to determine the // recipients, but sends using the caller's specified sender. // The sender can be empty, which is useful for server-generated // error messages... procedure TIdSMTPBase.Send(AMsg: TIdMessage; const AFrom: string); var LRecipients: TIdEMailAddressList; begin LRecipients := TIdEMailAddressList.Create(Self); try LRecipients.AddItems(AMsg.Recipients); LRecipients.AddItems(AMsg.CCList); LRecipients.AddItems(AMsg.BccList); Send(AMsg, LRecipients, AFrom); finally FreeAndNil(LRecipients); end; end; // this version of Send() uses the caller's specified sender and // recipients. The sender can be empty, which is useful for // server-generated error messages... procedure TIdSMTPBase.Send(AMsg: TIdMessage; ARecipients: TIdEMailAddressList; const AFrom: string); begin InternalSend(AMsg, AFrom, ARecipients); end; end.
unit Frame; interface uses PositionRecord; type TFrame = class protected fImageIndex : Integer; fOffset : TPositionRecord; fLengthSeconds : Double; public constructor Create(aImageIndex : Integer; aOffset : TPositionRecord; aLengthSeconds : Double); function GetLengthSeconds() : Double; function GetOffset() : TPositionRecord; function GetImageIndex() : Integer; end; implementation constructor TFrame.Create(aImageIndex: Integer; aOffset: TPositionRecord; aLengthSeconds: Double); begin fImageIndex := aImageIndex; fOffset := aOffset; fLengthSeconds := aLengthSeconds; end; function TFrame.GetImageIndex: Integer; begin Result := fImageIndex; end; function TFrame.GetLengthSeconds: Double; begin Result := fLengthSeconds; end; function TFrame.GetOffset: TPositionRecord; begin Result := fOffset; end; end.
unit LUX.Data.List.core; interface //#################################################################### ■ type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 TListObject = class; TListParent = class; TListChildr = class; TListEnumer = class; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TListObject TListObject = class private protected _Prev :TListChildr; _Next :TListChildr; ///// アクセス function GetPrev :TListChildr; virtual; function GetNext :TListChildr; virtual; ///// メソッド class procedure Bind( const C0_,C1_:TListChildr ); overload; inline; class procedure Bind( const C0_,C1_,C2_:TListChildr ); overload; inline; class procedure Bind( const C0_,C1_,C2_,C3_:TListChildr ); overload; inline; public constructor Create; overload; virtual; ///// プロパティ property Prev :TListChildr read GetPrev; property Next :TListChildr read GetNext; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TListParent TListParent = class( TListObject ) private ///// アクセス function GetOrigin :TListChildr; procedure SetOrigin( const Origin_:TListChildr ); function GetIndexes( const I_:Integer ) :TListChildr; procedure SetIndexes( const I_:Integer; const Indexe_:TListChildr ); function GetIndexesN :Integer; procedure SetIndexesN( const IndexesN_:Integer ); protected _Indexes :TArray<TListChildr>; _MaxOrder :Integer; _ChildrsN :Integer; ///// アクセス function GetHeader :TListChildr; virtual; function GetTailer :TListChildr; virtual; function GetChildrs( const I_:Integer ) :TListChildr; virtual; procedure SetChildrs( const I_:Integer; const Childr_:TListChildr ); virtual; function GetChildrsN :Integer; virtual; ///// プロパティ property Origin :TListChildr read GetOrigin write SetOrigin ; property Indexes[ const I_:Integer ] :TListChildr read GetIndexes write SetIndexes ; property IndexesN :Integer read GetIndexesN write SetIndexesN; ///// メソッド procedure FindTo( const Childr_:TListChildr ); overload; procedure FindTo( const Order_:Integer ); overload; procedure InsertBind( const C0_,C1_,C2_:TListChildr ); procedure _InsertHead( const Childr_:TListChildr ); procedure _InsertTail( const Childr_:TListChildr ); ///// イベント procedure OnInsertChild( const Childr_:TListChildr ); virtual; procedure OnRemoveChild( const Childr_:TListChildr ); virtual; public constructor Create; overload; override; destructor Destroy; override; ///// プロパティ property Header :TListChildr read GetHeader ; property Tailer :TListChildr read GetTailer ; property Childrs[ const I_:Integer ] :TListChildr read GetChildrs write SetChildrs; default; property ChildrsN :Integer read GetChildrsN ; ///// メソッド procedure Clear; virtual; procedure InsertHead( const Childr_:TListChildr ); procedure InsertTail( const Childr_:TListChildr ); class procedure Swap( const C1_,C2_:TListChildr ); overload; procedure Swap( const I1_,I2_:Integer ); overload; function GetEnumerator: TListEnumer; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TListChildr TListChildr = class( TListObject ) private ///// アクセス function GetIsOrdered :Boolean; protected _Parent :TListParent; _Order :Integer; ///// プロパティ property IsOrdered :Boolean read GetIsOrdered; ///// アクセス function GetParent :TListParent; virtual; procedure SetParent( const Parent_:TListParent ); virtual; function GetOrder :Integer; virtual; procedure SetOrder( const Order_:Integer ); virtual; ///// メソッド procedure _Remove; public constructor Create; overload; override; constructor Create( const Parent_:TListParent ); overload; virtual; destructor Destroy; override; ///// プロパティ property Parent :TListParent read GetParent write SetParent; property Order :Integer read GetOrder write SetOrder ; ///// メソッド procedure Remove; procedure InsertPrev( const Siblin_:TListChildr ); procedure InsertNext( const Siblin_:TListChildr ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TListEnumer TListEnumer = class private protected _Container :TListParent; _Current :TListChildr; ///// アクセス function GetCurrent: TListChildr; virtual; public constructor Create( Container_:TListParent ); ///// プロパティ property Current :TListChildr read GetCurrent; ///// メソッド function MoveNext :Boolean; end; //const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TListObject //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TListObject.GetPrev :TListChildr; begin Result := _Prev; end; function TListObject.GetNext :TListChildr; begin Result := _Next; end; /////////////////////////////////////////////////////////////////////// メソッド class procedure TListObject.Bind( const C0_,C1_:TListChildr ); begin C0_._Next := C1_; C1_._Prev := C0_; end; class procedure TListObject.Bind( const C0_,C1_,C2_:TListChildr ); begin Bind( C0_, C1_ ); Bind( C1_, C2_ ); end; class procedure TListObject.Bind( const C0_,C1_,C2_,C3_:TListChildr ); begin Bind( C0_, C1_ ); Bind( C1_, C2_ ); Bind( C2_, C3_ ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TListObject.Create; begin inherited; _Prev := TListChildr( Self ); _Next := TListChildr( Self ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TListParent //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private /////////////////////////////////////////////////////////////////////// アクセス function TListParent.GetOrigin :TListChildr; begin Result := TListChildr( Self ); end; procedure TListParent.SetOrigin( const Origin_:TListChildr ); begin Indexes[ -1 ] := Origin_; end; function TListParent.GetIndexes( const I_:Integer ) :TListChildr; begin Result := _Indexes[ 1 + I_ ]; end; procedure TListParent.SetIndexes( const I_:Integer; const Indexe_:TListChildr ); begin _Indexes[ 1 + I_ ] := Indexe_; end; function TListParent.GetIndexesN :Integer; begin Result := Length( _Indexes ) - 1; end; procedure TListParent.SetIndexesN( const IndexesN_:Integer ); begin SetLength( _Indexes, IndexesN_ + 1 ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TListParent.GetHeader :TListChildr; begin Result := Origin._Next; end; function TListParent.GetTailer :TListChildr; begin Result := Origin._Prev; end; //------------------------------------------------------------------------------ function TListParent.GetChildrs( const I_:Integer ) :TListChildr; begin if I_ > _MaxOrder then FindTo( I_ ); Result := Indexes[ I_ ]; end; procedure TListParent.SetChildrs( const I_:Integer; const Childr_:TListChildr ); var S :TListChildr; begin with Childrs[ I_ ] do begin S := Childrs[ I_ ]._Prev; Remove; end; S.InsertNext( Childr_ ); end; //------------------------------------------------------------------------------ function TListParent.GetChildrsN :Integer; begin Result := _ChildrsN; end; /////////////////////////////////////////////////////////////////////// メソッド procedure TListParent.FindTo( const Childr_:TListChildr ); var P :TListChildr; begin if _ChildrsN > IndexesN then IndexesN := _ChildrsN; P := Indexes[ _MaxOrder ]; repeat P := P._Next; Inc( _MaxOrder ); Indexes[ _MaxOrder ] := P; P._Order := _MaxOrder; until P = Childr_; end; procedure TListParent.FindTo( const Order_:Integer ); var P :TListChildr; I :Integer; begin if _ChildrsN > IndexesN then IndexesN := _ChildrsN; P := Indexes[ _MaxOrder ]; for I := _MaxOrder + 1 to Order_ do begin P := P._Next; Indexes[ I ] := P; P._Order := I; end; _MaxOrder := Order_; end; //------------------------------------------------------------------------------ procedure TListParent.InsertBind( const C0_,C1_,C2_:TListChildr ); begin C1_._Parent := Self; Bind( C0_, C1_, C2_ ); Inc( _ChildrsN ); OnInsertChild( C1_ ); end; procedure TListParent._InsertHead( const Childr_:TListChildr ); begin InsertBind( Origin, Childr_, Header ); _MaxOrder := -1; end; procedure TListParent._InsertTail( const Childr_:TListChildr ); begin InsertBind( Tailer, Childr_, Origin ); end; /////////////////////////////////////////////////////////////////////// イベント procedure TListParent.OnInsertChild( const Childr_:TListChildr ); begin end; procedure TListParent.OnRemoveChild( const Childr_:TListChildr ); begin end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TListParent.Create; begin inherited; IndexesN := 0; Origin := Origin; _MaxOrder := -1; _ChildrsN := 0; end; destructor TListParent.Destroy; begin Clear; inherited; end; /////////////////////////////////////////////////////////////////////// メソッド procedure TListParent.Clear; var N :Integer; begin for N := 1 to _ChildrsN do Origin._Prev.Free; end; //------------------------------------------------------------------------------ procedure TListParent.InsertHead( const Childr_:TListChildr ); begin Childr_.Remove; _InsertHead( Childr_ ); end; procedure TListParent.InsertTail( const Childr_:TListChildr ); begin Childr_.Remove; _InsertTail( Childr_ ); end; //------------------------------------------------------------------------------ class procedure TListParent.Swap( const C1_,C2_:TListChildr ); var P1, P2 :TListParent; C1n, C1u, C2n, C2u :TListChildr; B1, B2 :Boolean; I1, I2 :Integer; begin with C1_ do begin P1 := _Parent ; B1 := IsOrdered; I1 := _Order ; C1n := _Prev; C1u := _Next; end; with C2_ do begin P2 := _Parent ; B2 := IsOrdered; I2 := _Order ; C2n := _Prev; C2u := _Next; end; C1_._Parent := P2; C2_._Parent := P1; if C1_ = C2n then Bind( C1n, C2_, C1_, C2u ) else if C1_ = C2u then Bind( C2n, C1_, C2_, C1u ) else begin Bind( C1n, C2_, C1u ); Bind( C2n, C1_, C2u ); end; if B1 then begin P1.Indexes[ I1 ] := C2_; C2_._Order := I1; end; if B2 then begin P2.Indexes[ I2 ] := C1_; C1_._Order := I2; end; end; procedure TListParent.Swap( const I1_,I2_:Integer ); begin Swap( Childrs[ I1_ ], Childrs[ I2_ ] ); end; //------------------------------------------------------------------------------ function TListParent.GetEnumerator: TListEnumer; begin Result := TListEnumer.Create( Self ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TListChildr //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private /////////////////////////////////////////////////////////////////////// アクセス function TListChildr.GetIsOrdered :Boolean; begin Result := ( _Order <= _Parent._MaxOrder ) and ( _Parent.Indexes[ _Order ] = Self ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TListChildr.GetParent :TListParent; begin Result := _Parent; end; procedure TListChildr.SetParent( const Parent_:TListParent ); begin Remove; if Assigned( Parent_ ) then Parent_._InsertTail( Self ); end; //------------------------------------------------------------------------------ function TListChildr.GetOrder :Integer; begin if not IsOrdered then _Parent.FindTo( Self ); Result := _Order; end; procedure TListChildr.SetOrder( const Order_:Integer ); begin TListParent.Swap( Self, _Parent.Childrs[ Order_ ] ); end; /////////////////////////////////////////////////////////////////////// メソッド procedure TListChildr._Remove; begin Bind( _Prev, _Next ); if IsOrdered then _Parent._MaxOrder := _Order - 1; with _Parent do begin Dec( _ChildrsN ); if _ChildrsN * 2 < IndexesN then IndexesN := _ChildrsN; end; _Parent := nil; _Order := -1; _Prev := Self; _Next := Self; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TListChildr.Create; begin inherited; _Parent := nil; _Order := -1; end; constructor TListChildr.Create( const Parent_:TListParent ); begin Create; Parent_._InsertTail( Self ); end; destructor TListChildr.Destroy; begin Remove; inherited; end; /////////////////////////////////////////////////////////////////////// メソッド procedure TListChildr.Remove; begin if Assigned( _Parent ) then _Remove; end; //------------------------------------------------------------------------------ procedure TListChildr.InsertPrev( const Siblin_:TListChildr ); begin Siblin_.Remove; _Parent.InsertBind( _Prev, Siblin_, Self ); if IsOrdered then _Parent._MaxOrder := _Order - 1; end; procedure TListChildr.InsertNext( const Siblin_:TListChildr ); begin Siblin_.Remove; _Parent.InsertBind( Self, Siblin_, _Next ); if IsOrdered then _Parent._MaxOrder := _Order; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TListEnumer //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TListEnumer.GetCurrent: TListChildr; begin Result := _Current; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TListEnumer.Create( Container_:TListParent ); begin inherited Create; _Container := Container_; _Current := Container_.Origin; end; /////////////////////////////////////////////////////////////////////// メソッド function TListEnumer.MoveNext :Boolean; begin _Current := _Current.Next; Result := _Current <> _Container.Origin; end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 end. //######################################################################### ■
unit RichMemoRTF; interface {$mode objfpc}{$h+} uses Classes, SysUtils, LCLProc, LCLIntf, LConvEncoding, Graphics, RichMemo, RTFParsPre211; function MVCParserLoadStream(ARich: TCustomRichMemo; Source: TStream): Boolean; procedure RegisterRTFLoader; type TEncConvProc = function (const s: string): string; //todo: rewrite! it's not language based but fontchar-set based procedure LangConvAdd(lang: Integer; convproc: TEncConvProc); function LangConvGet(lang: Integer; var convproc: TEncConvProc): Boolean; type TSaveParams = record // reserved start : Integer; // the first character for the extract len : Integer; // the number of characters to extract end; // the function depends on GetStyleRange and to be implemented properly // if GetStyleRange, GetParaMetric, GetParaAlignment is not working properly // the resulting RTF would not contain any styles or the text styles would be wrong procedure IntSaveStream(ARich: TcustomRichMemo; SaveParams: TSaveParams; Dst: TStream); function SaveStream(ARich: TCustomRichMemo; Dst: TStream): Boolean; procedure RegisterRTFSaver; implementation var LangConvTable : array of record lang: integer; proc: TEncConvProc end; LangCount : Integer = 0; procedure LangConvAdd(lang: Integer; convproc: TEncConvProc); var i : integer; begin for i:=0 to LangCount-1 do if LangConvTable[i].lang=lang then begin LangConvTable[i].proc:=convproc; Exit; end; if LangCount=length(LangConvTable) then begin if LangCount=0 then SetLength(LangConvTable, 64) else SetLength(LangConvTable, LangCount*2); end; LangConvTable[LangCount].lang:=lang; LangConvTable[LangCount].proc:=convproc; inc(LangCount); end; type { TRTFMemoParser } { TRTFParams } TRTFParams = class(TObject) public fnt : TFontParams; pm : TParaMetric; pa : TParaAlignment; fnum : Integer; // font index in the font table prev : TRTFParams; constructor Create(aprev: TRTFParams); end; TRTFMemoParser = class(TRTFParser) private txtbuf : String; // keep it UTF8 encoded! txtlen : Integer; HLFromCTable : Boolean; prm : TRTFParams; lang : Integer; langproc : TEncConvProc; procedure AddText(const atext: string); protected procedure classUnk; procedure classText; procedure classControl; procedure classGroup; procedure classEof; procedure doChangePara(aminor, aparam: Integer); procedure doSpecialChar; procedure doChangeCharAttr(aminor, aparam: Integer); function DefaultTextColor: TColor; procedure PushText; public Memo : TCustomRichMemo; constructor Create(AMemo: TCustomRichMemo; AStream: TStream); procedure StartReading; end; function LangConvGet(lang: Integer; var convproc: TEncConvProc): Boolean; var i : integer; begin for i:=0 to LangCount-1 do if LangConvTable[i].lang=lang then begin convproc:=LangConvTable[i].proc; Result:=true; Exit; end; Result:=false; end; procedure LangConvInit; begin LangConvAdd(1052, @CP1250ToUTF8); // Albanian LangConvAdd(1050, @CP1250ToUTF8); // Croatian LangConvAdd(1029, @CP1250ToUTF8); // Czech LangConvAdd(1038, @CP1250ToUTF8); // Hungarian LangConvAdd(1045, @CP1250ToUTF8); // Polish LangConvAdd(1048, @CP1250ToUTF8); // Romanian LangConvAdd(2074, @CP1250ToUTF8); // Serbian - Latin LangConvAdd(1051, @CP1250ToUTF8); // Slovak LangConvAdd(1060, @CP1250ToUTF8); // Slovenian LangConvAdd(2092, @CP1251ToUTF8); // Azeri - Cyrillic LangConvAdd(1059, @CP1251ToUTF8); // Belarusian LangConvAdd(1026, @CP1251ToUTF8); // Bulgarian LangConvAdd(1071, @CP1251ToUTF8); // FYRO Macedonia LangConvAdd(1087, @CP1251ToUTF8); // Kazakh LangConvAdd(1088, @CP1251ToUTF8); // Kyrgyz - Cyrillic LangConvAdd(1104, @CP1251ToUTF8); // Mongolian LangConvAdd(1049, @CP1251ToUTF8); // Russian LangConvAdd(3098, @CP1251ToUTF8); // Serbian - Cyrillic LangConvAdd(1092, @CP1251ToUTF8); // Tatar LangConvAdd(1058, @CP1251ToUTF8); // Ukrainian LangConvAdd(2115, @CP1251ToUTF8); // Uzbek - Cyrillic LangConvAdd(1078, @CP1252ToUTF8); // Afrikaans LangConvAdd(1069, @CP1252ToUTF8); // Basque LangConvAdd(1027, @CP1252ToUTF8); // Catalan LangConvAdd(1030, @CP1252ToUTF8); // Danish LangConvAdd(2067, @CP1252ToUTF8); // Dutch - Belgium LangConvAdd(1043, @CP1252ToUTF8); // Dutch - Netherlands LangConvAdd(3081, @CP1252ToUTF8); // English - Australia LangConvAdd(10249,@CP1252ToUTF8); // English - Belize LangConvAdd(4105, @CP1252ToUTF8); // English - Canada LangConvAdd(9225, @CP1252ToUTF8); // English - Caribbean LangConvAdd(2057, @CP1252ToUTF8); // English - Great Britain LangConvAdd(6153, @CP1252ToUTF8); // English - Ireland LangConvAdd(8201, @CP1252ToUTF8); // English - Jamaica LangConvAdd(5129, @CP1252ToUTF8); // English - New Zealand LangConvAdd(13321,@CP1252ToUTF8); // English - Phillippines LangConvAdd(7177, @CP1252ToUTF8); // English - Southern Africa LangConvAdd(11273,@CP1252ToUTF8); // English - Trinidad LangConvAdd(1033, @CP1252ToUTF8); // English - United States LangConvAdd(12297,@CP1252ToUTF8); // English - Zimbabwe LangConvAdd(1080, @CP1252ToUTF8); // Faroese LangConvAdd(1035, @CP1252ToUTF8); // Finnish LangConvAdd(2060, @CP1252ToUTF8); // French - Belgium LangConvAdd(3084, @CP1252ToUTF8); // French - Canada LangConvAdd(1036, @CP1252ToUTF8); // French - France LangConvAdd(5132, @CP1252ToUTF8); // French - Luxembourg LangConvAdd(6156, @CP1252ToUTF8); // French - Monaco LangConvAdd(4108, @CP1252ToUTF8); // French - Switzerland LangConvAdd(1110, @CP1252ToUTF8); // Galician LangConvAdd(3079, @CP1252ToUTF8); // German - Austria LangConvAdd(1031, @CP1252ToUTF8); // German - Germany LangConvAdd(5127, @CP1252ToUTF8); // German - Liechtenstein LangConvAdd(4103, @CP1252ToUTF8); // German - Luxembourg LangConvAdd(2055, @CP1252ToUTF8); // German - Switzerland LangConvAdd(1039, @CP1252ToUTF8); // Icelandic LangConvAdd(1057, @CP1252ToUTF8); // Indonesian LangConvAdd(1040, @CP1252ToUTF8); // Italian - Italy LangConvAdd(2064, @CP1252ToUTF8); // Italian - Switzerland LangConvAdd(2110, @CP1252ToUTF8); // Malay - Brunei LangConvAdd(1086, @CP1252ToUTF8); // Malay - Malaysia LangConvAdd(1044, @CP1252ToUTF8); // Norwegian - Bokml LangConvAdd(2068, @CP1252ToUTF8); // Norwegian - Nynorsk LangConvAdd(1046, @CP1252ToUTF8); // Portuguese - Brazil LangConvAdd(2070, @CP1252ToUTF8); // Portuguese - Portugal LangConvAdd(1274, @CP1252ToUTF8); // Spanish - Argentina LangConvAdd(16394,@CP1252ToUTF8); // Spanish - Bolivia LangConvAdd(13322,@CP1252ToUTF8); // Spanish - Chile LangConvAdd(9226, @CP1252ToUTF8); // Spanish - Colombia LangConvAdd(5130, @CP1252ToUTF8); // Spanish - Costa Rica LangConvAdd(7178, @CP1252ToUTF8); // Spanish - Dominican Republic LangConvAdd(12298,@CP1252ToUTF8); // Spanish - Ecuador LangConvAdd(17418,@CP1252ToUTF8); // Spanish - El Salvador LangConvAdd(4106, @CP1252ToUTF8); // Spanish - Guatemala LangConvAdd(18442,@CP1252ToUTF8); // Spanish - Honduras LangConvAdd(2058, @CP1252ToUTF8); // Spanish - Mexico LangConvAdd(19466,@CP1252ToUTF8); // Spanish - Nicaragua LangConvAdd(6154, @CP1252ToUTF8); // Spanish - Panama LangConvAdd(15370,@CP1252ToUTF8); // Spanish - Paraguay LangConvAdd(10250,@CP1252ToUTF8); // Spanish - Peru LangConvAdd(20490,@CP1252ToUTF8); // Spanish - Puerto Rico LangConvAdd(1034, @CP1252ToUTF8); // Spanish - Spain (Traditional) LangConvAdd(14346,@CP1252ToUTF8); // Spanish - Uruguay LangConvAdd(8202, @CP1252ToUTF8); // Spanish - Venezuela LangConvAdd(1089, @CP1252ToUTF8); // Swahili LangConvAdd(2077, @CP1252ToUTF8); // Swedish - Finland LangConvAdd(1053, @CP1252ToUTF8); // Swedish - Sweden LangConvAdd(1032, @CP1253ToUTF8); // greek LangConvAdd(1068, @CP1254ToUTF8); // Azeri - Latin LangConvAdd(1055, @CP1254ToUTF8); // turkish LangConvAdd(1091, @CP1254ToUTF8); // Uzbek - Latin LangConvAdd(1037, @CP1255ToUTF8); // hebrew LangConvAdd(5121, @CP1256ToUTF8); // Arabic - Algeria LangConvAdd(15361,@CP1256ToUTF8); // Arabic - Bahrain LangConvAdd(3073, @CP1256ToUTF8); // Arabic - Egypt LangConvAdd(2049, @CP1256ToUTF8); // Arabic - Iraq LangConvAdd(11265,@CP1256ToUTF8); // Arabic - Jordan LangConvAdd(13313,@CP1256ToUTF8); // Arabic - Kuwait LangConvAdd(12289,@CP1256ToUTF8); // Arabic - Lebanon LangConvAdd(4097, @CP1256ToUTF8); // Arabic - Libya LangConvAdd(6145, @CP1256ToUTF8); // Arabic - Morocco LangConvAdd(8193, @CP1256ToUTF8); // Arabic - Oman LangConvAdd(16385,@CP1256ToUTF8); // Arabic - Qatar LangConvAdd(1025, @CP1256ToUTF8); // Arabic - Saudi Arabia LangConvAdd(10241,@CP1256ToUTF8); // Arabic - Syria LangConvAdd(7169, @CP1256ToUTF8); // Arabic - Tunisia LangConvAdd(14337,@CP1256ToUTF8); // Arabic - United Arab Emirates LangConvAdd(9217, @CP1256ToUTF8); // Arabic - Yemen LangConvAdd(1065, @CP1256ToUTF8); // Farsi - Persian LangConvAdd(1056, @CP1256ToUTF8); // Urdu LangConvAdd(1061, @CP1257ToUTF8); // Estonian LangConvAdd(1062, @CP1257ToUTF8); // Latvian LangConvAdd(1063, @CP1257ToUTF8); // Lithuanian LangConvAdd(1066, @CP1258ToUTF8); // vietnam end; { TRTFParams } constructor TRTFParams.Create(aprev: TRTFParams); begin prev:=aprev; if Assigned(prev) then begin fnt:=prev.fnt; pm:=prev.pm; pa:=prev.pa; fnum:=prev.fnum; end else begin InitFontParams(fnt); InitParaMetric(pm) end; end; { TRTFMemoParserr } procedure TRTFMemoParser.AddText(const atext: string); var nl : Integer; l : Integer; begin nl:=txtlen+length(atext); if nl>length(txtbuf) then begin l:=length(txtbuf); while l<nl do if l=0 then l:=256 else l:=l*2; SetLength(txtbuf, l); end; Move(atext[1], txtbuf[txtlen+1], length(atext)); inc(txtlen, length(atext)); end; procedure TRTFMemoParser.classUnk; var txt : string; ws : UnicodeString; begin if not Assigned(prm) then exit; txt:=GetRtfText; if (txt='\object') then begin SkipGroup; Exit; end; if (length(txt)>2) and (txt[1]='\') and (txt[2]='u') and (txt[3] in ['0'..'9']) then begin SetLength(Ws,1); ws[1]:=UnicodeChar(rtfParam); AddText( UTF8Encode(ws) ); end; end; function CharToByte(const ch: AnsiChar): Byte; begin Result:=0; if ch in ['0'..'9'] then Result:=byte(ch)-byte('0') else if ch in ['a'..'f'] then Result:=byte(ch)-byte('a')+10 else if ch in ['A'..'F'] then Result:=byte(ch)-byte('A')+10 end; function RTFCharToByte(const s: string): byte; inline; begin // \'hh A hexadecimal value, based on the specified character set (may be used to identify 8-bit values). Result:=(CharToByte(s[3]) shl 4) or (CharToByte(s[4])); end; procedure TRTFMemoParser.classText; var txt : string; bt : Char; begin if not Assigned(prm) then exit; txt:=Self.GetRtfText; if (length(txt)=4) and (txt[1]='\') and (txt[2]=#39) then begin if Assigned(langproc) then begin bt:=char(RTFCharToByte(txt)); AddText( langproc(bt) ); end; end else begin AddText(txt); end; end; procedure TRTFMemoParser.classControl; begin if not Assigned(prm) then exit; if txtlen>0 then begin PushText; end; //writeln('ctrl: ', rtfClass,' ', rtfMajor, ' ', Self.GetRtfText, ' ',rtfMinor,' ', rtfParam); case rtfMajor of rtfSpecialChar: doSpecialChar; rtfCharAttr: doChangeCharAttr(rtfMinor, rtfParam); rtfParAttr: doChangePara(rtfMinor, rtfParam); end; end; procedure TRTFMemoParser.classGroup; var t : TRTFParams; begin if not Assigned(prm) then exit; //todo: Exit; case rtfMajor of rtfBeginGroup: begin t:=TRTFParams.Create(prm); prm:=t; end; rtfEndGroup: begin t:=prm.prev; prm.Free; prm:=t; end; end; //writeln('group: ', rtfMajor, ' ',rtfMinor,' ', rtfParam, ' ', GetRtfText); end; procedure TRTFMemoParser.classEof; begin PushText; end; procedure TRTFMemoParser.doChangePara(aminor, aparam: Integer); begin case aminor of rtfParDef:begin prm.pa:=paLeft; end; rtfQuadLeft: prm.pa:=paLeft; rtfQuadRight: prm.pa:=paRight; rtfQuadJust: prm.pa:=paJustify; rtfQuadCenter: prm.pa:=paCenter; rtfFirstIndent: begin prm.pm.FirstLine:=aparam / 20; end; rtfLeftIndent: begin prm.pm.HeadIndent:=aparam / 20; end; rtfRightIndent: prm.pm.TailIndent := aparam / 20; rtfSpaceBefore: prm.pm.SpaceBefore := aparam / 20; rtfSpaceAfter: prm.pm.SpaceAfter := aparam / 20; rtfSpaceBetween: prm.pm.LineSpacing := aparam / 200; // \slN - surprise! the "line spacing" is actually a multiplier based on the FONT size, not linesize // where linesize = fontsize * 1.2 rtfLanguage: begin lang:=rtfParam; langproc:=nil; LangConvGet(lang, langproc); end; end; end; procedure TRTFMemoParser.doSpecialChar; const {$ifdef MSWINDOWS} CharPara = #13#10; {$else} CharPara = #10; {$endif} CharTab = #9; CharLine = #13; begin case rtfMinor of rtfOptDest: SkipGroup; rtfLine: AddText(CharLine); rtfPar: AddText(CharPara); rtfTab: AddText(CharTab); end; end; procedure TRTFMemoParser.doChangeCharAttr(aminor, aparam: Integer); var p : PRTFColor; const HColor : array [1..16] of TColor = ( clBlack ,clBlue ,clAqua // Cyan ,clLime // Green ,clFuchsia //Magenta ,clRed ,clYellow ,clGray // unused! ,clNavy // DarkBlue ,clTeal // DarkCyan ,clGreen // DarkGreen ,clPurple // clDarkMagenta ,clMaroon // clDarkRed ,clOlive // clDarkYellow ,clGray //clDarkGray ,clSilver //clLightGray ); begin case aminor of rtfPlain: prm.fnt.Style:=[]; rtfBold: if aparam=0 then Exclude(prm.fnt.Style,fsBold) else Include(prm.fnt.Style, fsBold); rtfItalic: if aparam=0 then Exclude(prm.fnt.Style,fsItalic) else Include(prm.fnt.Style, fsItalic); rtfStrikeThru: if aparam=0 then Exclude(prm.fnt.Style,fsStrikeOut) else Include(prm.fnt.Style, fsStrikeOut); rtfFontNum: prm.fnum:=aparam; rtfFontSize: prm.fnt.Size:=round(aparam/2); rtfUnderline: if aparam=0 then Exclude(prm.fnt.Style,fsUnderline) else Include(prm.fnt.Style, fsUnderline); rtfNoUnderline: Exclude(prm.fnt.Style, fsUnderline); rtfHighlight: begin prm.fnt.HasBkClr := (aparam>0) and (aparam<=high(HColor)); if prm.fnt.HasBkClr then begin if HLFromCTable then prm.fnt.BkColor:=HColor[aparam] else begin p:=Colors[aparam]; if Assigned(p) then prm.fnt.BkColor:=RGBToColor(p^.rtfCRed, p^.rtfCGreen, p^.rtfCBlue) // fallback? else prm.fnt.BkColor:=HColor[aparam]; end; end; end; rtfForeColor: begin if rtfParam<>0 then p:=Colors[rtfParam] else p:=nil; if not Assigned(p) then prm.fnt.Color:=DefaultTextColor else prm.fnt.Color:=RGBToColor(p^.rtfCRed, p^.rtfCGreen, p^.rtfCBlue); end; end; end; function TRTFMemoParser.DefaultTextColor:TColor; begin Result:=ColorToRGB(Memo.Font.Color); end; procedure TRTFMemoParser.PushText; var len : Integer; pf : PRTFFONT; selst : Integer; b : string; begin if not Assigned(prm) then exit; if txtlen=0 then Exit; b:=Copy(txtbuf, 1, txtlen); len:=UTF8Length(b); txtlen:=0; txtbuf:=''; if len=0 then Exit; Memo.SelStart:=MaxInt; selst:=Memo.SelStart; // in order to get the start selection, we need to switch to the last character // and then get the value. SelStart doesn't match GetTextLen, since // "StartSel" is based on number of visible characters (i.e. line break is 1 character) // while GetTextLen is based on number of actual string characters // selst:=Memo.GetTextLen; Memo.SelStart:=selst; Memo.SelLength:=0; Memo.SelText:=b; if Assigned(prm) then begin prm.pm.FirstLine:=prm.pm.HeadIndent+prm.pm.FirstLine; Memo.SetParaMetric(selst, 1, prm.pm ); prm.pm.FirstLine:=prm.pm.FirstLine-prm.pm.HeadIndent; Memo.SetParaAlignment(selst, 1, prm.pa ); end; // Memo.GetTextAttributes(selst, font); pf:=Fonts[prm.fnum]; if Assigned(pf) then prm.fnt.Name:=pf^.rtfFName; //prm.fnt.Size:=round(fsz); //prm.fnt.Style:=fst; //prm.fnt.Color:=ColorToRGB(fColor); //prm.fnt.HasBkClr:=hasbk; //prm.fnt.BkColor:=bcolor; Memo.SetTextAttributes(selst, len, prm.fnt); end; constructor TRTFMemoParser.Create(AMemo:TCustomRichMemo;AStream:TStream); begin inherited Create(AStream); Memo:=AMemo; ClassCallBacks[rtfText]:=@classText; ClassCallBacks[rtfControl]:=@classControl; ClassCallBacks[rtfGroup]:=@classGroup; ClassCallBacks[rtfUnknown]:=@classUnk; ClassCallBacks[rtfEof]:=@classEof; end; procedure TRTFMemoParser.StartReading; var t : TRTFParams; begin Memo.Lines.BeginUpdate; try prm:=TRTFParams.Create(nil); prm.fnt.Size:=12; //\fsN Font size in half-points (the default is 24). prm.fnum:=0; inherited StartReading; PushText; // clear the stack, if overflow while Assigned(prm) do begin t:=prm.prev; prm.Free; prm:=t; end; Memo.SelStart:=0; Memo.SelLength:=0; finally Memo.Lines.EndUpdate; end; end; function MVCParserLoadStream(ARich: TCustomRichMemo; Source: TStream): Boolean; var p : TRTFMemoParser; begin Result:=Assigned(ARich) and Assigned(Source); if not Result then Exit; p:=TRTFMemoParser.Create(ARich, Source); try p.StartReading; finally p.Free; end; Result:=True; end; procedure RegisterRTFLoader; begin RTFLoadStream:=@MVCParserLoadStream; LangConvInit; end; function SaveStream(ARich: TcustomRichMemo; Dst: TStream): Boolean; var p : TSaveParams; begin FillChar(p, sizeof(p), 0); p.start:=-1; p.len:=-1; IntSaveStream(ARich, p, Dst); Result:=True; end; procedure RegisterRTFSaver; begin RTFSaveStream:=@SaveStream; end; type TStyleRange = class(TObject) font : TFontParams; fontId : Integer; // assigned font ID colorId : Integer; textStart : Integer; textLength : Integer; next : TStyleRange; end; procedure FreeStyleList(var root: TStyleRange); var t: TStyleRange; begin while Assigned(root) do begin t:=root.next; root.Free; root:=t; end; end; procedure PrepareFontTable(styleslist: TStyleRange; afontTable: TStringList); var rng : TStyleRange; i : integer; begin rng:=styleslist; while Assigned(rng) do begin i:=afontTable.IndexOf(rng.font.Name); if i<0 then i:=afontTable.Add(rng.font.Name); rng.fontId:=i; rng:=rng.next; end; // {\f0\fswiss\fcharset0 Arial;} end; function ColorToRtfText(const cl: TColor): string; var r: integer; begin r:=ColorToRGB(cl); Result:= '\red'+IntToStR( byte( (r and clRed) shr 0) ) +'\green'+IntToStR( byte( (r and clLime) shr 8) ) +'\blue'+IntToStR( byte( (r and clBlue) shr 16) ); end; procedure PrepareColorTable(styleslist: TStyleRange; acolorTable: TStringList); var rng : TStyleRange; i : integer; t : string; begin rng:=styleslist; acolorTable.Add(''); while Assigned(rng) do begin if rng.font.Color=clBlack then rng.colorId:=0 else begin t:=ColorToRtfText(rng.font.Color); i:=acolorTable.IndexOf(t); if i<0 then i:=acolorTable.Add(t); rng.colorId:=i; end; rng:=rng.next; end; // {\f0\fswiss\fcharset0 Arial;} end; function GetRTFWriteText(const u: UnicodeString; var idx : integer; var isNewPara: Boolean): string; var i : integer; begin Result:=''; i:=idx; isNewPara:=false; while i<=length(u) do begin if u[i]='\' then Result:=Result+'\\' else if u[i]=#10 then begin Result:=Result+'\par '; isNewPara:=true; inc(i); Break; end else if u[i]=#13 then begin Result:=Result+'\par '; isNewPara:=true; inc(i); Break; end else if u[i]<#127 then Result:=Result+char(byte(u[i])) else Result:=Result+'\u'+IntToStr(word(u[i]))+' '; inc(i); end; idx:=i; end; procedure IntSaveStream(ARich: TCustomRichMemo; SaveParams: TSaveParams; Dst: TStream); var ofs : Integer; needlen : Integer; endless : Boolean; root : TStyleRange; // first in the list last : TStyleRange; // last in the list rng : TStyleRange; // temproray st, len : Integer; u : UnicodeString; fontTable : TStringList; colorTable : TStringList; i : Integer; isnewpara : Boolean; s : string; isbold : Boolean; isitalic : Boolean; isuline : Boolean; isColor : integer; pm : TParaMetric; procedure RtfOut(const s: string); begin Dst.Write(s[1], length(s)); end; begin if SaveParams.start<0 then ofs:=0 else ofs:=SaveParams.start; root:=nil; last:=nil; needlen:=SaveParams.len; endless:=needlen<0; while ARich.GetStyleRange(ofs, st, len) do begin rng:=TStyleRange.Create; rng.textStart:=st; if not endless then begin if needlen<len then rng.textLength:=needlen else rng.textLength:=len; dec(needLen, len); end else rng.textLength:=len; ARich.GetTextAttributes(ofs, rng.font); if not Assigned(root) then root:=rng; if Assigned(last) then last.next:=rng; last:=rng; inc(ofs, len); if not endless and (needLen<=0) then break; end; if root=nil then begin // GetStyleRange failed - fallback to simple style export! root:=TStyleRange.Create; root.textStart:=0; root.textLength:=MaxInt; root.font.Name:=ARich.Font.Name; root.font.Size:=ARich.Font.Size; end; fontTable:=TStringList.Create; colorTable:=TStringList.Create; try PrepareFontTable(root, fontTable); PrepareColorTable(root, colorTable); RtfOut('{\rtf1\ansi\ansicp1252\deff0\deflan1033'); // start of RTF if fontTable.Count>0 then begin // at least on font should be present anyway. RtfOut('{\fonttbl'); for i:=0 to fontTable.Count-1 do begin // setting font id, charset to 0 and name RtfOut('{\f'+IntToStR(i)+'\fcharset0 '+fontTable[i]+';}'); end; RtfOut('}'); end; if colorTable.Count>1 then begin RtfOut('{\colortbl'); for i:=0 to colorTable.Count-1 do begin RtfOut( colortable[i] ); RtfOut( ';'); end; RtfOut('}'); end; isnewpara := true; rng:=root; isbold:=false; isitalic:=false; iscolor:=0; while Assigned(rng) do begin ARich.SelStart:=rng.textStart; ARich.SelLength:=rng.textLength; u:=UTF8Decode(ARich.SelText); RtfOut('\f'+IntToStr(rng.fontId)); RtfOut('\fs'+IntToStr(rng.font.Size*2)); if (fsBold in rng.font.Style) then begin RtfOut('\b'); isbold:=true; end else begin if isbold then RtfOut('\b0'); isbold:=false; end; if (fsUnderline in rng.font.Style) then begin RtfOut('\ul'); isuline:=true end else begin if isuline then RtfOut('\ulnone'); isuline:=false; end; if isColor<>rng.colorId then begin RtfOut('\cf'+IntToStR(rng.colorId)); isColor:=rng.ColorId; end; if (fsItalic in rng.font.Style) then begin RtfOut('\i'); isitalic:=true; end else begin if isitalic then RtfOut('\i0'); isitalic:=false; end; RtfOut(' '); i:=1; while i<=length(u) do begin if isNewPara then begin ARich.GetParaMetric(i+rng.textStart, pm); RtfOut('\pard'); case ARich.GetParaAlignment(i+rng.TextStart) of paRight: RtfOut('\qr'); paCenter: RtfOut('\qc'); paJustify: RtfOut('\qj'); else end; RtfOut('\li'+IntToStr(round(pm.HeadIndent*20))); if pm.FirstLine-pm.HeadIndent<>0 then RtfOut('\fi'+IntToStr(round((pm.FirstLine-pm.HeadIndent)*20))); if pm.TailIndent<>0 then RtfOut('\ri'+IntToStr(round(pm.TailIndent*20))); if pm.SpaceAfter<>0 then RtfOut('\sa'+IntToStr(round(pm.SpaceAfter*20))); if pm.SpaceBefore<>0 then RtfOut('\sb'+IntToStr(round(pm.SpaceBefore*20))); if pm.LineSpacing<>0 then RtfOut('\sl'+IntToStr(round(pm.LineSpacing*200))+'\slmult1'); RtfOut(' '); end; s:=GetRTFWriteText(u, i, isnewpara); RtfOut(s); end; rng:=rng.next; end; // end of RTF RtfOut('}'); finally fontTable.Free; colorTable.Free; end; FreeStyleList(root); end; initialization end.
unit crystalcastles_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m6502,main_engine,controls_engine,gfx_engine,rom_engine,pal_engine, sound_engine,pokey,file_engine; function iniciar_ccastles:boolean; implementation const ccastles_rom:array[0..4] of tipo_roms=( (n:'136022-403.1k';l:$2000;p:$2000;crc:$81471ae5),(n:'136022-404.1l';l:$2000;p:$0;crc:$820daf29), (n:'136022-405.1n';l:$2000;p:$4000;crc:$4befc296),(n:'136022-102.1h';l:$2000;p:$8000;crc:$f6ccfbd4), (n:'136022-101.1f';l:$2000;p:$6000;crc:$e2e17236)); ccastles_sprites:array[0..1] of tipo_roms=( (n:'136022-106.8d';l:$2000;p:$0;crc:$9d1d89fc),(n:'136022-107.8b';l:$2000;p:$2000;crc:$39960b7d)); ccastles_pal:array[0..3] of tipo_roms=( (n:'82s129-136022-108.7k';l:$100;p:$0;crc:$6ed31e3b),(n:'82s129-136022-109.6l';l:$100;p:$100;crc:$b3515f1a), (n:'82s129-136022-110.11l';l:$100;p:$200;crc:$068bdc7e),(n:'82s129-136022-111.10k';l:$100;p:$300;crc:$c29c18d9)); var rom_bank:array[0..1,0..$3fff] of byte; hscroll,vscroll,num_bank:byte; outlatch,bitmode_addr:array[0..1] of byte; video_ram:array[0..$7fff] of byte; syncprom,wpprom,priprom:array[0..$ff] of byte; weights_r,weights_g,weights_b:array[0..2] of single; procedure update_video_ccastles; var effy:integer; y,f,effx,mopix,pix,prindex,prvalue,flip,nchar,color:byte; x,pos_videoram:word; screen_data:array[0..255,0..319] of word; screen_sprites:array[0..255,0..319] of byte; procedure put_sprite_cc(nchar:dword;color:word;flip:boolean;sx,sy:byte); var x,y,pos_y,pos_x,pos_x_temp:byte; pos:pbyte; dir:integer; begin pos:=gfx[0].datos; inc(pos,nchar*8*16); if flip then begin pos_y:=15; dir:=-1; pos_x:=7; end else begin pos_y:=0; dir:=1; pos_x:=0; end; for y:=0 to 15 do begin pos_x_temp:=pos_x; for x:=0 to 7 do begin if not(gfx[0].trans[pos^]) then screen_sprites[sx+pos_x_temp,sy+pos_y]:=pos^+color; pos_x_temp:=pos_x_temp+dir; inc(pos); end; pos_y:=pos_y+dir; end; end; begin if (outlatch[1] and $10)<>0 then flip:=$ff else flip:=0; pos_videoram:=((outlatch[1] and $80) shl 1) or $8e00; fillchar(screen_sprites,$14000,$ff); for f:=0 to $27 do begin x:=memoria[pos_videoram+3+(f*4)]; y:=(240-memoria[pos_videoram+1+(f*4)]) and $ff; nchar:=memoria[pos_videoram+(f*4)]; color:=memoria[pos_videoram+2+(f*4)] shr 7; put_sprite_cc(nchar,color shl 3,flip<>0,x,y); end; for y:=0 to 255 do begin // if we're in the VBLANK region, just fill with black if (syncprom[y] and 1)<>0 then begin for x:=0 to 319 do screen_data[y,x]:=paleta[$400]; // non-VBLANK region: merge the sprites and the bitmap end else begin // the "POTATO" chip does some magic here; this is just a guess if (flip<>0) then effy:=(((y-24)+0) xor flip) and $ff else effy:=(((y-24)+vscroll) xor flip) and $ff; if (effy<24) then effy:=24; pos_videoram:=effy*128; // loop over X for x:=0 to 319 do begin // if we're in the HBLANK region, just store black if (x>=256) then begin screen_data[y,x]:=paleta[$400] // otherwise, process normally end else begin effx:=(hscroll+(x xor flip)) and $ff; // low 4 bits = left pixel, high 4 bits = right pixel pix:=(video_ram[pos_videoram+(effx div 2)] shr ((effx and 1)*4)) and $0f; mopix:=screen_sprites[x,y]; { Inputs to the priority PROM: Bit 7 = GND Bit 6 = /CRAM Bit 5 = BA4 Bit 4 = MV2 Bit 3 = MV1 Bit 2 = MV0 Bit 1 = MPI Bit 0 = BIT3} prindex:=$40 or ((mopix and 7) shl 2) or ((mopix and 8) shr 2) or ((pix and 8) shr 3); prvalue:=priprom[prindex]; // Bit 1 of prvalue selects the low 4 bits of the final pixel if (prvalue and 2)<>0 then pix:=mopix; // Bit 0 of prvalue selects bit 4 of the final color pix:=pix or ((prvalue and 1) shl 4); // store the pixel value and also a priority value based on the topmost bit screen_data[y,x]:=paleta[pix]; end; end; end; end; putpixel(0,0,$14000,@screen_data,1); actualiza_trozo(0,24,256,232,1,0,0,256,232,PANT_TEMP); end; procedure eventos_ccastles; begin if main_vars.service1 then marcade.in0:=marcade.in0 and $ef else marcade.in0:=marcade.in0 or $10; if event.arcade then begin //in0 if arcade_input.coin[1] then marcade.in0:=marcade.in0 and $fe else marcade.in0:=marcade.in0 or 1; if arcade_input.coin[0] then marcade.in0:=marcade.in0 and $fd else marcade.in0:=marcade.in0 or 2; if arcade_input.but0[0] then marcade.in0:=marcade.in0 and $bf else marcade.in0:=marcade.in0 or $40; if arcade_input.but1[0] then marcade.in0:=marcade.in0 and $7f else marcade.in0:=marcade.in0 or $80; //in1 if arcade_input.start[0] then marcade.in1:=marcade.in1 and $f7 else marcade.in1:=marcade.in1 or 8; if arcade_input.start[1] then marcade.in1:=marcade.in1 and $ef else marcade.in1:=marcade.in1 or $10; end; end; procedure principal_ccastles; var f:byte; frame:single; begin init_controls(false,false,false,true); frame:=m6502_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to 255 do begin m6502_0.run(frame); frame:=frame+m6502_0.tframes-m6502_0.contador; //video case f of 0:begin marcade.in0:=marcade.in0 or $20; m6502_0.change_irq(ASSERT_LINE); end; 23:marcade.in0:=marcade.in0 and $df; 64,128,192:m6502_0.change_irq(ASSERT_LINE); end; end; update_video_ccastles; eventos_ccastles; video_sync; end; end; procedure bitmode_autoinc; begin // auto increment in the x-direction if it's enabled if (outlatch[1] and 1)=0 then begin // /AX if (outlatch[1] and 4)=0 then bitmode_addr[0]:=bitmode_addr[0]+1 // /XINC else bitmode_addr[0]:=bitmode_addr[0]-1; end; // auto increment in the y-direction if it's enabled if (outlatch[1] and 2)=0 then begin // /AY if (outlatch[1] and 8)=0 then bitmode_addr[1]:=bitmode_addr[1]+1 // /YINC else bitmode_addr[1]:=bitmode_addr[1]-1; end; end; function getbyte_ccastles(direccion:word):byte; var res:byte; tempw:word; begin case direccion of 0,1,3..$7fff:getbyte_ccastles:=video_ram[direccion]; 2:begin // in bitmode, the address comes from the autoincrement latches tempw:=(bitmode_addr[1] shl 7) or (bitmode_addr[0] shr 1); // the appropriate pixel is selected into the upper 4 bits res:=video_ram[tempw] shl ((not(bitmode_addr[0]) and 1)*4); // autoincrement because /BITMD was selected bitmode_autoinc; // the low 4 bits of the data lines are not driven so make them all 1's getbyte_ccastles:=res or $0f; end; $8000..$8fff,$e000..$ffff:getbyte_ccastles:=memoria[direccion]; $9000..$93ff:getbyte_ccastles:=memoria[(direccion and $ff)+$9000]; //nvram_r $9400..$95ff:case (direccion and 3) of 0:getbyte_ccastles:=analog.c[0].y[0]; 1:getbyte_ccastles:=analog.c[0].x[0]; 2,3:getbyte_ccastles:=$ff; end; $9600..$97ff:getbyte_ccastles:=marcade.in0; //in_0 $9800..$99ff:getbyte_ccastles:=pokey_0.read(direccion and $f); $9a00..$9bff:getbyte_ccastles:=pokey_1.read(direccion and $f); $a000..$dfff:getbyte_ccastles:=rom_bank[num_bank,direccion and $3fff]; end; end; procedure ccastles_write_vram(direccion:word;valor:byte;bitmd:boolean;pixba:byte); var promaddr,wpbits:byte; dest:word; begin dest:=direccion and $7ffe; { Inputs to the write-protect PROM: Bit 7 = BA1520 = 0 if (BA15-BA12 != 0), or 1 otherwise Bit 6 = DRBA11 Bit 5 = DRBA10 Bit 4 = /BITMD Bit 3 = GND Bit 2 = BA0 Bit 1 = PIXB Bit 0 = PIXA} promaddr:=(byte((direccion and $f000)=0) shl 7) or ((direccion and $0c00) shr 5) or (byte(not(bitmd)) shl 4) or ((direccion and $0001) shl 2) or (pixba shl 0); // look up the PROM result wpbits:=wpprom[promaddr]; // write to the appropriate parts of VRAM depending on the result if ((wpbits and 1)=0) then video_ram[dest]:=(video_ram[dest] and $f0) or (valor and $0f); if ((wpbits and 2)=0) then video_ram[dest]:=(video_ram[dest] and $0f) or (valor and $f0); if ((wpbits and 4)=0) then video_ram[dest+1]:=(video_ram[dest+1] and $f0) or (valor and $0f); if ((wpbits and 8)=0) then video_ram[dest+1]:=(video_ram[dest+1] and $0f) or (valor and $f0); end; procedure putbyte_ccastles(direccion:word;valor:byte); var tempw:word; r,g,b,bit0,bit1,bit2:byte; color:tcolor; begin case direccion of 0..1:begin ccastles_write_vram(direccion,valor,false,0); bitmode_addr[direccion]:=valor; end; 2:begin tempw:=(bitmode_addr[1] shl 7) or (bitmode_addr[0] shr 1); // the upper 4 bits of data are replicated to the lower 4 bits valor:=(valor and $f0) or (valor shr 4); // write through the generic VRAM routine, passing the low 2 X bits as PIXB/PIXA ccastles_write_vram(tempw,valor,true,bitmode_addr[0] and 3); // autoincrement because /BITMD was selected bitmode_autoinc; end; 3..$7fff:ccastles_write_vram(direccion,valor,false,0); $8000..$8fff:memoria[direccion]:=valor; $9000..$93ff:memoria[(direccion and $ff)+$9000]:=valor; //nvram_w $9800..$99ff:pokey_0.write(direccion and $f,valor); $9a00..$9bff:pokey_1.write(direccion and $f,valor); $9c00..$9c7f:; //nvram_recall_w $9c80..$9cff:hscroll:=valor; $9d00..$9d7f:vscroll:=valor; $9d80..$9dff:m6502_0.change_irq(CLEAR_LINE); $9e00..$9e7f:; //watchdog $9e80..$9eff:case (direccion and 7) of 0..6:; 7:num_bank:=valor and 1; end; $9f00..$9f7f:outlatch[1]:=(outlatch[1] and not(1 shl (direccion and 7))) or (((valor shr 3) and 1) shl (direccion and 7)); $9f80..$9fff:begin // extract the raw RGB bits r:=not(((valor and $c0) shr 6) or ((direccion and $20) shr 3)); b:=not((valor and $38) shr 3); g:=not(valor and $07); // red component (inverted) bit0:=(r shr 0) and $01; bit1:=(r shr 1) and $01; bit2:=(r shr 2) and $01; color.r:=combine_3_weights(@weights_r,bit0,bit1,bit2); // green component (inverted) bit0:=(g shr 0) and $01; bit1:=(g shr 1) and $01; bit2:=(g shr 2) and $01; color.g:=combine_3_weights(@weights_g,bit0,bit1,bit2); // blue component (inverted) bit0:=(b shr 0) and $01; bit1:=(b shr 1) and $01; bit2:=(b shr 2) and $01; color.b:=combine_3_weights(@weights_b,bit0,bit1,bit2); set_pal_color(color,direccion and $1f); end; $a000..$ffff:; //ROM end; end; function input_in1(pot:byte):byte; begin input_in1:=marcade.in1; end; procedure ccastles_sound_update; begin pokey_0.update; pokey_1.update; end; //Main procedure reset_ccastles; begin m6502_0.reset; pokey_0.reset; pokey_1.reset; reset_audio; num_bank:=0; bitmode_addr[0]:=0; bitmode_addr[1]:=0; outlatch[0]:=0; outlatch[1]:=0; hscroll:=0; vscroll:=0; marcade.in0:=$ff; marcade.in1:=$df; end; procedure close_ccastles; begin write_file(Directory.Arcade_nvram+'ccastles.nv',@memoria[$9000],$100); end; function iniciar_ccastles:boolean; var memoria_temp:array[0..$ffff] of byte; longitud:integer; const ps_x:array[0..7] of dword=(0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3); ps_y:array[0..15] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16, 8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16); resistances:array[0..2] of integer=(22000,10000,4700); begin llamadas_maquina.bucle_general:=principal_ccastles; llamadas_maquina.reset:=reset_ccastles; llamadas_maquina.fps_max:=61.035156; llamadas_maquina.close:=close_ccastles; iniciar_ccastles:=false; iniciar_audio(false); screen_init(1,320,256); iniciar_video(256,232); //Main CPU m6502_0:=cpu_m6502.create(10000000 div 8,256,TCPU_M6502); m6502_0.change_ram_calls(getbyte_ccastles,putbyte_ccastles); m6502_0.init_sound(ccastles_sound_update); //analog init_analog(m6502_0.numero_cpu,m6502_0.clock); analog_0(10,-30,$7f,$ff,0,false,true,false,true); //Sound Chip pokey_0:=pokey_chip.create(10000000 div 8); pokey_1:=pokey_chip.create(10000000 div 8); pokey_1.change_all_pot(input_in1); //cargar roms if not(roms_load(@memoria_temp,ccastles_rom)) then exit; copymemory(@rom_bank[0,0],@memoria_temp[0],$4000); copymemory(@memoria[$e000],@memoria_temp[$4000],$2000); copymemory(@rom_bank[1,0],@memoria_temp[$6000],$4000); //Cargar sprites if not(roms_load(@memoria_temp,ccastles_sprites)) then exit; init_gfx(0,8,16,$100); gfx[0].trans[7]:=true; gfx_set_desc_data(3,0,32*8,4,$2000*8,$2000*8+4); convert_gfx(0,0,@memoria_temp,@ps_x,@ps_y,false,false); //poner la paleta if not(roms_load(@memoria_temp,ccastles_pal)) then exit; copymemory(@syncprom,@memoria_temp[0],$100); copymemory(@wpprom,@memoria_temp[$200],$100); copymemory(@priprom,@memoria_temp[$300],$100); compute_resistor_weights(0, 255, -1.0, 3,@resistances,@weights_r,1000,0, 3,@resistances,@weights_g,1000,0, 3,@resistances,@weights_b,1000,0); //cargar NVram if read_file_size(Directory.Arcade_nvram+'ccastles.nv',longitud) then read_file(Directory.Arcade_nvram+'ccastles.nv',@memoria[$9000],longitud); //final reset_ccastles; iniciar_ccastles:=true; end; end.
{ ---------------------------------------------------------------------------- zbnc - Multi user IRC bouncer Copyright (c) Michael "Zipplet" Nixon 2009. Licensed under the MIT license, see license.txt in the project trunk. Unit: socketwrap.pas Purpose: Wrapper for lsocket that provides a multi-connection TCP server. Note: Taken from Neutron NMS (trunk/shared/socketwrap.pas) ---------------------------------------------------------------------------- } unit socketwrap; { ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- } interface uses {$include usescore.inc} classes, sysutils; const sockwrap_version: string = '1.2'; type { -------------------------------------------------------------------------- tconnection: TCP client -------------------------------------------------------------------------- } tconnection = class(tobject) sock: twsocket; calleduser: boolean; destroying: boolean; tag: integer; server: tobject; ptr_next, ptr_prev: tconnection; { events } ondestroy__internal: procedure(client: tconnection) of object; { overrides (when inheriting) } procedure afteraccept; virtual; abstract; procedure beforedestroy(error: integer; local: boolean); virtual; abstract; procedure dataavailable(Sender: TObject; Error: Word); virtual; abstract; procedure bgexception(sender: tobject; e: exception; var canclose: boolean); virtual; abstract; { procs } procedure handleaccept; procedure sessionclosed(Sender: TObject; Error: Word); procedure removesocketevents; procedure handlebgexception(b: boolean); constructor create; virtual; destructor destroy; override; end; { -------------------------------------------------------------------------- tconnectionclass: used to pass the "type of" connection to be created. -------------------------------------------------------------------------- } tconnectionclass = class of tconnection; { -------------------------------------------------------------------------- tservertcp: TCP server -------------------------------------------------------------------------- } tservertcp = class(tobject) sock: twsocket; connections: integer; port: integer; bind: string; listening: boolean; destroying: boolean; l_first, l_last: tconnection; { events } onacceptquery: procedure(peerip: string; peerport: integer; var canaccept: boolean; var createclass: tconnectionclass; var tag: integer) of object; ondisconnect: procedure(client: tconnection) of object; { procs } function listen(lport: integer; bindip: string): boolean; procedure close; procedure dropclients; procedure accepthandler(sender: tobject; error: word); procedure drophandler(client: tconnection); constructor create; destructor destroy; override; end; implementation { ---------------------------------------------------------------------------- tservertcp: accept connection handler (socket) ---------------------------------------------------------------------------- } procedure tservertcp.accepthandler(sender: tobject; error: word); var s: twsocket; b: boolean; c: tconnection; ct: tconnectionclass; tg: integer; begin try s := twsocket.create(nil); s.dup(twsocket(sender).accept); b := false; if assigned(onacceptquery) then begin { s.portnum is almost definately wrong todo: find out the remote port number for onacceptquery. } onacceptquery(s.getpeeraddr, 0, b, ct, tg); end; if not b then begin { onacceptquery returned false so this connection is denied } s.Close; s.Release; exit; end; { accept it } inc(connections); c := ct.create; c.ondestroy__internal := self.drophandler; c.sock := s; c.server := self; c.tag := tg; { insert into list } c.ptr_next := nil; if not assigned(l_first) then begin l_first := c; l_last := c; c.ptr_prev := nil; end else begin l_last.ptr_next := c; c.ptr_prev := l_last; l_last := c; end; { fire the accept } c.handleaccept; except end; end; { ---------------------------------------------------------------------------- Start listening on the given port and bind IP. Returns FALSE if it failed. ---------------------------------------------------------------------------- } function tservertcp.listen(lport: integer; bindip: string): boolean; begin try try port := lport; bind := bindip; sock.addr := bind; sock.Port := inttostr(port); sock.Proto := 'tcp'; sock.OnSessionAvailable := self.accepthandler; sock.Listen; result := true; except result := false; end; listening := result; except end; end; { ---------------------------------------------------------------------------- Stop listening, drop all clients ---------------------------------------------------------------------------- } procedure tservertcp.close; begin try if connections <> 0 then dropclients; sock.Close; listening := false; except end; end; { ---------------------------------------------------------------------------- Drop all clients but keep listening ---------------------------------------------------------------------------- } procedure tservertcp.dropclients; var p, p2: tconnection; begin try if not assigned(l_first) then exit; p := tconnection(l_first); repeat p2 := p.ptr_next; p.Destroy; p := p2; until not assigned(p); except end; end; { ---------------------------------------------------------------------------- tservertcp: Constructor ---------------------------------------------------------------------------- } constructor tservertcp.create; begin try inherited create; sock := twsocket.create(nil); connections := 0; port := 0; bind := ''; listening := false; destroying := false; l_first := nil; l_last := nil; onacceptquery := nil; ondisconnect := nil; except end; end; { ---------------------------------------------------------------------------- tservertcp: Destructor ---------------------------------------------------------------------------- } destructor tservertcp.destroy; begin try if destroying then exit; destroying := true; sock.release; sock := nil; inherited destroy; except end; end; { ---------------------------------------------------------------------------- drop handler (client is going) ---------------------------------------------------------------------------- } procedure tservertcp.drophandler(client: tconnection); begin try if assigned(ondisconnect) then ondisconnect(client); dec(connections); { Remove from the linked list. } if assigned(client.ptr_prev) then client.ptr_prev.ptr_next := client.ptr_next; if assigned(client.ptr_next) then client.ptr_next.ptr_prev := client.ptr_prev; if not assigned(client.ptr_prev) then l_first := client.ptr_next; if not assigned(client.ptr_next) then l_last := client.ptr_prev; except end; end; { ---------------------------------------------------------------------------- **************************************************************************** **************************************************************************** tconnection follows (big marker so I can see it easily while scrolling) **************************************************************************** **************************************************************************** ---------------------------------------------------------------------------- } { ---------------------------------------------------------------------------- Handle bg exceptions? ---------------------------------------------------------------------------- } procedure tconnection.handlebgexception(b: boolean); begin try if b then sock.OnBgException := self.bgexception else sock.onbgexception := nil; except end; end; { ---------------------------------------------------------------------------- Handle an accept ---------------------------------------------------------------------------- } procedure tconnection.handleaccept; begin try { this exists incase I need more actions before passing it on I originally thought I needed it but I may not (and may remove it) } sock.OnSessionClosed := self.sessionclosed; sock.OnDataAvailable := self.dataavailable; afteraccept; except end; end; { ---------------------------------------------------------------------------- Socket: session closed ---------------------------------------------------------------------------- } procedure tconnection.sessionclosed(Sender: TObject; Error: Word); begin try self.destroy; except end; end; { ---------------------------------------------------------------------------- tconnection constructor ---------------------------------------------------------------------------- } constructor tconnection.create; begin try inherited create; calleduser := false; destroying := false; tag := 0; server := nil; except end; end; { ---------------------------------------------------------------------------- tconnection destructor ---------------------------------------------------------------------------- } destructor tconnection.destroy; begin try if destroying then exit; destroying := true; removesocketevents; if not calleduser then begin calleduser := true; beforedestroy(0, true); end; ondestroy__internal(self); sock.release; sock := nil; inherited destroy; except end; end; { ---------------------------------------------------------------------------- Remove all socket events and turn off receiveloop ---------------------------------------------------------------------------- } procedure tconnection.removesocketevents; begin try sock.ComponentOptions := sock.ComponentOptions + [wsonoreceiveloop]; sock.onbgexception := nil; sock.ondataavailable := nil; sock.onsessionclosed := nil; sock.OnDataSent := nil; handlebgexception(false); except end; end; end.
{| Unit: pmord | Version: 1.00 | translated from file pmord.H | Original translation: Peter Sawatzki (ps) | Contributing: | (fill in) | | change history: | Date: Ver: Author: | 11/19/93 1.00 ps original translation by ps } Unit pmord; Interface Uses Os2Def, PmGpi; {***************************** Module Header ******************************\ * * This is the include file which defines all the structures and constants * that can be used to build or intepret GOCA orders for the GPI * * ========================================================================== * * The orders fall into 4 categories :- * * 1) 1-byte orders * * 2) 2-byte orders - second byte contains the value * * 3) Long orders - second byte gives the order length, subsequent bytes * contain the values * * 4) Very long orders - third and fourth bytes gives the order length, * subsequent bytes contain the values * \**************************************************************************} {**************************************************************************\ * * Miscellaneous structures used in this file * \**************************************************************************} { form of RECTL with shorts instead of longs } Type RECT1S = Record { rcs } xLeft, yBottom, xRight, yTop: SHORT End; { form of POINTL with 1 byte offsets instead of longs } ODPOINT = Record { odpt } dx, dy: Char End; { form of SIZEL with shorts instead of longs } SIZES = Record { sizs } cx, cy: SHORT End; { unsigned two-byte swapped integer } SWPUSHORT = Record { swpus } HiByte, LoByte: UCHAR End; {**************************************************************************\ * * 1-byte orders * \**************************************************************************} { macro to tell whether this is a 1-byte order } { UNSURE #define BYTE_ORDER(oc) ((oc)==OCODE_GNOP1 || (oc)==OCODE_GESD) } { 1-byte order codes } Const OCODE_GNOP1 = $00; { No-operation } OCODE_GESD = $FF; { End symbol definition } {**************************************************************************\ * * 2-byte orders * \**************************************************************************} { definitions to help determine whether an order code is a 2-byte order } OCODE2_1 = $80; OCODE2_2 = $88; { UNSURE #define SHORT_ORDER(oc) ((((oc)^OCODE2_1)&OCODE2_2)==OCODE2_2)} { General 2-byte order structure } Type ORDER = Record { ord } idCode, uchData: UCHAR End; { 2-byte order codes } Const OCODE_GBAR = $68; { Begin area } OCODE_GCFIG = $7D; { Close figure } OCODE_GEEL = $49; { End element } OCODE_GEPTH = $7F; { End path } OCODE_GEPROL = $3E; { End prologue } OCODE_GPOP = $3F; { Pop } OCODE_GSBMX = $0D; { Set background mix } OCODE_GPSBMX = $4D; { Push & set b/g mix } OCODE_GSCD = $3A; { Set char direction } OCODE_GPSCD = $7A; { Push & set char direction } OCODE_GSCR = $39; { Set char precision } OCODE_GPSCR = $79; { Push & set char precision } OCODE_GSCS = $38; { Set char set } OCODE_GPSCS = $78; { Push & set char set } OCODE_GSCOL = $0A; { Set color } OCODE_GPSCOL = $4A; { Push & set color } OCODE_GSLE = $1A; { Set line end } OCODE_GPSLE = $5A; { Push & set line end } OCODE_GSLJ = $1B; { Set line join } OCODE_GPSLJ = $5B; { Push & set line join } OCODE_GSLT = $18; { Set line type } OCODE_GPSLT = $58; { Push & set line type } OCODE_GSLW = $19; { Set line width } OCODE_GPSLW = $59; { Push & set line width } OCODE_GSMP = $3B; { Set marker precision } OCODE_GPSMP = $7B; { Push & set marker precision } OCODE_GSMS = $3C; { Set marker set } OCODE_GPSMS = $7C; { Push & set marker set } OCODE_GSMT = $29; { Set marker symbol } OCODE_GPSMT = $69; { Push & set marker symbol } OCODE_GSMX = $0C; { Set mix } OCODE_GPSMX = $4C; { Push & set mix } OCODE_GSPS = $08; { Set pattern set } OCODE_GPSPS = $48; { Push & set pattern set } OCODE_GSPT = $28; { Set pattern symbol } OCODE_GPSPT = $09; { Push & set pattern symbol } { constants for 2-byte orders } { Begin area } GBAR_RESERVED = $80; GBAR_BOUNDARY = $C0; GBAR_NOBOUNDARY = $80; GBAR_WINDING = $A0; GBAR_ALTERNATE = $80; { Set Character Precision } GSCR_PRECISION = $0F; {**************************************************************************\ * * Long orders * \**************************************************************************} { definitions to help determine whether an order code is a long order } OCODE_VLONG = $FE; { UNSURE #define LONG_ORDER(oc) (!((oc)==OCODE_VLONG||BYTE_ORDER(oc)||SHORT_ORDER(oc)))} { long order structure } LORDER_ML = 253; Type LORDER = Record { lord } idCode, uchLength: UCHAR; uchData: Array [0..LORDER_ML-1] Of UCHAR End; { Long orders for which the length of data is normally zero } Const OCODE_GEAR = $60; { End Area } OCODE_GEIMG = $93; { End Image } { Long orders for which the data is contained in a type already defined } { Character String } OCODE_GCCHST = $83; { char string at curr posn } GCCHST_MC = 255; { Max len of string in bytes } OCODE_GCHST = $C3; { char string at given pos } GCHST_SMC = 251; { Max len of string (S) } GCHST_LMC = 247; { Max len of string (L) } { Character String Move } OCODE_GCCHSTM = $B1; { char string move at c.p. } GCCHSTM_MC = 255; { Max len of string in byte } OCODE_GCHSTM = $F1; { char string move at g.p. } GCHSTM_SMC = 251; { Max len of string (S) } GCHSTM_LMC = 247; { Max len of string (L) } { Comment } OCODE_GCOMT = $01; { Comment } GCOMT_ML = 255; { Maximum len of comment data } { Image } OCODE_GIMD = $92; { Image data } GIMD_ML = 255; { Maximum len of image data } { Full Arc } OCODE_GCFARC = $87; { full arc at current posn } OCODE_GFARC = $C7; { full arc at given posn } { Label } OCODE_GLABL = $D3; { Label } { Set Current Position } OCODE_GSCP = $21; { Set current position } OCODE_GPSCP = $61; { Push and set curr posn } { Bezier spline } OCODE_GCBEZ = $A5; { Bezier spline at curr pos } GCBEZ_SMB = 21; { Max number of splines (S) } GCBEZ_LMB = 10; { Max number of splines (L) } OCODE_GBEZ = $E5; { Bezier spline at given pos } GBEZ_SMB = 20; { Max number of splines (S) } GBEZ_LMB = 10; { Max number of splines (L) } { Fillet } OCODE_GCFLT = $85; { fillet at current posn } GCFLT_SMP = 63; { Max number of points (S) } GCFLT_LMP = 31; { Max number of points (L) } OCODE_GFLT = $C5; { fillet at given position } GFLT_SMP = 62; { Max number of points (S) } GFLT_LMP = 30; { Max number of points (L) } { Polyline } OCODE_GCLINE = $81; { polyline at current posn } GCLINE_SMP = 63; { Max number of points (S) } GCLINE_LMP = 31; { Max number of points (L) } OCODE_GLINE = $C1; { polyline at given posn } GLINE_SMP = 62; { Max number of points (S) } GLINE_LMP = 30; { Max number of points (L) } { Polymarker } OCODE_GCMRK = $82; { marker at current posn } GCMRK_SMP = 63; { Max number of points (S) } GCMRK_LMP = 31; { Max number of points (L) } OCODE_GMRK = $C2; { marker at given posn } GMRK_SMP = 62; { Max number of points (S) } GMRK_LMP = 30; { Max number of points (L) } { Relative Line } OCODE_GCRLINE = $A1; { Relative line at curr pos } GCRLINE_MP = 127; { Max number of points } OCODE_GRLINE = $E1; { Relative line at givn pos } GRLINE_SMP = 125; { Max number of points (S) } GRLINE_LMP = 123; { Max number of points (L) } { Set Background Color } OCODE_GSBCOL = $25; { Set background color } OCODE_GPSBCOL = $65; { Push and set b/g color } { Set Extended Color } OCODE_GSECOL = $26; { Set extended color } OCODE_GPSECOL = $66; { Push and set ext color } { Extended Color values } SECOL_DEFAULT0 = $0000; SECOL_DEFAULT1 = $FF00; SECOL_NEUTRAL = $FF07; SECOL_RESET = $FF08; { Set Character Angle } OCODE_GSCA = $34; { Set character angle } OCODE_GPSCA = $74; { Push and set char angle } { Set Character Shear } OCODE_GSCH = $35; { Set character shear } OCODE_GPSCH = $75; { Push and set char shear } { Set Fractional Line Width } OCODE_GSFLW = $11; { Set fractional line width } OCODE_GPSFLW = $51; { Push and set frac l width } { Set Pick Identifier } OCODE_GSPIK = $43; { Set pick identifier } OCODE_GPSPIK = $23; { Push and set pick id } { Long Orders for which a structure can be defined for the data } { Arc } OCODE_GCARC = $86; { Arc at Current Position } OCODE_GARC = $C6; { Arc at Given Position } Type ORDERS_GCARC = Record { osgcarc } ptInter, ptEnd: POINTS End; ORDERL_GCARC = Record { olgcarc } ptInter, ptEnd: POINTL End; { Begin Element } Const OCODE_GBEL = $D2; { Begin Element } GBEL_DL = 251; Type ORDER_GBEL = Record { ogbel } lElementType: LongInt; achDesc: Array[0..GBEL_DL-1] Of Char End; { Begin Image } Const OCODE_GCBIMG = $91; { Begin Image at curr posn } OCODE_GBIMG = $D1; { Begin Image at given posn } Type ORDER_GCBIMG = Record { ogbimg } uchFormat, uchReserved: UCHAR; cx, cy: SWPUSHORT End; { Begin Path } Const OCODE_GBPTH = $D0; { Begin Path } Type ORDER_GBPTH = Record { ogbpth } usReserved: USHORT; idPath: LongInt End; { Box } Const OCODE_GCBOX = $80; { Box at current position } OCODE_GBOX = $C0; { Box at given position } Type ORDERS_GCBOX = Record { osgcbox } fbFlags, uchReserved: UCHAR; ptCorner: POINTS; hAxis, vAxis: SHORT End; ORDERL_GCBOX = Record { olgcbox } fbFlags, uchReserved: UCHAR; ptCorner: POINTL; hAxis, vAxis: LongInt End; Const GCBOX_FILL = $40; GCBOX_BOUNDARY = $20; { Call Segment } OCODE_GCALLS = $07; { call segment } Type ORDER_GCALLS = Record { ogcalls } sReserved: USHORT; idSegment: LongInt End; { Fill Path } Const OCODE_GFPTH = $D7; { Fill path } Type ORDER_GFPTH = Record { ogfpth } fbFlags, uchReserved: UCHAR; idPath: LongInt End; Const GFPTH_ALTERNATE = $00; GFPTH_WINDING = $40; GFPTH_MODIFY = $20; { Outline Path } OCODE_GOPTH = $D4; { Outline Path } Type ORDER_GOPTH = Record { ogopth } fbFlags, uchReserved: UCHAR; idPath: LongInt End; { Modify Path } Const OCODE_GMPTH = $D8; { modify path } Type ORDER_GMPTH = Record { ogmpth } uchMode, uchReserved: UCHAR; idPath: LongInt End; Const GMPTH_STROKE = $06; { Partial Arc } OCODE_GCPARC = $A3; { Partial arc at curr posn } OCODE_GPARC = $E3; { Partial arc at given posn } Type ORDERS_GCPARC = Record { osgcparc } ptCenter: POINTS; ufx88Multiplier: FIXED88; usStartAngle, usSweepAngle: LongInt End; ORDERL_GCPARC = Record { olgcparc } ptCenter: POINTL; ufxMultiplier: FIXED; usStartAngle, usSweepAngle: LongInt End; { Set Clip Path } Const OCODE_GSCPTH = $B4; { Set clip path } Type ORDER_GSCPTH = Record { ogscpth } fbFlags, uchReserved: UCHAR; idPath: LongInt End; Const GSCPTH_ALTERNATE = $00; GSCPTH_WINDING = $40; GSCPTH_RESET = $00; GSCPTH_INTERSECT = $20; { Set Arc Parameters } OCODE_GSAP = $22; { Set arc parameters } OCODE_GPSAP = $62; { Push and set arc params } Type ORDERS_GSAP = Record { osgsap } p, q, r, s: SHORT End; ORDERL_GSAP = Record { olgsap } p, q, r, s: LongInt End; { Set Background Indexed Color } Const OCODE_GSBICOL = $A7; { Set b/g indexed color } OCODE_GPSBICOL = $E7; { Push and set b/g ind color } OCODE_GSICOL = $A6; { Set indexed color } OCODE_GPSICOL = $E6; { Push and set indexd color } Type ORDER_GSBICOL = Record { ogbicol } fbFlags: UCHAR; auchColor: Array[0..2] Of UCHAR End; Const SICOL_SPECIFY = $00; SICOL_SPECIAL = $40; SICOL_DEFAULT = $80; SICOL_BLACK = 1; SICOL_WHITE = 2; SICOL_ONES = 4; SICOL_ZEROES = 5; { Set Character Cell } OCODE_GSCC = $33; { Set character cell } OCODE_GPSCC = $03; { Push and set char cell } Type ORDERS_GSCC = Record { osgscc } cxInt, cyInt: SHORT; cxFract, cyFract: USHORT; fbFlags, uchReserved: UCHAR End; ORDERL_GSCC = Record { olgscc } cxInt, cyInt: LongInt; cxFract, cyFract: USHORT; fbFlags, uchReserved: UCHAR End; Const GSCC_ZERODEF = $00; GSCC_ZEROZERO = $80; { Set Marker Cell } OCODE_GSMC = $37; { Set marker cell } OCODE_GPSMC = $77; { Push and set marker cell } Type ORDERS_GSMC = Record { osgsmc } cx, cy: SHORT; fbFlags, uchReserved: UCHAR End; ORDERL_GSMC = Record { olgsmc } cx, cy: LongInt; fbFlags, uchReserved: UCHAR End; Const GSMC_ZERODEF = $00; GSMC_ZEROZERO = $80; { Set Pattern Reference Point } OCODE_GSPRP = $A0; { Set pattern ref point } OCODE_GPSPRP = $E0; { Push and set patt ref pt } Type ORDERS_GSPRP = Record { osgsprp } fbFlags, uchReserved: UCHAR; ptPos: POINTS End; ORDERL_GSPRP = Record { olgsprp } fbFlags, uchReserved: UCHAR; ptPos: POINTL End; Const GSPRP_DEFAULT = $80; GSPRP_SPECIFY = $00; { Set Individual Attribute } OCODE_GSIA = $14; { Set individual attribute } OCODE_GPSIA = $54; { Push and set ind attr } GSIA_VL = 3; Type ORDER_GSIA = Record { ogsia } uchAttrType, uchPrimType, fbFlags: UCHAR; auchValue: Array[0..GSIA_VL-1] Of UCHAR End; Const GSIA_COLOR = $01; GSIA_BCOLOR = $02; GSIA_MIX = $03; GSIA_BMIX = $04; GSIA_LINE = $01; GSIA_CHAR = $02; GSIA_MARKER = $03; GSIA_PATTERN = $04; GSIA_IMAGE = $05; GSIA_SPECIFY = $00; GSIA_SPECIAL = $40; GSIA_DEFAULT = $80; GSIA_BLACK = 1; GSIA_WHITE = 2; GSIA_ONES = 4; GSIA_ZEROES = 5; { Set Model /Viewing Transform } OCODE_GSTM = $24; { Set model transform } OCODE_GPSTM = $64; { Push and set model tfm } OCODE_GSTV = $31; { Set Viewing Transform } GSTM_ML = 16; Type ORDERS_GSTM = Record { osgstm } uchReserved, fbFlags: UCHAR; fsMask: USHORT; asMatrix: Array[0..GSTM_ML-1] Of SHORT End; ORDERL_GSTM = Record { olgstm } uchReserved, fbFlags: UCHAR; fsMask: USHORT; alMatrix: Array[0..GSTM_ML-1] Of LongInt End; Const GSTM_M11 = $8000; GSTM_M12 = $4000; GSTM_M13 = $2000; GSTM_M14 = $1000; GSTM_M21 = $0800; GSTM_M22 = $0400; GSTM_M23 = $0200; GSTM_M24 = $0100; GSTM_M31 = $0080; GSTM_M32 = $0040; GSTM_M33 = $0020; GSTM_M34 = $0010; GSTM_M41 = $0008; GSTM_M42 = $0004; GSTM_M43 = $0002; GSTM_M44 = $0001; GSTM_UNITY = $00; GSTM_AFTER = $01; GSTM_BEFORE = $02; GSTM_OVERWRITE = $03; GSTV_OVERWRITE = $00; GSTV_AFTER = $04; { Set Segment Boundary, Viewing Window } OCODE_GSSB = $32; { Set segment boundary } OCODE_GSVW = $27; { Set viewing window } OCODE_GPSVW = $67; { Push and set view window } GSSB_ML = 4; Type ORDERS_GSSB = Record { osgssb } fbFlags, fbMask: UCHAR; alMatrix: Array[0..GSSB_ML-1] Of SHORT End; ORDERL_GSSB = Record { olgssb } fbFLags, fbMask: UCHAR; alMatrix: Array[0..GSSB_ML-1] Of LongInt End; Const GSSB_XLEFT = $20; GSSB_XRIGHT = $10; GSSB_YBOTTOM = $08; GSSB_YTOP = $04; GSVW_INTERSECT = $00; GSVW_REPLACE = $80; { Set Segment Characteristics } OCODE_GSGCH = $04; { Set segment characteristics } GSGCH_ML = 254; Type ORDER_GSGCH = Record { ogsgch } uchIdent: UCHAR; auchData: Array[0..GSGCH_ML-1] Of UCHAR End; { Set Stroke Line Width } Const OCODE_GSSLW = $15; { Set stroke line width } OCODE_GPSSLW = $55; { Push and set strk l width } Type ORDERS_GSSLW = Record { osgsslw } fbFlags, uchReserved: UCHAR; LineWidth: SHORT End; ORDERL_GSSLW = Record { olgsslw } fbFlags, uchReserved: UCHAR; LineWidth: LongInt End; Const GSSLW_DEFAULT = $80; GSSLW_SPECIFY = $00; { Sharp Fillet at Current Position } OCODE_GCSFLT = $A4; { Sharp fillet at curr pos } OCODE_GSFLT = $E4; { Sharp fillet at given pos } GCSFLT_SMF = 21; GSFLT_SMF = 20; Type ORDERS_GCSFLT = Record { osgcsflt } apt: Array[0..2*GCSFLT_SMF-1] Of POINTS; afxSharpness: Array[0..GCSFLT_SMF-1] Of FIXED End; Const GCSFLT_LMF = 12; GSFLT_LMF = 12; Type ORDERL_GCSFLT = Record { olgcsflt } apt: Array[0..2*GCSFLT_SMF-1] Of POINTS; afxSharpness: Array[0..GCSFLT_SMF-1] Of FIXED End; { Bitblt } Const OCODE_GBBLT = $D6; { Bitblt } Type ORDERS_GBBLT = Record { osgbblt } fsFlags, usMix: USHORT; hbmSrc: HBITMAP; lOptions: LongInt; rcsTargetRect: RECT1S; rclSourceRect: RECTL End; ORDERL_GBBLT = Record { olgbblt } fsFlags, usMix: USHORT; hbmSrc: HBITMAP; lOptions: LongInt; rclTargetRect, rclSourceRect: RECTL End; { Escape } Const OCODE_GESCP = $D5; { Escape } { * type describes type of escape order, identifier gives the escape * order if the type is registered } GESCP_ML = 253; Type ORDER_GESCP = Record { ogescp } uchType, uchIdent: UCHAR; auchData: Array[0..GESCP_ML-1] Of UCHAR { Escape data } End; Const GESCP_REG = $80; { identifier is registered } { Escape} GEBB_REGID = $02; { uchIdent - Bitblt } ETYPE_GEBB = $800200D5 ; GEBB_LMP = 29; Type ORDERL_GEBB = Record { olgebb } fbFlags: UCHAR; usMix: USHORT; cPoints: UCHAR; hbmSrc: HBITMAP; lReserved, lOptions: LongInt; aptPoints: Array[0..GEBB_LMP-1] Of POINTL End; { Escape } Const GEPEL_REGID = $01; { uchIdent - Set Pel } ETYPE_GEPEL = $800100D5 ; { Element Types for attribute bundles } ETYPE_LINEBUNDLE = $0000FD01 ; ETYPE_CHARBUNDLE = $0000FD02 ; ETYPE_MARKERBUNDLE = $0000FD03 ; ETYPE_AREABUNDLE = $0000FD04 ; ETYPE_IMAGEBUNDLE = $0000FD05 ; {**************************************************************************\ * * Very long orders * \**************************************************************************} { macro to tell whether this is a very long order } { UNSURE #define VLONG_ORDER(oc) ((oc)==OCODE_VLONG)} { Very long order structure } VORDER_ML = 65531; Type VORDER = Record { vord } idCode, uchQualifier: UCHAR; uchLength: SWPUSHORT; uchData: Array[0..VORDER_ML-1] Of UCHAR End; { Character String Extended } Const OCODEQ_GCCHSTE = $B0; { Qualifier - current posn } OCODEQ_GCHSTE = $F0; { Qualifier - given position } ETYPE_GCCHSTE = $0000FEB0 ; ETYPE_GCHSTE = $0000FEF0 ; Type ORDERS_GCCHSTE = Record { osgcchste } fbFlags, uchReserved: UCHAR; ptRect: Array[0..1] Of POINTS; cchString: SWPUSHORT; achString: Array[0..0] Of Char; adx: Array[0..0] Of SHORT End; ORDERL_GCCHSTE = Record { olgcchste } fbFlags, uchReserved: UCHAR; ptRect: Array[0..1] Of POINTL; cchString: SWPUSHORT; achString: Array[0..0] Of Char; adx: Array[0..0] Of LongInt End; Const GCCHSTE_DRAWRECT = $80; GCCHSTE_NORECT = $00; GCCHSTE_CLIP = $40; GCCHSTE_NOCLIP = $00; GCCHSTE_DEEMPHASIZE = $20; GCCHSTE_NODEEMPHASIZE = $00; GCCHSTE_LEAVEPOS = $10; GCCHSTE_MOVEPOS = $00; { Extended Escape } OCODEQ_GEESCP = $D5; { Qualifier - extended escape } GEESCP_ML = 65533; Type ORDER_GEESCP = Record { ogeescp } uchType, uchIdent: UCHAR; auchData: Array[0..GEESCP_ML-1] Of UCHAR End; Implementation End.
unit afwStatus; {* Реализация строки статуса. } // Модуль: "w:\common\components\gui\Garant\AFW\implementation\afwStatus.pas" // Стереотип: "SimpleClass" // Элемент модели: "TafwStatus" MUID: (478787DD01FE) {$Include w:\common\components\gui\Garant\AFW\afwDefine.inc} interface uses l3IntfUses , l3CProtoObject , afwInterfaces , IafwStatusElementPtrList ; type TafwStatus = class(Tl3CProtoObject, IafwStatus) {* Реализация строки статуса. } private f_MainForm: Pointer; f_Elements: TIafwStatusElementPtrList; protected procedure AddElement(const anElement: IafwStatusElement); procedure RemoveElement(const anElement: IafwStatusElement); procedure Update; procedure GetStatus(out theStatus: TafwStatusInfo); procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(const aMainForm: IafwMainForm); reintroduce; class function Make(const aMainForm: IafwMainForm): IafwStatus; reintroduce; {* Создает экземпляр класса, в виде интерфейса IafwStatus. } end;//TafwStatus implementation uses l3ImplUses , l3String , l3Base //#UC START# *478787DD01FEimpl_uses* //#UC END# *478787DD01FEimpl_uses* ; constructor TafwStatus.Create(const aMainForm: IafwMainForm); //#UC START# *47878A1D02C4_478787DD01FE_var* //#UC END# *47878A1D02C4_478787DD01FE_var* begin //#UC START# *47878A1D02C4_478787DD01FE_impl* inherited Create; f_MainForm := Pointer(aMainForm); //#UC END# *47878A1D02C4_478787DD01FE_impl* end;//TafwStatus.Create class function TafwStatus.Make(const aMainForm: IafwMainForm): IafwStatus; {* Создает экземпляр класса, в виде интерфейса IafwStatus. } var l_Inst : TafwStatus; begin l_Inst := Create(aMainForm); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TafwStatus.Make procedure TafwStatus.AddElement(const anElement: IafwStatusElement); //#UC START# *473D964C00F9_478787DD01FE_var* //#UC END# *473D964C00F9_478787DD01FE_var* begin //#UC START# *473D964C00F9_478787DD01FE_impl* if (f_Elements = nil) then f_Elements := TIafwStatusElementPtrList.Create; if (f_Elements.IndexOf(anElement) < 0) then f_Elements.Add(anElement); //#UC END# *473D964C00F9_478787DD01FE_impl* end;//TafwStatus.AddElement procedure TafwStatus.RemoveElement(const anElement: IafwStatusElement); //#UC START# *473D96570159_478787DD01FE_var* //#UC END# *473D96570159_478787DD01FE_var* begin //#UC START# *473D96570159_478787DD01FE_impl* if (f_Elements <> nil) then f_Elements.Remove(anElement); //#UC END# *473D96570159_478787DD01FE_impl* end;//TafwStatus.RemoveElement procedure TafwStatus.Update; //#UC START# *473D965F03DB_478787DD01FE_var* var l_Status : TafwStatusInfo; //#UC END# *473D965F03DB_478787DD01FE_var* begin //#UC START# *473D965F03DB_478787DD01FE_impl* if (f_MainForm <> nil) AND (IafwMainForm(f_MainForm).StatusBar <> nil) then begin GetStatus(l_Status); IafwMainForm(f_MainForm).StatusBar.UpdateStrings(l_Status); end;//f_MainForm <> nil.. //#UC END# *473D965F03DB_478787DD01FE_impl* end;//TafwStatus.Update procedure TafwStatus.GetStatus(out theStatus: TafwStatusInfo); //#UC START# *473D9669014B_478787DD01FE_var* var l_Caption : IafwCString; l_NeedProgress : Boolean; l_Index : Integer; l_Element : IafwStatusElement; //#UC END# *473D9669014B_478787DD01FE_var* begin //#UC START# *473D9669014B_478787DD01FE_impl* theStatus.rNeedProgress := False; if (f_Elements <> nil) then with f_Elements do begin l_Index := Lo; while (l_Index < Count) do begin l_Element := Items[l_Index]; (* try l_Element := Items[l_Index]; except f_Elements.Delete(l_Index); continue; end;//try..except*) if (l_Element <> nil) then with theStatus do begin l_Element.GetStatusInfo(l_Caption, l_NeedProgress); rNeedProgress := rNeedProgress or l_NeedProgress; if not l3IsNil(l_Caption) then begin SetLength(rStrings, Length(rStrings) + 1); rStrings[Length(rStrings) - 1] := l_Caption; end;//not l3IsNil(l_Caption) end;//with theStatus Inc(l_Index); end;//while l_Index end;//with f_Elements //#UC END# *473D9669014B_478787DD01FE_impl* end;//TafwStatus.GetStatus procedure TafwStatus.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_478787DD01FE_var* //#UC END# *479731C50290_478787DD01FE_var* begin //#UC START# *479731C50290_478787DD01FE_impl* l3Free(f_Elements); inherited; //#UC END# *479731C50290_478787DD01FE_impl* end;//TafwStatus.Cleanup end.
unit WcryptHelper; interface uses Windows, Classes, SysUtils, JwaWinCrypt, JwaCryptUIApi, VipNet, TSP, asn1util; const CERT_STORE_NAME = 'MY'; MY_CERT_STORE_NAME = CERT_STORE_NAME; CA_CERT_STORE_NAME = 'CA'; ROOT_CERT_STORE_NAME = 'ROOT'; MY_ENCODING_TYPE = PKCS_7_ASN_ENCODING or X509_ASN_ENCODING; type ECryptException = class(Exception); function CryptCheck(RetVal: BOOL; FuncName: string): BOOL; function GetSignerCert(hwnd: HWND; StoreName: String): PCCERT_CONTEXT; function FindSignerCert(StoreName: String; Name: String): PCCERT_CONTEXT; procedure SignFileSimple(SignerCert: PCCERT_CONTEXT; FileName: string; DetachedSign: boolean; TSPUrl: String); procedure SignFile(SignerCert: PCCERT_CONTEXT; FileName: string; StreamOut: TMemoryStream; DetachedSign: boolean; TSPUrl: AnsiString); procedure SignStream(SignerCert: PCCERT_CONTEXT; StreamIn: TMemoryStream; StreamOut: TMemoryStream; DetachedSign: boolean; TSPUrl: AnsiString); implementation function CryptCheck(RetVal: BOOL; FuncName: string): BOOL; begin try Result := Win32Check(RetVal); except on E: EOSError do raise ECryptException.Create(FuncName + sLineBreak + E.Message); else raise; end; end; function GetSignerCert(hwnd: HWND; StoreName: String): PCCERT_CONTEXT; var hCertStoreHandle: HCERTSTORE; begin hCertStoreHandle := CertOpenSystemStore(0, @StoreName[1]); if (not assigned(hCertStoreHandle)) then CryptCheck(False, Format('CertOpenSystemStore: %s', [StoreName])); try Result := CryptUIDlgSelectCertificateFromStore( hCertStoreHandle, hwnd, nil, nil, CRYPTUI_SELECT_LOCATION_COLUMN, 0, nil); finally try CertCloseStore(hCertStoreHandle, CERT_CLOSE_STORE_CHECK_FLAG); except end; end; end; function FindSignerCert(StoreName: String; Name: String): PCCERT_CONTEXT; var hCertStoreHandle: HCERTSTORE; cName: PWideChar; begin hCertStoreHandle := CertOpenSystemStore(0, @StoreName[1]); if (not assigned(hCertStoreHandle)) then CryptCheck(False, Format('CertOpenSystemStore: %s', [StoreName])); try GetMem(cName, 2 * Length(Name) + 1); try StringToWideChar(Name, cName, 2 * Length(Name) + 1); Result := CertFindCertificateInStore(hCertStoreHandle, MY_ENCODING_TYPE, 0, CERT_FIND_SUBJECT_STR, cName, nil ); finally FreeMem(cName); end; finally try CertCloseStore(hCertStoreHandle, CERT_CLOSE_STORE_CHECK_FLAG); except end; end; end; procedure GetHashStream(Cert: PCCERT_CONTEXT; DataStream: TMemoryStream; var Hash: String); var hProv: HCRYPTPROV; DataLen: DWORD; hHash: HCRYPTHASH; dwKeySpec: DWORD; OutStream: TMemoryStream; begin CryptCheck(CryptAcquireCertificatePrivateKey( Cert, 0, nil, hProv, @dwKeySpec, nil), 'CryptAcquireCertificatePrivateKey'); OutStream := TMemoryStream.Create; try begin CryptCheck(CryptCreateHash(hProv, CALG_GR3411, 0, 0, hHash), 'CryptCreateHash'); try CryptCheck(CryptHashData(hHash, DataStream.Memory, DataStream.Size, 0), 'CryptHashData'); CryptCheck(CryptGetHashParam(hHash, HP_HASHVAL, nil, DataLen, 0), 'CryptGetHashParam'); OutStream.Size := DataLen; CryptCheck(CryptGetHashParam(hHash, HP_HASHVAL, OutStream.Memory, DataLen, 0), 'CryptGetHashParam'); SetLength(Hash, DataLen); Move(OutStream.Memory, PAnsiChar(@Hash[1])^, DataLen); finally CryptCheck(CryptDestroyHash(hHash), 'CryptDestroyHash'); end; end; finally OutStream.Free; CryptCheck(CryptReleaseContext(hProv, 0), 'CryptReleaseContext'); end; end; procedure SignStream(SignerCert: PCCERT_CONTEXT; StreamIn: TMemoryStream; StreamOut: TMemoryStream; DetachedSign: boolean; TSPUrl: AnsiString); var MessageArray: array of PByte; MessageSize: array of DWORD; SigParams: CRYPT_SIGN_MESSAGE_PARA; cbSignedMessage: DWORD; caSigTime, caTimeStamp: CRYPT_ATTRIBUTE; FTime: TFileTime; cabSigTime, cabTimeStamp: CRYPT_ATTR_BLOB; pbSigTime: array of byte; cbSigTime: DWORD; Hash: AnsiString; SignStream: TMemoryStream; TimeStampStream: TMemoryStream; TimeStampBytes: AnsiString; hMsg: HCRYPTMSG; cbDigestSize: DWORD; pbDigestSize: TMemoryStream; encodedAttributeSize: DWORD; encodedAttribute: TMemoryStream; unauthenticatedParam: CMSG_CTRL_ADD_SIGNER_UNAUTH_ATTR_PARA; encodedMessageLength: DWORD; pData: TMemoryStream; pbSignedMessage: TMemoryStream; begin if not Assigned(SignerCert) then begin raise ECryptException.Create('Signer certificate is null'); Exit; end; hMsg := nil; pbSignedMessage := TMemoryStream.Create; TimeStampStream := TMemoryStream.Create; SignStream := TMemoryStream.Create; pbDigestSize := TMemoryStream.Create; encodedAttribute := TMemoryStream.Create; pData := TMemoryStream.Create; try // Sig params SetLength(MessageArray, 1); SetLength(MessageSize, 1); MessageArray[0] := StreamIn.Memory; MessageSize[0] := StreamIn.Size; FillChar(SigParams, SizeOf(CRYPT_SIGN_MESSAGE_PARA), #0); SigParams.cbSize := SizeOF(CRYPT_SIGN_MESSAGE_PARA); SigParams.dwMsgEncodingType := PKCS_7_ASN_ENCODING or X509_ASN_ENCODING; SigParams.pSigningCert := SignerCert; SigParams.HashAlgorithm.pszObjId := SignerCert.pCertInfo.SignatureAlgorithm.pszObjId; SigParams.cMsgCert := 1; SigParams.rgpMsgCert := @SignerCert; GetSystemTimeAsFileTime(fTime); CryptEncodeObject(MY_ENCODING_TYPE, szOID_RSA_signingTime, @fTime, nil, cbSigTime); SetLength(pbSigTime, cbSigTime); CryptEncodeObject(MY_ENCODING_TYPE, szOID_RSA_signingTime, @fTime, Pointer(pbSigTime), cbSigTime); cabSigTime.cbData := cbSigTime; cabSigTime.pbData := Pointer(pbSigTime); caSigTime.pszObjId := szOID_RSA_signingTime; caSigTime.cValue := 1; caSigTime.rgValue := @cabSigTime; SigParams.cAuthAttr := 1; SigParams.rgAuthAttr := @caSigTime; cbSignedMessage := 0; CryptCheck(CryptSignMessage(@SigParams, DetachedSign, 1, Pointer(MessageArray), Pointer(MessageSize), nil, cbSignedMessage), 'CryptSignMessage'); pbSignedMessage.Size := cbSignedMessage; CryptCheck(CryptSignMessage(@SigParams, DetachedSign, 1, Pointer(MessageArray), Pointer(MessageSize), pbSignedMessage.Memory, cbSignedMessage), 'CryptSignMessage'); pbSignedMessage.Size := cbSignedMessage; StreamOut.Clear; StreamOut.CopyFrom(pbSignedMessage, 0); if TSPUrl <> '' then begin hMsg := CryptMsgOpenToDecode(X509_ASN_ENCODING or PKCS_7_ASN_ENCODING, CMSG_DETACHED_FLAG, 0, 0, nil, nil); if hMsg <> nil then begin pbSignedMessage.Position := 0; CryptCheck(CryptMsgUpdate(hMsg, pbSignedMessage.Memory, pbSignedMessage.Size, True), 'CryptMsgUpdate'); cbDigestSize := 0; CryptCheck(CryptMsgGetParam(hMsg, CMSG_ENCRYPTED_DIGEST, 0, nil, cbDigestSize), 'CryptMsgGetParam'); pbDigestSize.Size := cbDigestSize; CryptCheck(CryptMsgGetParam(hMsg, CMSG_ENCRYPTED_DIGEST, 0, pbDigestSize.Memory, cbDigestSize), 'CryptMsgGetParam'); GetHashStream(SignerCert, pbDigestSize, Hash); TSPGetResponse(TSPUrl, Hash, TimeStampStream); TimeStampStream.Position := 0; TimeStampBytes := ASN1ExtractSequence(szOID_RSA_signedData, TimeStampStream.Memory, TimeStampStream.Size); TimeStampBytes := ASNObject(TimeStampBytes, ASN1_SEQ); TimeStampStream.Clear; TimeStampStream.WriteBuffer(TimeStampBytes[1], Length(TimeStampBytes)); FillChar(cabTimeStamp, SizeOf(CRYPT_ATTR_BLOB), #0); cabTimeStamp.cbData := TimeStampStream.Size; cabTimeStamp.pbData := TimeStampStream.Memory; caTimeStamp.pszObjId := '1.2.840.113549.1.9.16.2.14'; caTimeStamp.cValue := 1; caTimeStamp.rgValue := @cabTimeStamp; CryptCheck(CryptEncodeObject(X509_ASN_ENCODING or PKCS_7_ASN_ENCODING, PKCS_ATTRIBUTE, @caTimeStamp, nil, encodedAttributeSize), 'CryptEncodeObject'); encodedAttribute.Size := encodedAttributeSize; CryptCheck(CryptEncodeObject(X509_ASN_ENCODING or PKCS_7_ASN_ENCODING, PKCS_ATTRIBUTE, @caTimeStamp, encodedAttribute.Memory, encodedAttributeSize), 'CryptEncodeObject'); encodedAttribute.Size := encodedAttributeSize; unauthenticatedParam.cbSize := SizeOf(CMSG_CTRL_ADD_SIGNER_UNAUTH_ATTR_PARA); unauthenticatedParam.dwSignerIndex := 0; //only have 1 cert unauthenticatedParam.blob.cbData := encodedAttributeSize; unauthenticatedParam.blob.pbData := encodedAttribute.Memory; CryptCheck(CryptMsgControl(hMsg, 0, CMSG_CTRL_ADD_SIGNER_UNAUTH_ATTR, @unauthenticatedParam), 'CryptMsgControl'); encodedMessageLength := 0; CryptCheck(CryptMsgGetParam(hMsg, CMSG_ENCODED_MESSAGE, 0, nil, encodedMessageLength), 'CryptMsgGetParam'); pData.Size := encodedMessageLength; CryptCheck(CryptMsgGetParam(hMsg, CMSG_ENCODED_MESSAGE, 0, pData.Memory, encodedMessageLength), 'CryptMsgGetParam'); pData.Size := encodedMessageLength; StreamOut.Clear; StreamOut.CopyFrom(pData, 0); end; end; finally pbSignedMessage.Free; encodedAttribute.Free; pData.Free; TimeStampStream.Free; SignStream.Free; pbDigestSize.Free; if hMsg <> nil then CryptMsgClose(hMsg); end; end; procedure SignFile(SignerCert: PCCERT_CONTEXT; FileName: string; StreamOut: TMemoryStream; DetachedSign: boolean; TSPUrl: AnsiString); var FS: TMemoryStream; begin FS := TMemoryStream.Create(); try FS.LoadFromFile(filename); SignStream(SignerCert, FS, StreamOut, DetachedSign, TSPUrl); finally FS.Free; end; end; procedure SignFileSimple(SignerCert: PCCERT_CONTEXT; FileName: string; DetachedSign: boolean; TSPUrl: String); var FS: TMemoryStream; begin FS := TMemoryStream.Create(); try SignFile(SignerCert, FileName, FS, DetachedSign, TSPUrl); FS.SaveToFile(FileName + '.sig'); finally FS.Free; end; end; end.
unit cSampleData; interface uses Generics.Collections, xn.grid.common; type TSampleData = class private const TABLE_20: array [0 .. 19, 0 .. 5] of string = ( ('0', 'Aqua', 'MD', '2,01', '71', 'T'), ('2', 'Yellow', 'LA', '3,76', '29', 'T'), ('4', 'DkGray', 'VT', '4,74', '47', 'T'), ('6', 'Teal', 'NE', '2,06', '6', 'F'), ('8', 'Red', 'LA', '2,82', '80', 'F'), ('10', 'Black', 'OH', '2,06', '6', 'T'), ('12', 'Lime', 'HI', '2,82', '32', 'F'), ('14', 'White', 'UT', '2,9', '75', 'T'), ('16', 'Lime', 'VT', '3,17', '75', 'F'), ('18', 'Olive', 'VA', '3,17', '88', 'F'), ('20', 'Gray', 'PA', '1,53', '25', 'F'), ('22', 'Red', 'WA', '2,82', '34', 'F'), ('24', 'White', 'RI', '4,04', '29', 'T'), ('26', 'Purple', 'MS', '3,17', '70', 'T'), ('28', 'Fuchsia', 'ND', '3,6', '77', 'F'), ('30', 'Silver', 'AR', '3,76', '25', 'F'), ('32', 'Maroon', 'MT', '3,94', '88', 'T'), ('34', 'LtGray', 'AZ', '3,94', '10', 'F'), ('36', 'Silver', 'NY', '3,76', '8', 'F'), ('38', 'Purple', 'HI', '2,56', '68', 'F')); public class function RowCount: Integer; class function Value(aCol, aRow: Integer): string; end; TSampleGridData = class(TInterfacedObject, IxnGridData) public function RowCountGet: Integer; function AsDebug: string; function ValueString(aCol, aRow: Integer): String; function ValueFloat(aCol, aRow: Integer): Double; end; TSampleGridData2By2 = class(TInterfacedObject, IxnGridData) private fItems: TList<Integer>; procedure Fill(aCount: Integer); virtual; procedure Rand; virtual; public constructor Create(aCount: Integer); virtual; destructor Destroy; override; function RowCountGet: Integer; virtual; function AsDebug: string; virtual; function ValueString(aCol, aRow: Integer): String; virtual; function ValueFloat(aCol, aRow: Integer): Double; virtual; end; TSampleGridDataRandom = class(TSampleGridData2By2) private procedure Fill(aCount: Integer); override; end; TSampleGridDataList = class(TInterfacedObject, IxnGridData) type TItem = record NN: String; CC: String; SS: String; FF: String; II: string; BB: string; constructor Create(aNN, aCC, aSS, aFF, aII, aBB: string); end; private fItems: TList<TItem>; public constructor Create; destructor Destroy; override; function RowCountGet: Integer; function AsDebug: string; function ValueString(aCol, aRow: Integer): String; function ValueFloat(aCol, aRow: Integer): Double; end; implementation uses System.Math, System.SysUtils; { TABLE_20 0;Aqua;MD;2,01;71;T 2;Yellow;LA;3,76;29;T 4;DkGray;VT;4,74;47;T 6;Teal;NE;2,06;6;F 8;Red;LA;2,82;80;F 10;Black;OH;2,06;6;T 12;Lime;HI;2,82;32;F 14;White;UT;2,9;75;T 16;Lime;VT;3,17;75;F 18;Olive;VA;3,17;88;F 20;Gray;PA;1,53;25;F 22;Red;WA;2,82;34;F 24;White;RI;4,04;29;T 26;Purple;MS;3,17;70;T 28;Fuchsia;ND;3,6;77;F 30;Silver;AR;3,76;25;F 32;Maroon;MT;3,94;88;T 34;LtGray;AZ;3,94;10;F 36;Silver;NY;3,76;8;F 38;Purple;HI;2,56;68;F } class function TSampleData.RowCount: Integer; begin Result := Length(TABLE_20); end; class function TSampleData.Value(aCol, aRow: Integer): string; begin Result := TABLE_20[aRow, aCol]; end; { TSampleGridData } function TSampleGridData.AsDebug: string; var r: Integer; begin Result := ''; for r := 0 to RowCountGet - 1 do Result := Result + ValueString(0, r) + ',' end; function TSampleGridData.RowCountGet: Integer; begin Result := TSampleData.RowCount end; function TSampleGridData.ValueFloat(aCol, aRow: Integer): Double; begin Result := StrToFloat(ValueString(aCol, aRow)); end; function TSampleGridData.ValueString(aCol, aRow: Integer): String; begin Result := TSampleData.Value(aCol, aRow); end; { TSampleGridData10000 } function TSampleGridData2By2.AsDebug: string; var r: Integer; begin Result := ''; for r := 0 to RowCountGet - 1 do Result := Result + ValueString(0, r) + ',' end; constructor TSampleGridData2By2.Create(aCount: Integer); begin inherited Create; fItems := TList<Integer>.Create; Fill(aCount); Rand; end; destructor TSampleGridData2By2.Destroy; begin fItems.Free; end; procedure TSampleGridData2By2.Fill(aCount: Integer); var i: Integer; begin for i := 0 to aCount - 1 do fItems.Add(2 * i); end; procedure TSampleGridData2By2.Rand; var i: Integer; a: Integer; b: Integer; begin for i := 0 to RowCountGet - 1 do begin a := RandomRange(0, RowCountGet); b := RandomRange(0, RowCountGet); fItems.Exchange(a, b); end; end; function TSampleGridData2By2.RowCountGet: Integer; begin Result := fItems.Count; end; function TSampleGridData2By2.ValueFloat(aCol, aRow: Integer): Double; begin Result := fItems[aRow]; end; function TSampleGridData2By2.ValueString(aCol, aRow: Integer): String; begin Result := IntToStr(fItems[aRow]); end; { TSampleGridDataRandom } procedure TSampleGridDataRandom.Fill(aCount: Integer); var i: Integer; begin for i := 0 to aCount - 1 do fItems.Add(RandomRange(0, 100)); end; { TSampleList.TItem } constructor TSampleGridDataList.TItem.Create(aNN, aCC, aSS, aFF, aII, aBB: string); begin NN := aNN; CC := aCC; SS := aSS; FF := aFF; II := aII; BB := aBB; end; { TSampleList } function TSampleGridDataList.AsDebug: string; var r: Integer; begin Result := ''; for r := 0 to RowCountGet - 1 do Result := Result + ValueString(0, r) + ',' end; constructor TSampleGridDataList.Create; var i: Integer; begin fItems := TList<TItem>.Create; for i := 0 to Length(TSampleData.TABLE_20) - 1 do fItems.Add(TItem.Create( TSampleData.TABLE_20[i][0], TSampleData.TABLE_20[i][1], TSampleData.TABLE_20[i][2], TSampleData.TABLE_20[i][3], TSampleData.TABLE_20[i][4], TSampleData.TABLE_20[i][5])); end; destructor TSampleGridDataList.Destroy; begin fItems.Free; inherited; end; function TSampleGridDataList.RowCountGet: Integer; begin Result := fItems.Count; end; function TSampleGridDataList.ValueFloat(aCol, aRow: Integer): Double; begin Result := StrToFloat(ValueString(aCol, aRow)); end; function TSampleGridDataList.ValueString(aCol, aRow: Integer): String; begin case aCol of 0: Result := fItems[aRow].NN; 1: Result := fItems[aRow].CC; 2: Result := fItems[aRow].SS; 3: Result := fItems[aRow].FF; 4: Result := fItems[aRow].II; 5: Result := fItems[aRow].BB; else raise Exception.Create('Invalid column index.'); end; end; end.
unit udmEmpresasEDI; interface uses Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS; type TdmEmpresasEDI = class(TdmPadrao) qryManutencaoCGC: TStringField; qryManutencaoIDENTIFICACAO: TStringField; qryManutencaoAGRUPA_NFS: TStringField; qryManutencaoANO_2000: TStringField; qryManutencaoCHV_OCORRENCIA: TStringField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryManutencaoOPERADOR: TStringField; qryManutencaoNM_EMPRESA: TStringField; qryLocalizacaoCGC: TStringField; qryLocalizacaoIDENTIFICACAO: TStringField; qryLocalizacaoAGRUPA_NFS: TStringField; qryLocalizacaoANO_2000: TStringField; qryLocalizacaoCHV_OCORRENCIA: TStringField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoOPERADOR: TStringField; qryLocalizacaoNM_EMPRESA: TStringField; protected procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; private FCod_Cliente: string; FCod_Identificacao: string; function GetSQL_DEFAULT: string; public property Cod_Cliente: string read FCod_Cliente write FCod_Cliente; property Cod_Identificacao: string read FCod_Identificacao write FCod_Identificacao; property SQLPadrao: string read GetSQL_DEFAULT; function LocalizarPorIdentificador(DataSet: TDataSet = nil): Boolean; end; const SQL_DEFAULT = 'SELECT ' + ' CGC, ' + ' IDENTIFICACAO, ' + ' AGRUPA_NFS, ' + ' ANO_2000, ' + ' CHV_OCORRENCIA, ' + ' DT_ALTERACAO, ' + ' OPERADOR, ' + ' NOME NM_EMPRESA ' + 'FROM STWOPETEDI1 ' + 'LEFT JOIN STWOPETCLI ON STWOPETCLI.CGC = STWOPETEDI1.CGC '; var dmEmpresasEDI : TdmEmpresasEDI; implementation {$R *.dfm} { TdmEmpresasEDI } function TdmEmpresasEDI.GetSQL_DEFAULT: string; begin result := SQL_DEFAULT; end; function TdmEmpresasEDI.LocalizarPorIdentificador(DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE IDENTIFICACAO = :IDENTIFICACAO'); SQL.Add('ORDER BY CGC'); Params[0].AsString := FCod_Identificacao; Open; Result := not IsEmpty; end; end; procedure TdmEmpresasEDI.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE CGC = :CGC'); SQL.Add('ORDER BY CGC'); Params[0].AsString := FCod_Cliente; end; end; procedure TdmEmpresasEDI.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('ORDER BY CGC'); end; end; end.
unit Ping2; interface function PingHost(const HostName: AnsiString; TimeoutMS: cardinal = 500): boolean; implementation uses Windows, SysUtils, WinSock; function IcmpCreateFile: THandle; stdcall; external 'iphlpapi.dll'; function IcmpCloseHandle(icmpHandle: THandle): boolean; stdcall; external 'iphlpapi.dll'; function IcmpSendEcho(icmpHandle: THandle; DestinationAddress: In_Addr; RequestData: Pointer; RequestSize: Smallint; RequestOptions: Pointer; ReplyBuffer: Pointer; ReplySize: DWORD; Timeout: DWORD): DWORD; stdcall; external 'iphlpapi.dll'; type TEchoReply = packed record Addr: In_Addr; Status: DWORD; RoundTripTime: DWORD; end; PEchoReply = ^TEchoReply; var WSAData: TWSAData; procedure Startup; begin if WSAStartup($0101, WSAData) <> 0 then raise Exception.Create('WSAStartup'); end; procedure Cleanup; begin if WSACleanup <> 0 then raise Exception.Create('WSACleanup'); end; function PingHost(const HostName: AnsiString; TimeoutMS: cardinal = 500): boolean; const rSize = $400; var e: PHostEnt; a: PInAddr; h: THandle; d: string; r: array [0 .. rSize - 1] of byte; i: cardinal; begin Startup; e := gethostbyname(PAnsiChar(HostName)); if e = nil then RaiseLastOSError; if e.h_addrtype = AF_INET then Pointer(a) := e.h_addr^ else raise Exception.Create('Name doesn''t resolve to an IPv4 address'); d := FormatDateTime('yyyymmddhhnnsszzz', Now); h := IcmpCreateFile; if h = INVALID_HANDLE_VALUE then RaiseLastOSError; try i := IcmpSendEcho(h, a^, PChar(d), Length(d), nil, @r[0], rSize, TimeoutMS); Result := (i <> 0) and (PEchoReply(@r[0]).Status = 0); finally IcmpCloseHandle(h); end; Cleanup; end; end.
unit shootout_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m6502,main_engine,controls_engine,ym_2203,gfx_engine,rom_engine, pal_engine,sound_engine,misc_functions; function iniciar_shootout:boolean; implementation const shootout_rom:array[0..2] of tipo_roms=( (n:'cu00.b1';l:$8000;p:$0;crc:$090edeb6),(n:'cu02.c3';l:$8000;p:$8000;crc:$2a913730), (n:'cu01.c1';l:$4000;p:$10000;crc:$8843c3ae)); shootout_char:tipo_roms=(n:'cu11.h19';l:$4000;p:$0;crc:$eff00460); shootout_sprite:array[0..5] of tipo_roms=( (n:'cu04.c7';l:$8000;p:$0;crc:$ceea6b20),(n:'cu03.c5';l:$8000;p:$8000;crc:$b786bb3e), (n:'cu06.c10';l:$8000;p:$10000;crc:$2ec1d17f),(n:'cu05.c9';l:$8000;p:$18000;crc:$dd038b85), (n:'cu08.c13';l:$8000;p:$20000;crc:$91290933),(n:'cu07.c12';l:$8000;p:$28000;crc:$19b6b94f)); shootout_audio:tipo_roms=(n:'cu09.j1';l:$4000;p:$c000;crc:$c4cbd558); shootout_tiles:tipo_roms=(n:'cu10.h17';l:$8000;p:$0;crc:$3854c877); shootout_pal:tipo_roms=(n:'gb08.k10';l:$100;p:$0;crc:$509c65b6); //Dip shootout_dip_a:array [0..5] of def_dip=( (mask:$3;name:'Coin A';number:4;dip:((dip_val:$0;dip_name:'2C 1C'),(dip_val:$3;dip_name:'1C 1C'),(dip_val:$2;dip_name:'1C 2C'),(dip_val:$1;dip_name:'1C 3C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Coin B';number:4;dip:((dip_val:$0;dip_name:'2C 1C'),(dip_val:$c;dip_name:'1C 1C'),(dip_val:$8;dip_name:'1C 2C'),(dip_val:$4;dip_name:'1C 3C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$20;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$40;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Freeze';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); shootout_dip_b:array [0..3] of def_dip=( (mask:$3;name:'Lives';number:4;dip:((dip_val:$1;dip_name:'1'),(dip_val:$3;dip_name:'3'),(dip_val:$2;dip_name:'5'),(dip_val:$0;dip_name:'Infinite'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Bonus Life';number:4;dip:((dip_val:$c;dip_name:'20K 70K+'),(dip_val:$8;dip_name:'30K 80K+'),(dip_val:$4;dip_name:'40K 90K+'),(dip_val:$0;dip_name:'70K'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Difficulty';number:4;dip:((dip_val:$30;dip_name:'Easy'),(dip_val:$20;dip_name:'Normal'),(dip_val:$10;dip_name:'Hard'),(dip_val:$0;dip_name:'Very Hard'),(),(),(),(),(),(),(),(),(),(),(),())),()); var mem_bank,mem_bank_dec:array[0..2,0..$3fff] of byte; mem_dec:array[0..$7fff] of byte; banco,sound_latch:byte; bflicker,old_val:boolean; procedure update_video_shootout; var f,nchar,color:word; x,y,atrib:byte; procedure sprites(prioridad:byte); var f,atrib,x,y:byte; nchar:word; begin { 76543210 xxx----- bank ---x---- vertical size ----x--- priority -----x-- horizontal flip ------x- flicker -------x enable} for f:=$7f downto 0 do begin atrib:=memoria[$19fd-(f*4)]; if (((atrib and $1)<>0) and ((atrib and 8)=prioridad)) then begin if (bflicker or ((atrib and $2)=0)) then begin nchar:=memoria[$19ff-(f*4)]+((atrib shl 3) and $700); x:=240-memoria[$19fe-(f*4)]; y:=240-memoria[$19fc-(f*4)]; if (atrib and $10)<>0 then begin //tamaņo doble nchar:=nchar and $7fe; put_gfx_sprite_diff(nchar,64,(atrib and $4)<>0,false,1,0,0); put_gfx_sprite_diff(nchar+1,64,(atrib and $4)<>0,false,1,0,16); actualiza_gfx_sprite_size(x,y-16,3,16,32); end else begin put_gfx_sprite(nchar,64,(atrib and $4)<>0,false,1); actualiza_gfx_sprite(x,y,3,1); end; end; end; end; end; begin for f:=0 to $3ff do begin //tiles if gfx[2].buffer[f] then begin x:=f mod 32; y:=f div 32; atrib:=memoria[$2c00+f]; color:=(atrib and $f0) shr 2; nchar:=memoria[$2800+f]+((atrib and $07) shl 8); put_gfx(x*8,y*8,nchar,color,2,2); gfx[2].buffer[f]:=false; end; //Chars if gfx[0].buffer[f] then begin x:=f mod 32; y:=f div 32; atrib:=memoria[$2400+f]; color:=(atrib and $f0) shr 2; nchar:=memoria[$2000+f]+((atrib and $03) shl 8); put_gfx_trans(x*8,y*8,nchar,color+128,1,0); gfx[0].buffer[f]:=false; end; end; actualiza_trozo(0,0,256,256,2,0,0,256,256,3); sprites(8); actualiza_trozo(0,0,256,256,1,0,0,256,256,3); sprites(0); actualiza_trozo_final(0,8,256,240,3); bflicker:=not(bflicker); end; procedure eventos_shootout; begin if event.arcade then begin //P1 if arcade_input.right[0] then marcade.in0:=marcade.in0 and $fe else marcade.in0:=marcade.in0 or 1; if arcade_input.left[0] then marcade.in0:=marcade.in0 and $fd else marcade.in0:=marcade.in0 or 2; if arcade_input.up[0] then marcade.in0:=marcade.in0 and $fb else marcade.in0:=marcade.in0 or 4; if arcade_input.down[0] then marcade.in0:=marcade.in0 and $f7 else marcade.in0:=marcade.in0 or 8; if arcade_input.but0[0] then marcade.in0:=marcade.in0 and $ef else marcade.in0:=marcade.in0 or $10; if arcade_input.but1[0] then marcade.in0:=marcade.in0 and $df else marcade.in0:=marcade.in0 or $20; if arcade_input.start[0] then marcade.in0:=marcade.in0 and $bf else marcade.in0:=marcade.in0 or $40; if arcade_input.start[1] then marcade.in0:=marcade.in0 and $7f else marcade.in0:=marcade.in0 or $80; //P2 if arcade_input.right[1] then marcade.in1:=marcade.in1 and $fe else marcade.in1:=marcade.in1 or 1; if arcade_input.left[1] then marcade.in1:=marcade.in1 and $fd else marcade.in1:=marcade.in1 or 2; if arcade_input.up[1] then marcade.in1:=marcade.in1 and $fb else marcade.in1:=marcade.in1 or 4; if arcade_input.down[1] then marcade.in1:=marcade.in1 and $f7 else marcade.in1:=marcade.in1 or 8; if arcade_input.but0[1] then marcade.in1:=marcade.in1 and $ef else marcade.in1:=marcade.in1 or $10; if arcade_input.but1[1] then marcade.in1:=marcade.in1 and $df else marcade.in1:=marcade.in1 or $20; if (arcade_input.coin[0] and not(old_val)) then begin marcade.dswb:=marcade.dswb and $bf; marcade.in1:=marcade.in1 and $7f; m6502_0.change_nmi(ASSERT_LINE); end else begin marcade.dswb:=(marcade.dswb or $40); marcade.in1:=(marcade.in1 or $80); m6502_0.change_nmi(CLEAR_LINE); end; old_val:=arcade_input.coin[0]; end; end; procedure principal_shootout; var frame_m,frame_s:single; f:word; begin init_controls(false,false,false,true); frame_m:=m6502_0.tframes; frame_s:=m6502_1.tframes; while EmuStatus=EsRuning do begin for f:=0 to 261 do begin m6502_0.run(frame_m); frame_m:=frame_m+m6502_0.tframes-m6502_0.contador; m6502_1.run(frame_s); frame_s:=frame_s+m6502_1.tframes-m6502_1.contador; case f of 7:marcade.dswb:=marcade.dswb or $80; 247:begin marcade.dswb:=marcade.dswb and $7f; update_video_shootout; end; end; end; eventos_shootout; video_sync; end; end; function getbyte_shootout(direccion:word):byte; begin case direccion of 0..$fff,$1004..$19ff,$2000..$2fff:getbyte_shootout:=memoria[direccion]; $1000:getbyte_shootout:=marcade.dswa; $1001:getbyte_shootout:=marcade.in0; $1002:getbyte_shootout:=marcade.in1; $1003:getbyte_shootout:=marcade.dswb; $4000..$7fff:if m6502_0.opcode then getbyte_shootout:=mem_bank_dec[banco,direccion and $3fff] else getbyte_shootout:=mem_bank[banco,direccion and $3fff]; $8000..$ffff:if m6502_0.opcode then getbyte_shootout:=mem_dec[direccion and $7fff] else getbyte_shootout:=memoria[direccion]; end; end; procedure putbyte_shootout(direccion:word;valor:byte); begin case direccion of 0..$fff,$1004..$19ff:memoria[direccion]:=valor; $1000:banco:=valor and $f; $1003:begin sound_latch:=valor; m6502_1.change_nmi(ASSERT_LINE); end; $2000..$27ff:if memoria[direccion]<>valor then begin gfx[0].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $2800..$2fff:if memoria[direccion]<>valor then begin gfx[2].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $4000..$ffff:; //ROM end; end; function getbyte_snd_shootout(direccion:word):byte; begin case direccion of 0..$7ff,$c000..$ffff:getbyte_snd_shootout:=mem_snd[direccion]; $4000:getbyte_snd_shootout:=ym2203_0.status; $a000:begin getbyte_snd_shootout:=sound_latch; m6502_1.change_nmi(CLEAR_LINE); end; end; end; procedure putbyte_snd_shootout(direccion:word;valor:byte); begin case direccion of 0..$7ff:mem_snd[direccion]:=valor; $4000:ym2203_0.control(valor); $4001:ym2203_0.write(valor); $c000..$ffff:; //ROM end; end; procedure shootout_sound_update; begin ym2203_0.update; end; procedure snd_irq(irqstate:byte); begin m6502_1.change_irq(irqstate); end; //Main procedure reset_shootout; begin m6502_0.reset; m6502_1.reset; ym2203_0.reset; reset_audio; marcade.in0:=$ff; marcade.in1:=$3f; bflicker:=false; banco:=0; sound_latch:=0; old_val:=false; end; function iniciar_shootout:boolean; var colores:tpaleta; f:word; mem_temp:array[0..$7fff] of byte; memoria_temp:array[0..$2ffff] of byte; const pc_x:array[0..7] of dword=(($2000*8)+0, ($2000*8)+1, ($2000*8)+2, ($2000*8)+3, 0, 1, 2, 3); ps_x:array[0..15] of dword=(128+0, 128+1, 128+2, 128+3, 128+4, 128+5, 128+6, 128+7, 0, 1, 2, 3, 4, 5, 6, 7); ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8); pt_x:array[0..7] of dword=(($4000*8)+0, ($4000*8)+1, ($4000*8)+2, ($4000*8)+3, 0, 1, 2, 3); begin llamadas_maquina.bucle_general:=principal_shootout; llamadas_maquina.reset:=reset_shootout; llamadas_maquina.fps_max:=12000000/2/384/262; iniciar_shootout:=false; iniciar_audio(false); //Chars trans screen_init(1,256,256,true); screen_init(2,256,256); screen_init(3,256,256,false,true); iniciar_video(256,240); //Main CPU m6502_0:=cpu_m6502.create(2000000,262,TCPU_M6502); m6502_0.change_ram_calls(getbyte_shootout,putbyte_shootout); //sound CPU m6502_1:=cpu_m6502.create(1500000,262,TCPU_M6502); m6502_1.change_ram_calls(getbyte_snd_shootout,putbyte_snd_shootout); m6502_1.init_sound(shootout_sound_update); //Sound Chip ym2203_0:=ym2203_chip.create(1500000); ym2203_0.change_irq_calls(snd_irq); //cargar roms if not(roms_load(@memoria_temp,shootout_rom)) then exit; //Copio las ROM en su sitio copymemory(@memoria[$8000],@memoria_temp[0],$8000); copymemory(@mem_bank[0,0],@memoria_temp[$8000],$4000); copymemory(@mem_bank[1,0],@memoria_temp[$c000],$4000); copymemory(@mem_bank[2,0],@memoria_temp[$10000],$4000); //Y las desencripto for f:=0 to $7fff do mem_dec[f]:=BITSWAP8(memoria[f+$8000],7,5,6,4,3,2,1,0); for f:=0 to $3fff do begin mem_bank_dec[0,f]:=BITSWAP8(mem_bank[0,f],7,5,6,4,3,2,1,0); mem_bank_dec[1,f]:=BITSWAP8(mem_bank[1,f],7,5,6,4,3,2,1,0);; mem_bank_dec[2,f]:=BITSWAP8(mem_bank[2,f],7,5,6,4,3,2,1,0);; end; //Roms audio if not(roms_load(@mem_snd,shootout_audio)) then exit; //Cargar chars if not(roms_load(@memoria_temp,shootout_char)) then exit; init_gfx(0,8,8,1024); gfx[0].trans[0]:=true; gfx_set_desc_data(2,0,8*8,0,4); convert_gfx(0,0,@memoria_temp,@pc_x,@ps_y,false,false); //sprites if not(roms_load(@memoria_temp,shootout_sprite)) then exit; init_gfx(1,16,16,2048); gfx[1].trans[0]:=true; gfx_set_desc_data(3,0,32*8,0*$10000*8,1*$10000*8,2*$10000*8); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false); //tiles if not(roms_load(@memoria_temp,shootout_tiles)) then exit; //mover para sacar tiles copymemory(@mem_temp[0],@memoria_temp[0],$2000); copymemory(@mem_temp[$4000],@memoria_temp[$2000],$2000); copymemory(@mem_temp[$2000],@memoria_temp[$4000],$2000); copymemory(@mem_temp[$6000],@memoria_temp[$6000],$2000); init_gfx(2,8,8,2048); gfx_set_desc_data(2,0,8*8,0,4); convert_gfx(2,0,@mem_temp,@pt_x,@ps_y,false,false); //poner la paleta if not(roms_load(@memoria_temp,shootout_pal)) then exit; for f:=0 to 255 do begin colores[f].r:=$21*((memoria_temp[f] shr 0) and 1)+$47*((memoria_temp[f] shr 1) and 1)+$97*((memoria_temp[f] shr 2) and 1); colores[f].g:=$21*((memoria_temp[f] shr 3) and 1)+$47*((memoria_temp[f] shr 4) and 1)+$97*((memoria_temp[f] shr 5) and 1); colores[f].b:=$21*0+$47*((memoria_temp[f] shr 6) and 1)+$97*((memoria_temp[f] shr 7) and 1); end; set_pal(colores,256); //Dip marcade.dswa:=$bf; marcade.dswb:=$ff; marcade.dswa_val:=@shootout_dip_a; marcade.dswb_val:=@shootout_dip_b; //final reset_shootout; iniciar_shootout:=true; end; end.
unit psychic5_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,ym_2203,gfx_engine,rom_engine,pal_engine, sound_engine,qsnapshot; function iniciar_psychic5:boolean; implementation const psychic5_rom:array[0..1] of tipo_roms=( (n:'myp5d';l:$8000;p:0;crc:$1d40a8c7),(n:'myp5e';l:$10000;p:$8000;crc:$2fa7e8c0)); psychic5_snd_rom:tipo_roms=(n:'myp5a';l:$10000;p:0;crc:$6efee094); psychic5_char:tipo_roms=(n:'p5f';l:$8000;p:0;crc:$04d7e21c); psychic5_sprites:array[0..1] of tipo_roms=( (n:'p5b';l:$10000;p:0;crc:$7e3f87d4),(n:'p5c';l:$10000;p:$10000;crc:$8710fedb)); psychic5_tiles:array[0..1] of tipo_roms=( (n:'myp5g';l:$10000;p:0;crc:$617b074b),(n:'myp5h';l:$10000;p:$10000;crc:$a9dfbe67)); //Dip psychic5_dip_a:array [0..5] of def_dip=( (mask:$1;name:'Flip Screen';number:2;dip:((dip_val:$1;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$8;name:'Difficulty';number:2;dip:((dip_val:$8;dip_name:'Normal'),(dip_val:$0;dip_name:'Hard'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$10;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$10;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$20;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c0;name:'Lives';number:4;dip:((dip_val:$80;dip_name:'2'),(dip_val:$c0;dip_name:'3'),(dip_val:$40;dip_name:'4'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())),()); psychic5_dip_b:array [0..3] of def_dip=( (mask:$1;name:'Invulnerability';number:2;dip:((dip_val:$1;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$e0;name:'Coin A';number:8;dip:((dip_val:$0;dip_name:'5C 1C'),(dip_val:$20;dip_name:'4C 1C'),(dip_val:$40;dip_name:'3C 1C'),(dip_val:$60;dip_name:'2C 1C'),(dip_val:$e0;dip_name:'1C 1C'),(dip_val:$c0;dip_name:'1C 2C'),(dip_val:$a0;dip_name:'1C 3C'),(dip_val:$80;dip_name:'1C 4C'),(),(),(),(),(),(),(),())), (mask:$1c;name:'Coin B';number:8;dip:((dip_val:$0;dip_name:'5C 1C'),(dip_val:$4;dip_name:'4C 1C'),(dip_val:$8;dip_name:'3C 1C'),(dip_val:$c;dip_name:'2C 1C'),(dip_val:$1c;dip_name:'1C 1C'),(dip_val:$18;dip_name:'1C 2C'),(dip_val:$14;dip_name:'1C 3C'),(dip_val:$10;dip_name:'1C 4C'),(),(),(),(),(),(),(),())),()); var mem_rom:array[0..3,0..$3fff] of byte; mem_ram:array[0..2,0..$fff] of byte; bg_clip_mode,banco_rom,banco_vram,sound_latch,bg_control:byte; title_screen:boolean; scroll_x,scroll_y,sy1,sy2,sx1:word; procedure update_video_psychic5; var f,color,nchar,x,y,clip_x,clip_y,clip_w,clip_h:word; attr,flip_x,spr1,spr2,spr3,spr4,sy1_old,sx1_old,sy2_old:byte; begin //fondo if (bg_control and 1)<>0 then begin //fondo activo? for f:=0 to $7ff do begin attr:=mem_ram[0,1+(f shl 1)]; color:=attr and $f; if (gfx[2].buffer[f] or buffer_color[color+$10]) then begin x:=(f and $1f) shl 4; y:=(63-(f shr 5)) shl 4; color:=(color shl 4)+$100+((bg_control and 2) shl 8); nchar:=mem_ram[0,(f shl 1)]+((attr and $c0) shl 2); put_gfx_flip(x,y,nchar,color,3,2,(attr and $20)<>0,(attr and $10)<>0); gfx[2].buffer[f]:=false; end; end; if not(title_screen) then begin scroll_x_y(3,4,scroll_x,768-scroll_y); bg_clip_mode:=0; sx1:=0; sy1:=0; sy2:=0; end else begin clip_x:=0; clip_y:=0; clip_w:=256; clip_h:=256; sy1_old:=sy1; sx1_old:=sx1; sy2_old:=sy2; sy1:=memoria[$f200+11]; // sprite 0 sx1:=memoria[$f200+12]; sy2:=memoria[$f200+11+128]; // sprite 8 case bg_clip_mode of 0,4:if (sy1_old<>sy1) then bg_clip_mode:=bg_clip_mode+1; 2,6:if (sy2_old<>sy2) then bg_clip_mode:=bg_clip_mode+1; 8,10,12,14:if (sx1_old<>sx1) then bg_clip_mode:=bg_clip_mode+1; 1,5:if (sy1=$f0) then bg_clip_mode:=bg_clip_mode+1; 3,7:if (sy2=$f0) then bg_clip_mode:=bg_clip_mode+1; 9,11:if (sx1=$f0) then bg_clip_mode:=bg_clip_mode+1; 13,15:if (sx1_old=$f0) then bg_clip_mode:=bg_clip_mode+1; 16:if (sy1<>$00) then bg_clip_mode:=0; end; case bg_clip_mode of 0,4,8,12,16:begin clip_x:=0; clip_y:=0; clip_w:=0; clip_h:=0; end; 1:clip_y:=sy1; 3:clip_h:=sy2; 5:clip_h:=sy1; 7:clip_y:=sy2; 9,15:clip_x:=sx1; 11,13:clip_w:=sx1; end; fill_full_screen(4,$800); actualiza_trozo((scroll_x+clip_y) and $1ff,((768-scroll_y)+clip_x) and $3ff,clip_h,clip_w,3,clip_y,clip_x,clip_h,clip_w,4); end; end else fill_full_screen(4,$800); //sprites if not(title_screen) then begin for f:=0 to $5f do begin attr:=memoria[$f20d+(f*16)]; flip_x:=(attr and $20) shr 5; nchar:=memoria[$f20e+(f*16)]+((attr and $c0) shl 2); color:=(memoria[$f20f+(f*16)] and $f) shl 4; x:=memoria[$f20b+(f*16)]+((attr and 4) shl 6); y:=(256-(memoria[$f20c+(f*16)]+16))+((attr and 1) shl 8); if (attr and 8)<>0 then begin //Sprites grandes spr1:=0 xor flip_x; spr2:=1 xor flip_x; spr3:=2 xor flip_x; spr4:=3 xor flip_x; put_gfx_sprite_diff(nchar+spr1,color,(attr and $20)<>0,(attr and $10)<>0,1,0,16); put_gfx_sprite_diff(nchar+spr2,color,(attr and $20)<>0,(attr and $10)<>0,1,16,16); put_gfx_sprite_diff(nchar+spr3,color,(attr and $20)<>0,(attr and $10)<>0,1,0,0); put_gfx_sprite_diff(nchar+spr4,color,(attr and $20)<>0,(attr and $10)<>0,1,16,0); actualiza_gfx_sprite_size(x,y-16,4,32,32); end else begin put_gfx_sprite(nchar,color,(attr and $20)<>0,(attr and $10)<>0,1); actualiza_gfx_sprite(x,y,4,1); end; end; end; //chars for f:=0 to $3ff do begin attr:=mem_ram[1,1+(f shl 1)]; color:=attr and $f; if (gfx[0].buffer[f] or buffer_color[color]) then begin x:=(f and $1f) shl 3; y:=(31-(f shr 5)) shl 3; nchar:=mem_ram[1,f shl 1]+((attr and $c0) shl 2); put_gfx_trans_flip(x,y,nchar,(color shl 4)+$200,1,0,(attr and $20)<>0,(attr and $10)<>0); gfx[0].buffer[f]:=false; end; end; actualiza_trozo(0,0,256,256,1,0,0,256,256,4); actualiza_trozo_final(16,0,224,256,4); fillchar(buffer_color,MAX_COLOR_BUFFER,0); end; procedure eventos_psychic5; begin if event.arcade then begin //P1 if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); //P2 if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1); if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2); if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4); if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8); if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10); if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20); //SYSTEM if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80); end; end; procedure psychic5_principal; var f:byte; frame_m,frame_s:single; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; frame_s:=z80_1.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //Main CPU z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; //Sound CPU z80_1.run(frame_s); frame_s:=frame_s+z80_1.tframes-z80_1.contador; case f of $0:begin //rst 8 z80_0.im0:=$cf; z80_0.change_irq(HOLD_LINE); end; 239:begin //rst 10 z80_0.im0:=$d7 ; z80_0.change_irq(HOLD_LINE); update_video_psychic5; end; end; end; eventos_psychic5; video_sync; end; end; function ram_paginada_r(direccion:word):byte; begin case (direccion+((banco_vram and 1) shl 13)) of 0..$fff:ram_paginada_r:=mem_ram[0,direccion]; $1000..$1fff:ram_paginada_r:=mem_ram[2,direccion and $fff]; $2000:ram_paginada_r:=marcade.in0; $2001:ram_paginada_r:=marcade.in1; $2002:ram_paginada_r:=marcade.in2; $2003:ram_paginada_r:=marcade.dswa; $2004:ram_paginada_r:=marcade.dswb; $230c:ram_paginada_r:=bg_control; $2400..$25ff:ram_paginada_r:=buffer_paleta[direccion and $1ff]; $2800..$29ff:ram_paginada_r:=buffer_paleta[(direccion and $1ff)+$200]; $2a00..$2bff:ram_paginada_r:=buffer_paleta[(direccion and $1ff)+$400]; $3000..$3fff:ram_paginada_r:=mem_ram[1,direccion and $fff]; end; end; procedure cambiar_color(pos:word); var valor:byte; color,color_g:tcolor; begin valor:=buffer_paleta[pos]; color.r:=pal4bit(valor shr 4); color.g:=pal4bit(valor); valor:=buffer_paleta[pos+1]; color.b:=pal4bit(valor shr 4); //val:=(palette_ram[offset or 1] and $0f) and $0f ; //a:=(val shl 4) or val; //jal_blend_table[pos]:=a; pos:=pos shr 1; set_pal_color(color,pos); case pos of $200..$2ff:buffer_color[(pos shr 4) and $f]:=true; $100..$1ff:begin //Paleta gris valor:=(color.r+color.g+color.b) div 3; color_g.r:=valor; color_g.g:=valor; color_g.b:=valor; //con intensidad? {if (ix<>0) then begin ir:=palette_ram[$1fe] shr 4; ir:=(ir shl 4) or ir; ig:=palette_ram[$1fe] and 15; ig:=(ig shl 4) or ig; ib:=palette_ram[$1ff] shr 4; ib:=(ib shl 4) or ib; //UINT32 result = jal_blend_func(MAKE_RGB(val,val,val), MAKE_RGB(ir, ig, ib), jal_blend_table[0xff]) ; end;} set_pal_color(color_g,pos+512); buffer_color[((pos shr 4) and $f)+$10]:=true; end end; end; procedure ram_paginada_w(direccion:word;valor:byte); begin case (direccion+((banco_vram and 1) shl 13)) of 0..$fff:if mem_ram[0,direccion]<>valor then begin mem_ram[0,direccion]:=valor; gfx[2].buffer[direccion shr 1]:=true; end; $1000..$1fff:mem_ram[2,direccion and $fff]:=valor; $2308:scroll_y:=valor or (scroll_y and $300); $2309:scroll_y:=(scroll_y and $ff) or ((valor and $3) shl 8); $230a:scroll_x:=valor or (scroll_x and $100); $230b:scroll_x:=(scroll_x and $ff) or ((valor and 1) shl 8); $230c:begin if (bg_control and 2)<>(valor and 2) then fillchar(gfx[2].buffer[0],$800,1); bg_control:=valor; end; $2400..$25ff:if buffer_paleta[direccion and $1ff]<>valor then begin buffer_paleta[direccion and $1ff]:=valor; cambiar_color(direccion and $1fe); end; $2800..$29ff:if buffer_paleta[(direccion and $1ff)+$200]<>valor then begin buffer_paleta[(direccion and $1ff)+$200]:=valor; cambiar_color((direccion and $1fe)+$200); end; $2a00..$2bff:if buffer_paleta[(direccion and $1ff)+$400]<>valor then begin buffer_paleta[(direccion and $1ff)+$400]:=valor; cambiar_color((direccion and $1fe)+$400); end; $3000..$3fff:if mem_ram[1,direccion and $fff]<>valor then begin mem_ram[1,direccion and $fff]:=valor; gfx[0].buffer[(direccion and $fff) shr 1]:=true; end; end; end; function psychic5_getbyte(direccion:word):byte; begin case direccion of 0..$7fff,$e000..$efff,$f200..$ffff:psychic5_getbyte:=memoria[direccion]; $8000..$bfff:psychic5_getbyte:=mem_rom[banco_rom and 3,direccion and $3fff]; $c000..$dfff:psychic5_getbyte:=ram_paginada_r(direccion and $1fff); $f002:psychic5_getbyte:=banco_rom; $f003:psychic5_getbyte:=banco_vram; end; end; procedure psychic5_putbyte(direccion:word;valor:byte); begin case direccion of 0..$bfff:; $c000..$dfff:ram_paginada_w(direccion and $1fff,valor); $e000..$efff,$f200..$ffff:memoria[direccion]:=valor; $f000:sound_latch:=valor; $f001:main_screen.flip_main_screen:=(valor and $80)<>0; $f002:banco_rom:=valor; $f003:banco_vram:=valor; $f005:title_screen:=(valor<>0); end; end; function psychic5_snd_getbyte(direccion:word):byte; begin case direccion of 0..$7fff,$c000..$c7ff:psychic5_snd_getbyte:=mem_snd[direccion]; $e000:psychic5_snd_getbyte:=sound_latch; end; end; procedure psychic5_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; $c000..$c7ff:mem_snd[direccion]:=valor; end; end; procedure psychic5_outbyte(puerto:word;valor:byte); begin case (puerto and $ff) of 0:ym2203_0.control(valor); 1:ym2203_0.write(valor); $80:ym2203_1.control(valor); $81:ym2203_1.write(valor); end; end; procedure psychic5_sound_update; begin ym2203_0.Update; ym2203_1.Update; end; procedure snd_irq(irqstate:byte); begin z80_1.change_irq(irqstate); end; procedure psychic5_qsave(nombre:string); var data:pbyte; buffer:array[0..4] of byte; size:word; begin open_qsnapshot_save('psychic5'+nombre); getmem(data,20000); //CPU size:=z80_0.save_snapshot(data); savedata_qsnapshot(data,size); size:=z80_1.save_snapshot(data); savedata_qsnapshot(data,size); //SND size:=ym2203_0.save_snapshot(data); savedata_com_qsnapshot(data,size); size:=ym2203_1.save_snapshot(data); savedata_com_qsnapshot(data,size); //MEM savedata_com_qsnapshot(@memoria[$8000],$8000); savedata_com_qsnapshot(@mem_snd[$8000],$8000); //MISC savedata_com_qsnapshot(@mem_ram[0,0],$1000); savedata_com_qsnapshot(@mem_ram[1,0],$1000); savedata_com_qsnapshot(@mem_ram[2,0],$1000); buffer[0]:=banco_rom; buffer[1]:=banco_vram; buffer[2]:=byte(title_screen); buffer[3]:=sound_latch; buffer[4]:=bg_control; savedata_qsnapshot(@buffer,5); savedata_com_qsnapshot(@buffer_paleta,$600*2); freemem(data); close_qsnapshot; end; procedure psychic5_qload(nombre:string); var data:pbyte; buffer:array[0..4] of byte; f:word; begin if not(open_qsnapshot_load('psychic5'+nombre)) then exit; getmem(data,20000); //CPU loaddata_qsnapshot(data); z80_0.load_snapshot(data); loaddata_qsnapshot(data); z80_1.load_snapshot(data); //SND loaddata_qsnapshot(data); ym2203_0.load_snapshot(data); loaddata_qsnapshot(data); ym2203_1.load_snapshot(data); //MEM loaddata_qsnapshot(@memoria[$8000]); loaddata_qsnapshot(@mem_snd[$8000]); //MISC loaddata_qsnapshot(@mem_ram[0,0]); loaddata_qsnapshot(@mem_ram[1,0]); loaddata_qsnapshot(@mem_ram[2,0]); loaddata_qsnapshot(@buffer[0]); banco_rom:=buffer[0]; banco_vram:=buffer[1]; title_screen:=buffer[2]<>0; sound_latch:=buffer[3]; bg_control:=buffer[4]; loaddata_qsnapshot(@buffer_paleta); freemem(data); close_qsnapshot; //END for f:=0 to $2ff do cambiar_color(f*2); end; //Main procedure reset_psychic5; begin z80_0.reset; z80_1.reset; YM2203_0.reset; YM2203_1.reset; reset_audio; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; banco_rom:=0; banco_vram:=0; sound_latch:=0; title_screen:=false; bg_control:=0; bg_clip_mode:=0; end; function iniciar_psychic5:boolean; var f:word; memoria_temp:array[0..$1ffff] of byte; const ps_x:array[0..15] of dword=(0, 4, 8, 12, 16, 20, 24, 28, 64*8, 64*8+4, 64*8+8, 64*8+12, 64*8+16, 64*8+20, 64*8+24, 64*8+28); ps_y:array[0..15] of dword=(0*8, 4*8, 8*8, 12*8, 16*8, 20*8, 24*8, 28*8, 32*8, 36*8, 40*8, 44*8, 48*8, 52*8, 56*8, 60*8); begin llamadas_maquina.bucle_general:=psychic5_principal; llamadas_maquina.reset:=reset_psychic5; llamadas_maquina.fps_max:=54.001512; llamadas_maquina.save_qsnap:=psychic5_qsave; llamadas_maquina.load_qsnap:=psychic5_qload; iniciar_psychic5:=false; iniciar_audio(false); screen_init(1,256,256,true); screen_init(2,512,512,true); screen_init(3,512,1024); screen_mod_scroll(3,512,256,511,1024,256,1023); screen_init(4,512,512,false,true); iniciar_video(224,256); //Main CPU z80_0:=cpu_z80.create(6000000,256); z80_0.change_ram_calls(psychic5_getbyte,psychic5_putbyte); //Sound CPU z80_1:=cpu_z80.create(5000000,256); z80_1.change_ram_calls(psychic5_snd_getbyte,psychic5_snd_putbyte); z80_1.change_io_calls(nil,psychic5_outbyte); z80_1.init_sound(psychic5_sound_update); //Sound Chips YM2203_0:=ym2203_chip.create(1500000,1,0.75); ym2203_0.change_irq_calls(snd_irq); YM2203_1:=ym2203_chip.create(1500000,1,0.75); //cargar roms if not(roms_load(@memoria_temp,psychic5_rom)) then exit; //Poner las ROMS en sus bancos copymemory(@memoria,@memoria_temp,$8000); for f:=0 to 3 do copymemory(@mem_rom[f,0],@memoria_temp[$8000+(f*$4000)],$4000); //cargar ROMS sonido if not(roms_load(@mem_snd,psychic5_snd_rom)) then exit; //convertir chars if not(roms_load(@memoria_temp,psychic5_char)) then exit; init_gfx(0,8,8,1024); gfx[0].trans[15]:=true; gfx_set_desc_data(4,0,32*8,0,1,2,3); convert_gfx(0,0,@memoria_temp,@ps_x,@ps_y,false,true); //convertir sprites if not(roms_load(@memoria_temp,psychic5_sprites)) then exit; init_gfx(1,16,16,1024); gfx[1].trans[15]:=true; gfx_set_desc_data(4,0,128*8,0,1,2,3); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,true); //convertir tiles if not(roms_load(@memoria_temp,psychic5_tiles)) then exit; init_gfx(2,16,16,1024); convert_gfx(2,0,@memoria_temp,@ps_x,@ps_y,false,true); //DIP marcade.dswa:=$ef; marcade.dswb:=$ff; marcade.dswa_val:=@psychic5_dip_a; marcade.dswb_val:=@psychic5_dip_b; //final reset_psychic5; iniciar_psychic5:=true; end; end.
unit K461701432; {* [Requestlink:461701432] } // Модуль: "w:\common\components\rtl\Garant\Daily\K461701432.pas" // Стереотип: "TestCase" // Элемент модели: "K461701432" MUID: (51DA9D410127) // Имя типа: "TK461701432" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , EVDtoEVDWriterTest ; type TK461701432 = class(TEVDtoEVDWriterTest) {* [Requestlink:461701432] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK461701432 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *51DA9D410127impl_uses* //#UC END# *51DA9D410127impl_uses* ; function TK461701432.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := '7.9'; end;//TK461701432.GetFolder function TK461701432.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '51DA9D410127'; end;//TK461701432.GetModelElementGUID initialization TestFramework.RegisterTest(TK461701432.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
{ id:109291 PROG:sprime LANG:PASCAL } { USER: r z [rz109291] TASK: sprime LANG: PASCAL Compiling... Compile: OK Executing... Test 1: TEST OK [0.000 secs, 276 KB] Test 2: TEST OK [0.000 secs, 276 KB] Test 3: TEST OK [0.000 secs, 276 KB] Test 4: TEST OK [0.000 secs, 276 KB] Test 5: TEST OK [0.000 secs, 276 KB] All tests OK. Your program ('sprime') produced all correct answers! This is your submission #2 for this problem. Congratulations! } const b:array[1..6]of 1..9 =(1,2,3,5,7,9); var i,j,n:longint; s:string; function isprime(t:longint):boolean; var i:longint; begin if t<2 then exit(false); for i:=2 to trunc(sqrt(t)) do if t mod i =0 then exit(false); exit(true); end; procedure dfs(i,r:longint); var k:longint; t:longint; bol:boolean; begin if(i>n)then exit; for k:=1 to 6 do begin t:=r; r:=10*r+b[k]; {if (i<>1)and(k=2) then continue;} bol:=isprime(r); //writeln(i,' ',r); if not bol then begin r:=t; continue; end else if bol and(i=n) then writeln(r); dfs(i+1,r); r:=t; end; end; begin assign(input,'sprime.in');reset(input); assign(output,'sprime.out');rewrite(output); readlN(n); dfs(1,0); close(output); close(input); end.
{ *************************************************************************** } { } { } { Copyright (C) Amarildo Lacerda } { } { https://github.com/amarildolacerda } { } { } { *************************************************************************** } { } { 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 plugin.FormManager; interface {$I plugin.inc} uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.ValEdit, Vcl.ExtCtrls, Vcl.StdCtrls, Data.DB, 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, Vcl.DBGrids; type TPluginFormManagerDlg = class(TForm) Panel1: TPanel; Panel2: TPanel; Button1: TButton; DBGrid1: TDBGrid; DataSource1: TDataSource; FDMemTable1: TFDMemTable; FDMemTable1Item: TStringField; FDMemTable1Plugin: TStringField; Button2: TButton; Button3: TButton; procedure FormShow(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure FormCreate(Sender: TObject); private FFilename: string; procedure SetFilename(const Value: string); procedure CarregarLista; procedure SalvarLista; procedure Reordena; { Private declarations } public { Public declarations } property Filename: string read FFilename write SetFilename; end; function PluginFormManagerDlg: TPluginFormManagerDlg; implementation {$R *.dfm} uses IniFiles, {$IFDEF USE_INIFILEEx} IniFilesEx, {$ENDIF} plugin.Manager; var FFormDlg: TPluginFormManagerDlg; function PluginFormManagerDlg: TPluginFormManagerDlg; begin if not assigned(FFormDlg) then FFormDlg := TPluginFormManagerDlg.Create(nil); result := FFormDlg; end; procedure TPluginFormManagerDlg.Button1Click(Sender: TObject); var appDir: string; dlg: TOpenDialog; begin appDir := GetCurrentDir; dlg := TOpenDialog.Create(self); try dlg.InitialDir := appDir; dlg.Filter := ' DLL de Plugin (*.dll)|*.dll'; if dlg.execute then begin //if GetPluginManager.InstallPlugin(dlg.Filename) >= 0 then begin CarregarLista; end; end; finally dlg.Free; end; end; procedure TPluginFormManagerDlg.FormCreate(Sender: TObject); begin FFilename := 'Plugin.ini'; end; procedure TPluginFormManagerDlg.FormShow(Sender: TObject); begin CarregarLista; end; procedure TPluginFormManagerDlg.Reordena; var i: integer; begin FDMemTable1.first; i := 0; while FDMemTable1.Eof = false do begin FDMemTable1.edit; FDMemTable1Item.Value := 'Plugin' + IntToStr(i); FDMemTable1.Post; FDMemTable1.next; inc(i); end; end; procedure TPluginFormManagerDlg.SalvarLista; var app, key: string; n: integer; begin app := ExtractFileName(ParamStr(0)); with TIniFile.Create(FFilename) do try EraseSection(app); n := 0; FDMemTable1.first; while FDMemTable1.Eof = false do begin key := 'Plugin' + IntToStr(n); WriteString(app, key, FDMemTable1Plugin.Value); inc(n); FDMemTable1.next; end; finally Free; end; CarregarLista; end; procedure TPluginFormManagerDlg.SetFilename(const Value: string); begin FFilename := Value; end; procedure TPluginFormManagerDlg.Button2Click(Sender: TObject); begin SalvarLista; close; end; procedure TPluginFormManagerDlg.Button3Click(Sender: TObject); begin FDMemTable1.Delete; Reordena; end; procedure TPluginFormManagerDlg.CarregarLista; var str: TStringList; app: String; key: string; n, i: integer; s: string; begin FDMemTable1.EmptyDataSet; str := TStringList.Create; try app := ExtractFileName(ParamStr(0)); with TIniFile.Create(FFilename) do try ReadSection(app, str); n := 0; for i := 0 to str.count - 1 do begin key := 'Plugin' + IntToStr(i); s := ReadString(app, key, 'fim'); if s <> 'fim' then begin FDMemTable1.append; FDMemTable1Item.Value := key; FDMemTable1Plugin.Value := s; FDMemTable1.Post; end; end; finally Free; end; Reordena; finally str.Free; end; end; initialization finalization if assigned(FFormDlg) then FreeAndNil(FFormDlg); end.
unit Main; 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.ScrollBox, FMX.Memo, WinTab32; type TForm1 = class(TForm) Memo1: TMemo; Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { private 宣言 } public { public 宣言 } FTablet :HCTX; ///// procedure BeginTablet; procedure EndTablet; end; var Form1: TForm1; implementation //############################################################### {$R *.fmx} uses FMX.Platform.Win; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% public procedure TForm1.BeginTablet; var lc :LOGCONTEXT; npAxis :AXIS; begin if not IsWinTab32Available then Exit; // get default WTInfo( WTI_DEFSYSCTX, 0, @lc ); // modify the digitizing region StrCopy( lc.lcName, PChar( 'PaintWindow '+IntToHex( HInstance, 8 ) ) ); lc.lcOptions := lc.lcOptions or CXO_SYSTEM; lc.lcMsgBase := WT_DEFBASE; lc.lcPktData := PACKETDATA; lc.lcPktMode := PACKETMODE; lc.lcMoveMask := PACKETDATA; lc.lcBtnUpMask := lc.lcBtnDnMask; lc.lcOutExtX := lc.lcOutExtX * 10; lc.lcOutExtY := lc.lcOutExtY * 10; CreateHandle; FTablet := WTOpen( WindowHandleToPlatform( Handle ).Wnd, lc, True ); Assert( FTablet > 0, 'FTablet = 0' ); WTInfo( WTI_DEVICES + lc.lcDevice, DVC_NPRESSURE, @npAxis ); Memo1.Lines.Add( 'npAxis.axMin = ' + npAxis.axMin .ToString ); Memo1.Lines.Add( 'npAxis.axMax = ' + npAxis.axMax .ToString ); Memo1.Lines.Add( 'npAxis.axUnits = ' + npAxis.axUnits .ToString ); Memo1.Lines.Add( 'npAxis.axResolution = ' + npAxis.axResolution.ToString ); end; procedure TForm1.EndTablet; begin if FTablet <> 0 then begin WTClose( FTablet ); FTablet := 0; end; end; //////////////////////////////////////////////////////////////////////////////// procedure TForm1.FormCreate(Sender: TObject); begin BeginTablet; end; procedure TForm1.FormDestroy(Sender: TObject); begin EndTablet; end; //////////////////////////////////////////////////////////////////////////////// procedure TForm1.Timer1Timer(Sender: TObject); var PsN, I :Integer; Ps :array[ 0..31 ] of PACKET; begin PsN := WTPacketsGet( FTablet, 32, @Ps ); if PsN > 0 then begin Memo1.Lines.Clear; for I := 0 to PsN-1 do begin with Ps[ I ] do Memo1.Lines.Add( pkX.ToString + ', ' + pkY.ToString + ', ' + pkNormalPressure.ToString ); end; end; end; end. //#########################################################################
unit l3PopupMenuHelper; // Модуль: "w:\common\components\rtl\Garant\L3\l3PopupMenuHelper.pas" // Стереотип: "Service" // Элемент модели: "Tl3PopupMenuHelper" MUID: (550013770000) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface {$If NOT Defined(NoVCL)} uses l3IntfUses , l3ProtoObject , Menus , Classes , Types ; type Tl3PopupMenuHelperCallback = procedure(aMenu: TMenuItem) of object; (* Ml3PopupMenuHelper = interface {* Контракт сервиса Tl3PopupMenuHelper } function GetPopupMenu(aControl: TComponent; const aPoint: TPoint): TMenuItem; procedure GetPopupMenuForComponentInfo(aControl: TComponent; const aPoint: TPoint; aCallback: Tl3PopupMenuHelperCallback); end;//Ml3PopupMenuHelper *) Il3PopupMenuHelper = interface {* Интерфейс сервиса Tl3PopupMenuHelper } function GetPopupMenu(aControl: TComponent; const aPoint: TPoint): TMenuItem; procedure GetPopupMenuForComponentInfo(aControl: TComponent; const aPoint: TPoint; aCallback: Tl3PopupMenuHelperCallback); end;//Il3PopupMenuHelper Tl3PopupMenuHelper = {final} class(Tl3ProtoObject) private f_Alien: Il3PopupMenuHelper; {* Внешняя реализация сервиса Il3PopupMenuHelper } protected procedure pm_SetAlien(const aValue: Il3PopupMenuHelper); procedure ClearFields; override; public function GetPopupMenu(aControl: TComponent; const aPoint: TPoint): TMenuItem; procedure GetPopupMenuForComponentInfo(aControl: TComponent; const aPoint: TPoint; aCallback: Tl3PopupMenuHelperCallback); class function Instance: Tl3PopupMenuHelper; {* Метод получения экземпляра синглетона Tl3PopupMenuHelper } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } public property Alien: Il3PopupMenuHelper write pm_SetAlien; {* Внешняя реализация сервиса Il3PopupMenuHelper } end;//Tl3PopupMenuHelper {$IfEnd} // NOT Defined(NoVCL) implementation {$If NOT Defined(NoVCL)} uses l3ImplUses , Controls , SysUtils , l3Base //#UC START# *550013770000impl_uses* //#UC END# *550013770000impl_uses* ; type TControlFriend = {abstract} class(TControl) {* Друг к классу TControl } end;//TControlFriend var g_Tl3PopupMenuHelper: Tl3PopupMenuHelper = nil; {* Экземпляр синглетона Tl3PopupMenuHelper } procedure Tl3PopupMenuHelperFree; {* Метод освобождения экземпляра синглетона Tl3PopupMenuHelper } begin l3Free(g_Tl3PopupMenuHelper); end;//Tl3PopupMenuHelperFree procedure Tl3PopupMenuHelper.pm_SetAlien(const aValue: Il3PopupMenuHelper); begin Assert((f_Alien = nil) OR (aValue = nil)); f_Alien := aValue; end;//Tl3PopupMenuHelper.pm_SetAlien function Tl3PopupMenuHelper.GetPopupMenu(aControl: TComponent; const aPoint: TPoint): TMenuItem; //#UC START# *5506BF830025_550013770000_var* var l_M : TMenu; //#UC END# *5506BF830025_550013770000_var* begin //#UC START# *5506BF830025_550013770000_impl* if (f_Alien = nil) then begin if (aControl Is TControl) then begin l_M := TControlFriend(aControl).PopupMenu; if (l_M = nil) then Result := nil else Result := l_M.Items; end//aControl Is TControl else Result := nil; end//f_Alien = nil else Result := f_Alien.GetPopupMenu(aControl, aPoint); //#UC END# *5506BF830025_550013770000_impl* end;//Tl3PopupMenuHelper.GetPopupMenu procedure Tl3PopupMenuHelper.GetPopupMenuForComponentInfo(aControl: TComponent; const aPoint: TPoint; aCallback: Tl3PopupMenuHelperCallback); //#UC START# *5506BFB302ED_550013770000_var* //#UC END# *5506BFB302ED_550013770000_var* begin //#UC START# *5506BFB302ED_550013770000_impl* if Assigned(f_Alien) then f_Alien.GetPopupMenuForComponentInfo(aControl, aPoint, aCallback) else aCallback(Self.GetPopupMenu(aControl, aPoint)); //#UC END# *5506BFB302ED_550013770000_impl* end;//Tl3PopupMenuHelper.GetPopupMenuForComponentInfo class function Tl3PopupMenuHelper.Instance: Tl3PopupMenuHelper; {* Метод получения экземпляра синглетона Tl3PopupMenuHelper } begin if (g_Tl3PopupMenuHelper = nil) then begin l3System.AddExitProc(Tl3PopupMenuHelperFree); g_Tl3PopupMenuHelper := Create; end; Result := g_Tl3PopupMenuHelper; end;//Tl3PopupMenuHelper.Instance class function Tl3PopupMenuHelper.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_Tl3PopupMenuHelper <> nil; end;//Tl3PopupMenuHelper.Exists procedure Tl3PopupMenuHelper.ClearFields; begin Alien := nil; inherited; end;//Tl3PopupMenuHelper.ClearFields {$IfEnd} // NOT Defined(NoVCL) end.
{$MODE OBJFPC} program SequenceCounting; const InputFile = 'SEQCOUNT.INP'; OutputFile = 'SEQCOUNT.OUT'; modulo = 1234567890; p: array[1..5] of Integer = (2, 3, 5, 3607, 3803); e: array[1..5] of Integer = (1, 2, 1, 1, 1); var fi, fo: TextFile; n, m: Int64; procedure Analysis(k: Int64); var p, e: Int64; begin p := 2; while k <> 1 do begin e := 0; while k mod p = 0 do begin Inc(e); k := k div p; end; if e <> 0 then WriteLn(p, '^', e); Inc(p); if (k > 1) and (p * p > k) then p := k; end; end; function Inverse(a, m: Int64): Int64; //GCD(a, m) = 1; return a^-1 mod m var xa, xm, xr, r, q: Int64; begin xa := 1; xm := 0; while m <> 0 do begin q := a div m; r := a - q * m; a := m; m := r; xr := xa - q * xm; xa := xm; xm := xr; end; Result := xa; end; function IntPower(p, k: Int64): Int64; //p^k begin if k = 0 then Exit(1); Result := Sqr(IntPower(p, k div 2)); if Odd(k) then Result := Result * p; end; function IntPowerMod(p, k, m: Int64): Int64; //p^k mod m begin if k = 0 then Exit(1 mod m); Result := Sqr(IntPowerMod(p, k div 2, m)) mod m; if Odd(k) then Result := Result * p mod m; end; {p: So nguyen to, e so mu Tinh xem n! chua bao nhieu luy thua cua p: power Va neu bo het cac thua so p trong khai trien n!, so du cua no khi chia cho p^e bang bao nhieu: remainder} procedure FactorialAnalysis(n, p, e: Int64; var power, remainder: Int64); var i, j: Integer; temp, pe: Int64; begin //Tinh power temp := n; power := 0; while temp > 0 do begin temp := temp div p; Inc(power, temp); end; //Tinh remainder remainder := 1; pe := IntPower(p, e); while n > 0 do begin temp := 1; for i := 1 to pe do if i mod p <> 0 then temp := temp * i mod pe; remainder := remainder * IntPowerMod(temp, n div pe, pe) mod pe; for i := 1 to n mod pe do if i mod p <> 0 then remainder := remainder * i mod pe; n := n div p; end; end; //Cal C(k, n) mod (p^e) function GetRemainder(n, k: Int64; p, e: Int64): Int64; var r1, p1, r2, p2, r3, p3, modulo: Int64; begin FactorialAnalysis(n, p, e, p1, r1); FactorialAnalysis(k, p, e, p2, r2); FactorialAnalysis(n - k, p, e, p3, r3); modulo := IntPower(p, e); Result := r1 * IntPowerMod(p, p1 - p2 - p3, modulo) mod modulo; Result := Result * Inverse(r2, modulo) mod modulo; Result := Result * Inverse(r3, modulo) mod modulo; Result := (Result + modulo) mod modulo; end; //C(k, n) mod modulo function Solve(n, k: Int64): Int64; var a, m, c, y: Int64; i: Integer; begin Result := 0; for i := 1 to 5 do begin a := GetRemainder(n, k, p[i], e[i]); m := IntPower(p[i], e[i]); c := modulo div m; //chinese remainder theorem Result := (Result + a * c mod Modulo * Inverse(c, m) mod modulo) mod Modulo; end; Result := (Result + Modulo) mod Modulo; end; procedure SolveAll; var iTest, nTests: Integer; begin ReadLn(fi, nTests); for iTest := 1 to nTests do begin ReadLn(fi, m, n); WriteLn(fo, Solve(m + n - 1, m)); end; end; begin {Analysis(1234567890); Halt;} AssignFile(fi, InputFile); Reset(fi); AssignFile(fo, OutputFile); Rewrite(fo); try SolveAll; finally CloseFile(fi); CloseFile(fo); end; end. { For testing only function Fac(n: Int64): Int64; var i: Integer; begin Result := 1; for i := 1 to n do Result := Result * i; end; function C(n, k: Int64): Int64; var i: Integer; begin Result := 1; for i := 1 to k do Result := Result * (n - i + 1) div i; end; }
unit IO; interface procedure ParseCMDLine(out FilenameInput: string; out FilenameOutput: string); function ReadFileToString(const AFilename: string): string; procedure WriteStringToFile(const AStr: string; const AFilename: string); implementation uses Classes, SysUtils; procedure ParseCMDLine(out FilenameInput: string; out FilenameOutput: string); begin if ParamCount <> 2 then raise Exception.Create('Input parameters is bad'); FilenameInput := ParamStr(1); FilenameOutput := ParamStr(2); end; function ReadFileToString(const AFilename: string): string; var fl: TStringList; begin fl := TStringList.Create; try fl.LoadFromFile(AFilename); Result := fl.Text; finally fl.Free; end; end; procedure WriteStringToFile(const AStr: string; const AFilename: string); var fl: TStringList; begin fl := TStringList.Create; try fl.Text := AStr; fl.SaveToFile(AFilename); finally fl.Free; end; end; end.
unit ConfigHandler; interface uses VoyagerInterfaces, Config, Classes, Controls, Registry, VCLUtils; type TConfigHandler = class( TInterfacedObject, IMetaURLHandler, IURLHandler, IConfigHolder ) public constructor Create(TestVer : boolean); private fTestVer : boolean; // IConfigHandler private function ReadString ( System : boolean; DataOwner, DataId, DefaultValue : string ) : string; function ReadInteger ( System : boolean; DataOwner, DataId : string; DefaultValue : integer ) : integer; function ReadBoolean ( System : boolean; DataOwner, DataId : string; DefaultValue : boolean ) : boolean; procedure WriteString ( System : boolean; DataOwner, DataId, Value : string ); procedure WriteInteger( System : boolean; DataOwner, DataId : string; Value : integer ); procedure WriteBoolean( System : boolean; DataOwner, DataId : string; Value : boolean ); procedure RetrieveUserList( UserList : TStrings ); private function InitRegistry( System : boolean; DataOwner : string ) : TRegistry; // IMetaURLHandler private function getName : string; function getOptions : TURLHandlerOptions; function getCanHandleURL( URL : TURL ) : THandlingAbility; function Instantiate : IURLHandler; // IURLHandler private function HandleURL( URL : TURL ) : TURLHandlingResult; function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; function getControl : TControl; procedure setMasterURLHandler( const URLHandler : IMasterURLHandler ); private fMasterURLHandler : IMasterURLHandler; end; const tidMetaHandler_ConfigHandler = 'ConfigHandler'; const VOYAGER_ROOT = '\SOFTWARE\Oceanus Communications\Legacy Online\Client\'; TEST_VOYAGER_ROOT = '\SOFTWARE\Oceanus Communications\Legacy Online Test\Client\'; implementation uses Windows, VoyagerEvents, URLParser, SysUtils; constructor TConfigHandler.Create(TestVer : boolean); begin inherited Create; fTestVer := TestVer; end; function TConfigHandler.ReadString( System : boolean; DataOwner, DataId, DefaultValue : string ) : string; var Reg : TRegistry; begin try Reg := InitRegistry( System, DataOwner ); try try result := Reg.ReadString( DataId ); if result = '' then result := DefaultValue; except result := DefaultValue; end; finally Reg.Free; end; except result := DefaultValue; end; end; function TConfigHandler.ReadInteger( System : boolean; DataOwner, DataId : string; DefaultValue : integer ) : integer; var Reg : TRegistry; begin try Reg := InitRegistry( System, DataOwner ); try try result := Reg.ReadInteger( DataId ); except result := DefaultValue; end; finally Reg.Free; end; except result := DefaultValue; end; end; function TConfigHandler.ReadBoolean( System : boolean; DataOwner, DataId : string; DefaultValue : boolean ) : boolean; var Reg : TRegistry; begin try Reg := InitRegistry( System, DataOwner ); try try result := Reg.ReadBool( DataId ); except result := DefaultValue; end; finally Reg.Free; end; except result := DefaultValue; end; end; procedure TConfigHandler.WriteString( System : boolean; DataOwner, DataId, Value : string ); var Reg : TRegistry; begin try Reg := InitRegistry( System, DataOwner ); try Reg.WriteString( DataId, Value ); finally Reg.Free; end; except end; end; procedure TConfigHandler.WriteInteger( System : boolean; DataOwner, DataId : string; Value : integer ); var Reg : TRegistry; begin try Reg := InitRegistry( System, DataOwner ); try Reg.WriteInteger( DataId, Value ); finally Reg.Free; end; except end; end; procedure TConfigHandler.WriteBoolean( System : boolean; DataOwner, DataId : string; Value : boolean ); var Reg : TRegistry; begin try Reg := InitRegistry( System, DataOwner ); try Reg.WriteBool( DataId, Value ); finally Reg.Free; end; except end; end; procedure TConfigHandler.RetrieveUserList( UserList : TStrings ); var Reg : TRegistry; //aUserList : TStrings; i : integer; KeyName : string; begin try Reg := InitRegistry( false, 'QuickLogon' ); try //aUserList := TStringList.Create; Reg.GetKeyNames( UserList ); { if aUserList.Count>0 then begin for i:=0 to aUserList.Count-1 do begin KeyName := 'QuickLogon\' + aUserList[i]; if ReadString( false, KeyName, 'MasterUserName', '')<>'' then UserList.Add(aUserList[i]); end; end; } finally Reg.Free; // aUserList.Free; end; except end; end; function TConfigHandler.InitRegistry( System : boolean; DataOwner : string ) : TRegistry; var KeyName : string; begin result := TRegistry.Create; try if System then begin result.RootKey := HKEY_LOCAL_MACHINE; if fTestVer then KeyName := TEST_VOYAGER_ROOT + 'System\' + DataOwner else KeyName := VOYAGER_ROOT + 'System\' + DataOwner end else begin result.RootKey := HKEY_CURRENT_USER; if fTestVer then KeyName := TEST_VOYAGER_ROOT + 'Users\' + DataOwner else KeyName := VOYAGER_ROOT + 'Users\' + DataOwner; end; if not result.OpenKey( KeyName, true ) then raise Exception.Create( 'Cannot open registry key: ' + KeyName ); except result.Free; raise; end; end; function TConfigHandler.getName : string; begin result := tidMetaHandler_ConfigHandler; end; function TConfigHandler.getOptions : TURLHandlerOptions; begin result := [hopCacheable, hopNonVisual]; end; function TConfigHandler.getCanHandleURL( URL : TURL ) : THandlingAbility; begin result := 0; end; function TConfigHandler.Instantiate : IURLHandler; begin result := self; end; function TConfigHandler.HandleURL( URL : TURL ) : TURLHandlingResult; begin result := urlNotHandled; end; function TConfigHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; var ConfigHolder : IConfigHolder absolute info; ChangeInfo : boolean absolute info; begin result := evnHandled; case EventId of evnAnswerConfigHolder : ConfigHolder := self; evnShutDown : fMasterURLHandler := nil; evnChangeConfig: fTestVer := ChangeInfo else result := evnHandled; end; end; function TConfigHandler.getControl : TControl; begin result := nil; end; procedure TConfigHandler.setMasterURLHandler( const URLHandler : IMasterURLHandler ); begin fMasterURLHandler := URLHandler; end; end.
unit StockMinuteData_Save; interface uses Classes, Sysutils, BaseApp, StockMinuteDataAccess; function SaveStockMinuteData(App: TBaseApp; ADataAccess: TStockMinuteDataAccess): Boolean; overload; function SaveStockMinuteData(App: TBaseApp; ADataAccess: TStockMinuteDataAccess; AFileUrl: string): Boolean; overload; implementation uses Windows, BaseWinFile, //utilsLog, define_price, define_datetime, define_datasrc, define_stock_quotes, define_dealstore_header, define_dealstore_file, StockMinuteData_Load; function SaveStockMinuteDataToBuffer(App: TBaseApp; ADataAccess: TStockMinuteDataAccess; AMemory: pointer): Boolean; var tmpHead: PStore_Quote_M1_Minute_Header_V1Rec; tmpQuoteData: PStore64; tmpStoreMinuteData: PStore_Quote32_Minute; tmpRTMinuteData: PRT_Quote_Minute; tmpCode: AnsiString; i: integer; begin Result := false; if nil = ADataAccess then exit; if nil = AMemory then exit; tmpHead := AMemory; tmpHead.Header.BaseHeader.CommonHeader.Signature.Signature := 7784; // 6 tmpHead.Header.BaseHeader.CommonHeader.Signature.DataVer1 := 1; tmpHead.Header.BaseHeader.CommonHeader.Signature.DataVer2 := 0; tmpHead.Header.BaseHeader.CommonHeader.Signature.DataVer3 := 0; // 字节存储顺序 java 和 delphi 不同 // 00 // 01 tmpHead.Header.BaseHeader.CommonHeader.Signature.BytesOrder:= 1; tmpHead.Header.BaseHeader.CommonHeader.HeadSize := SizeOf(TStore_Quote_M1_Minute_Header_V1Rec); // 1 -- 7 tmpHead.Header.BaseHeader.CommonHeader.StoreSizeMode.Value := 16; // 1 -- 8 page size mode { 表明是什么数据 } tmpHead.Header.BaseHeader.CommonHeader.DataType := DataType_Stock; // 2 -- 10 tmpHead.Header.BaseHeader.CommonHeader.DataMode := DataMode_MinuteData; // 1 -- 11 tmpHead.Header.BaseHeader.CommonHeader.RecordSizeMode.Value:= 6; // 1 -- 12 tmpHead.Header.BaseHeader.CommonHeader.RecordCount := ADataAccess.RecordCount; // 4 -- 16 tmpHead.Header.BaseHeader.CommonHeader.CompressFlag := 0; // 1 -- 17 tmpHead.Header.BaseHeader.CommonHeader.EncryptFlag := 0; // 1 -- 18 tmpHead.Header.BaseHeader.CommonHeader.DataSourceId := GetDealDataSourceCode(ADataAccess.DataSource); // 2 -- 20 tmpCode := ADataAccess.StockCode; if '' <> tmpCode then CopyMemory(@tmpHead.Header.BaseHeader.Code[0], @tmpCode[1], Length(tmpCode)); //Move(ADataAccess.StockItem.Code, tmpHead.Header.BaseHeader.Code[0], Length(ADataAccess.StockItem.Code)); // 12 - 32 // ---------------------------------------------------- tmpHead.Header.BaseHeader.StorePriceFactor := 1000; // 2 - 34 tmpHead.Header.FirstDealDateTime := ADataAccess.FirstDealDateTime; // 2 - 36 tmpHead.Header.LastDealDateTime := ADataAccess.LastDealDateTime; // 2 - 38 tmpHead.Header.Minute := ADataAccess.Minute; Inc(tmpHead); tmpQuoteData := PStore64(tmpHead); ADataAccess.Sort; for i := 0 to ADataAccess.RecordCount - 1 do begin tmpRTMinuteData := ADataAccess.RecordItem[i]; if nil <> tmpRTMinuteData then begin tmpStoreMinuteData := PStore_Quote32_Minute(tmpQuoteData); RTPricePackRange2StorePriceRange(@tmpStoreMinuteData.PriceRange, @tmpRTMinuteData.PriceRange); tmpStoreMinuteData.DealVolume := tmpRTMinuteData.DealVolume; // 8 - 24 成交量 tmpStoreMinuteData.DealAmount := tmpRTMinuteData.DealAmount; // 8 - 32 成交金额 tmpStoreMinuteData.StockDateTime := tmpRTMinuteData.DealDateTime; //tmpStoreMinuteData.DealDate := tmpRTMinuteData.DealDate.Value; // 4 - 36 交易日期 //tmpStoreMinuteData.Weight.Value := tmpRTMinuteData.Weight.Value; // 4 - 40 复权权重 * 100 //tmpStoreMinuteData.TotalValue := tmpRTMinuteData.TotalValue; // 8 - 48 总市值 //tmpStoreMinuteData.DealValue := tmpRTMinuteData.DealValue; // 8 - 56 流通市值 Inc(tmpQuoteData); end; end; end; function SaveStockMinuteData(App: TBaseApp; ADataAccess: TStockMinuteDataAccess): Boolean; var tmpFileUrl: string; begin //Log('SaveStockMinuteData.pas', 'SaveStockMinuteData 1:' + IntToStr(ADataAccess.Minute)); Result := false; if nil = ADataAccess then exit; if 0 < ADataAccess.Minute then begin if 240 > ADataAccess.Minute then begin if nil = ADataAccess.StockItem then begin if '' <> ADataAccess.StockCode then begin end; end; if nil <> ADataAccess.StockItem then begin if weightNone <> ADataAccess.WeightMode then begin tmpFileUrl := App.Path.GetFileUrl(ADataAccess.DBType, ADataAccess.DataType, GetDealDataSourceCode(ADataAccess.DataSource), ADataAccess.Minute, ADataAccess.StockItem); end else begin tmpFileUrl := App.Path.GetFileUrl(ADataAccess.DBType, ADataAccess.DataType, GetDealDataSourceCode(ADataAccess.DataSource), ADataAccess.Minute, ADataAccess.StockItem); end; end; Result := SaveStockMinuteData(App, ADataAccess, tmpFileUrl); end; end; end; function SaveStockMinuteData(App: TBaseApp; ADataAccess: TStockMinuteDataAccess; AFileUrl: string): Boolean; var tmpWinFile: TWinFile; tmpFileMapView: Pointer; tmpFileNewSize: integer; tmpMergeDataAccess: TStockMinuteDataAccess; tmpIdxMergeSrc, tmpIdxDest: integer; tmpMinuteMergeSrc: PRT_Quote_Minute; tmpMinuteDest: PRT_Quote_Minute; tmpAddList: TList; i: integer; begin Result := false; if nil = ADataAccess then exit; if '' = Trim(AFileUrl) then exit; //Log('SaveStockMinuteData.pas', 'SaveStockMinuteData:' + tmpFileUrl); if FileExists(AFileUrl) then begin // merge data tmpMergeDataAccess := TStockMinuteDataAccess.Create(ADataAccess.StockItem, GetDealDataSource(ADataAccess.DataSrcID), ADataAccess.WeightMode); try if LoadStockMinuteData(App, tmpMergeDataAccess, AFileUrl) then begin if tmpMergeDataAccess.Minute = ADataAccess.Minute then begin tmpAddList := TList.Create; try ADataAccess.Sort; tmpMergeDataAccess.Sort; tmpIdxMergeSrc := 0; tmpIdxDest := 0; while (tmpIdxMergeSrc < tmpMergeDataAccess.RecordCount) and (tmpIdxDest < ADataAccess.RecordCount) do begin tmpMinuteDest := ADataAccess.MinuteDataByIndex(tmpIdxDest); tmpMinuteMergeSrc := tmpMergeDataAccess.MinuteDataByIndex(tmpIdxMergeSrc); if (tmpMinuteDest.DealDateTime.Date.Value = tmpMinuteMergeSrc.DealDateTime.Date.Value) then begin if (tmpMinuteDest.DealDateTime.Time.Value = tmpMinuteMergeSrc.DealDateTime.Time.Value) then begin Inc(tmpIdxMergeSrc); Inc(tmpIdxDest); end else begin if (tmpMinuteDest.DealDateTime.Time.Value < tmpMinuteMergeSrc.DealDateTime.Time.Value) then begin Inc(tmpIdxDest); end else begin tmpAddList.Add(tmpMinuteMergeSrc); Inc(tmpIdxMergeSrc); end; end; end else begin if (tmpMinuteDest.DealDateTime.Date.Value < tmpMinuteMergeSrc.DealDateTime.Date.Value) then begin Inc(tmpIdxDest); end else begin tmpAddList.Add(tmpMinuteMergeSrc); Inc(tmpIdxMergeSrc); end; end; end; while (tmpIdxMergeSrc < tmpMergeDataAccess.RecordCount) do begin tmpMinuteMergeSrc := tmpMergeDataAccess.MinuteDataByIndex(tmpIdxMergeSrc); tmpAddList.Add(tmpMinuteMergeSrc); Inc(tmpIdxMergeSrc); end; for i := 0 to tmpAddList.Count - 1 do begin tmpMinuteMergeSrc := PRT_Quote_Minute(tmpAddList.Items[i]); tmpMinuteDest := ADataAccess.CheckOutRecord(tmpMinuteMergeSrc.DealDateTime); if nil <> tmpMinuteDest then begin tmpMinuteDest^ := tmpMinuteMergeSrc^; end; end; tmpAddList.Clear; finally tmpAddList.Free; end; end; end; finally tmpMergeDataAccess.Free; end; end; tmpWinFile := TWinFile.Create; try if tmpWinFile.OpenFile(AFileUrl, true) then begin tmpFileNewSize := SizeOf(TStore_Quote_M1_Minute_Header_V1Rec) + ADataAccess.RecordCount * SizeOf(TStore64); //400k tmpFileNewSize := ((tmpFileNewSize div (64 * 1024)) + 1) * 64 * 1024; tmpWinFile.FileSize := tmpFileNewSize; tmpFileMapView := tmpWinFile.OpenFileMap; if nil <> tmpFileMapView then begin Result := SaveStockMinuteDataToBuffer(App, ADataAccess, tmpFileMapView); end; end; finally tmpWinFile.Free; end; end; end.
(* ************************************************************************** * name: FreeDoor BBS Door Engine * version: 2.0.0 * author: Mike Hodgson * copyright: 2014, Mike Hodgson * licence: The MIT License * http://opensource.org/licenses/MIT * credits: Mike Hodgson, Michael Preslar, Rick Parrish, Maarten Bekers, * Sean Dennis * **************************************************************************) unit FreeDoor; {$mode objfpc} interface uses Classes, StrUtils, SysUtils,{$IFDEF WIN32} Windows, {$ENDIF}Crt, Dos, Ansi, EleNorm; type TFDObj = class private FDebug: Boolean; procedure DbgWriteLn(Text: string); public property Debug: Boolean read FDebug write FDebug; end; type TUser = class(TFDObj) private FName: string; FHandle: string; FLocation: string; FBBS: string; FBaudRate: Integer; FConnType: Integer; FNode: Integer; FPort: Integer; FLevel: Integer; FTime: Integer; FAnsi: Boolean; FRemote: Boolean; public constructor Create(Dbg: Boolean = false); destructor Destroy; override; property Name: string read FName write FName; property Handle: string read FHandle write FHandle; property Location: string read FLocation write FLocation; property BBS: string read FBBS write FBBS; property BaudRate: Integer read FBaudRate write FBaudRate; property ConnType: Integer read FConnType write FConnType; property Node: Integer read FNode write FNode; property Port: Integer read FPort write FPort; property Level: Integer read FLevel write FLevel; property Time: Integer read FTime write FTime; property ANSI: Boolean read FAnsi write FAnsi; property Remote: Boolean read FRemote write FRemote; end; type TDoor = class(TFDObj) private FDropFile: string; FLocalOnly: Boolean; FUser: TUser; procedure ParseCommandLine; procedure GetLocalInformation; procedure SetDropFile(DropFileName: string); public constructor Create(Dbg: Boolean = false); destructor Destroy; override; procedure ErrorWriteLn(Err: string); property DropFile: string read FDropFile write SetDropFile; property LocalOnly: Boolean read FLocalOnly write FLocalOnly; property User: TUser read FUser; end; implementation (* TFDObj Base Class *) procedure TFDObj.DbgWriteLn(Text: string); begin if (FDebug) then WriteLn('### ' + Text); end; (* TUser Class *) constructor TUser.Create(Dbg: Boolean = false); begin FDebug := Dbg; DbgWriteLn('User object created'); end; destructor TUser.Destroy; begin DbgWriteLn('User object destroyed'); inherited; end; (* TDoor Class *) constructor TDoor.Create(Dbg: Boolean = false); begin FLocalOnly := true; FDebug := Dbg; DbgWriteLn('Door object created'); FUser := TUser.Create(FDebug); ParseCommandLine; end; destructor TDoor.Destroy; begin FreeAndNil(FUser); DbgWriteLn('Door object destroyed'); inherited; end; procedure TDoor.ErrorWriteLn(Err: string); begin TextColor(4); WriteLn(Err); TextColor(7); end; procedure TDoor.ParseCommandLine; var I: Integer; begin for I := 1 to ParamCount do begin case UpperCase(ParamStr(I)) of (* Read drop file *) '/D': begin SetDropFile(ParamStr(I + 1)); DbgWriteLn('Dropfile set to: ' + FDropFile); end; (* Local only, ask user for information *) '/L': begin FLocalOnly := true; DbgWriteLn('Entering local only mode...'); GetLocalInformation; end; end; end; end; procedure TDoor.GetLocalInformation; begin end; procedure TDoor.SetDropFile(DropFileName: string); var directory: DirStr; var name: NameStr; var ext: ExtStr; procedure ReadDorinfoDef; begin end; procedure ReadDoorSys; begin end; procedure ReadDoor32Sys; var f: text; var s: string; var i: integer; begin assign(f, FDropFile); reset(f); readln (f,s); val(s,FUser.ConnType,i); readln (f,s); val(s,FUser.Port,i); readln (f,s); val(s,FUser.BaudRate,i); readln (f,s); FUser.BBS := s; readln (f,s); readln (f,s); FUser.Name := s; readln (f,s); FUser.Handle := s; readln (f,s); val(s,FUser.Level,i); readln (f,s); val(s,FUser.Time,i); readln (f,s); if (s = '1') then FUser.ANSI := true else FUser.ANSI := false; readln (f,s); val(s,FUser.Node,i); close(f); DbgWriteLn('Door32.sys read succesfully!'); end; procedure ReadXtrnDat; begin end; begin FDropFile := DropFileName; FSplit(AnsiLowerCase(FDropFile), directory, name, ext); if not (FileExists(FDropFile)) then begin raise Exception.Create('Drop file does not exist: ' + FDropFile); end; if (name = 'door') then ReadDoorSys else if (name = 'door32') then ReadDoor32Sys else if (pos('dorinfo', name) > 0) then ReadDorinfoDef else if (name = 'xtrn') then ReadXtrnDat else raise Exception.Create('Invalid drop file format. Valid formats: door.sys, door32.sys, dorinfox.def, xtrn.dat'); end; end.
namespace Sugar.Test; interface uses Sugar, Sugar.Xml, RemObjects.Elements.EUnit; type CharacterDataTest = public class (Test) private Doc: XmlDocument; Text: XmlText; CData: XmlCDataSection; Comment: XmlComment; method Data(Node: XmlCharacterData; Content: String); method Length(Node: XmlCharacterData; Content: String); method Value(Node: XmlCharacterData; Content: String); method AppendData(Node: XmlCharacterData; Content: String); method DeleteData(Node: XmlCharacterData; Content: String); method InsertData(Node: XmlCharacterData; Content: String); method ReplaceData(Node: XmlCharacterData; Content: String); method Substring(Node: XmlCharacterData; Content: String); public method Setup; override; method Data; method Length; method Value; method AppendData; method DeleteData; method InsertData; method ReplaceData; method Substring; method NodeType; end; implementation method CharacterDataTest.Setup; begin Doc := XmlDocument.FromString(XmlTestData.CharXml); Assert.IsNotNil(Doc); var Node := Doc["Book"]; Assert.IsNotNil(Node); Text := Node[0].FirstChild as XmlText; Assert.IsNotNil(Text); var X := Node[1].FirstChild; CData := X as XmlCDataSection; Assert.IsNotNil(CData); Comment := Node[2] as XmlComment; Assert.IsNotNil(Comment); end; method CharacterDataTest.AppendData; begin AppendData(Text, "Text"); AppendData(CData, "Description"); AppendData(Comment, "Comment"); end; method CharacterDataTest.DeleteData; begin DeleteData(Text, "Text"); DeleteData(CData, "Description"); DeleteData(Comment, "Comment"); end; method CharacterDataTest.InsertData; begin InsertData(Text, "Text"); InsertData(CData, "Description"); InsertData(Comment, "Comment"); end; method CharacterDataTest.ReplaceData; begin ReplaceData(Text, "Text"); ReplaceData(CData, "Description"); ReplaceData(Comment, "Comment"); end; method CharacterDataTest.Substring; begin Substring(Text, "Text"); Substring(CData, "Description"); Substring(Comment, "Comment"); end; method CharacterDataTest.Data; begin Data(Text, "Text"); Data(CData, "Description"); Data(Comment, "Comment"); end; method CharacterDataTest.Length; begin Length(Text, "Text"); Length(CData, "Description"); Length(Comment, "Comment"); end; method CharacterDataTest.Value; begin Value(Text, "Text"); Value(CData, "Description"); Value(Comment, "Comment"); end; method CharacterDataTest.AppendData(Node: XmlCharacterData; Content: String); begin Assert.IsNotNil(Node); Assert.AreEqual(Node.Data, Content); Node.AppendData("Test"); Assert.AreEqual(Node.Data, Content+"Test"); Node.AppendData(nil); Assert.AreEqual(Node.Data, Content+"Test"); end; method CharacterDataTest.Data(Node: XmlCharacterData; Content: String); begin Assert.IsNotNil(Node); Assert.IsNotNil(Node.Data); Assert.AreEqual(Node.Data, Content); Node.Data := "Test"; Assert.AreEqual(Node.Data, "Test"); Assert.Throws(->begin Node.Data := nil; end); end; method CharacterDataTest.DeleteData(Node: XmlCharacterData; Content: String); begin Assert.IsNotNil(Node); Assert.AreEqual(Node.Data, Content); Node.Data := "Test"; Assert.AreEqual(Node.Data, "Test"); Node.DeleteData(1, 2); Assert.AreEqual(Node.Data, "Tt"); Assert.Throws(->Node.DeleteData(-1, 1)); Assert.Throws(->Node.DeleteData(1, -1)); Assert.Throws(->Node.DeleteData(25, 1)); Assert.Throws(->Node.DeleteData(1, 25)); end; method CharacterDataTest.InsertData(Node: XmlCharacterData; Content: String); begin Assert.IsNotNil(Node); Assert.AreEqual(Node.Data, Content); Node.Data := "Tt"; Assert.AreEqual(Node.Data, "Tt"); Node.InsertData(1, "es"); Assert.AreEqual(Node.Data, "Test"); Assert.Throws(->Node.InsertData(-1, "x")); Assert.Throws(->Node.InsertData(55, "x")); Assert.Throws(->Node.InsertData(1, nil)); end; method CharacterDataTest.Length(Node: XmlCharacterData; Content: String); begin Assert.IsNotNil(Node); Assert.AreEqual(Node.Data, Content); Assert.AreEqual(Node.Length, Content.Length); Assert.AreEqual(Node.Length, Node.Data.Length); Node.Data := "Test"; Assert.AreEqual(Node.Data, "Test"); Assert.AreEqual(Node.Length, 4); end; method CharacterDataTest.ReplaceData(Node: XmlCharacterData; Content: String); begin Assert.IsNotNil(Node); Assert.AreEqual(Node.Data, Content); Node.Data := "Test"; Assert.AreEqual(Node.Data, "Test"); Node.ReplaceData(1, 2, "arge"); Assert.AreEqual(Node.Data, "Target"); Node.ReplaceData(1, 4, ""); Assert.AreEqual(Node.Data, "Tt"); Node.ReplaceData(0, Node.Length, "Test"); Assert.AreEqual(Node.Data, "Test"); Assert.Throws(->Node.ReplaceData(-1, 1, "x")); Assert.Throws(->Node.ReplaceData(1, -1, "x")); Assert.Throws(->Node.ReplaceData(55, 1, "x")); Assert.Throws(->Node.ReplaceData(1, 55, "x")); Assert.Throws(->Node.ReplaceData(1, 1, nil)); end; method CharacterDataTest.Substring(Node: XmlCharacterData; Content: String); begin Assert.IsNotNil(Node); Assert.AreEqual(Node.Data, Content); Node.Data := "Test"; Assert.AreEqual(Node.Data, "Test"); Assert.AreEqual(Node.Substring(1, 2), "es"); Assert.AreEqual(Node.Substring(0, Node.Length), "Test"); Assert.Throws(->Node.Substring(-1, 1)); Assert.Throws(->Node.Substring(1, -1)); Assert.Throws(->Node.Substring(55, 1)); Assert.Throws(->Node.Substring(1, 55)); end; method CharacterDataTest.Value(Node: XmlCharacterData; Content: String); begin Assert.IsNotNil(Node); Assert.IsNotNil(Node.Value); Assert.AreEqual(Node.Value, Content); Node.Value := "Test"; Assert.AreEqual(Node.Value, "Test"); Assert.Throws(->begin Node.Value := nil; end); end; method CharacterDataTest.NodeType; begin Assert.AreEqual(Text.NodeType, XmlNodeType.Text); Assert.AreEqual(Comment.NodeType, XmlNodeType.Comment); Assert.AreEqual(CData.NodeType, XmlNodeType.CDATA); end; end.
unit Mat.SupportedDevelopmentTools; interface type // List of supported developent tools and their versions. TSupportedDevelopmentTools = (stdUnknown = 0, sdtDelphi5, sdtDelphi7); implementation end.
{$I ACBr.inc} unit pciotProprietarioW; interface uses SysUtils, Classes, pcnConversao, pciotCIOT, ASCIOTUtil; type TGeradorOpcoes = class; TProprietarioW = class(TPersistent) private FGerador: TGerador; FProprietario: TProprietario; FOperacao: TpciotOperacao; FOpcoes: TGeradorOpcoes; public constructor Create(AOwner: TProprietario; AOperacao: TpciotOperacao = opObter); destructor Destroy; override; function GerarXML: boolean; published property Gerador: TGerador read FGerador write FGerador; property Proprietario: TProprietario read FProprietario write FProprietario; property Opcoes: TGeradorOpcoes read FOpcoes write FOpcoes; end; TGeradorOpcoes = class(TPersistent) private FAjustarTagNro: boolean; FNormatizarMunicipios: boolean; FGerarTagAssinatura: TpcnTagAssinatura; FPathArquivoMunicipios: string; FValidarInscricoes: boolean; FValidarListaServicos: boolean; published property AjustarTagNro: boolean read FAjustarTagNro write FAjustarTagNro; property NormatizarMunicipios: boolean read FNormatizarMunicipios write FNormatizarMunicipios; property GerarTagAssinatura: TpcnTagAssinatura read FGerarTagAssinatura write FGerarTagAssinatura; property PathArquivoMunicipios: string read FPathArquivoMunicipios write FPathArquivoMunicipios; property ValidarInscricoes: boolean read FValidarInscricoes write FValidarInscricoes; property ValidarListaServicos: boolean read FValidarListaServicos write FValidarListaServicos; end; implementation { TProprietarioW } uses ASCIOT; constructor TProprietarioW.Create(AOwner: TProprietario; AOperacao: TpciotOperacao); begin FProprietario := AOwner; FOperacao := AOperacao; FGerador := TGerador.Create; FGerador.FIgnorarTagNivel := '|?xml version|CTe xmlns|infCTe versao|obsCont|obsFisco|'; FOpcoes := TGeradorOpcoes.Create; FOpcoes.FAjustarTagNro := True; FOpcoes.FNormatizarMunicipios := False; FOpcoes.FGerarTagAssinatura := taSomenteSeAssinada; FOpcoes.FValidarInscricoes := False; FOpcoes.FValidarListaServicos := False; end; destructor TProprietarioW.Destroy; begin FGerador.Free; FOpcoes.Free; inherited Destroy; end; function TProprietarioW.GerarXML: boolean; var chave: AnsiString; Gerar: boolean; xProtCTe : String; begin Gerador.Opcoes.IdentarXML := True; Gerador.Opcoes.TagVaziaNoFormatoResumido := False; Gerador.ArquivoFormatoXML := ''; case FOperacao of opObter: begin Gerador.wGrupo('ObterRequest ' + NAME_SPACE_EFRETE_PROPRIETARIOS_EFRETE); Gerador.wTexto('<Integrador ' + NAME_SPACE_EFRETE_OBJECTS + '>' + TAmsCIOT( FProprietario.Owner ).Configuracoes.Integradora.Identificacao + '</Integrador>'); Gerador.wTexto('<Versao ' + NAME_SPACE_EFRETE_OBJECTS + '>2</Versao>'); Gerador.wCampo(tcInt, '', 'CNPJ', 001, 014, 1, FProprietario.CNPJ, ''); Gerador.wCampo(tcStr, '', 'RNTRC', 001, 008, 1, FProprietario.RNTRC, ''); Gerador.wGrupo('/ObterRequest'); end; opAdicionar: begin Gerador.wGrupo('GravarRequest ' + NAME_SPACE_EFRETE_PROPRIETARIOS_EFRETE, 'VP01'); Gerador.wTexto('<Integrador ' + NAME_SPACE_EFRETE_OBJECTS + '>' + TAmsCIOT( FProprietario.Owner ).Configuracoes.Integradora.Identificacao + '</Integrador>'); Gerador.wTexto('<Versao ' + NAME_SPACE_EFRETE_OBJECTS + '>3</Versao>'); Gerador.wCampo(tcStr, 'PP03', 'CNPJ', 001, 014, 1, FProprietario.CNPJ, ''); Gerador.wCampo(tcStr, 'PP04', 'TipoPessoa', 001, 001, 1, TpCiotTipoPessoaToStr(FProprietario.TipoPessoa)); Gerador.wGrupo('Endereco', 'P05'); Gerador.wCampo(tcStr, 'PP06', 'Bairro', 001, 001, 1, FProprietario.Endereco.Bairro, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'PP07', 'CEP', 001, 009, 1, Copy(FProprietario.Endereco.CEP, 1, 5) + '-' + Copy(FProprietario.Endereco.CEP, 6, 3), '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'PP08', 'CodigoMunicipio', 001, 007, 1, FProprietario.Endereco.CodigoMunicipio, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'PP09', 'Rua', 001, 001, 1, FProprietario.Endereco.Rua, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'PP10', 'Numero', 001, 001, 1, FProprietario.Endereco.Numero, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'PP11', 'Complemento', 001, 001, 1, FProprietario.Endereco.Complemento, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wGrupo('/Endereco'); Gerador.wCampo(tcStr, 'PP12', 'RNTRC', 001, 008, 1, FProprietario.RNTRC, 'RNTRC do Proprietário'); Gerador.wCampo(tcStr, 'PP13', 'RazaoSocial', 001, 001, 1, FProprietario.RazaoSocial, ''); with FProprietario.Telefones do begin Gerador.wGrupo('Telefones', 'PP14'); Gerador.wGrupo('Celular ' + NAME_SPACE_EFRETE_OBJECTS, 'PP15'); Gerador.wCampo(tcInt, 'PP16', 'DDD', 001, 002, 1, Celular.DDD); Gerador.wCampo(tcInt, 'PP17', 'Numero', 001, 009, 1, Celular.Numero); Gerador.wGrupo('/Celular'); Gerador.wGrupo('Fax ' + NAME_SPACE_EFRETE_OBJECTS, 'PP18'); Gerador.wCampo(tcInt, 'PP19', 'DDD', 001, 002, 1, Fax.DDD); Gerador.wCampo(tcInt, 'PP20', 'Numero', 001, 009, 1, Fax.Numero); Gerador.wGrupo('/Fax'); Gerador.wGrupo('Fixo ' + NAME_SPACE_EFRETE_OBJECTS, 'PP21'); Gerador.wCampo(tcInt, 'PP22', 'DDD', 001, 002, 1, Fixo.DDD); Gerador.wCampo(tcInt, 'PP23', 'Numero', 001, 009, 1, Fixo.Numero); Gerador.wGrupo('/Fixo'); Gerador.wGrupo('/Telefones'); end; Gerador.wGrupo('/GravarRequest'); end; end; Result := (Gerador.ListaDeAlertas.Count = 0); end; end.
unit PJSONParser; interface uses Sysutils, classes, System.JSON.Builders, System.JSON.Readers, System.Rtti, Generics.Collections, PPlaceRoad; type TMap = class protected AdjacencyList: TObjectList<TPlace>; Map: TextFile; public constructor Create; procedure Parse(MapName:string); procedure Print; procedure Clear; function ReturnList: TObjectList<TPlace>; destructor Destroy; end; implementation { TMap } procedure TMap.Clear; begin AdjacencyList.Clear; end; constructor TMap.Create; //initialse the list begin AdjacencyList := TObjectList<TPlace>.Create(true); end; destructor TMap.Destroy; begin AdjacencyList.Free; end; procedure TMap.Parse(MapName:string); //Creates an adjacency list from a given JSON map file var Iterator: TJSONIterator; Reader: TJSONTextReader; StringReader: TStringReader; MapData, ALine: string; i,n,NumberEdges,c,NumberVertices: integer; TempPlace: TPlace; TempRoad: TRoad; begin MapData := ''; AssignFile(Map, MapName); reset(Map); while not eof(Map) do begin readln(Map, ALine); MapData := MapData + ALine + sLineBreak ; //create a formatted string of JSON end; StringReader := TStringReader.Create(MapData); //Initialsing JSON reader Reader := TJSONTextReader.Create(StringReader); // requires text reader type Iterator := TJSONIterator.Create(Reader); Iterator.Recurse; //prep to enter object Iterator.Next; Iterator.Recurse; //enter vertices object Iterator.Recurse; Iterator.Next; //enter array Iterator.Recurse; Iterator.Next; //enter first object in array NumberVertices := Iterator.AsInteger; for i := 0 to NumberVertices -1 do //for the number of places in the map begin tempPlace := TPlace.Create; //dynamically create a TPlace Iterator.Return; //return to array Iterator.Recurse; Iterator.Next; //go to next object in array Iterator.Recurse; Iterator.Next; //enter object TempPlace.SetName(Iterator.AsString); //read the name into TempPlace Iterator.Next; //go to next key-value pair within the object TempPlace.SetDist(Iterator.AsInteger); //read the distance Iterator.Next; Iterator.Recurse; //prep to enter edges array Iterator.Next; Iterator.Recurse; //enter edges array Iterator.Next; NumberEdges:=Iterator.AsInteger; //read the number of edges for n := 0 to NumberEdges -1 do //for the number of edges of the place begin TempRoad := TRoad.Create; //dynamincally create a TRoad Iterator.Return; //return to edges array Iterator.Recurse; Iterator.Next; Iterator.Recurse; //go to next key-value pair in the array Iterator.Next; TempRoad.SetNode(Iterator.AsString); //read the name of the node Iterator.Next; TempRoad.SetWeight(Iterator.AsInteger); //read the weight TempPlace.AddEdge(tempRoad); //add TempRoad to TempPlace end; Iterator.Return; //return to edges array Iterator.Recurse; Iterator.Next; Iterator.Return; //return to object Iterator.Recurse; Iterator.Next; Iterator.Recurse; //prep to enter neighbours array Iterator.Next; for c := 0 to NumberEdges -1 do //for the number of neighbouring place begin Iterator.Recurse; //go to next key-value pair Iterator.Next; TempPlace.AddNeighbour(Iterator.AsString); //read the name Iterator.Return; //return to neighbours array Iterator.Recurse; Iterator.Next; end; Iterator.Return; //return to the object Iterator.Recurse; Iterator.Next; //reached the end of the object, prep to enter next object AdjacencyList.Add(TempPlace); //add fully build TempPlace to the list end; end; procedure TMap.Print; //prints the contents of the list, for debugging use var I,n,c:integer; begin writeln(' '); writeln('Contents of AdjacencyList: '); for I := 0 to AdjacencyList.Count-1 do begin writeln(' '); writeln('Place: ' ,AdjacencyList[I].GetName); writeln('Edges: '); for n :=0 to AdjacencyList[I].Edges.Count -1 do begin writeln(' Node: ', AdjacencyList[I].Edges[n].GetName, ' Weight: ', AdjacencyList[I].Edges[n].GetWeight); end; writeln('Current Distance from source: ' ,AdjacencyList[I].GetDist); for c := 0 to AdjacencyList[I].Neighbours.Count -1 do begin writeln('Neighbours: ', AdjacencyList[I].Neighbours[c]); end; end; end; function TMap.ReturnList: TObjectList<TPlace>; //perform deep copy of list var Copy:TObjectList<TPlace>; i:integer; begin Copy := TObjectList<TPlace>.Create(False); for i := 0 to AdjacencyList.Count -1 do begin Copy.Add(AdjacencyList.List[i].Clone); end; result:=Copy; end; end.