text
stringlengths
14
6.51M
unit UPedidos; interface uses Data.DB, SysUtils, Forms, Vcl.Dialogs, FireDAC.Comp.Client,Classes; type TVenda = class private FQry : TFDQuery; FITEMS : TStringList; FDATAVENDA: TDateTime; FdFORMAPAGAMENTO: string; FVALORVENDA: Double; FDESCRICAOVENDA: string; // itens venda FFIDPRODUTO: Integer; FFIDVENDA: Integer; FFQUANTIDADE: Integer; FVENDA_IDTIPOCOBRANCA: string; FFITENS_MESA: Integer; FFITENS_VENDA_IDCOMPLEMENTO: Integer; FFITENS_IDGRUPO: Integer; FPEDIDOSTATUS: string; FPEDIDOPESSOAS: Integer; FPEDIDOS_IDMESA: Integer; FIDPEDIDO: Integer; FIDTENS_MESA: Integer; FITENS_IDPEDIDOS: Integer; FITENS_IDCOMPLEMENTOS: Integer; FIDITENS_COMPLEMENTOS: Integer; FIDCAIXA: Integer; FITENS_VENDA_OBSERVACAO: String; FFPEDIDOSTATUS: String; FFIDMESA: String; procedure SetDATAVENDA(const Value: TDateTime); procedure SetDESCRICAOVENDA(const Value: string); procedure SetFIDPRODUTO(const Value: Integer); procedure SetFIDVENDA(const Value: Integer); procedure SetFITENS_IDGRUPO(const Value: Integer); procedure SetFITENS_MESA(const Value: Integer); procedure SetFITENS_VENDA_IDCOMPLEMENTO(const Value: Integer); procedure SetFORMAPAGAMENTO(const Value: string); procedure SetFQUANTIDADE(const Value: Integer); procedure SetIDITENS_COMPLEMENTOS(const Value: Integer); procedure SetIDPEDIDO(const Value: Integer); procedure SetIDTENS_MESA(const Value: Integer); procedure SetITENS_IDCOMPLEMENTOS(const Value: Integer); procedure SetITENS_IDPEDIDOS(const Value: Integer); procedure SetPEDIDOPESSOAS(const Value: Integer); procedure SetPEDIDOS_IDMESA(const Value: Integer); procedure SetPEDIDOSTATUS(const Value: string); procedure SetVALORVENDA(const Value: Double); procedure SetVENDA_IDTIPOCOBRANCA(const Value: string); procedure SetIDCAIXA(const Value: Integer); procedure SetITENS_VENDA_OBSERVACAO(const Value: String); procedure SetFPEDIDOSTATUS(const Value: String); procedure SetFIDMESA(const Value: String); public constructor Create(aQry: TFDQuery); property ITENS_VENDA_IDCOMPLEMENTO : Integer read FFITENS_VENDA_IDCOMPLEMENTO write SetFITENS_VENDA_IDCOMPLEMENTO; property FIDVENDA: Integer read FFIDVENDA write SetFIDVENDA; property FQUANTIDADE: Integer read FFQUANTIDADE write SetFQUANTIDADE; property FIDPRODUTO: Integer read FFIDPRODUTO write SetFIDPRODUTO; property VALORVENDA: Double read FVALORVENDA write SetVALORVENDA; property DATAVENDA: TDateTime read FDATAVENDA write SetDATAVENDA; property DESCRICAOVENDA: string read FDESCRICAOVENDA write SetDESCRICAOVENDA; property FORMAPAGAMENTO: string read FdFORMAPAGAMENTO write SetFORMAPAGAMENTO; property VENDA_IDTIPOCOBRANCA: string read FVENDA_IDTIPOCOBRANCA write SetVENDA_IDTIPOCOBRANCA; property FITENS_MESA : Integer read FFITENS_MESA write SetFITENS_MESA; property FITENS_IDGRUPO : Integer read FFITENS_IDGRUPO write SetFITENS_IDGRUPO; property PEDIDOSTATUS : string read FPEDIDOSTATUS write SetPEDIDOSTATUS; property PEDIDOPESSOAS : Integer read FPEDIDOPESSOAS write SetPEDIDOPESSOAS; property PEDIDOS_IDMESA : Integer read FPEDIDOS_IDMESA write SetPEDIDOS_IDMESA; property IDPEDIDO : Integer read FIDPEDIDO write SetIDPEDIDO; property IDTENS_MESA : Integer read FIDTENS_MESA write SetIDTENS_MESA; property IDITENS_COMPLEMENTOS : Integer read FIDITENS_COMPLEMENTOS write SetIDITENS_COMPLEMENTOS; property ITENS_IDCOMPLEMENTOS : Integer read FITENS_IDCOMPLEMENTOS write SetITENS_IDCOMPLEMENTOS; property ITENS_IDPEDIDOS : Integer read FITENS_IDPEDIDOS write SetITENS_IDPEDIDOS; property IDCAIXA : Integer read FIDCAIXA write SetIDCAIXA; property ITENS_VENDA_OBSERVACAO : String read FITENS_VENDA_OBSERVACAO write SetITENS_VENDA_OBSERVACAO; property FIDMESA : String read FFIDMESA write SetFIDMESA; procedure ItensVenda; procedure Gravar_ItensComplementos; procedure Movimentacoes; procedure Venda; procedure PedidosMesa; procedure BuscaPedido; procedure Itens_Mesa; procedure Atualizar_Pedido; function GetIdPedido : Integer; end; implementation { TVenda } procedure TVenda.Atualizar_Pedido; begin FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('UPDATE PEDIDOS SET PEDIDOS.PEDIDOS_STATUS =:STATUS WHERE PEDIDOS.PEDIDOS_IDMESA =:IDMESA'); FQry.ParamByName('STATUS').AsString := 'FECHADO'; FQry.ParamByName('IDMESA').AsInteger := FPEDIDOS_IDMESA; FQry.ExecSQL; FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('UPDATE MESAS SET MESAS.MESAS_STATUS =:STATUS WHERE MESAS.IDMESAS =:IDMESA'); FQry.ParamByName('IDMESA').AsInteger := FPEDIDOS_IDMESA; FQry.ParamByName('STATUS').AsInteger := 0; FQry.ExecSQL; end; procedure TVenda.BuscaPedido; begin try FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('SELECT MAX(PEDIDOS.idpedidos) FROM PEDIDOS'); //MAX(PEDIDOS.idpedidos) FQry.Active := True; FIDPEDIDO := FQry.Fields[0].AsInteger; except on E: Exception do end; end; constructor TVenda.Create(aQry: TFDQuery); begin FQry := aQry; end; function TVenda.GetIdPedido: Integer; begin Result := FIDPEDIDO; end; procedure TVenda.Gravar_ItensComplementos; var itens_venda : String; begin try FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('INSERT INTO ITENS_COMPLEMENTO'); FQry.SQL.Add('(ITENS_IDCOMPLEMENTO , ITENS_IDPEDIDOS,POST_TYPE)'); FQry.SQL.Add('VALUES(:ITENS_IDCOMPLEMENTO ,:ITENS_IDPEDIDOS,:POST_TYPE)'); FQry.ParamByName('ITENS_IDCOMPLEMENTO').AsInteger := FITENS_IDCOMPLEMENTOS; FQry.ParamByName('ITENS_IDPEDIDOS').AsInteger := FITENS_IDPEDIDOS; FQry.ParamByName('POST_TYPE').AsInteger := 0; FQry.ExecSQL; except on E: Exception do raise Exception.Create(' Error no Cadastro de ItensComplementos! ' + E.Message); end; end; procedure TVenda.ItensVenda; var itensvenda : TStringList; i : Integer; quantidade_venda_itens : Integer; begin try quantidade_venda_itens := 1; FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('select gen_id(gen_vendas_id, 0) from rdb$database'); FQry.Active := True; FIDVENDA := FQry.Fields[0].AsInteger; FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('INSERT INTO ITENS_VENDA'); FQry.SQL.Add('(itens_venda.vendas_idvendas, itens_venda.itens_idproduto,itens_venda.itens_venda_quantidade,itens_venda.itens_venda_idmesa,itens_venda.itens_idpedido,ITENS_MESA_IDPEDIDO,POST_TYPE,ITENS_VENDA_OBSERVACAO,ITENS_VENDA_QUANTIDADE_VENDA)'); FQry.SQL.Add('VALUES(:vendas_idvendas, :itens_idproduto,:itens_venda_quantidade,:itens_venda_idmesa,:itens_idpedido,:ITENS_MESA_IDPEDIDO,:POST_TYPE,:ITENS_VENDA_OBSERVACAO,:ITENS_VENDA_QUANTIDADE_VENDA)'); FQry.ParamByName('vendas_idvendas').AsInteger := FIDVENDA; FQry.ParamByName('itens_idproduto').AsInteger := FFIDPRODUTO; FQry.ParamByName('itens_venda_quantidade').AsInteger := FQUANTIDADE; FQry.ParamByName('itens_venda_idmesa').AsInteger := FITENS_MESA; FQry.ParamByName('itens_idpedido').AsInteger := FIDPEDIDO; FQry.ParamByName('ITENS_VENDA_OBSERVACAO').AsString := FITENS_VENDA_OBSERVACAO; FQry.ParamByName('ITENS_VENDA_QUANTIDADE_VENDA').AsInteger := + 1; FQry.ParamByName('POST_TYPE').AsInteger := 1; FQry.ExecSQL; FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('UPDATE MESAS SET MESAS.MESAS_STATUS =:STATUS WHERE MESAS.IDMESAS = :IDMESA'); FQry.ParamByName('IDMESA').AsInteger := FITENS_MESA; FQry.ParamByName('STATUS').AsInteger := 1; FQry.ExecSQL; FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('UPDATE ESTOQUE SET ESTOQUE.ESTOQUEMAX = ESTOQUE.ESTOQUEMAX - :QUANT WHERE ESTOQUE.PRODUTO_IDPRODUTO = :IDPRO'); FQry.ParamByName('QUANT').AsInteger := FQUANTIDADE; FQry.ParamByName('IDPRO').AsInteger := FFIDPRODUTO; FQry.ExecSQL; except on E: Exception do raise Exception.Create(' Error no Cadastro de Itens Vendas! '); end; end; procedure TVenda.Itens_Mesa; begin try FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('INSERT INTO ITENS_MESA'); FQry.SQL.Add('(IDITENS_MESA)VALUES(:IDITENS_MESA)'); FQry.ParamByName('IDITENS_MESA').AsInteger := FIDTENS_MESA; FQry.ExecSQL; except on E: Exception do raise Exception.Create('Error' + E.Message); end; end; procedure TVenda.Movimentacoes; begin try FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('select gen_id(gen_caixa_id, 0) from rdb$database'); FQry.Active := True; FIDCAIXA := FQry.Fields[0].AsInteger; FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('INSERT INTO MOVIMENTACOES'); FQry.SQL.Add('( ENTRADA_MOVIMENTACOES , MOVIMENTACOES_IDVENDAS , MOVIMENTACOES_IDCAIXA , DATA_MOVIMENTACOES)'); FQry.SQL.Add('VALUES(:ENTRADA_MOVIMENTACOES , :MOVIMENTACOES_IDVENDAS , :MOVIMENTACOES_IDCAIXA , :DATA_MOVIMENTACOES)'); FQry.ParamByName('MOVIMENTACOES_IDVENDAS').AsInteger := FIDVENDA; FQry.ParamByName('MOVIMENTACOES_IDCAIXA').AsInteger := FIDCAIXA; FQry.ParamByName('ENTRADA_MOVIMENTACOES').AsString := 'E'; FQry.ParamByName('DATA_MOVIMENTACOES').AsDateTime := StrToDateTime(FormatDateTime('DD/MM/YYYY', Now)); FQry.ExecSQL; except on E: Exception do raise Exception.Create(' Error no Inserir os Dados de Movimentacoes! '); end; end; procedure TVenda.PedidosMesa; begin try FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('INSERT INTO pedidos'); FQry.SQL.Add('(pedidos.pedidos_status , pedidos.pedidos_pessoas , PEDIDOS_IDMESA , PEDIDOS_DATA)'); FQry.SQL.Add('values(:pedidos_status , :pedidos_pessoas , :PEDIDOS_IDMESA , :PEDIDOS_DATA)'); FQry.ParamByName('pedidos_status').AsString := FPEDIDOSTATUS; FQry.ParamByName('pedidos_pessoas').AsInteger := FPEDIDOPESSOAS; FQry.ParamByName('PEDIDOS_IDMESA').AsInteger := FPEDIDOS_IDMESA; FQry.ParamByName('PEDIDOS_DATA').AsDateTime := StrToDateTime(FormatDateTime('dd/mm/yyyy', Now)); FQry.ExecSQL; except on E: Exception do raise Exception.Create(' Error no Inserir os Dados na Mesa! '); end; end; procedure TVenda.SetDATAVENDA(const Value: TDateTime); begin FDATAVENDA := Value; end; procedure TVenda.SetDESCRICAOVENDA(const Value: string); begin FDESCRICAOVENDA := Value; end; procedure TVenda.SetFIDMESA(const Value: String); begin FFIDMESA := Value; end; procedure TVenda.SetFIDPRODUTO(const Value: Integer); begin FFIDPRODUTO := Value; end; procedure TVenda.SetFIDVENDA(const Value: Integer); begin FFIDVENDA := Value; end; procedure TVenda.SetFITENS_IDGRUPO(const Value: Integer); begin FFITENS_IDGRUPO := Value; end; procedure TVenda.SetFITENS_MESA(const Value: Integer); begin FFITENS_MESA := Value; end; procedure TVenda.SetFITENS_VENDA_IDCOMPLEMENTO(const Value: Integer); begin FFITENS_VENDA_IDCOMPLEMENTO := Value; end; procedure TVenda.SetFORMAPAGAMENTO(const Value: string); begin FdFORMAPAGAMENTO := Value; end; procedure TVenda.SetFPEDIDOSTATUS(const Value: String); begin FFPEDIDOSTATUS := Value; end; procedure TVenda.SetFQUANTIDADE(const Value: Integer); begin FFQUANTIDADE := Value; end; procedure TVenda.SetIDCAIXA(const Value: Integer); begin FIDCAIXA := Value; end; procedure TVenda.SetIDITENS_COMPLEMENTOS(const Value: Integer); begin FIDITENS_COMPLEMENTOS := Value; end; procedure TVenda.SetIDPEDIDO(const Value: Integer); begin FIDPEDIDO := Value; end; procedure TVenda.SetIDTENS_MESA(const Value: Integer); begin FIDTENS_MESA := Value; end; procedure TVenda.SetITENS_IDCOMPLEMENTOS(const Value: Integer); begin FITENS_IDCOMPLEMENTOS := Value; end; procedure TVenda.SetITENS_IDPEDIDOS(const Value: Integer); begin FITENS_IDPEDIDOS := Value; end; procedure TVenda.SetITENS_VENDA_OBSERVACAO(const Value: String); begin FITENS_VENDA_OBSERVACAO := Value; end; procedure TVenda.SetPEDIDOPESSOAS(const Value: Integer); begin FPEDIDOPESSOAS := Value; end; procedure TVenda.SetPEDIDOSTATUS(const Value: string); begin FPEDIDOSTATUS := Value; end; procedure TVenda.SetPEDIDOS_IDMESA(const Value: Integer); begin FPEDIDOS_IDMESA := Value; end; procedure TVenda.SetVALORVENDA(const Value: Double); begin FVALORVENDA := Value; end; procedure TVenda.SetVENDA_IDTIPOCOBRANCA(const Value: string); begin FVENDA_IDTIPOCOBRANCA := Value; end; procedure Tvenda.Venda; var idvenda :Integer; valorvenda : Double; begin try idvenda := 0; valorvenda := 0.00; FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('select gen_id(gen_caixa_id, 0) from rdb$database'); FQry.Active := True; FIDCAIXA := FQry.Fields[0].AsInteger; if(FPEDIDOSTATUS = 'EM CONSUMO')then begin FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('SELECT * FROM VENDAS'); FQry.SQL.Add('LEFT JOIN ITENS_VENDA ON VENDAS.idvendas = itens_venda.vendas_idvendas'); FQry.SQL.Add('LEFT JOIN PEDIDOS ON itens_venda.itens_idpedido = PEDIDOS.idpedidos'); FQry.SQL.Add('WHERE itens_venda.itens_venda_idmesa =:idmesa'); FQry.SQL.Add('AND PEDIDOS.pedidos_status =:status'); FQry.ParamByName('idmesa').AsString := FIDMESA; FQry.ParamByName('status').AsString := 'ABERTO'; FQry.Active := True; if(FQry.RecordCount > 0) then begin valorvenda := FQry.FieldByName('VENDAS_VALOR_VENDA').AsFloat; idvenda := FQry.FieldByName('VENDAS_IDVENDAS').AsInteger; FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('UPDATE VENDAS SET VENDAS.VENDAS_VALOR_VENDA =:VALOR'); FQry.SQL.Add('WHERE VENDAS.IDVENDAS =:id'); FQry.ParamByName('id').AsInteger := idvenda; FQry.ParamByName('VALOR').AsFloat := valorvenda + FVALORVENDA; FQry.ExecSQL; if(FIDCAIXA <> 0) then begin FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('INSERT INTO MOVIMENTACOES'); FQry.SQL.Add('( ENTRADA_MOVIMENTACOES , MOVIMENTACOES_IDVENDAS , MOVIMENTACOES_IDCAIXA , DATA_MOVIMENTACOES)'); FQry.SQL.Add('VALUES(:ENTRADA_MOVIMENTACOES , :MOVIMENTACOES_IDVENDAS , :MOVIMENTACOES_IDCAIXA , :DATA_MOVIMENTACOES)'); FQry.ParamByName('MOVIMENTACOES_IDVENDAS').AsInteger := idvenda; FQry.ParamByName('MOVIMENTACOES_IDCAIXA').AsInteger := FIDCAIXA; FQry.ParamByName('ENTRADA_MOVIMENTACOES').AsString := 'E'; FQry.ParamByName('DATA_MOVIMENTACOES').AsDateTime := StrToDateTime(FormatDateTime('DD/MM/YYYY', Now)); FQry.ExecSQL; end else begin // FQry.Close; // FQry.SQL.Clear; // FQry.SQL.Add('select gen_id(gen_caixa_id, 0) from rdb$database'); // FQry.Active := True; // FIDCAIXA := FQry.Fields[0].AsInteger; FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('INSERT INTO MOVIMENTACOES'); FQry.SQL.Add('( ENTRADA_MOVIMENTACOES , MOVIMENTACOES_IDVENDAS , MOVIMENTACOES_IDCAIXA , DATA_MOVIMENTACOES)'); FQry.SQL.Add('VALUES(:ENTRADA_MOVIMENTACOES , :MOVIMENTACOES_IDVENDAS , :MOVIMENTACOES_IDCAIXA , :DATA_MOVIMENTACOES)'); FQry.ParamByName('MOVIMENTACOES_IDVENDAS').AsInteger := idvenda; FQry.ParamByName('MOVIMENTACOES_IDCAIXA').AsInteger := FIDCAIXA; FQry.ParamByName('ENTRADA_MOVIMENTACOES').AsString := 'E'; FQry.ParamByName('DATA_MOVIMENTACOES').AsDateTime := StrToDateTime(FormatDateTime('DD/MM/YYYY', Now)); FQry.ExecSQL; end; end; end else if(FPEDIDOSTATUS = 'OCUPADA')then begin FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('INSERT INTO VENDAS'); FQry.SQL.Add('( VENDAS_VALOR_VENDA , VENDAS_DTVENDAS , VENDAS_DESCRICAO_VENDA , VENDAS_IDFORMA_PAGAMENTO)'); FQry.SQL.Add('VALUES( :VENDAS_VALOR_VENDA , :VENDAS_DTVENDAS , :VENDAS_DESCRICAO_VENDA , :VENDAS_IDFORMA_PAGAMENTO)'); FQry.ParamByName('VENDAS_VALOR_VENDA').AsFloat := FVALORVENDA; FQry.ParamByName('VENDAS_DTVENDAS').AsDateTime := StrToDateTime(FormatDateTime('dd/mm/yyyy', Now)); FQry.ParamByName('VENDAS_DESCRICAO_VENDA').AsString := FDESCRICAOVENDA; FQry.ParamByName('VENDAS_IDFORMA_PAGAMENTO').AsString:= FdFORMAPAGAMENTO; FQry.ExecSQL; FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('select gen_id(GEN_VENDAS_ID, 0) from rdb$database'); FQry.Active := True; FIDVENDA := FQry.Fields[0].AsInteger; FQry.Close; FQry.SQL.Clear; FQry.SQL.Add('INSERT INTO MOVIMENTACOES'); FQry.SQL.Add('( ENTRADA_MOVIMENTACOES , MOVIMENTACOES_IDVENDAS , MOVIMENTACOES_IDCAIXA , DATA_MOVIMENTACOES)'); FQry.SQL.Add('VALUES(:ENTRADA_MOVIMENTACOES , :MOVIMENTACOES_IDVENDAS , :MOVIMENTACOES_IDCAIXA , :DATA_MOVIMENTACOES)'); FQry.ParamByName('MOVIMENTACOES_IDVENDAS').AsInteger := FIDVENDA; FQry.ParamByName('MOVIMENTACOES_IDCAIXA').AsInteger := FIDCAIXA; FQry.ParamByName('ENTRADA_MOVIMENTACOES').AsString := 'E'; FQry.ParamByName('DATA_MOVIMENTACOES').AsDateTime := StrToDateTime(FormatDateTime('DD/MM/YYYY', Now)); FQry.ExecSQL; end; except on E: Exception do raise Exception.Create(' Error no Cadastro de Vendas! '); end; end; end.
unit ufrmSalesReportContrabon; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterBrowse, StdCtrls, ExtCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus, cxButtons, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBExtLookupComboBox, cxTextEdit, cxMaskEdit, cxCalendar, dxBarBuiltInMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData, System.Actions, Vcl.ActnList, ufraFooter4Button, cxLabel, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxPC; type TfrmSalesReportContrabon = class(TfrmMasterBrowse) pnlTop: TPanel; lbl3: TLabel; cbpSuplierCodeFrom: TcxExtLookupComboBox; edtsuplierNameFrom: TEdit; lbl4: TLabel; lbl5: TLabel; cbpSuplierCodeTo: TcxExtLookupComboBox; edtSuplierCodeTo: TEdit; pnlMiddle: TPanel; grp1: TGroupBox; lbl6: TLabel; chkAll: TCheckBox; cbbtipe1: TComboBox; cxgrdSupplier: TcxGrid; grdSupplier: TcxGridDBTableView; grdlvlSupplier: TcxGridLevel; procedure actAddExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure actExportExecute(Sender: TObject); procedure actRefreshExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure cbpSuplierCodeFromKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cbpSuplierCodeToKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cbpSuplierCodeToKeyPress(Sender: TObject; var Key: Char); procedure cbpSuplierCodeFromKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure dtTglFromKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dtTglToKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure strgGridListSuplierRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cbpSuplierCodeFromExit(Sender: TObject); procedure cbpSuplierCodeToExit(Sender: TObject); procedure chkAllClick(Sender: TObject); private function GetSQLDetilContrabonSalesBySupCode(aSupCode: String; aDtAwal: TDateTime; aDtAkhir: TDateTime): string; function GetSQLDetilContrabonSalesBySupCodeList(aSupCOdeFrom: string; aSupCodeTo: string; aDtAwal: TDateTime; aDtAkhir: TDateTime; aHeader : string =''): string; function GetSQLRptContrabonByDateAndSuplier(aSupCOdeFrom: string; aSupCodeTo: string; aDtAwal: TDateTime; aDtAkhir: TDateTime; aHeader : string =''): string; function GetSQLSuplier(aSupCode: String =''): string; procedure ParseComboSuplier(cbplus:TcxExtLookupComboBox; aSql: string); procedure ParseDataSalesContrabon; procedure ParseDataSalesContrabonDetilBySupCode(ACode: string); public procedure LoadDatatipe; end; var frmSalesReportContrabon: TfrmSalesReportContrabon; implementation uses uTSCommonDlg, uConstanta, uDMReport, uAppUtils; {$R *.dfm} const {No Suplier Code Suplier Name Gross Sales Disc. Amount Tax Amount Net Sales Total Sales } _kolNo : Integer = 0; _kolSupCode : Integer = 1; _kolSupNm : Integer = 2; _kolAmount : Integer = 3; _kolDisc : Integer = 4; _kolTax : Integer = 5; _kolNet : Integer = 6; _kolTot : Integer = 7; { No Product Code Product Name UOM Qty Unit Price Gross Sales Disc. Amount Tax Amount Net Sales Total sales } _kolDNo : Integer = 0; _kolDPLU : Integer = 1; _kolDPluNm : Integer = 2; _kolDUom : Integer = 3; _kolDQty : Integer = 4; _kolDPrice : Integer = 5; _kolDGross : Integer = 6; _kolDDisc : Integer = 7; _kolDTax : Integer = 8; _kolDNet : Integer = 9; _kolDTot : Integer = 10; procedure TfrmSalesReportContrabon.actAddExecute(Sender: TObject); var sSQL: string; begin inherited; { sSQL := GetSQLRptContrabonByDateAndSuplier(cbpSuplierCodeFrom.Text, cbpSuplierCodeTo.Text, dtAwalFilter.Date, dtAkhirFilter.Date, GetCompanyHeader(FLoginFullname, MasterNewUnit.Nama, dtTglFrom.Date, dtTglTo.Date)); dmReportNew.EksekusiReport('frCetakRekapSalesContrabon', sSQL, '', True); } end; procedure TfrmSalesReportContrabon.actEditExecute(Sender: TObject); var sSQL: string; begin inherited; {sSQL := GetSQLDetilContrabonSalesBySupCodeList(cbpSuplierCodeFrom.Text, cbpSuplierCodeTo.Text, dtAwalFilter.Date, dtAkhirFilter.Date, GetCompanyHeader(FLoginFullname, MasterNewUnit.Nama, dtTglFrom.Date, dtTglTo.Date)); dmReportNew.EksekusiReport('frCetakSalesContrabon', sSQL, '', True); } end; procedure TfrmSalesReportContrabon.actExportExecute(Sender: TObject); var aLlow: Boolean; i: Integer; FSaveDlg : TSaveDialog; begin inherited; FSaveDlg := TSaveDialog.Create(Self); FSaveDlg.Filter := 'File Excel|*.XLS'; FSaveDlg.DefaultExt := 'XLS'; { self.Enabled := False; try if FSaveDlg.Execute then begin cShowWaitWindow(); try SaveXLS(strgGridListSuplier, FSaveDlg.FileName, ''); for i := strgGridListSuplier.FixedRows to strgGridListSuplier.RowCount - 1 do begin cShowWaitWindow('Export kode suplier '+ strgGridListSuplier.Cells[_kolSupCode, i]); strgGridListSuplierRowChanging(nil,i, i, aLlow); SaveXLS(strgGrid, FSaveDlg.FileName, strgGridListSuplier.Cells[_kolSupCode, i]); end; finally cCloseWaitWindow; end; CommonDlg.ShowMessage('Sukses simpan Excel!!'); end; Finally FSaveDlg.Free; Self.Enabled := True; end; } end; procedure TfrmSalesReportContrabon.actRefreshExecute(Sender: TObject); begin inherited; if (dtAwalFilter.Text <> ' / / ') and (dtAkhirFilter.Text <> ' / / ') and (cbpSuplierCodeFrom.Text <> '') and (cbpSuplierCodeTo.Text <> '') then begin ParseDataSalesContrabon; actAdd.Enabled := True; actEdit.Enabled := True; // ParseDataSalesContrabonDetilBySupCode(strgGridListSuplier.Cells[_kolSupCode, 1]); end else CommonDlg.ShowError('Date From, Date To, Suplier From, and Suplier To ' + ER_EMPTY); end; procedure TfrmSalesReportContrabon.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; procedure TfrmSalesReportContrabon.FormDestroy(Sender: TObject); begin inherited; frmSalesReportContrabon := nil; frmSalesReportContrabon.Free; end; procedure TfrmSalesReportContrabon.cbpSuplierCodeFromKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; { if (StrLength(cbpSuplierCodeFrom.Value) = 1) then ParseComboSuplier(cbpSuplierCodeFrom, GetSQLSuplier(cbpSuplierCodeFrom.Text)); if (Key = VK_RETURN) then begin edtsuplierNameFrom.Text := cbpSuplierCodeFrom.Cells[2, cbpSuplierCodeFrom.Row]; cbpSuplierCodeTo.SetFocus; end; } end; procedure TfrmSalesReportContrabon.cbpSuplierCodeToKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; {if (StrLength(cbpSuplierCodeTo.Value) = 1) then ParseComboSuplier(cbpSuplierCodeTo, GetSQLSuplier(cbpSuplierCodeTo.Text)); if (Key = VK_RETURN) then begin edtSuplierCodeTo.Text := cbpSuplierCodeTo.Cells[2, cbpSuplierCodeTo.Row]; btnView.SetFocus; end; } end; procedure TfrmSalesReportContrabon.cbpSuplierCodeToKeyPress( Sender: TObject; var Key: Char); begin inherited; Key := UpCase(Key); end; procedure TfrmSalesReportContrabon.cbpSuplierCodeFromKeyPress( Sender: TObject; var Key: Char); begin inherited; Key := UpCase(Key); end; procedure TfrmSalesReportContrabon.FormShow(Sender: TObject); begin inherited; dtAwalFilter.SetFocus; ParseComboSuplier(cbpSuplierCodeFrom, GetSQLSuplier(cbpSuplierCodeFrom.Text)); ParseComboSuplier(cbpSuplierCodeTo, GetSQLSuplier(cbpSuplierCodeTo.Text)); LoadDatatipe; end; procedure TfrmSalesReportContrabon.dtTglFromKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Key = VK_RETURN) then dtAkhirFilter.SetFocus; end; procedure TfrmSalesReportContrabon.dtTglToKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Key = VK_RETURN) then cbpSuplierCodeFrom.SetFocus; end; procedure TfrmSalesReportContrabon.ParseDataSalesContrabon; var j: Integer; i: Integer; begin { with strgGridListSuplier do begin with cOpenQuery(GetSQLRptContrabonByDateAndSuplier(cbpSuplierCodeFrom.Text, cbpSuplierCodeTo.Text, dtTglFrom.Date, dtTglTo.Date)) do begin try i := FixedRows; if not IsEmpty then begin Last; RowCount := RecordCount + FixedRows; First; j := 1; while not Eof do begin Cells[_kolNo, i] := IntToStr(j); Cells[_kolSupCode, i] := FieldByName('SUP_CODE').AsString; Cells[_kolSupNm, i] := FieldByName('SUP_NAME').AsString; Cells[_kolAmount, i] := FieldByName('AMOUNT').AsString; Cells[_kolDisc, i] := FieldByName('AMOUNT_DISC').AsString; Cells[_kolTax, i] := FieldByName('TAX_AMOUNT').AsString; Cells[_kolNet, i] := FieldByName('NET_SALES').AsString; Cells[_kolTot, i] := FieldByName('TOTAL_SALES').AsString; Inc(i); Inc(j); Next; end; end else begin RowCount := 2; Cells[_kolNo, i] := ''; Cells[_kolSupCode, i] := ''; Cells[_kolSupNm, i] := ''; Cells[_kolAmount, i] := ''; Cells[_kolDisc, i] := ''; Cells[_kolTax, i] := ''; Cells[_kolNet, i] := ''; Cells[_kolTot, i] := ''; end; AutoSize := True; FixedRows := 1; finally Free; end end; end; } end; procedure TfrmSalesReportContrabon.ParseDataSalesContrabonDetilBySupCode( ACode: string); var j: Integer; i: Integer; begin { with strgGrid do begin with cOpenQuery(GetSQLDetilContrabonSalesBySupCode(ACode, dtTglFrom.Date, dtTglTo.Date)) do begin try i := FixedRows; if not IsEmpty then begin Last; RowCount := RecordCount + FixedRows; First; j := 1; while not Eof do begin Cells[_kolDNo, i] := IntToStr(j); Cells[_kolDPLU, i] := FieldByName('BRG_CODE').AsString; Cells[_kolDPluNm, i] := FieldByName('BRG_ALIAS').AsString; Cells[_kolDUom, i] := FieldByName('UOM').AsString; Cells[_kolDQty, i] := FieldByName('QTY').AsString; Cells[_kolDPrice, i] := FieldByName('UNIT_PRICE').AsString; Cells[_kolDGross, i] := FieldByName('GROSS_SALES').AsString; Cells[_kolDDisc, i] := FieldByName('AMOUNT_DISC').AsString; Cells[_kolDTax, i] := FieldByName('TAX_AMOUNT').AsString; Cells[_kolDNet, i] := FieldByName('NET_SALES').AsString; Cells[_kolDTot, i] := FieldByName('TOTAL_SALES').AsString; Inc(i); Inc(j); Next; end; end else begin RowCount := 2; Cells[_kolDNo, i] := ''; Cells[_kolDPLU, i] := ''; Cells[_kolDPluNm, i] := ''; Cells[_kolDUom, i] := ''; Cells[_kolDQty, i] := ''; Cells[_kolDPrice, i] := ''; Cells[_kolDGross, i] := ''; Cells[_kolDDisc, i] := ''; Cells[_kolDTax, i] := ''; Cells[_kolDNet, i] := ''; Cells[_kolDTot, i] := ''; end; finally Free; end; end; AutoSize := True; FixedRows := 1; end; } end; procedure TfrmSalesReportContrabon.strgGridListSuplierRowChanging( Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); begin inherited; // ParseDataSalesContrabonDetilBySupCode(strgGridListSuplier.Cells[_kolSupCode, NewRow]); end; procedure TfrmSalesReportContrabon.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin // inherited; if(Key = Ord('D')) and (ssctrl in Shift) then //dulunya blm ada shortcut actEditExecute(sender) else if(Key = Ord('S')) and (ssctrl in Shift) then //dulunya blm ada shortcut actAddExecute(sender) else if(Key = Ord('C')) and (ssctrl in Shift) then //dulunya blm ada shortcut actEditExecute(sender); end; function TfrmSalesReportContrabon.GetSQLDetilContrabonSalesBySupCode(aSupCode: String; aDtAwal: TDateTime; aDtAkhir: TDateTime): string; var cfilter2:string; begin cfilter2:=''; if chkAll.Checked= False then begin if cbbtipe1.ItemIndex = 0 then cfilter2:=' and TRANSD.TRANSD_TPBRG_ID = 2' else if cbbtipe1.ItemIndex= 1 then cfilter2:=' and TRANSD.TRANSD_TPBRG_ID = 3'; end else cfilter2:=' and TRANSD.TRANSD_TPBRG_ID in (2,3)'; Result := 'SELECT BRG.BRG_CODE, BRG.BRG_NAME,BRG.BRG_ALIAS, BHJ.BHJ_SAT_CODE AS UOM,' + ' TRANSD.TRANSD_QTY AS QTY, TRANSD.TRANSD_SELL_PRICE AS UNIT_PRICE,' + ' SUM((TRANSD.TRANSD_QTY * TRANSD.TRANSD_SELL_PRICE)) AS GROSS_SALES,' + ' SUM(DIF(TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,0)) AS AMOUNT_DISC,' // + ' SUM(((TRANSD.TRANSD_QTY * TRANSD.TRANSD_SELL_PRICE) * 0.1)) AS TAX_AMOUNT, ' + ' SUM((PJK.PJK_PPN * TRANSD.TRANSD_QTY * TRANSD.TRANSD_SELL_PRICE_DISC) / 100) AS TAX_AMOUNT,' + ' SUM(((TRANSD.TRANSD_QTY * TRANSD.TRANSD_SELL_PRICE) - ' + ' DIF(TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,0))) AS NET_SALES, ' + ' SUM((((TRANSD.TRANSD_QTY * TRANSD.TRANSD_SELL_PRICE) * 0.1) + ' + ' ((TRANSD.TRANSD_QTY * TRANSD.TRANSD_SELL_PRICE) - ' + ' DIF(TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,0)))) AS TOTAL_SALES ' + ' FROM TRANSAKSI_DETIL TRANSD ' + ' LEFT JOIN BARANG_HARGA_JUAL BHJ ON BHJ.BHJ_ID = TRANSD.TRANSD_BHJ_ID ' + ' AND BHJ.BHJ_UNT_ID = TRANSD.TRANSD_BHJ_UNT_ID AND BHJ.BHJ_BRG_CODE = TRANSD.TRANSD_BRG_CODE ' + ' LEFT JOIN BARANG BRG ON BRG.BRG_CODE = BHJ.BHJ_BRG_CODE ' + ' LEFT JOIN BARANG_SUPLIER BRGSUP ON BRGSUP.BRGSUP_BRG_CODE = BRG.BRG_CODE ' + ' LEFT JOIN SUPLIER SUP ON SUP.SUP_CODE = BRGSUP.BRGSUP_SUP_CODE ' + ' LEFT JOIN REF$PAJAK PJK ON PJK.PJK_ID = BRG.BRG_PJK_ID' + ' LEFT JOIN TRANSAKSI TRANS ON TRANS.TRANS_NO = TRANSD.TRANSD_TRANS_NO ' + ' AND TRANS.TRANS_UNT_ID = TRANSD.TRANSD_TRANS_UNT_ID ' + ' WHERE SUP.SUP_CODE = '+ QuotedStr(aSupCode) + ' AND TRANSD.TRANSD_UNT_ID = '+ IntToStr(MasterNewUnit) + cfilter2 + ' AND TRANS.TRANS_DATE >= '+ TAppUtils.QuotD(aDtAwal) + ' AND TRANS.TRANS_DATE <= '+ TAppUtils.QuotD(aDtAkhir, True) + ' GROUP BY BRG.BRG_CODE, BRG.BRG_NAME,BRG.BRG_ALIAS, BHJ.BHJ_SAT_CODE, ' + ' TRANSD.TRANSD_QTY, TRANSD.TRANSD_SELL_PRICE '; end; function TfrmSalesReportContrabon.GetSQLDetilContrabonSalesBySupCodeList( aSupCOdeFrom: string; aSupCodeTo: string; aDtAwal: TDateTime; aDtAkhir: TDateTime; aHeader : string =''): string; var cfilter2:string; begin cfilter2:=''; if chkAll.Checked= False then begin if cbbtipe1.ItemIndex = 0 then cfilter2:=' and TRANSD.TRANSD_TPBRG_ID = 2' else if cbbtipe1.ItemIndex= 1 then cfilter2:=' and TRANSD.TRANSD_TPBRG_ID = 3'; end else cfilter2:=' and TRANSD.TRANSD_TPBRG_ID in (2,3)'; Result := 'SELECT ' + aHeader + ' SUP.SUP_CODE, SUP.SUP_NAME, BRG.BRG_CODE, BRG.BRG_ALIAS AS BRG_NAME, BHJ.BHJ_SAT_CODE AS UOM,' + ' SUM(TRANSD.TRANSD_QTY) AS QTY, TRANSD.TRANSD_SELL_PRICE AS UNIT_PRICE,' + ' SUM(TRANSD.TRANSD_TOTAL) AS GROSS_SALES,' // + ' SUM(TRANSD.TRANSD_TOTAL * DIF(TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE, TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE, 0)) AS AMOUNT_DISC,' + ' SUM(DIF(TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,0)) AS AMOUNT_DISC,' // + ' SUM((PJK.PJK_PPN * TRANSD.TRANSD_TOTAL) / 100) AS TAX_AMOUNT,' + ' SUM((PJK.PJK_PPN * TRANSD.TRANSD_QTY * TRANSD.TRANSD_SELL_PRICE_DISC) / 100) AS TAX_AMOUNT,' // + ' (SUM(TRANSD.TRANSD_TOTAL) - SUM(DIF(TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE, TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE, 0))) AS NET_SALES,' + ' SUM(((TRANSD.TRANSD_QTY * TRANSD.TRANSD_SELL_PRICE) - DIF(TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,0))) AS NET_SALES,' // + ' (SUM((DIF(PJK.PJK_PPN, PJK.PJK_PPN, 0) * TRANSD.TRANSD_TOTAL) / 100) +' // + ' (SUM(TRANSD.TRANSD_TOTAL) - SUM(DIF(TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE, TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE, 0)))) AS TOTAL_SALES,' + ' SUM((((TRANSD.TRANSD_QTY * TRANSD.TRANSD_SELL_PRICE) * PJK.PJK_PPN /100) + ((TRANSD.TRANSD_QTY * TRANSD.TRANSD_SELL_PRICE) - DIF(TRANSD.TRANSD_SELL_PRICE_DISC -' + ' TRANSD.TRANSD_SELL_PRICE,TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,0)))) AS TOTAL_SALES,' + ' ((SUM(TRANSD.TRANSD_TOTAL) - SUM(DIF(TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE, TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE, 0))) / ' + ' (SUM((DIF(PJK.PJK_PPN, PJK.PJK_PPN, 0) * TRANSD.TRANSD_TOTAL) / 100) + ' + ' (SUM(TRANSD.TRANSD_TOTAL) - SUM(DIF(TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE, TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE, 0))))) AS PERSENTASE ' + ' FROM TRANSAKSI_DETIL TRANSD ' + ' LEFT JOIN BARANG_HARGA_JUAL BHJ ON BHJ.BHJ_ID = TRANSD.TRANSD_BHJ_ID ' + ' AND BHJ.BHJ_ID = TRANSD.TRANSD_BHJ_ID ' + ' LEFT JOIN BARANG BRG ON BRG.BRG_CODE = BHJ.BHJ_BRG_CODE ' + ' LEFT JOIN BARANG_SUPLIER BRGSUP ON BRGSUP.BRGSUP_BRG_CODE = BRG.BRG_CODE ' + ' LEFT JOIN SUPLIER SUP ON SUP.SUP_CODE = BRGSUP.BRGSUP_SUP_CODE ' + ' LEFT JOIN REF$PAJAK PJK ON PJK.PJK_ID = BRG.BRG_PJK_ID ' + ' LEFT JOIN TRANSAKSI TRANS ON TRANS.TRANS_NO = TRANSD.TRANSD_TRANS_NO ' + ' AND TRANS.TRANS_UNT_ID = TRANSD.TRANSD_TRANS_UNT_ID ' + ' WHERE SUP.SUP_CODE >= '+ QuotedStr(aSupCOdeFrom) + ' AND SUP.SUP_CODE <= '+ QuotedStr(aSupCodeTo) + ' AND TRANS.TRANS_DATE >= '+ TAppUtils.QuotD(aDtAwal) + ' AND TRANS.TRANS_DATE <= '+ TAppUtils.QuotD(aDtAkhir, True) + ' AND TRANSD.TRANSD_UNT_ID = '+ IntToStr(MasterNewUnit) + cfilter2 + ' GROUP BY SUP.SUP_CODE, SUP.SUP_NAME, BRG.BRG_CODE, BRG.BRG_ALIAS,' + ' BHJ.BHJ_SAT_CODE, TRANSD.TRANSD_SELL_PRICE ' + ' ORDER BY SUP.SUP_CODE ' end; function TfrmSalesReportContrabon.GetSQLRptContrabonByDateAndSuplier( aSupCOdeFrom: string; aSupCodeTo: string; aDtAwal: TDateTime; aDtAkhir: TDateTime; aHeader : string =''): string; var sSQL: string; cfilter:string; begin cfilter:=''; if chkAll.Checked= False then begin if cbbtipe1.ItemIndex = 0 then cfilter:=' and TRANSD.TRANSD_TPBRG_ID = 2' else if cbbtipe1.ItemIndex= 1 then cfilter:=' and TRANSD.TRANSD_TPBRG_ID = 3'; end else cfilter:=' and TRANSD.TRANSD_TPBRG_ID in (2,3)'; sSQL := 'SELECT '+ aHeader + ' SUP.SUP_CODE, SUP.SUP_NAME, SUM(TRANSD.TRANSD_TOTAL) AS AMOUNT,' + ' SUM(DIF(TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,0)) AS AMOUNT_DISC,' + ' SUM((DIF(PJK.PJK_PPN, PJK.PJK_PPN, 0) * TRANSD.TRANSD_TOTAL) / 100) AS TAX_AMOUNT,' + ' (SUM(TRANSD.TRANSD_TOTAL) - SUM(DIF(TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,0))) AS NET_SALES,' + ' (SUM((DIF(PJK.PJK_PPN, PJK.PJK_PPN, 0) * TRANSD.TRANSD_TOTAL) / 100) +' + ' (SUM(TRANSD.TRANSD_TOTAL) - SUM(DIF(TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,0)))) AS TOTAL_SALES,' + ' ((SUM(TRANSD.TRANSD_TOTAL) - SUM(DIF(TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,0))) /' + ' (SUM((DIF(PJK.PJK_PPN, PJK.PJK_PPN, 0) * TRANSD.TRANSD_TOTAL) / 100) +' + ' (SUM(TRANSD.TRANSD_TOTAL) - SUM(DIF(TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,TRANSD.TRANSD_SELL_PRICE_DISC - TRANSD.TRANSD_SELL_PRICE,0))))) AS PERSENTASE' + ' FROM TRANSAKSI_DETIL TRANSD ' + ' LEFT JOIN BARANG_HARGA_JUAL BHJ ON BHJ.BHJ_ID = TRANSD.TRANSD_BHJ_ID ' + ' AND BHJ.BHJ_UNT_ID = TRANSD.TRANSD_BHJ_UNT_ID ' + ' LEFT JOIN BARANG BRG ON BRG.BRG_CODE = BHJ.BHJ_BRG_CODE ' + ' LEFT JOIN BARANG_SUPLIER BRGSUP ON BRGSUP.BRGSUP_BRG_CODE = BRG.BRG_CODE ' + ' LEFT JOIN SUPLIER SUP ON SUP.SUP_CODE = BRGSUP.BRGSUP_SUP_CODE ' + ' LEFT JOIN REF$PAJAK PJK ON PJK.PJK_ID = BRG.BRG_PJK_ID ' + ' LEFT JOIN TRANSAKSI TRANS ON TRANS.TRANS_NO = TRANSD.TRANSD_TRANS_NO ' + ' AND TRANS.TRANS_UNT_ID = TRANSD.TRANSD_TRANS_UNT_ID ' + ' WHERE ' + ' SUP.SUP_CODE >= '+ QuotedStr(aSupCOdeFrom) + ' AND SUP.SUP_CODE <= '+ QuotedStr(aSupCodeTo) + cfilter + ' AND TRANS.TRANS_DATE >= '+ TAppUtils.QuotD(aDtAwal) + ' AND TRANS.TRANS_DATE <= '+ TAppUtils.QuotD(aDtAkhir, True) + ' AND TRANSD.TRANSD_UNT_ID = '+ IntToStr(MasterNewUnit) + ' GROUP BY SUP.SUP_CODE, SUP.SUP_NAME '; Result := sSQL; end; function TfrmSalesReportContrabon.GetSQLSuplier(aSupCode: String =''): string; begin aSupCode := trim(aSupCode); if aSupCode = '' then aSupCode := 'A%' else aSupCode := aSupCode + '%'; Result := 'SELECT SUP_CODE, SUP_NAME FROM SUPLIER' + ' WHERE SUP_CODE LIKE '+ QuotedStr(aSupCode); end; procedure TfrmSalesReportContrabon.cbpSuplierCodeFromExit(Sender: TObject); begin inherited; // edtsuplierNameFrom.Text := cbpSuplierCodeFrom.Cells[2, cbpSuplierCodeFrom.Row]; cbpSuplierCodeTo.SetFocus; end; procedure TfrmSalesReportContrabon.cbpSuplierCodeToExit(Sender: TObject); begin inherited; // edtSuplierCodeTo.Text := cbpSuplierCodeTo.Cells[2, cbpSuplierCodeTo.Row]; btnSearch.SetFocus; end; procedure TfrmSalesReportContrabon.ParseComboSuplier(cbplus:TcxExtLookupComboBox; aSql: string); var i: Integer; begin { with cbplus do begin ClearGridData; with cOpenQuery(aSql) do begin try if not IsEmpty then begin Last; RowCount := RecordCount + 1; First; AddRow(['Id', 'Suplier Code', 'Suplier Name']); i := 1; while not Eof do begin AddRow([IntToStr(i), FieldByName('SUP_CODE').AsString, FieldByName('SUP_NAME').AsString]); Inc(i); Next; end; end else begin RowCount := 2; AddRow(['Id', 'Suplier Code', 'Suplier Name']); AddRow(['1', ' ', ' ']); end; finally Free; end; end; FixedRows := 1; SizeGridToData; Text := Value; end; } end; procedure TfrmSalesReportContrabon.chkAllClick(Sender: TObject); begin inherited; if chkAll.Checked= True then begin cbbTipe1.Text:='All'; cbbTipe1.Enabled:=False; end else cbbTipe1.Enabled:=True; end; procedure TfrmSalesReportContrabon.LoadDatatipe; var sSQL: string; begin sSQL := 'select tpbrg_id,tpbrg_name from ref$tipe_BARANG where tpbrg_id in (2,3)'; // cQueryToComboObject(cbbtipe1, sSQL); end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [PESSOA] The MIT License Copyright: Copyright (C) 2010 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (t2ti.com@gmail.com) @version 1.0 *******************************************************************************} unit PessoaVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL, PessoaFisicaVO, PessoaJuridicaVO, PessoaEnderecoVO, PessoaContatoVO, PessoaTelefoneVO; type TPessoaVO = class(TVO) private FID: Integer; FNOME: String; FTIPO: String; FEMAIL: String; FSITE: String; FCLIENTE: String; FFORNECEDOR: String; FCOLABORADOR: String; FTRANSPORTADORA: String; FListaPessoaContatoVO: TListaPessoaContatoVO; FListaPessoaEnderecoVO: TListaPessoaEnderecoVO; FListaPessoaTelefoneVO: TListaPessoaTelefoneVO; FPessoaFisicaVO: TPessoaFisicaVO; FPessoaJuridicaVO: TPessoaJuridicaVO; published constructor Create; override; destructor Destroy; override; property Id: Integer read FID write FID; property Nome: String read FNOME write FNOME; property Tipo: String read FTIPO write FTIPO; property Email: String read FEMAIL write FEMAIL; property Site: String read FSITE write FSITE; property Cliente: String read FCLIENTE write FCLIENTE; property Fornecedor: String read FFORNECEDOR write FFORNECEDOR; property Colaborador: String read FCOLABORADOR write FCOLABORADOR; property Transportadora: String read FTRANSPORTADORA write FTRANSPORTADORA; property PessoaFisicaVO: TPessoaFisicaVO read FPessoaFisicaVO write FPessoaFisicaVO; property PessoaJuridicaVO: TPessoaJuridicaVO read FPessoaJuridicaVO write FPessoaJuridicaVO; property ListaPessoaContatoVO: TListaPessoaContatoVO read FListaPessoaContatoVO write FListaPessoaContatoVO; property ListaPessoaEnderecoVO: TListaPessoaEnderecoVO read FListaPessoaEnderecoVO write FListaPessoaEnderecoVO; property ListaPessoaTelefoneVO: TListaPessoaTelefoneVO read FListaPessoaTelefoneVO write FListaPessoaTelefoneVO; end; TListaPessoaVO = specialize TFPGObjectList<TPessoaVO>; implementation { TPessoaVO } constructor TPessoaVO.Create; begin inherited; FPessoaFisicaVO := TPessoaFisicaVO.Create; FPessoaJuridicaVO := TPessoaJuridicaVO.Create; FListaPessoaContatoVO := TListaPessoaContatoVO.Create; FListaPessoaEnderecoVO := TListaPessoaEnderecoVO.Create; FListaPessoaTelefoneVO := TListaPessoaTelefoneVO.Create; end; destructor TPessoaVO.Destroy; begin FreeAndNil(FListaPessoaContatoVO); FreeAndNil(FListaPessoaEnderecoVO); FreeAndNil(FListaPessoaTelefoneVO); FreeAndNil(FPessoaFisicaVO); FreeAndNil(FPessoaJuridicaVO); inherited; end; initialization Classes.RegisterClass(TPessoaVO); finalization Classes.UnRegisterClass(TPessoaVO); end.
unit uNoCardVipFind_Frm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uBaseEditFrm, cxGraphics, Menus, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, StdCtrls, cxButtons, cxDropDownEdit, cxContainer, cxTextEdit, cxMaskEdit, cxCalendar, ExtCtrls, DBClient, ActnList; type TNoVipListFrm = class(TSTBaseEdit) pnTop: TPanel; Image1: TImage; lbBegin: TLabel; btOK: TcxButton; cxGrid1: TcxGrid; dbgList: TcxGridDBTableView; cxGrid1Level1: TcxGridLevel; cxStyle: TcxTextEdit; cdsList: TClientDataSet; dsList: TDataSource; PopupMenu1: TPopupMenu; actEditCard: TActionList; actEditCard1: TAction; N1: TMenuItem; procedure dbgListDblClick(Sender: TObject); procedure btOKClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure actEditCard1Execute(Sender: TObject); private { Private declarations } procedure CreateGridColumn(tcdsList : TClientDataSet; cxDetail: TcxGridDBTableView); public { Public declarations } CardFID : string; VipBaseDateSet : TClientDataSet; VipCardDateSet : TClientDataSet; end; var NoVipListFrm: TNoVipListFrm; function FindVipFrm(VipDateSet,cds_Vipcard : TClientDataSet; CardFID : string) : Boolean; //查找未发卡会员 implementation uses FrmCliDM,Pub_Fun; {$R *.dfm} function FindVipFrm(VipDateSet,cds_Vipcard : TClientDataSet; CardFID : string) : Boolean; //查找未发卡会员 begin if NoVipListFrm <> nil then begin NoVipListFrm.Show; NoVipListFrm.SetFocus; NoVipListFrm.VipBaseDateSet := VipDateSet; //aadedby owen2012-07-30 NoVipListFrm.VipCardDateSet := cds_Vipcard; Exit; end; Application.CreateForm(TNoVipListFrm,NoVipListFrm); NoVipListFrm.CardFID := CardFID; NoVipListFrm.VipBaseDateSet := VipDateSet; NoVipListFrm.VipCardDateSet := cds_Vipcard; NoVipListFrm.Show; NoVipListFrm.SetFocus; end; procedure TNoVipListFrm.CreateGridColumn( tcdsList: TClientDataSet; cxDetail: TcxGridDBTableView); var i:Integer; FieldName : string; GridColumn : TcxGridDBColumn; begin //设置列 try cxDetail.BeginUpdate; cxDetail.ClearItems; for i :=0 to tcdsList.FieldCount-1 do begin FieldName := tcdsList.Fields[i].FieldName; if UpperCase(FieldName) = UpperCase('FID') then Continue; //FID隐藏 GridColumn := cxDetail.CreateColumn; with GridColumn do begin Caption := FieldName; Name := 'TNoVipListFrm'+ IntToStr(i); DataBinding.FieldName := FieldName; Width := 100; //列宽 Options.Sorting := True; //排序 Options.Filtering := True; //过滤 Options.Focusing := True; //鼠标停留 Options.Editing := False; //是否可以编辑 end; end; finally cxDetail.EndUpdate; end; end; procedure TNoVipListFrm.dbgListDblClick(Sender: TObject); begin inherited; actEditCard1.Execute; end; procedure TNoVipListFrm.btOKClick(Sender: TObject); var ErrMsg,FieldName: string; i : Integer; begin inherited; try btOK.Enabled := False; CliDM.Get_OpenBaseList('NoCardVIPBaseData',Trim(cxStyle.Text),'',cdsList,ErrMsg); if dbgList.ColumnCount=0 then CreateGridColumn(cdsList,dbgList); for i := 0 to dbgList.ColumnCount -1 do dbgList.Columns[i].Visible := False; dbgList.GetColumnByFieldName('FNAME_L2').Visible := True; dbgList.GetColumnByFieldName('FNAME_L2').Caption := '姓名'; dbgList.GetColumnByFieldName('FNAME_L2').Index:=0; dbgList.GetColumnByFieldName('FNumber').Visible := True; dbgList.GetColumnByFieldName('FNumber').Caption := '会员编号'; dbgList.GetColumnByFieldName('FNumber').Index:=1; dbgList.GetColumnByFieldName('FMOBILEPHONNO').Visible := True; dbgList.GetColumnByFieldName('FMOBILEPHONNO').Caption := '手机号码'; dbgList.GetColumnByFieldName('FMOBILEPHONNO').Index:=2; dbgList.GetColumnByFieldName('FBIRTHDAY').Visible := True; dbgList.GetColumnByFieldName('FBIRTHDAY').Caption := '出生日期'; dbgList.GetColumnByFieldName('FTELEPHONENO').Visible := True; dbgList.GetColumnByFieldName('FTELEPHONENO').Caption := '固定电话'; dbgList.GetColumnByFieldName('FLiveAddress').Visible := True; dbgList.GetColumnByFieldName('FLiveAddress').Caption := '居住地址'; dbgList.GetColumnByFieldName('FEMAIL').Visible := True; dbgList.GetColumnByFieldName('FEMAIL').Caption := '邮箱'; dbgList.GetColumnByFieldName('FPostalcode').Visible := True; dbgList.GetColumnByFieldName('FPostalcode').Caption := '居住地邮编'; dbgList.GetColumnByFieldName('FWORKZIPCODE').Visible := True; dbgList.GetColumnByFieldName('FWORKZIPCODE').Caption := '工作地邮编'; dbgList.GetColumnByFieldName('FRemark').Visible := True; dbgList.GetColumnByFieldName('FRemark').Caption := '备注'; finally btOK.Enabled := True; end; end; procedure TNoVipListFrm.FormCreate(Sender: TObject); begin inherited; LoadImage(UserInfo.ExePath+'\Img\POS_Edit_Top2.jpg',Image1); end; procedure TNoVipListFrm.actEditCard1Execute(Sender: TObject); var i : integer; FieldName,VipBaseFID,strsql,ErrMsg : string; begin inherited; if not cdsList.Active then Exit; if cdsList.IsEmpty then Exit; /////这种写法不会产生重复记录owen2013-01-18 VipBaseDateSet.Close; strsql := 'select * from T_RT_VIPBaseData where FID='+quotedstr(cdsList.fieldByName('FID').AsString); CliDM.Get_OpenSQL(CliDM.cdstemp,strsql,ErrMsg); VipBaseDateSet.Data := CliDM.cdstemp.Data; CliDM.cdstemp.Close; ////之前的写法会产生重复数据owen 2013-01-18 {if not(VipBaseDateSet.State in DB.dsEditModes) then VipBaseDateSet.Edit; with VipBaseDateSet do begin VipBaseDateSet.Close; VipBaseDateSet.CreateDataSet; VipBaseDateSet.Append; FieldByName('FID').AsString := cdsList.fieldByName('FID').Value; FieldByName('FNUMBER').Value := cdsList.fieldByName('FNUMBER').Value; FieldByName('FNAME_L2').Value := cdsList.fieldByName('FNAME_L2').Value; FieldByName('FMOBILEPHONNO').Value := trim(cdsList.fieldByName('FMOBILEPHONNO').Value); FieldByName('FBIRTHDAY').Value := cdsList.fieldByName('FBIRTHDAY').Value; FieldByName('FGender').Value := cdsList.fieldByName('FGender').Value; FieldByName('FCERTTYPE').Value := cdsList.fieldByName('FCERTTYPE').Value; FieldByName('FIDCARD').Value := cdsList.fieldByName('FIDCARD').Value; FieldByName('FTELEPHONENO').Value := cdsList.fieldByName('FTELEPHONENO').Value; FieldByName('FQQNUMBER').Value := cdsList.fieldByName('FQQNUMBER').Value; FieldByName('FEMAIL').Value := cdsList.fieldByName('FEMAIL').Value; FieldByName('FFAMILYCOUNT').Value := cdsList.fieldByName('FFAMILYCOUNT').Value; FieldByName('FRemark').Value := cdsList.fieldByName('FRemark').Value; FieldByName('FWORKUNIT').Value := cdsList.fieldByName('FWORKUNIT').Value; FieldByName('FWORKZIPCODE').Value := cdsList.fieldByName('FWORKZIPCODE').Value; FieldByName('FLiveAddress').Value := cdsList.fieldByName('FLiveAddress').Value; FieldByName('FPostalcode').Value := cdsList.fieldByName('FPostalcode').Value; FieldByName('CFRelName').Value := cdsList.fieldByName('CFRelName').Value; FieldByName('CFRelBirth').Value := cdsList.fieldByName('CFRelBirth').Value; FieldByName('CFRelGender').Value := cdsList.fieldByName('CFRelGender').Value; end; } { for i :=0 to cdsList.FieldCount-1 do begin FieldName := cdsList.Fields[i].FieldName; if FieldName = 'FID' then Break; if VipBaseDateSet.FindField(FieldName)<>nil then begin if not(VipBaseDateSet.State in DB.dsEditModes) then VipBaseDateSet.Edit; VipBaseDateSet.FindField(FieldName).Value := cdsList.Fields[i].Value; end; end; } VipBaseFID := cdsList.fieldbyName('FID').AsString; if not(VipCardDateSet.State in DB.dsEditModes) then VipCardDateSet.Edit; VipCardDateSet.FieldByName('FVIPNUMBER').Value := VipBaseFID; //修改会员卡关联的会员ID Close; end; end.
program dequeappl; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, CustApp, udeque, crt { you can add units after this }; type { DequeApp } DequeApp = class(TCustomApplication) protected procedure DoRun; override; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp; virtual; end; { DequeApp } procedure DequeApp.DoRun; var ErrorMsg, query: String; history: array[1..10000] of String; hsize, curhindex:integer; k:char; m:deque; dict:array[1..6] of string = ('help', 'show', 'popback', 'popfront', 'pushback', 'pushfront'); chopped:tstringarray; valprovided, legit:boolean; val, i:integer; begin // quick check parameters ErrorMsg:=CheckOptions('h', 'help'); if ErrorMsg<>'' then begin ShowException(Exception.Create(ErrorMsg)); Terminate; Exit; end; // parse parameters if HasOption('h', 'help') then begin WriteHelp; Terminate; Exit; end; query:=''; hsize:=0; repeat begin hsize:=hsize+1; history[hsize]:=''; query:=''; curhindex:=hsize; repeat begin clrscr; write(query); k:=readkey; if k=#13 then break else if (k=#9) then begin legit:=false; for i:=1 to 8 do begin if(leftstr(dict[i],length(query))=query) then begin legit:=true; break; end; end; if(legit) then query:=dict[i]; end else if k=#8 then query:=leftstr(query, length(query)-1) else if k=#0 then begin k:=readkey; if (k=#80) and (curhindex<hsize) then begin curhindex:=curhindex+1; query:=history[curhindex]; end; if (k=#72) and (curhindex>1) then begin curhindex:=curhindex-1; query:=history[curhindex]; end; end else query:=query+k; if curhindex=hsize then history[hsize]:=query; end until false; if query='' then continue; chopped:=query.split(' '); valprovided:=true; legit:=false; try val:=strtoint(chopped[1]); except valprovided:=false; end; if query[1]='q' then break; for i:=1 to 6 do begin if(leftstr(dict[i],length(chopped[0]))=chopped[0]) then begin legit:=true; break; end; end; if legit then begin writeln; if i=1 then begin write('help, show, popback, popfront, pushback [value], pushfront [value], q* to quit. Press Enter to continue.'); readln; end else if i=2 then begin show(m); write('Press Enter to continue');readln; end else if i=3 then pop_back(m) else if i=4 then pop_front(m) else if valprovided then begin if i=5 then push_back(m, val) else push_front(m, val); end else begin write('Value to push wasn`t provided or couldnt be converted to integer. Press Enter to continue'); readln; end; end else begin writeln; write('Command '+chopped[0]+' not found. Try "help" and use lowercase. Press Enter to continue.'); readln; end; end until false; // stop program loop Terminate; end; constructor DequeApp.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException:=True; end; destructor DequeApp.Destroy; begin inherited Destroy; end; procedure DequeApp.WriteHelp; begin { add your help code here } writeln('Usage: ', ExeName, ' -h'); end; var Application: DequeApp; begin Application:=DequeApp.Create(nil); Application.Title:='DoubleEndedQ'; Application.Run; Application.Free; end.
unit TListTestCase; interface uses Classes, SysUtils, TestFrameWork; type TTestCaseList = class(TTestCase) private FEmpty: TList; FFull: TList; protected procedure SetUp; override; procedure TearDown; override; published procedure TestBugCallAFunctionThatNotExists; procedure TestQuote; procedure TestQuote1; procedure testAdd; end; implementation uses uLang; procedure TTestCaseList.SetUp; begin end; procedure TTestCaseList.TearDown; begin end; procedure TTestCaseList.TestAdd; var n : TLispNode ; begin n := LispLang.EvalStr('(print 2)'); Check (n.isInt = true,'Not Success'); Check(n.getInt = 2 ,'Not 2'); end; procedure TTestCaseList.TestQuote; var n : TLispNode ; begin n := LispLang.EvalStr('(quote 2)'); Check (n.isInt = true,'Not Success'); n := LispLang.EvalStr('(quote (2))'); Check (n.isList = true,'Not Success'); n := LispLang.EvalStr('(setq1 a 1)'); Check (n.isList = true,'Not Success'); end; procedure TTestCaseList.TestBugCallAFunctionThatNotExists; var n : TLispNode ; begin n := LispLang.EvalStr('(setq1 a 1)'); Check (n.isList = true,'Not Success'); end; procedure TTestCaseList.TestQuote1; var n : TLispNode ; begin n := LispLang.EvalStr('(downfile "www.163.com" "/" "c:\ff.htm")'); n := LispLang.EvalStr('(ftp "user" "password" "ftp.163.com" "/adir" "c:\ff.htm" 3)'); end; initialization RegisterTest('', TTestCaseList.Suite); end.
unit ACMIn; interface uses Windows, Messages, ListUnit, ACMConvertor, MMSystem, MSACM; type TACMBufferCount = 2..64; TBufferFullEvent = procedure(Sender : TObject; Data : Pointer; Size:longint) of object; TACMIn = class(TObject) private FActive : Boolean; FBufferList : TList; FBufferSize : DWord; FFormat : TACMWaveFormat; FNumBuffers : TACMBufferCount; FWaveInHandle : HWaveIn; FWindowHandle : HWnd; FOnBufferFull : TBufferFullEvent; procedure DoBufferFull(Header : PWaveHdr); procedure SetBufferSize(const Value: DWord); procedure SetNumBuffers(const Value: TACMBufferCount); protected function NewHeader : PWaveHDR; procedure DisposeHeader(Header : PWaveHDR); procedure WndProc(Var Message : TMessage); public constructor Create; destructor Destroy; override; procedure Open(aFormat : TACMWaveFormat); procedure Close; property Active : Boolean read FActive; property WindowHandle : HWnd read FWindowHandle; published property BufferSize : DWord read FBufferSize write SetBufferSize; property NumBuffers : TACMBufferCount read FNumBuffers write SetNumBuffers; property OnBufferFull : TBufferFullEvent read FOnBufferFull write FOnBufferFull; end; function SetRecordingInput(Index: integer): boolean; function IsRecordingInput(Index: integer): boolean; implementation function SetRecordingInput(Index: integer): boolean; var mixer:HMIXER; mixerlineid:array [0..255] of integer; m_ctrl:array [0..255] of TMIXERCONTROL; ctrl_sel:integer; caps:TMIXERCAPS; line:TMIXERLINE; MaxLinecnt:integer; i,j,k,err:integer; curDest:integer; mxc:TMIXERCONTROLDETAILS; mxcl:array [0..100] of integer; LineID:integer; ctrl:TMIXERLINECONTROLS; begin Result := False; mixerOpen(@mixer,0,0,0,CALLBACK_WINDOW); mixerGetDevCaps(mixer,@caps,sizeof(caps)); MaxLinecnt := 255; line.cbStruct := sizeof(line); curDest := -1; for i := 0 to maxlinecnt do begin inc(curDest); line.dwDestination:=curDest; err := mixerGetLineInfo(mixer, @line, MIXER_GETLINEINFOF_DESTINATION or MIXER_OBJECTF_HMIXER); if err <> 0 then break; if Pos('Rec', string(line.szname)) <> 0 then begin line.cbStruct:=sizeof(line); line.dwDestination:=curDest; mixerGetLineInfo(mixer,@line,MIXER_GETLINEINFOF_DESTINATION or MIXER_OBJECTF_HMIXER); mixerlineid[0]:=line.dwLineID; LineId:=line.dwLineID; line.cbStruct:=sizeof(line); line.dwLineID:=LineID; mixerGetLineInfo(mixer,@line,MIXER_GETLINEINFOF_LINEID); if line.cControls=0 then exit; ctrl.cbStruct:=sizeof(ctrl); ctrl.cbmxctrl:=sizeof(TMIXERCONTROL); ctrl.dwLineID:=LineID; ctrl.cControls:=line.cControls; ctrl.pamxctrl:=@m_ctrl; mixerGetLineControls(mixer,@ctrl,MIXER_GETLINECONTROLSF_ALL); for j := 0 to ctrl.cControls-1 do begin if pos('Rec', m_ctrl[j].szName) <> 0 then ctrl_sel := j; end; line.dwDestination:=curDest; line.dwSource:=Index; err:=mixerGetLineInfo(mixer,@line,MIXER_GETLINEINFOF_SOURCE or MIXER_OBJECTF_HMIXER); if err<>0 then break; for k := 0 to m_ctrl[ctrl_sel].cMultipleItems - 1 do begin if k = Index then begin mxcl[k] := 1; end else mxcl[k] := 0; end; mxc.cbStruct:=sizeof(mxc); mxc.dwControlID:=m_ctrl[ctrl_sel].dwControlID; MXC.cMultipleItems:=m_ctrl[ctrl_sel].cMultipleItems; mxc.cChannels:=1; mxc.cbDetails:=sizeof(mxcl); mxc.paDetails:=@mxcl; if MixerSetControlDetails(mixer,@mxc,0) = 0 then Result := True; mixerClose(mixer); Exit; end; end; end; function IsRecordingInput(Index: integer): boolean; var mixer:HMIXER; mixerlineid:array [0..255] of integer; m_ctrl:array [0..255] of TMIXERCONTROL; ctrl_sel:integer; caps:TMIXERCAPS; line:TMIXERLINE; MaxLinecnt:integer; i,j,k,err:integer; curDest:integer; mxc:TMIXERCONTROLDETAILS; mxcl:array [0..100] of integer; LineID:integer; ctrl:TMIXERLINECONTROLS; begin Result := False; mixerOpen(@mixer,0,0,0,CALLBACK_WINDOW); mixerGetDevCaps(mixer,@caps,sizeof(caps)); MaxLinecnt := 255; line.cbStruct := sizeof(line); curDest := -1; for i := 0 to maxlinecnt do begin inc(curDest); line.dwDestination:=curDest; err := mixerGetLineInfo(mixer, @line, MIXER_GETLINEINFOF_DESTINATION or MIXER_OBJECTF_HMIXER); if err <> 0 then break; if Pos('Rec', string(line.szname)) <> 0 then begin line.cbStruct:=sizeof(line); line.dwDestination:=curDest; mixerGetLineInfo(mixer,@line,MIXER_GETLINEINFOF_DESTINATION or MIXER_OBJECTF_HMIXER); mixerlineid[0]:=line.dwLineID; LineId:=line.dwLineID; line.cbStruct:=sizeof(line); line.dwLineID:=LineID; mixerGetLineInfo(mixer,@line,MIXER_GETLINEINFOF_LINEID); if line.cControls=0 then exit; ctrl.cbStruct:=sizeof(ctrl); ctrl.cbmxctrl:=sizeof(TMIXERCONTROL); ctrl.dwLineID:=LineID; ctrl.cControls:=line.cControls; ctrl.pamxctrl:=@m_ctrl; mixerGetLineControls(mixer,@ctrl,MIXER_GETLINECONTROLSF_ALL); for j := 0 to ctrl.cControls-1 do begin if pos('Rec', m_ctrl[j].szName) <> 0 then ctrl_sel := j; end; line.dwDestination:=curDest; line.dwSource:=Index; err := mixerGetLineInfo(mixer,@line,MIXER_GETLINEINFOF_SOURCE or MIXER_OBJECTF_HMIXER); if err = 0 then Result := True; mixerClose(mixer); Exit; end; end; end; var UtilWindowClass: TWndClass = ( style: 0; lpfnWndProc: @DefWindowProc; cbClsExtra: 0; cbWndExtra: 0; hInstance: 0; hIcon: 0; hCursor: 0; hbrBackground: 0; lpszMenuName: nil; lpszClassName: 'TPUtilWindow'); const InstanceCount = 313; type TWndMethod = procedure(var Message: TMessage) of object; type PObjectInstance = ^TObjectInstance; TObjectInstance = packed record Code: Byte; Offset: Integer; case Integer of 0: (Next: PObjectInstance); 1: (Method: TWndMethod); end; type PInstanceBlock = ^TInstanceBlock; TInstanceBlock = packed record Next: PInstanceBlock; Code: array[1..2] of Byte; WndProcPtr: Pointer; Instances: array[0..InstanceCount] of TObjectInstance; end; var InstBlockList: PInstanceBlock; InstFreeList: PObjectInstance; function StdWndProc(Window: HWND; Message, WParam: Longint; LParam: Longint): Longint; stdcall; assembler; asm XOR EAX,EAX PUSH EAX PUSH LParam PUSH WParam PUSH Message MOV EDX,ESP MOV EAX,[ECX].Longint[4] CALL [ECX].Pointer ADD ESP,12 POP EAX end; function CalcJmpOffset(Src, Dest: Pointer): Longint; begin Result := Longint(Dest) - (Longint(Src) + 5); end; function MakeObjectInstance(Method: TWndMethod): Pointer; const BlockCode: array[1..2] of Byte = ( $59, { POP ECX } $E9); { JMP StdWndProc } PageSize = 4096; var Block: PInstanceBlock; Instance: PObjectInstance; begin if InstFreeList = nil then begin Block := VirtualAlloc(nil, PageSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); Block^.Next := InstBlockList; Move(BlockCode, Block^.Code, SizeOf(BlockCode)); Block^.WndProcPtr := Pointer(CalcJmpOffset(@Block^.Code[2], @StdWndProc)); Instance := @Block^.Instances; repeat Instance^.Code := $E8; { CALL NEAR PTR Offset } Instance^.Offset := CalcJmpOffset(Instance, @Block^.Code); Instance^.Next := InstFreeList; InstFreeList := Instance; Inc(Longint(Instance), SizeOf(TObjectInstance)); until Longint(Instance) - Longint(Block) >= SizeOf(TInstanceBlock); InstBlockList := Block; end; Result := InstFreeList; Instance := InstFreeList; InstFreeList := Instance^.Next; Instance^.Method := Method; end; procedure FreeObjectInstance(ObjectInstance: Pointer); begin if ObjectInstance <> nil then begin PObjectInstance(ObjectInstance)^.Next := InstFreeList; InstFreeList := ObjectInstance; end; end; function AllocateHWnd(Method: TWndMethod): HWND; var TempClass: TWndClass; ClassRegistered: Boolean; begin UtilWindowClass.hInstance := HInstance; {$IFDEF PIC} UtilWindowClass.lpfnWndProc := @DefWindowProc; {$ENDIF} ClassRegistered := GetClassInfo(HInstance, UtilWindowClass.lpszClassName, TempClass); if not ClassRegistered or (TempClass.lpfnWndProc <> @DefWindowProc) then begin if ClassRegistered then Windows.UnregisterClass(UtilWindowClass.lpszClassName, HInstance); Windows.RegisterClass(UtilWindowClass); end; Result := CreateWindowEx(WS_EX_TOOLWINDOW, UtilWindowClass.lpszClassName, '', WS_POPUP {!0}, 0, 0, 0, 0, 0, 0, HInstance, nil); if Assigned(Method) then SetWindowLong(Result, GWL_WNDPROC, Longint(MakeObjectInstance(Method))); end; procedure DeallocateHWnd(Wnd: HWND); var Instance: Pointer; begin Instance := Pointer(GetWindowLong(Wnd, GWL_WNDPROC)); DestroyWindow(Wnd); if Instance <> @DefWindowProc then FreeObjectInstance(Instance); end; constructor TACMIn.Create; begin inherited; FBufferList := TList.Create; FActive := False; FBufferSize := 8192; FWaveInHandle := 0; FWindowHandle := AllocateHWND(WndProc); FNumBuffers := 4; end; procedure TACMIn.DoBufferFull(Header : PWaveHdr); var Res : Integer; BytesRecorded : Integer; Data : Pointer; begin if Active then begin Res := WaveInUnPrepareHeader(FWaveInHandle,Header,sizeof(TWavehdr)); if Res <>0 then Exit; BytesRecorded:=header.dwBytesRecorded; if assigned(FOnBufferFull) then begin Getmem(Data, BytesRecorded); try move(header.lpData^,Data^,BytesRecorded); FOnBufferFull(Self, Data, BytesRecorded); finally Freemem(Data); end; end; header.dwbufferlength:=FBufferSize; header.dwBytesRecorded:=0; header.dwUser:=0; header.dwflags:=0; header.dwloops:=0; FillMemory(Header.lpData,FBufferSize,0); Res := WaveInPrepareHeader(FWaveInHandle,Header,sizeof(TWavehdr)); if Res <> 0 then Exit; Res:=WaveInAddBuffer(FWaveInHandle,Header,sizeof(TWaveHdr)); if Res <> 0 then Exit; end else DisposeHeader(Header); end; procedure TACMIn.Open(aFormat : TACMWaveFormat); var Res : Integer; J : Integer; begin if Active then exit; Res := WaveInOpen(@FWaveInHandle,0,@aFormat.Format,FWindowHandle,0,CALLBACK_WINDOW or WAVE_MAPPED); if Res <> 0 then Exit; for j:= 1 to FNumBuffers do NewHeader; Res := WaveInStart(FWaveInHandle); if Res <> 0 then Exit; FFormat := aFormat; FActive := True; end; destructor TACMIn.Destroy; begin if Active then Close; FBufferList.Free; DeAllocateHWND(FWindowHandle); inherited; end; procedure TACMIn.WndProc(var Message: TMessage); begin case Message.Msg of MM_WIM_Data: DoBufferFull(PWaveHDR(Message.LParam)); end; end; procedure TACMIn.Close; var X : Integer; begin if not Active then Exit; FActive := False; WaveInReset(FWaveInHandle); WaveInClose(FWaveInHandle); FWaveInHandle := 0; For X:=FBufferList.Count-1 downto 0 do DisposeHeader(PWaveHDR(FBufferList[X])); end; procedure TACMIn.SetBufferSize(const Value: DWord); begin if Active then exit; FBufferSize := Value; end; function TACMIn.NewHeader: PWaveHDR; var Res : Integer; begin Getmem(Result, SizeOf(TWaveHDR)); FBufferList.Add(Result); with Result^ do begin Getmem(lpData,FBufferSize); dwBufferLength := FBufferSize; dwBytesRecorded := 0; dwFlags := 0; dwLoops := 0; Res := WaveInPrepareHeader(FWaveInHandle,Result,sizeof(TWaveHDR)); if Res <> 0 then Exit; Res := WaveInAddBuffer(FWaveInHandle,Result,SizeOf(TWaveHDR)); if Res <> 0 then Exit; end; end; procedure TACMIn.SetNumBuffers(const Value: TACMBufferCount); begin if Active then exit; FNumBuffers := Value; end; procedure TACMIn.DisposeHeader(Header: PWaveHDR); var X : Integer; begin X := FBufferList.IndexOf(Header); if X < 0 then exit; Freemem(header.lpData); Freemem(header); FBufferList.Delete(X); end; end.
unit Objekt.DHLValidateShipmentorderResponse; interface uses System.SysUtils, System.Classes, Objekt.DHLVersionResponse, Objekt.DHLStatusinformation, Objekt.DHLValidateStateList; type TDHLValidateShipmentorderResponse = class private fVersion: TDHLVersionResponse; fStatus: TDHLStatusinformation; fValidationState: TDHLValidateStateList; public constructor Create; destructor Destroy; override; property Version: TDHLVersionResponse read fVersion write fVersion; property Status: TDHLStatusinformation read fStatus write fStatus; property ValidationState: TDHLValidateStateList read fValidationState write fValidationState; end; implementation { TDHLValidateShipmentorderResponse } constructor TDHLValidateShipmentorderResponse.Create; begin fVersion := TDHLVersionResponse.Create; fStatus := TDHLStatusinformation.Create; fValidationState := TDHLValidateStateList.Create; end; destructor TDHLValidateShipmentorderResponse.Destroy; begin FreeAndNil(fVersion); FreeAndNil(fStatus); FreeAndNil(fValidationState); inherited; end; end.
unit FormOptimizeMesh; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Spin; type TFrmOptimizeMesh = class(TForm) LbThreshold: TLabel; BvlBottomLine: TBevel; BtOK: TButton; BtCancel: TButton; cbIgnoreColours: TCheckBox; Label1: TLabel; EdThreshold: TEdit; procedure BtOKClick(Sender: TObject); procedure BtCancelClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } Apply : boolean; Threshold : real; end; implementation {$R *.dfm} procedure TFrmOptimizeMesh.BtCancelClick(Sender: TObject); begin Close; end; procedure TFrmOptimizeMesh.BtOKClick(Sender: TObject); begin Threshold := StrToFloatDef(EdThreshold.Text,-1); if (Threshold >= 0) and (Threshold <= 180) then begin Threshold := cos((Threshold * Pi) / 180); BtOK.Enabled := false; Apply := true; Close; end else begin ShowMessage('Please, insert an angle between 0 and 180.'); end; end; procedure TFrmOptimizeMesh.FormCreate(Sender: TObject); begin Apply := false; end; end.
unit frmDelphiLibraryHelperU; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.UITypes, Vcl.Buttons, Vcl.ExtCtrls, LibraryHelperU, LibraryPathsU, Vcl.ComCtrls, System.Actions, Vcl.ActnList, System.ImageList, Vcl.ImgList, Vcl.Menus, System.Types; type TfrmDelphiLibraryHelper = class(TForm) GroupBox1: TGroupBox; GroupBox2: TGroupBox; GroupBox3: TGroupBox; Panel1: TPanel; BitBtn1: TBitBtn; BitBtn2: TBitBtn; BitBtn3: TBitBtn; BitBtn4: TBitBtn; BitBtn7: TBitBtn; StatusBar: TStatusBar; ActionList: TActionList; ActionAddEnvironmentVariables: TAction; ActionDeleteEnvironmentVariable: TAction; ActionAddLibraryPath: TAction; ActionDeleteLibraryPath: TAction; ActionDeleteAllLibraryPaths: TAction; ActionSave: TAction; ActionLoad: TAction; ListViewLibrary: TListView; ActionApplyTemplate: TAction; BitBtn8: TBitBtn; MainMenu: TMainMenu; File1: TMenuItem; Load1: TMenuItem; Save1: TMenuItem; N1: TMenuItem; emplates1: TMenuItem; ApplyTemplate2: TMenuItem; Help1: TMenuItem; ActionExit: TAction; ActionAbout: TAction; Exit1: TMenuItem; About1: TMenuItem; ActionFindReplace: TAction; BitBtn9: TBitBtn; PopupMenuLibrary: TPopupMenu; Add1: TMenuItem; Delete1: TMenuItem; N2: TMenuItem; DeleteAll1: TMenuItem; N3: TMenuItem; Replace1: TMenuItem; N4: TMenuItem; ActionCopyLibraryPath: TAction; ActionOpenFolder: TAction; Openfolder1: TMenuItem; ActionCopyLibraryValue: TAction; Copy1: TMenuItem; Copypath1: TMenuItem; Copyvalue1: TMenuItem; Panel6: TPanel; comboDelphiInstallations: TComboBox; lblRootPath: TLabel; ActionSearch: TAction; BitBtn10: TBitBtn; Search1: TMenuItem; ActionSystemProperties: TAction; ActionExport: TAction; ActionImport: TAction; GroupBox4: TGroupBox; BitBtn17: TBitBtn; BitBtn18: TBitBtn; BitBtn12: TBitBtn; BitBtn13: TBitBtn; BitBtn14: TBitBtn; BitBtn15: TBitBtn; Export1: TMenuItem; Import1: TMenuItem; ImportExport1: TMenuItem; SystemProperties1: TMenuItem; Panel8: TPanel; comboLibraries: TComboBox; comboPathType: TComboBox; TimerMain: TTimer; btnTools: TBitBtn; PopupMenuTools: TPopupMenu; ActionCopySearchToBrowse: TAction; ActionCopyBrowseToSearch: TAction; Copybrowsepathstosearchpaths1: TMenuItem; Copysearchpathstobrowsepaths1: TMenuItem; N5: TMenuItem; Copysearchpathstobrowsepaths2: TMenuItem; Copybrowsepathstosearchpaths2: TMenuItem; ActionCleanUp: TAction; N6: TMenuItem; Cleanup1: TMenuItem; N7: TMenuItem; Cleanup2: TMenuItem; ools1: TMenuItem; Copybrowsepathstosearchpaths3: TMenuItem; Copysearchpathstobrowsepaths3: TMenuItem; Cleanup3: TMenuItem; Export2: TMenuItem; Import2: TMenuItem; N8: TMenuItem; N9: TMenuItem; ActionViewLog: TAction; Viewlog1: TMenuItem; ActionRemoveBrowseFromSearch: TAction; Removebrowsepathsfromsearchpaths1: TMenuItem; Removebrowsepathsfromsearchpaths2: TMenuItem; ActionDeduplicate: TAction; Deduplicate1: TMenuItem; Deduplicate2: TMenuItem; Deduplicate3: TMenuItem; Panel9: TPanel; cbDeduplicateOnSave: TCheckBox; Viewlog2: TMenuItem; N10: TMenuItem; GridPanel1: TGridPanel; Panel2: TPanel; Label1: TLabel; ListViewEnvironmentVariables: TListView; Panel4: TPanel; BitBtn5: TBitBtn; BitBtn6: TBitBtn; Panel3: TPanel; Label2: TLabel; ListViewSystemEnvironmentVariables: TListView; Panel5: TPanel; BitBtn11: TBitBtn; Panel7: TPanel; procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure comboDelphiInstallationsChange(Sender: TObject); procedure ActionLoadExecute(Sender: TObject); procedure ActionSaveUpdate(Sender: TObject); procedure ActionSaveExecute(Sender: TObject); procedure ActionLoadUpdate(Sender: TObject); procedure comboLibrariesChange(Sender: TObject); procedure ActionApplyTemplateUpdate(Sender: TObject); procedure ActionApplyTemplateExecute(Sender: TObject); procedure ActionDeleteLibraryPathExecute(Sender: TObject); procedure ActionDeleteAllLibraryPathsExecute(Sender: TObject); procedure ActionDeleteEnvironmentVariableExecute(Sender: TObject); procedure ActionAddLibraryPathExecute(Sender: TObject); procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure ActionAddEnvironmentVariablesExecute(Sender: TObject); procedure ListViewLibraryDblClick(Sender: TObject); procedure ActionExitExecute(Sender: TObject); procedure ActionAboutExecute(Sender: TObject); procedure ActionCleanUpExecute(Sender: TObject); procedure ActionCopyBrowseToSearchExecute(Sender: TObject); procedure ActionFindReplaceExecute(Sender: TObject); procedure ListViewLibraryCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); procedure ActionCopyLibraryPathUpdate(Sender: TObject); procedure ActionOpenFolderExecute(Sender: TObject); procedure ActionCopyLibraryPathExecute(Sender: TObject); procedure ListViewEnvironmentVariablesCustomDrawItem (Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); procedure ActionCopyLibraryValueExecute(Sender: TObject); procedure ActionCopySearchToBrowseExecute(Sender: TObject); procedure ActionDeduplicateExecute(Sender: TObject); procedure lblRootPathClick(Sender: TObject); procedure ActionSearchExecute(Sender: TObject); procedure ActionSystemPropertiesExecute(Sender: TObject); procedure ActionExportExecute(Sender: TObject); procedure ActionImportExecute(Sender: TObject); procedure ActionRemoveBrowseFromSearchExecute(Sender: TObject); procedure ActionViewLogExecute(Sender: TObject); procedure btnToolsClick(Sender: TObject); procedure TimerMainTimer(Sender: TObject); private FApplicationActive: Boolean; FModified: Boolean; FLibraryHelper: TLibraryHelper; FDelphiIsRunning: Boolean; FDelphiInstallation: TDelphiInstallation; FActiveDelphiLibrary: TDelphiLibrary; FActiveLibraryPathType: TLibraryPathType; procedure LoadDelphiInstallation; procedure LoadEnvironmentVariables; procedure SaveEnvironmentVariables; procedure LoadLibrary; procedure SaveLibrary; procedure LoadSystemEnvironmentVariables; function ValidatePath(APath: string): Boolean; procedure ProcessParameters; procedure Cleanup; procedure ApplyTemplate(AFileName: TFileName; AApplyToAllInstallations: Boolean; ADeduplicate: Boolean); function GetApplicationParameters(AParameter: string; var AValue: string): Boolean; public { Public declarations } end; var frmDelphiLibraryHelper: TfrmDelphiLibraryHelper; implementation {$R *.dfm} uses dmDelphiLibraryHelperU, frmAddLibraryPathU, frmAddEnvironmentVariableU, frmAboutU, frmFindReplaceU, frmSearchU, frmProgressU, LoggingU, frmLoggingU; procedure TfrmDelphiLibraryHelper.ActionAboutExecute(Sender: TObject); begin with TfrmAbout.Create(Self) do begin try ShowModal; finally Free; end; end; end; procedure TfrmDelphiLibraryHelper.ActionAddEnvironmentVariablesExecute (Sender: TObject); var LfrmAddEnvironmentVariable: TfrmAddEnvironmentVariable; begin LfrmAddEnvironmentVariable := TfrmAddEnvironmentVariable.Create(Self); try if LfrmAddEnvironmentVariable.Add(FDelphiInstallation) then begin FModified := True; LoadEnvironmentVariables; end; finally FreeAndNil(LfrmAddEnvironmentVariable); end; end; procedure TfrmDelphiLibraryHelper.ActionAddLibraryPathExecute(Sender: TObject); var LfrmAddLibraryPath: TfrmAddLibraryPath; begin LfrmAddLibraryPath := TfrmAddLibraryPath.Create(nil); try if LfrmAddLibraryPath.Add(FActiveDelphiLibrary, FDelphiInstallation) then begin FModified := True; LoadLibrary; end; finally FreeAndNil(LfrmAddLibraryPath); end; end; procedure TfrmDelphiLibraryHelper.ActionApplyTemplateExecute(Sender: TObject); var LOpenDialog: TOpenDialog; LApplyToAllInstallations: Boolean; begin LOpenDialog := TOpenDialog.Create(Self); try LOpenDialog.DefaultExt := '.dlht'; LOpenDialog.Filter := 'Delphi Library Helper Template (*.dlht)|*.dlht|All Files (*.*)|*' + '.*'; LOpenDialog.Options := [ofHideReadOnly, ofFileMustExist, ofEnableSizing]; LOpenDialog.InitialDir := ExtractFilePath(ParamStr(0)); if LOpenDialog.Execute then begin LApplyToAllInstallations := False; if FLibraryHelper.InstalledCount > 1 then begin MessageDlg (Format('Select from the following options on how to apply template "%s".' + #13#10 + #13#10 + '[Yes to All] - Apply to all "%d" installations' + #13#10 + '[Yes] - Apply to "%s" selected installation' + #13#10 + '[No] - Do not apply template to any installation', [ExtractFileName(LOpenDialog.FileName), FLibraryHelper.InstalledCount, FDelphiInstallation.ProductName]), mtConfirmation, [mbYesToAll, mbYes, mbNo], 0); end; ApplyTemplate(LOpenDialog.FileName, LApplyToAllInstallations, cbDeduplicateOnSave.Checked); end; finally FreeAndNil(LOpenDialog); end; end; procedure TfrmDelphiLibraryHelper.ActionApplyTemplateUpdate(Sender: TObject); begin ActionApplyTemplate.Enabled := Assigned(FDelphiInstallation); end; procedure TfrmDelphiLibraryHelper.ActionCleanUpExecute(Sender: TObject); begin if (MessageDlg('Remove all invalid paths?', mtConfirmation, [mbYes, mbNo], 0) = mrYes) then begin ShowProgress('Performing Cleanup...'); try Cleanup; LoadLibrary; FModified := True; finally HideProgress; end; end; end; procedure TfrmDelphiLibraryHelper.ActionCopyBrowseToSearchExecute (Sender: TObject); begin if (MessageDlg('Copy browse paths to search paths', mtConfirmation, [mbYes, mbNo], 0) = mrYes) then begin ShowProgress('Copy browse to search...'); try FDelphiInstallation.CopyBrowseToSearch; LoadLibrary; FModified := True; finally HideProgress; end; end; end; procedure TfrmDelphiLibraryHelper.ActionCopyLibraryPathExecute(Sender: TObject); begin if (Assigned(FDelphiInstallation)) and (Assigned(ListViewLibrary.Selected)) then begin FDelphiInstallation.CopyToClipBoard(ListViewLibrary.Selected.Caption, FActiveDelphiLibrary); end; end; procedure TfrmDelphiLibraryHelper.ActionCopyLibraryPathUpdate(Sender: TObject); begin (Sender as TAction).Enabled := Assigned(FDelphiInstallation) and Assigned(ListViewLibrary.Selected); end; procedure TfrmDelphiLibraryHelper.ActionCopyLibraryValueExecute (Sender: TObject); begin if (Assigned(FDelphiInstallation)) and (Assigned(ListViewLibrary.Selected)) then begin FDelphiInstallation.CopyToClipBoard(ListViewLibrary.Selected.Caption, FActiveDelphiLibrary, False); end; end; procedure TfrmDelphiLibraryHelper.ActionCopySearchToBrowseExecute (Sender: TObject); begin if (MessageDlg('Copy search paths to browse paths', mtConfirmation, [mbYes, mbNo], 0) = mrYes) then begin ShowProgress('Copy search to browse...'); try FDelphiInstallation.CopySearchToBrowse; LoadLibrary; FModified := True; finally HideProgress; end; end; end; procedure TfrmDelphiLibraryHelper.ActionDeduplicateExecute(Sender: TObject); var LExecute: Boolean; LCount: integer; begin case MessageDlg ('All paths will be expanded and duplicates removed, continue?', mtConfirmation, [mbYes, mbNo], 0) of mrYes: LExecute := True; else LExecute := False; end; if LExecute then begin ShowProgress('Deduplicating paths...'); try LCount := FDelphiInstallation.Deduplicate; HideProgress; MessageDlg(Format('%d path(s) have been removed.', [LCount]), mtInformation, [mbOK], 0); if LCount > 0 then begin LoadLibrary; FModified := True; end; finally HideProgress; end; end; end; procedure TfrmDelphiLibraryHelper.ActionDeleteAllLibraryPathsExecute (Sender: TObject); begin case MessageDlg (Format('Delete all from active library (Yes) or from across all libraries (All)?', []), mtConfirmation, [mbAll, mbYes, mbCancel], 0) of mrAll: begin FDelphiInstallation.DeleteAll(FActiveLibraryPathType); LoadLibrary; end; mrYes: begin ListViewLibrary.Clear; SaveLibrary; end; end; end; procedure TfrmDelphiLibraryHelper.ActionDeleteEnvironmentVariableExecute (Sender: TObject); begin if (MessageDlg('Delete Selected?', mtConfirmation, [mbYes, mbNo], 0) = mrYes) then begin ListViewEnvironmentVariables.DeleteSelected; SaveEnvironmentVariables; FModified := True; end; end; procedure TfrmDelphiLibraryHelper.ActionDeleteLibraryPathExecute (Sender: TObject); begin if (MessageDlg('Delete Selected?', mtConfirmation, [mbYes, mbNo], 0) = mrYes) then begin ListViewLibrary.DeleteSelected; SaveLibrary; end; end; procedure TfrmDelphiLibraryHelper.ActionExitExecute(Sender: TObject); begin Self.Close; end; procedure TfrmDelphiLibraryHelper.ActionExportExecute(Sender: TObject); var LSaveDialog: TSaveDialog; begin LSaveDialog := TSaveDialog.Create(Self); try LSaveDialog.DefaultExt := '.dlht'; LSaveDialog.Filter := 'Delphi Library Helper Template (*.dlht)|*.dlht|All Files (*.*)|*' + '.*'; LSaveDialog.Options := [ofHideReadOnly, ofEnableSizing]; LSaveDialog.InitialDir := ExtractFilePath(ParamStr(0)); if LSaveDialog.Execute then begin FDelphiInstallation.ExportLibrary(LSaveDialog.FileName); FDelphiInstallation.OpenFolder(ExtractFilePath(LSaveDialog.FileName), FActiveDelphiLibrary); end; finally FreeAndNil(LSaveDialog); end; end; procedure TfrmDelphiLibraryHelper.ActionFindReplaceExecute(Sender: TObject); var LFindReplace: TfrmFindReplace; begin LFindReplace := TfrmFindReplace.Create(Self); try if LFindReplace.Execute(FDelphiInstallation) then begin FModified := True; LoadLibrary; end; finally FreeAndNil(LFindReplace); end; end; procedure TfrmDelphiLibraryHelper.ActionImportExecute(Sender: TObject); var LOpenDialog: TOpenDialog; begin LOpenDialog := TOpenDialog.Create(Self); try LOpenDialog.DefaultExt := '.dlht'; LOpenDialog.Filter := 'Delphi Library Helper Template (*.dlht)|*.dlht|All Files (*.*)|*' + '.*'; LOpenDialog.Options := [ofHideReadOnly, ofFileMustExist, ofEnableSizing]; LOpenDialog.InitialDir := ExtractFilePath(ParamStr(0)); if LOpenDialog.Execute then begin FDelphiInstallation.ImportLibrary(LOpenDialog.FileName); comboLibrariesChange(nil); FModified := True; end; finally FreeAndNil(LOpenDialog); end; end; procedure TfrmDelphiLibraryHelper.ActionListUpdate(Action: TBasicAction; var Handled: Boolean); begin if FModified then begin StatusBar.Panels[0].Text := 'Modified'; end else begin StatusBar.Panels[0].Text := ''; end; if FDelphiIsRunning then begin StatusBar.Panels[1].Text := 'Delphi running.'; end else begin StatusBar.Panels[1].Text := 'Delphi is not running.'; end; end; procedure TfrmDelphiLibraryHelper.ActionLoadExecute(Sender: TObject); begin if comboDelphiInstallations.ItemIndex <> -1 then begin ShowProgress('Loading...'); try FDelphiInstallation := FLibraryHelper.Installation [comboDelphiInstallations.Text]; FDelphiInstallation.Load; lblRootPath.Caption := FDelphiInstallation.RootPath; LoadSystemEnvironmentVariables; LoadEnvironmentVariables; comboLibrariesChange(nil); FModified := False; finally HideProgress; end; end; end; procedure TfrmDelphiLibraryHelper.ActionLoadUpdate(Sender: TObject); begin ActionLoad.Enabled := comboDelphiInstallations.ItemIndex <> -1; end; procedure TfrmDelphiLibraryHelper.ActionOpenFolderExecute(Sender: TObject); begin if (Assigned(FDelphiInstallation)) and (Assigned(ListViewLibrary.Selected)) then begin FDelphiInstallation.OpenFolder(ListViewLibrary.Selected.Caption, FActiveDelphiLibrary); end; end; procedure TfrmDelphiLibraryHelper.ActionRemoveBrowseFromSearchExecute (Sender: TObject); var LExecute, LSmartEnabled: Boolean; LCount: integer; begin LExecute := True; LSmartEnabled := True; case MessageDlg ('Would you like to check folders for important files before removing from search folders? (This may take longer.)', mtConfirmation, [mbYes, mbNo, mbCancel], 0) of mrYes: LSmartEnabled := True; mrNo: LSmartEnabled := False; else LExecute := False; end; if LExecute then begin ShowProgress('Removing browse paths from search paths...'); try LCount := FDelphiInstallation.RemoveBrowseFromSearch(LSmartEnabled); HideProgress; MessageDlg(Format('%d path(s) have been removed.', [LCount]), mtInformation, [mbOK], 0); if LCount > 0 then begin LoadLibrary; FModified := True; end; finally HideProgress; end; end; end; procedure TfrmDelphiLibraryHelper.ActionSaveExecute(Sender: TObject); var LAllow: Boolean; begin LAllow := True; if FLibraryHelper.IsDelphiRunning then begin LAllow := False; if (MessageDlg('Delphi is still running, continue with save?', mtWarning, [mbYes, mbNo], 0) = mrYes) then begin LAllow := True; end; end; if LAllow then begin if Assigned(FDelphiInstallation) then begin ShowProgress('Saving...'); try FDelphiInstallation.Save(cbDeduplicateOnSave.Checked); LoadLibrary; FModified := False; finally HideProgress; end; end; end; end; procedure TfrmDelphiLibraryHelper.ActionSaveUpdate(Sender: TObject); begin ActionSave.Enabled := (Assigned(FDelphiInstallation)) and (FModified); end; procedure TfrmDelphiLibraryHelper.ActionSearchExecute(Sender: TObject); var LfrmSearch: TfrmSearch; begin LfrmSearch := TfrmSearch.Create(Self); try LfrmSearch.Execute(FDelphiInstallation); finally FreeAndNil(LfrmSearch); end; end; procedure TfrmDelphiLibraryHelper.ActionSystemPropertiesExecute (Sender: TObject); begin FDelphiInstallation.ExecuteFile('open', 'SystemPropertiesAdvanced', '', '', SW_SHOWNORMAL); end; procedure TfrmDelphiLibraryHelper.ActionViewLogExecute(Sender: TObject); begin if frmLogging.Showing then begin frmLogging.BringToFront; end else begin frmLogging.Show; end; end; procedure TfrmDelphiLibraryHelper.ApplyTemplate(AFileName: TFileName; AApplyToAllInstallations: Boolean; ADeduplicate: Boolean); var LDelphiInstallation: TDelphiInstallation; LIdx, LTotal, LApplied: integer; begin LApplied := 0; ShowProgress('Applying Template...'); try if AApplyToAllInstallations then begin LTotal := FLibraryHelper.Count; for LIdx := 0 to Pred(LTotal) do begin LDelphiInstallation := FLibraryHelper.Installations[LIdx]; if LDelphiInstallation.Installed then begin UpdateProgress(LIdx + 1, LTotal + 1, 'Applying template to ' + LDelphiInstallation.ProductName); LApplied := LApplied + LDelphiInstallation.Apply(AFileName); LDelphiInstallation.Save(ADeduplicate); end; end; end else begin LApplied := FDelphiInstallation.Apply(AFileName); end; UpdateProgress(100, Format('%d paths applied', [LApplied])); comboLibrariesChange(nil); FModified := not AApplyToAllInstallations; finally HideProgress; end; end; procedure TfrmDelphiLibraryHelper.btnToolsClick(Sender: TObject); begin with btnTools.ClientToScreen(point(0, 0)) do PopupMenuTools.Popup(X, Y); end; procedure TfrmDelphiLibraryHelper.Cleanup; begin FDelphiInstallation.Cleanup; end; procedure TfrmDelphiLibraryHelper.comboDelphiInstallationsChange (Sender: TObject); begin ActionLoad.Execute; end; procedure TfrmDelphiLibraryHelper.comboLibrariesChange(Sender: TObject); begin if (comboLibraries.ItemIndex <> -1) and (comboPathType.ItemIndex <> -1) then begin FActiveLibraryPathType := TLibraryPathType(comboPathType.ItemIndex + 2); FActiveDelphiLibrary := TDelphiLibrary(comboLibraries.ItemIndex); LoadLibrary; end; end; procedure TfrmDelphiLibraryHelper.FormActivate(Sender: TObject); begin if not FApplicationActive then begin FApplicationActive := True; LoadDelphiInstallation; ProcessParameters; TimerMainTimer(Sender); end; end; procedure TfrmDelphiLibraryHelper.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := not FModified; if not CanClose then begin if (MessageDlg('You have unsaved changes, are you sure you want to exit?', mtConfirmation, [mbYes, mbNo], 0) = mrYes) then begin CanClose := True; end; end; end; procedure TfrmDelphiLibraryHelper.FormCreate(Sender: TObject); begin Self.Width := Screen.Width - (Screen.Width div 4); Self.Height := Screen.Height - (Screen.Height div 4); FApplicationActive := False; FLibraryHelper := TLibraryHelper.Create; comboLibraries.ItemIndex := 0; lblRootPath.Font.Style := [fsUnderline]; lblRootPath.Font.Size := Self.Font.Size - 1; lblRootPath.Font.Color := clHighlight; end; procedure TfrmDelphiLibraryHelper.FormDestroy(Sender: TObject); begin FreeAndNil(FLibraryHelper); end; procedure TfrmDelphiLibraryHelper.lblRootPathClick(Sender: TObject); begin FDelphiInstallation.OpenFolder(lblRootPath.Caption, dlWin32); end; procedure TfrmDelphiLibraryHelper.ListViewEnvironmentVariablesCustomDrawItem (Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); begin if Odd(Item.Index) then begin Sender.Canvas.Font.Color := clBlack; Sender.Canvas.Brush.Color := clLtGray; end else begin Sender.Canvas.Font.Color := clBlack; Sender.Canvas.Brush.Color := clWhite; end; end; procedure TfrmDelphiLibraryHelper.ListViewLibraryCustomDrawItem (Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); begin if Odd(Item.Index) then begin Sender.Canvas.Font.Color := clBlack; Sender.Canvas.Brush.Color := clLtGray; end else begin Sender.Canvas.Font.Color := clBlack; Sender.Canvas.Brush.Color := clWhite; end; if not ValidatePath(Item.Caption) then begin Sender.Canvas.Font.Color := clWhite; Sender.Canvas.Brush.Color := clMaroon; end; end; procedure TfrmDelphiLibraryHelper.ListViewLibraryDblClick(Sender: TObject); begin ActionOpenFolder.Execute; end; procedure TfrmDelphiLibraryHelper.LoadDelphiInstallation; var LIdx: integer; begin comboDelphiInstallations.ItemIndex := -1; comboDelphiInstallations.Items.Clear; try FLibraryHelper.Load; for LIdx := 0 to Pred(FLibraryHelper.Count) do begin if FLibraryHelper.Installations[LIdx].Installed then begin comboDelphiInstallations.Items.Add(FLibraryHelper.Installations[LIdx] .ProductName); end; end; FLibraryHelper.GetLibraryNames(comboLibraries.Items); finally if comboPathType.Items.Count > 0 then begin comboPathType.ItemIndex := 0; end; if comboLibraries.Items.Count > 0 then begin comboLibraries.ItemIndex := 0; end; if comboDelphiInstallations.Items.Count > 0 then begin comboDelphiInstallations.ItemIndex := 0; comboDelphiInstallationsChange(nil); end; end; end; procedure TfrmDelphiLibraryHelper.LoadEnvironmentVariables; var LIdx: integer; begin ListViewEnvironmentVariables.Clear; if Assigned(FDelphiInstallation) then begin ListViewEnvironmentVariables.Items.BeginUpdate; try for LIdx := 0 to Pred(FDelphiInstallation.EnvironmentVariables.Count) do begin with ListViewEnvironmentVariables.Items.Add do begin Caption := FDelphiInstallation.EnvironmentVariables.Variable [LIdx].Name; SubItems.Add(FDelphiInstallation.EnvironmentVariables.Variable [LIdx].Value); end; end; finally ListViewEnvironmentVariables.Items.EndUpdate; end; end; end; procedure TfrmDelphiLibraryHelper.LoadSystemEnvironmentVariables; var LIdx: integer; begin ListViewSystemEnvironmentVariables.Clear; if Assigned(FDelphiInstallation) then begin ListViewSystemEnvironmentVariables.Items.BeginUpdate; try for LIdx := 0 to Pred(FDelphiInstallation.SystemEnvironmentVariables.Count) do begin with ListViewSystemEnvironmentVariables.Items.Add do begin Caption := FDelphiInstallation.SystemEnvironmentVariables.Variable [LIdx].Name; SubItems.Add(FDelphiInstallation.SystemEnvironmentVariables.Variable [LIdx].Value); end; end; finally ListViewSystemEnvironmentVariables.Items.EndUpdate; end; end; end; function TfrmDelphiLibraryHelper.GetApplicationParameters(AParameter: string; var AValue: string): Boolean; var LParamIdx: integer; begin Result := False; LParamIdx := 1; While (LParamIdx <= ParamCount) and (not Result) do begin try if Pos(AParameter, ParamStr(LParamIdx)) = 1 then begin AValue := ParamStr(LParamIdx); AValue := StringReplace(AValue, AParameter + ':', '', [rfReplaceAll, rfIgnoreCase]); AValue := StringReplace(AValue, AParameter, '', [rfReplaceAll, rfIgnoreCase]); AValue := AnsiDequotedStr(AValue, '"'); Result := True; end; finally Inc(LParamIdx); end; end; end; procedure TfrmDelphiLibraryHelper.ProcessParameters; var LParam: string; LDeduplicate: Boolean; begin LDeduplicate := False; if GetApplicationParameters('/CLEANUP', LParam) then begin Cleanup; end; if GetApplicationParameters('/DEDUPLICATE', LParam) then begin LDeduplicate := True; end; if GetApplicationParameters('/TEMPLATE', LParam) then begin if FileExists(LParam) then begin ApplyTemplate(LParam, True, LDeduplicate); if GetApplicationParameters('/CLOSE', LParam) then begin ShowProgress('Closing...'); Application.ProcessMessages; Sleep(2000); Application.ProcessMessages; HideProgress; Application.Terminate; end; end; end; end; procedure TfrmDelphiLibraryHelper.SaveEnvironmentVariables; var LIdx: integer; LName, LValue: string; begin if Assigned(FDelphiInstallation) then begin FDelphiInstallation.EnvironmentVariables.Clear; for LIdx := 0 to Pred(ListViewEnvironmentVariables.Items.Count) do begin LName := ListViewEnvironmentVariables.Items[LIdx].Caption; LValue := ListViewEnvironmentVariables.Items[LIdx].SubItems[0]; FDelphiInstallation.EnvironmentVariables.Add(LName, LValue); end; end; end; procedure TfrmDelphiLibraryHelper.SaveLibrary; var LLibrary: TStringList; LIdx: integer; begin LLibrary := TStringList.Create; try FModified := True; for LIdx := 0 to Pred(ListViewLibrary.Items.Count) do begin LLibrary.Add(ListViewLibrary.Items[LIdx].Caption); end; case FActiveDelphiLibrary of dlAndroid32: FDelphiInstallation.LibraryAndroid32 := LLibrary.Text; dlAndroid64: FDelphiInstallation.LibraryAndroid64 := LLibrary.Text; dlIOS32: FDelphiInstallation.LibraryIOS32 := LLibrary.Text; dlIOS64: FDelphiInstallation.LibraryIOS64 := LLibrary.Text; dlIOSimulator: FDelphiInstallation.LibraryIOSSimulator := LLibrary.Text; dlOSX32: FDelphiInstallation.LibraryOSX32 := LLibrary.Text; dlOSX64: FDelphiInstallation.LibraryOSX64 := LLibrary.Text; dlOSXARM64: FDelphiInstallation.LibraryOSXARM64 := LLibrary.Text; dlWin32: FDelphiInstallation.LibraryWin32 := LLibrary.Text; dlWin64: FDelphiInstallation.LibraryWin64 := LLibrary.Text; dlLinux64: FDelphiInstallation.LibraryLinux64 := LLibrary.Text; end; LoadLibrary; finally FreeAndNil(LLibrary); end; end; procedure TfrmDelphiLibraryHelper.LoadLibrary; var LLibrary: TStringList; LIdx: integer; LLibraryEntry, LLibraryPath: string; begin ListViewLibrary.Clear; if Assigned(FDelphiInstallation) then begin LLibrary := TStringList.Create; ListViewLibrary.Items.BeginUpdate; try FDelphiInstallation.LibraryPathType := FActiveLibraryPathType; case FActiveDelphiLibrary of dlAndroid32: LLibrary.Text := FDelphiInstallation.LibraryAndroid32; dlAndroid64: LLibrary.Text := FDelphiInstallation.LibraryAndroid64; dlIOS32: LLibrary.Text := FDelphiInstallation.LibraryIOS32; dlIOS64: LLibrary.Text := FDelphiInstallation.LibraryIOS64; dlIOSimulator: LLibrary.Text := FDelphiInstallation.LibraryIOSSimulator; dlOSX32: LLibrary.Text := FDelphiInstallation.LibraryOSX32; dlOSX64: LLibrary.Text := FDelphiInstallation.LibraryOSX64; dlOSXARM64: LLibrary.Text := FDelphiInstallation.LibraryOSXARM64; dlWin32: LLibrary.Text := FDelphiInstallation.LibraryWin32; dlWin64: LLibrary.Text := FDelphiInstallation.LibraryWin64; dlLinux64: LLibrary.Text := FDelphiInstallation.LibraryLinux64; end; for LIdx := 0 to Pred(LLibrary.Count) do begin LLibraryEntry := LLibrary[LIdx]; LLibraryPath := FDelphiInstallation.ExpandLibraryPath(LLibraryEntry, FActiveDelphiLibrary); if not DirectoryExists(LLibraryPath) then begin LLibraryPath := '*' + LLibraryPath; end; with ListViewLibrary.Items.Add do begin Caption := LLibraryEntry; SubItems.Add(LLibraryPath); end; end; finally FreeAndNil(LLibrary); ListViewLibrary.Items.EndUpdate; end; end; end; procedure TfrmDelphiLibraryHelper.TimerMainTimer(Sender: TObject); begin FDelphiIsRunning := Assigned(FLibraryHelper) and (FLibraryHelper.IsDelphiRunning); end; function TfrmDelphiLibraryHelper.ValidatePath(APath: string): Boolean; var LPath: string; begin Result := False; LPath := APath; if Trim(LPath) <> '' then begin LPath := FDelphiInstallation.ExpandLibraryPath(LPath, FActiveDelphiLibrary); Result := DirectoryExists(LPath); end; end; end.
unit TpComponentProperty; interface uses Classes, Controls, TypInfo, dcsystem, dcdsgnstuff, dcdsgnutil, ThComponentIterator, TpModule; type TTpComponentProperty = class(TDCDsgnComponentProperty) private Proc: TGetStrProc; protected procedure EnumModuleComps(inModule: TTpModule); procedure FindModules(inContainer: TWinControl); public procedure GetValues(Proc: TGetStrProc);override; end; procedure RegisterComponentProperty; implementation procedure RegisterComponentProperty; begin RegisterPropertyEditor(TypeInfo(TComponent), nil, '', TTpComponentProperty); end; { TTpComponentProperty } procedure TTpComponentProperty.EnumModuleComps(inModule: TTpModule); begin CompNamesToProc(inModule.ModuleForm, Designer.Root, GetTypeData(GetPropType), Proc); end; procedure TTpComponentProperty.FindModules(inContainer: TWinControl); begin with TThComponentIterator.Create(inContainer) do try while Next do begin if (Component is TTpModule) then EnumModuleComps(TTpModule(Component)); if (Component is TWinControl) then FindModules(TWinControl(Component)); end; finally Free; end; end; procedure TTpComponentProperty.GetValues(Proc: TGetStrProc); begin inherited; Self.Proc := Proc; FindModules(TWinControl(Designer.Root)); end; { procedure TDCDsgnComponentProperty.SetValue(const Value:string); var Component:TComponent; begin if Value='' then Component:=nil else begin Component:=Designer.GetComponent(Value); if not (Component is GetTypeData(GetPropType)^.ClassType) then raise EPropertyError.Create(SInvalidPropertyValue); end; SetOrdValue(LongInt(Component)); end; } end.
unit ufTarefa3; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls,controller.Factory, Data.DB; type TfTarefa3 = class(TForm) pnPrincipal: TPanel; pnTotais: TPanel; pnValoresProjeto: TPanel; grdValoresProjeto: TDBGrid; lblValoresProjeto: TLabel; btnObterTotal: TButton; edtTotal: TEdit; lblTotal: TLabel; lblTotalDivisoes: TLabel; btnObterTotalDivisoes: TButton; edtTotalDivisoes: TEdit; btnFechar: TButton; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure btnObterTotalClick(Sender: TObject); procedure btnObterTotalDivisoesClick(Sender: TObject); procedure btnFecharClick(Sender: TObject); private FDataSource: TDataSource; FClientDataSet: TClientDataSet; procedure ExibirValores; procedure ObterTotal; procedure ObterTotalDivisoes; public destructor Destroy;override; end; implementation {$R *.dfm} uses ufPrincipal; procedure TfTarefa3.btnFecharClick(Sender: TObject); begin Close; end; procedure TfTarefa3.btnObterTotalClick(Sender: TObject); begin ObterTotal; end; procedure TfTarefa3.btnObterTotalDivisoesClick(Sender: TObject); begin ObterTotalDivisoes; end; destructor TfTarefa3.Destroy; begin FClientDataSet.Destroy; FDataSource.Destroy; inherited; end; procedure TfTarefa3.ExibirValores; begin TControllerFactory.Novo.ProjetoController.RetornarDataSet(FClientDataSet); FDataSource.DataSet := FClientDataSet; grdValoresProjeto.DataSource := FDataSource; grdValoresProjeto.Columns[0].FieldName := 'IdProjeto'; grdValoresProjeto.Columns[1].FieldName := 'NomeProjeto'; grdValoresProjeto.Columns[2].FieldName := 'Valor'; end; procedure TfTarefa3.FormClose(Sender: TObject; var Action: TCloseAction); begin TfPrincipal(Owner).VariableClear(Self); Action := caFree; end; procedure TfTarefa3.FormCreate(Sender: TObject); begin FClientDataSet := TClientDataSet.Create(nil); FDataSource := TDataSource.Create(nil); ExibirValores; end; procedure TfTarefa3.ObterTotal; begin EdtTotal.Text := FormatFloat( ',0.00' ,TControllerFactory.Novo.ProjetoController.ObterTotal(FClientDataSet)); end; procedure TfTarefa3.ObterTotalDivisoes; begin edtTotalDivisoes.Text := CurrToStr(TControllerFactory.Novo.ProjetoController.ObterTotalDivisoes(FClientDataSet)); end; end.
// Copyright (c) 2009, ConTEXT Project Ltd // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. unit uScrollListBox; interface {$I ConTEXT.inc} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ComCtrls, StdCtrls, uCommon; type THScrollListBox = class(TListBox) private MaxExtent: integer; { maximum length of the strings in the listbox (in pixel) } function GetStringExtent( s: string ): integer; protected procedure OnCustomDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); public constructor Create( AOwner: TComponent ); override; function InsertString(Index:integer; s:string; Data:TObject):integer; function AddString(s:string; Data:TObject):integer; procedure DeleteString(i:integer); override; procedure ClearList; procedure AdjustWidth; published end; TFileData = record FileName :string[255]; IsDirectory :boolean; Icon :TBitmap; end; pTFileData = ^TFileData; implementation //////////////////////////////////////////////////////////////////////////////////////////// // THScrollListBox //////////////////////////////////////////////////////////////////////////////////////////// constructor THScrollListBox.Create( AOwner: TComponent ); begin inherited Create( AOwner ); OnDrawItem:=OnCustomDrawItem; MaxExtent := 0; end; function THScrollListBox.GetStringExtent( s: string ): integer; var dwExtent: DWORD; hDCListBox: HDC; hFontOld, hFontNew: HFONT; tm: TTextMetric; Size: TSize; begin hDCListBox := GetDC( Handle ); hFontNew := SendMessage( Handle, WM_GETFONT, 0, 0 ); hFontOld := SelectObject( hDCListBox, hFontNew ); GetTextMetrics( hDCListBox, tm ); { the following two lines should be modified for Delphi 1.0: call GetTextExtent } GetTextExtentPoint32( hDCListBox, PChar(s), Length(s), Size ); dwExtent := Size.cx + tm.tmAveCharWidth; SelectObject( hDCListBox, hFontOld ); ReleaseDC( Handle, hDCListBox ); GetStringExtent := LOWORD( dwExtent ); end; procedure THScrollListBox.OnCustomDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var bmp :TBitmap; ofs :Integer; rec :pTFileData; begin bmp:=nil; with Canvas do begin FillRect(Rect); ofs:=2; rec:=pTFileData(Items.Objects[Index]); if Assigned(rec^.Icon) then bmp:=rec^.Icon; if (bmp<>nil) then begin BrushCopy(Bounds(Rect.Left + 2, Rect.Top+1, bmp.Width, bmp.Height), bmp, Bounds(0, 0, bmp.Width, bmp.Height), BMP_MASK); ofs:=bmp.width+6; end; TextOut(Rect.Left+ofs,Rect.Top+2, Items[Index]) end; end; function THScrollListBox.InsertString(Index:integer; s:string; Data:TObject):integer; var StrExtent: integer; begin StrExtent := GetStringExtent( s ); if StrExtent > MaxExtent then begin MaxExtent := StrExtent; SendMessage( Handle, LB_SETHORIZONTALEXTENT, MaxExtent, 0 ); end; { adds the string to the listbox } Items.InsertObject(Index, s, Data); result:=Index; end; function THScrollListBox.AddString(s:string; Data:TObject):integer; begin result:=InsertString(Items.Count, s, Data); end; procedure THScrollListBox.DeleteString(i:integer); begin Items.Delete(i); AdjustWidth; end; procedure THScrollListBox.ClearList; begin MaxExtent := 0; SendMessage( Handle, LB_SETHORIZONTALEXTENT, 0, 0 ); { scrolls the listbox to the left } SendMessage( Handle, WM_HSCROLL, SB_TOP, 0 ); { clears the listbox } Items.Clear; AdjustWidth; end; procedure THScrollListBox.AdjustWidth; var i :integer; StrExtent :integer; begin SendMessage( Handle, WM_HSCROLL, SB_TOP, 0 ); MaxExtent:=0; i:=0; while (i<Items.Count) do begin StrExtent:=GetStringExtent(Items[i]); if (StrExtent>MaxExtent) then MaxExtent := StrExtent; inc(i); end; SendMessage( Handle, LB_SETHORIZONTALEXTENT, MaxExtent, 0 ); end; end.
// // Generated by JavaToPas v1.5 20160510 - 150044 //////////////////////////////////////////////////////////////////////////////// unit java.util.concurrent.FutureTask; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, java.util.concurrent.Callable, java.util.concurrent.TimeUnit; type JFutureTask = interface; JFutureTaskClass = interface(JObjectClass) ['{CE920642-D867-4AD4-93F5-FB5DB4FF8BCF}'] function cancel(mayInterruptIfRunning : boolean) : boolean; cdecl; // (Z)Z A: $1 function get : JObject; cdecl; overload; // ()Ljava/lang/Object; A: $1 function get(timeout : Int64; &unit : JTimeUnit) : JObject; cdecl; overload;// (JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object; A: $1 function init(callable : JCallable) : JFutureTask; cdecl; overload; // (Ljava/util/concurrent/Callable;)V A: $1 function init(runnable : JRunnable; result : JObject) : JFutureTask; cdecl; overload;// (Ljava/lang/Runnable;Ljava/lang/Object;)V A: $1 function isCancelled : boolean; cdecl; // ()Z A: $1 function isDone : boolean; cdecl; // ()Z A: $1 procedure run ; cdecl; // ()V A: $1 end; [JavaSignature('java/util/concurrent/FutureTask')] JFutureTask = interface(JObject) ['{C5DC6C8D-FA7F-474A-A886-AC7825D03B51}'] function cancel(mayInterruptIfRunning : boolean) : boolean; cdecl; // (Z)Z A: $1 function get : JObject; cdecl; overload; // ()Ljava/lang/Object; A: $1 function get(timeout : Int64; &unit : JTimeUnit) : JObject; cdecl; overload;// (JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object; A: $1 function isCancelled : boolean; cdecl; // ()Z A: $1 function isDone : boolean; cdecl; // ()Z A: $1 procedure run ; cdecl; // ()V A: $1 end; TJFutureTask = class(TJavaGenericImport<JFutureTaskClass, JFutureTask>) end; implementation end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Build mesh objects. How often do you miss a BuildSphereMesh function for testing or editors? Well this unit is intended to solve that problem. We want fast, flexible functions with lots of options... } unit VXS.MeshBuilder; interface uses System.SysUtils, System.Classes, VXS.Scene, VXS.VectorFileObjects, VXS.VectorTypes, VXS.VectorGeometry, VXS.VectorLists; procedure BuildCube(Mesh: TVXMeshObject; Position, Scale: TAffineVector); procedure BuildCylinder(Mesh: TVXMeshObject; Position, Scale: TAffineVector; Slices: Integer); procedure BuildCylinder2(Mesh: TVXMeshObject; Position, Scale: TAffineVector; TopRadius, BottomRadius, Height: single; Slices: Integer); // ---------------------------------------------------------------------------- implementation // ---------------------------------------------------------------------------- function VectorCombineWeighted(Position, Scale: TAffineVector; X, Y, Z: single) : TAffineVector; begin Result.X := Position.X + Scale.X * X; Result.Y := Position.Y + Scale.Y * Y; Result.Z := Position.Z + Scale.Z * Z; end; procedure BuildCube(Mesh: TVXMeshObject; Position, Scale: TAffineVector); var FGR: TFGVertexNormalTexIndexList; VertexOffset: Integer; NormalOffset: Integer; TextureOffset: Integer; begin // Vertexes VertexOffset := Mesh.Vertices.Add(VectorCombineWeighted(Position, Scale, 0.5, 0.5, 0.5)); Mesh.Vertices.Add(VectorCombineWeighted(Position, Scale, -0.5, 0.5, 0.5)); Mesh.Vertices.Add(VectorCombineWeighted(Position, Scale, 0.5, -0.5, 0.5)); Mesh.Vertices.Add(VectorCombineWeighted(Position, Scale, -0.5, -0.5, 0.5)); Mesh.Vertices.Add(VectorCombineWeighted(Position, Scale, 0.5, 0.5, -0.5)); Mesh.Vertices.Add(VectorCombineWeighted(Position, Scale, -0.5, 0.5, -0.5)); Mesh.Vertices.Add(VectorCombineWeighted(Position, Scale, 0.5, -0.5, -0.5)); Mesh.Vertices.Add(VectorCombineWeighted(Position, Scale, -0.5, -0.5, -0.5)); // Normals NormalOffset := Mesh.Normals.Add(AffineVectorMake(0, 0, 1)); Mesh.Normals.Add(AffineVectorMake(0, 0, -1)); Mesh.Normals.Add(AffineVectorMake(1, 0, 0)); Mesh.Normals.Add(AffineVectorMake(-1, 0, 0)); Mesh.Normals.Add(AffineVectorMake(0, 1, 0)); Mesh.Normals.Add(AffineVectorMake(0, -1, 0)); // Texture Coordinates TextureOffset := Mesh.TexCoords.Add(AffineVectorMake(1, 1, 1)); Mesh.TexCoords.Add(AffineVectorMake(0, 1, 1)); Mesh.TexCoords.Add(AffineVectorMake(1, 0, 1)); Mesh.TexCoords.Add(AffineVectorMake(0, 0, 1)); Mesh.TexCoords.Add(AffineVectorMake(1, 1, 0)); Mesh.TexCoords.Add(AffineVectorMake(0, 1, 0)); Mesh.TexCoords.Add(AffineVectorMake(1, 0, 0)); Mesh.TexCoords.Add(AffineVectorMake(0, 0, 0)); FGR := TFGVertexNormalTexIndexList.CreateOwned(Mesh.FaceGroups); FGR.Mode := fgmmTriangles; // front FGR.VertexIndices.Add(VertexOffset + 0, VertexOffset + 1, VertexOffset + 3); FGR.VertexIndices.Add(VertexOffset + 0, VertexOffset + 3, VertexOffset + 2); FGR.NormalIndices.Add(NormalOffset + 0, NormalOffset + 0, NormalOffset + 0); FGR.NormalIndices.Add(NormalOffset + 0, NormalOffset + 0, NormalOffset + 0); FGR.TexCoordIndices.Add(TextureOffset + 0, TextureOffset + 1, TextureOffset + 3); FGR.TexCoordIndices.Add(TextureOffset + 0, TextureOffset + 3, TextureOffset + 2); // back FGR.VertexIndices.Add(VertexOffset + 4, VertexOffset + 6, VertexOffset + 7); FGR.VertexIndices.Add(VertexOffset + 4, VertexOffset + 7, VertexOffset + 5); FGR.NormalIndices.Add(NormalOffset + 1, NormalOffset + 1, NormalOffset + 1); FGR.NormalIndices.Add(NormalOffset + 1, NormalOffset + 1, NormalOffset + 1); FGR.TexCoordIndices.Add(TextureOffset + 4, TextureOffset + 6, TextureOffset + 7); FGR.TexCoordIndices.Add(TextureOffset + 4, TextureOffset + 7, TextureOffset + 5); // right FGR.VertexIndices.Add(VertexOffset + 0, VertexOffset + 2, VertexOffset + 6); FGR.VertexIndices.Add(VertexOffset + 0, VertexOffset + 6, VertexOffset + 4); FGR.NormalIndices.Add(NormalOffset + 2, NormalOffset + 2, NormalOffset + 2); FGR.NormalIndices.Add(NormalOffset + 2, NormalOffset + 2, NormalOffset + 2); FGR.TexCoordIndices.Add(TextureOffset + 0, TextureOffset + 2, TextureOffset + 6); FGR.TexCoordIndices.Add(TextureOffset + 0, TextureOffset + 6, TextureOffset + 4); // left FGR.VertexIndices.Add(VertexOffset + 1, VertexOffset + 5, VertexOffset + 7); FGR.VertexIndices.Add(VertexOffset + 1, VertexOffset + 7, VertexOffset + 3); FGR.NormalIndices.Add(NormalOffset + 3, NormalOffset + 3, NormalOffset + 3); FGR.NormalIndices.Add(NormalOffset + 3, NormalOffset + 3, NormalOffset + 3); FGR.TexCoordIndices.Add(TextureOffset + 1, TextureOffset + 5, TextureOffset + 7); FGR.TexCoordIndices.Add(TextureOffset + 1, TextureOffset + 7, TextureOffset + 3); // top FGR.VertexIndices.Add(VertexOffset + 0, VertexOffset + 4, VertexOffset + 5); FGR.VertexIndices.Add(VertexOffset + 0, VertexOffset + 5, VertexOffset + 1); FGR.NormalIndices.Add(NormalOffset + 4, NormalOffset + 4, NormalOffset + 4); FGR.NormalIndices.Add(NormalOffset + 4, NormalOffset + 4, NormalOffset + 4); FGR.TexCoordIndices.Add(TextureOffset + 0, TextureOffset + 4, TextureOffset + 5); FGR.TexCoordIndices.Add(TextureOffset + 0, TextureOffset + 5, TextureOffset + 1); // bottom FGR.VertexIndices.Add(VertexOffset + 2, VertexOffset + 3, VertexOffset + 7); FGR.VertexIndices.Add(VertexOffset + 2, VertexOffset + 7, VertexOffset + 6); FGR.NormalIndices.Add(NormalOffset + 5, NormalOffset + 5, NormalOffset + 5); FGR.NormalIndices.Add(NormalOffset + 5, NormalOffset + 5, NormalOffset + 5); FGR.TexCoordIndices.Add(TextureOffset + 2, TextureOffset + 3, TextureOffset + 7); FGR.TexCoordIndices.Add(TextureOffset + 2, TextureOffset + 7, TextureOffset + 6); end; procedure BuildCylinder(Mesh: TVXMeshObject; Position, Scale: TAffineVector; Slices: Integer); var FGR: TFGVertexNormalTexIndexList; VertexOffset: Integer; NormalOffset: Integer; TextureOffset: Integer; Cosine, Sine: Array of single; xc, yc: Integer; begin If Slices < 3 then Exit; SetLength(Sine, Slices + 1); SetLength(Cosine, Slices + 1); PrepareSinCosCache(Sine, Cosine, 0, 360); VertexOffset := Mesh.Vertices.Count; NormalOffset := Mesh.Normals.Count; TextureOffset := Mesh.TexCoords.Count; For xc := 0 to Slices - 1 do begin Mesh.Vertices.Add(VectorCombineWeighted(Position, Scale, 0.5 * Cosine[xc], 0.5 * Sine[xc], 0.5)); Mesh.Vertices.Add(VectorCombineWeighted(Position, Scale, 0.5 * Cosine[xc], 0.5 * Sine[xc], -0.5)); // Normals Mesh.Normals.Add(AffineVectorMake(Cosine[xc], Sine[xc], 0)); // Texture Coordinates Mesh.TexCoords.Add(VectorCombineWeighted(Position, XYZVector, 0.5 * Cosine[xc], 0.5 * Sine[xc], 0.5)); Mesh.TexCoords.Add(VectorCombineWeighted(Position, XYZVector, 0.5 * Cosine[xc], 0.5 * Sine[xc], -0.5)); end; Mesh.Normals.Add(AffineVectorMake(0, 0, 1)); Mesh.Normals.Add(AffineVectorMake(0, 0, -1)); FGR := TFGVertexNormalTexIndexList.CreateOwned(Mesh.FaceGroups); FGR.Mode := fgmmTriangles; for xc := 0 to Slices - 1 do begin yc := xc + 1; If yc = Slices then yc := 0; FGR.VertexIndices.Add(VertexOffset + xc * 2, VertexOffset + xc * 2 + 1, VertexOffset + yc * 2 + 1); FGR.VertexIndices.Add(VertexOffset + xc * 2, VertexOffset + yc * 2 + 1, VertexOffset + yc * 2); FGR.NormalIndices.Add(NormalOffset + xc, NormalOffset + xc, NormalOffset + yc); FGR.NormalIndices.Add(NormalOffset + xc, NormalOffset + yc, NormalOffset + yc); FGR.TexCoordIndices.Add(TextureOffset + xc * 2, TextureOffset + xc * 2 + 1, TextureOffset + yc * 2 + 1); FGR.TexCoordIndices.Add(TextureOffset + xc * 2, TextureOffset + yc * 2 + 1, TextureOffset + yc * 2); end; for xc := 1 to Slices - 2 do begin yc := xc + 1; FGR.VertexIndices.Add(VertexOffset, VertexOffset + xc * 2, VertexOffset + yc * 2); FGR.VertexIndices.Add(VertexOffset + 1, VertexOffset + yc * 2 + 1, VertexOffset + xc * 2 + 1); FGR.NormalIndices.Add(NormalOffset + Slices, NormalOffset + Slices, NormalOffset + Slices); FGR.NormalIndices.Add(NormalOffset + Slices + 1, NormalOffset + Slices + 1, NormalOffset + Slices + 1); FGR.TexCoordIndices.Add(TextureOffset, TextureOffset + xc * 2, TextureOffset + yc * 2); FGR.TexCoordIndices.Add(TextureOffset + 1, TextureOffset + yc * 2 + 1, TextureOffset + xc * 2 + 1); end; end; procedure BuildCylinder2(Mesh: TVXMeshObject; Position, Scale: TAffineVector; TopRadius, BottomRadius, Height: single; Slices: Integer); var FGR: TFGVertexNormalTexIndexList; VertexOffset: Integer; NormalOffset: Integer; TextureOffset: Integer; Cosine, Sine: Array of single; xc, yc: Integer; begin If Slices < 3 then Exit; SetLength(Sine, Slices + 1); SetLength(Cosine, Slices + 1); PrepareSinCosCache(Sine, Cosine, 0, 360); VertexOffset := Mesh.Vertices.Count; NormalOffset := Mesh.Normals.Count; TextureOffset := Mesh.TexCoords.Count; for xc := 0 to Slices - 1 do Begin Mesh.Vertices.Add(VectorCombineWeighted(Position, Scale, TopRadius * 0.5 * Cosine[xc], TopRadius * 0.5 * Sine[xc], Height / 2)); Mesh.Vertices.Add(VectorCombineWeighted(Position, Scale, BottomRadius * 0.5 * Cosine[xc], BottomRadius * 0.5 * Sine[xc], -Height / 2)); // Normals Mesh.Normals.Add(AffineVectorMake(Cosine[xc], Sine[xc], 0)); // Texture Coordinates Mesh.TexCoords.Add(VectorCombineWeighted(Position, XYZVector, TopRadius * 0.5 * Cosine[xc], TopRadius * 0.5 * Sine[xc], Height / 2)); Mesh.TexCoords.Add(VectorCombineWeighted(Position, XYZVector, BottomRadius * 0.5 * Cosine[xc], BottomRadius * 0.5 * Sine[xc], -Height / 2)); end; Mesh.Normals.Add(AffineVectorMake(0, 0, 1)); Mesh.Normals.Add(AffineVectorMake(0, 0, -1)); FGR := TFGVertexNormalTexIndexList.CreateOwned(Mesh.FaceGroups); FGR.Mode := fgmmTriangles; for xc := 0 to Slices - 1 do begin yc := xc + 1; If yc = Slices then yc := 0; FGR.VertexIndices.Add(VertexOffset + xc * 2, VertexOffset + xc * 2 + 1, VertexOffset + yc * 2 + 1); FGR.VertexIndices.Add(VertexOffset + xc * 2, VertexOffset + yc * 2 + 1, VertexOffset + yc * 2); FGR.NormalIndices.Add(NormalOffset + xc, NormalOffset + xc, NormalOffset + yc); FGR.NormalIndices.Add(NormalOffset + xc, NormalOffset + yc, NormalOffset + yc); FGR.TexCoordIndices.Add(TextureOffset + xc * 2, TextureOffset + xc * 2 + 1, TextureOffset + yc * 2 + 1); FGR.TexCoordIndices.Add(TextureOffset + xc * 2, TextureOffset + yc * 2 + 1, TextureOffset + yc * 2); end; for xc := 1 to Slices - 2 do begin yc := xc + 1; FGR.VertexIndices.Add(VertexOffset, VertexOffset + xc * 2, VertexOffset + yc * 2); FGR.VertexIndices.Add(VertexOffset + 1, VertexOffset + yc * 2 + 1, VertexOffset + xc * 2 + 1); FGR.NormalIndices.Add(NormalOffset + Slices, NormalOffset + Slices, NormalOffset + Slices); FGR.NormalIndices.Add(NormalOffset + Slices + 1, NormalOffset + Slices + 1, NormalOffset + Slices + 1); FGR.TexCoordIndices.Add(TextureOffset, TextureOffset + xc * 2, TextureOffset + yc * 2); FGR.TexCoordIndices.Add(TextureOffset + 1, TextureOffset + yc * 2 + 1, TextureOffset + xc * 2 + 1); end; end; end.
unit ArtistsController; interface uses Generics.Collections, Aurelius.Engine.ObjectManager, Artist; type TArtistsController = class private FManager: TObjectManager; public constructor Create; destructor Destroy; override; procedure DeleteArtist(Artist: TArtist); function GetAllArtists: TList<TArtist>; end; implementation uses DBConnection; { TArtistController } constructor TArtistsController.Create; begin FManager := TDBConnection.GetInstance.CreateObjectManager; end; procedure TArtistsController.DeleteArtist(Artist: TArtist); begin if not FManager.IsAttached(Artist) then Artist := FManager.Find<TArtist>(Artist.Id); FManager.Remove(Artist); end; destructor TArtistsController.Destroy; begin FManager.Free; inherited; end; function TArtistsController.GetAllArtists: TList<TArtist>; begin FManager.Clear; Result := FManager.FindAll<TArtist>; end; end.
unit Produto.Controller; interface uses Produto.Controller.interf, Tipos.Controller.interf, Produto.Model.interf, System.SysUtils, TESTPRODUTO.Entidade.Model; type TProdutoController = class(TInterfacedObject, IProdutoController) private FProdutoModel: IProdutoModel; FRegistro: TTESTPRODUTO; public constructor Create; destructor Destroy; override; class function New: IProdutoController; function Incluir: IProdutoOperacaoIncluirController; function Alterar: IProdutoOperacaoAlterarController; function Excluir: IProdutoOperacaoExcluirController; function Duplicar: IProdutoOperacaoDuplicarController; function localizar(AValue: string): IProdutoController; function idProduto: string; function codigoSinapi: string; function descricao: string; function unidMedida: string; function origemPreco: string; function prMedio: string; function prMedioSinapi: string; end; implementation { TProdutoController } uses FacadeModel, ProdutoOperacaoIncluir.Controller, ProdutoOperacaoAlterar.Controller, ProdutoOperacaoDuplicar.Controller, ProdutoOperacaoExcluir.Controller; function TProdutoController.Alterar: IProdutoOperacaoAlterarController; begin Result := TProdutosOperacoesAlterarController.New .produtoModel(FProdutoModel) .produtoSelecionado(FRegistro); end; function TProdutoController.codigoSinapi: string; begin Result := FRegistro.CODIGO_SINAPI; end; constructor TProdutoController.Create; begin FProdutoModel := TFacadeModel.New.ModulosFacadeModel. estoqueFactoryModel.Produto; end; function TProdutoController.descricao: string; begin Result := FRegistro.descricao; end; destructor TProdutoController.Destroy; begin inherited; end; function TProdutoController.Duplicar: IProdutoOperacaoDuplicarController; begin Result := TProdutosOperacoesDuplicarController.New .produtoModel(FProdutoModel) .produtoSelecionado(FRegistro); end; function TProdutoController.Excluir: IProdutoOperacaoExcluirController; begin Result := TProdutoOperacaoExcluirController.New .produtoModel(FProdutoModel) .produtoSelecionado(FRegistro); end; function TProdutoController.idProduto: string; begin Result := IntToStr(FRegistro.idProduto); end; function TProdutoController.Incluir: IProdutoOperacaoIncluirController; begin Result := TProdutoOperacaoIncluirController.New .produtoModel(FProdutoModel); end; function TProdutoController.localizar(AValue: string): IProdutoController; begin Result := Self; FRegistro := FProdutoModel.DAO.FindWhere('CODIGO=' + QuotedStr(AValue), 'DESCRICAO').Items[0]; end; class function TProdutoController.New: IProdutoController; begin Result := Self.Create; end; function TProdutoController.origemPreco: string; begin Result := FRegistro.ORIGEM_PRECO; end; function TProdutoController.prMedio: string; begin Result := CurrToStr(FRegistro.prMedio); end; function TProdutoController.prMedioSinapi: string; begin Result := CurrToStr(FRegistro.PRMEDIO_SINAPI); end; function TProdutoController.unidMedida: string; begin Result := FRegistro.unidMedida; end; end.
unit EditUnitPackingFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, RzButton, ExtCtrls, RzPanel, StdCtrls, Mask, RzEdit, RzDBEdit, RzLabel, DBCtrls, DB, DBClient; type TfrmEditUnitPacking = class(TForm) RzPanel1: TRzPanel; btnSaveUnit: TRzBitBtn; btnCancelUnit: TRzBitBtn; RzLabel1: TRzLabel; RzDBEdit17: TRzDBEdit; RzLabel3: TRzLabel; RzDBEdit1: TRzDBEdit; RzDBEdit2: TRzDBEdit; RzLabel2: TRzLabel; DBCheckBox1: TDBCheckBox; cdsPackUnit: TClientDataSet; dsPackUnit: TDataSource; DBCheckBox2: TDBCheckBox; procedure btnCancelUnitClick(Sender: TObject); procedure btnSaveUnitClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private FPackUniUNI: integer; FPackUniCOD: integer; FPackPacName: string; procedure SetPackUniCOD(const Value: integer); procedure SetPackUniUNI(const Value: integer); procedure SetPackPacName(const Value: string); { Private declarations } public { Public declarations } property PackUniCOD : integer read FPackUniCOD write SetPackUniCOD; property PackUniUNI :integer read FPackUniUNI write SetPackUniUNI; property PackPacName : string read FPackPacName write SetPackPacName; end; var frmEditUnitPacking: TfrmEditUnitPacking; implementation uses CdeLIB, STDLIB; {$R *.dfm} { TfrmEditUnitPacking } procedure TfrmEditUnitPacking.SetPackUniCOD(const Value: integer); begin FPackUniCOD := Value; cdsPackUnit.Data := GetDataSet('select * from ICMTTPAC where PACCOD='+IntToStr(FPackUniCOD)); end; procedure TfrmEditUnitPacking.SetPackUniUNI(const Value: integer); begin FPackUniUNI := Value; end; procedure TfrmEditUnitPacking.btnCancelUnitClick(Sender: TObject); begin Close; end; procedure TfrmEditUnitPacking.btnSaveUnitClick(Sender: TObject); var IsNew : boolean; begin if cdsPackUnit.State in [dsinsert] then begin IsNew :=true; cdsPackUnit.FieldByName('PACUNI').AsInteger :=FPackUniUNI; if cdsPackUnit.FieldByName('PACFLG').IsNull then cdsPackUnit.FieldByName('PACFLG').AsString:='N'; if cdsPackUnit.FieldByName('PACACT').IsNull then cdsPackUnit.FieldByName('PACACT').AsString:='A'; // cdsPackUnit.FieldByName('PACCOD').AsInteger :=getCdeRunWithLen(FPackUniUNI,'SETTING','RUNNING','PACCOD','CDENM1'); cdsPackUnit.FieldByName('PACCOD').AsInteger :=getPackingRunWithLen(FPackUniUNI,'SETTING','RUNNING','PACCOD','CDENM1',FPackUniUNI); cdsPackUnit.FieldByName('PACCDE').AsInteger :=getPackingRunWithLen(FPackUniUNI,'SETTING','RUNNING','PACCOD','CDENM1',FPackUniUNI); // cdsPackUnit.FieldByName('PACCDE').AsString :=getPackingRunWithLenFormat(FPackUniUNI,'SETTING','RUNNING','PACCOD','CDENM1',FPackUniUNI); if cdsPackUnit.FieldByName('PACFLG').AsString<>'Y' then cdsPackUnit.FieldByName('PACNAM').AsString :=cdsPackUnit.FieldByName('PACNAM').AsString+'(x'+cdsPackUnit.FieldByName('PACRAT').AsString+')'; end; if cdsPackUnit.State in [dsedit,dsinsert] then cdsPackUnit.Post; if cdsPackUnit.ChangeCount>0 then begin UpdateDataset(cdsPackUnit,'select * from ICMTTPAC where PACCOD='+IntToStr(FPackUniCOD)) ; if IsNew then //setCdeRun('SETTING','RUNNING','PACCOD','CDENM1'); setPackingRun(FPackUniUNI); end; FPackUniCOD := cdsPackUnit.FieldByName('PACCOD').AsInteger; Close; end; procedure TfrmEditUnitPacking.SetPackPacName(const Value: string); begin FPackPacName := Value; end; procedure TfrmEditUnitPacking.FormShow(Sender: TObject); begin if trim(FPackPacName)<>'' then begin if not (cdsPackUnit.State in [dsinsert,dsedit]) then cdsPackUnit.Edit; cdsPackUnit.FieldByName('PACNAM').AsString :=FPackPacName; end; end; procedure TfrmEditUnitPacking.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key=VK_ESCAPE then btnCancelUnitClick(nil); if Key=VK_F11 then btnSaveUnitClick(nil); end; end.
unit uPlotInterpolator; { ***************************************************************************** * This file is part of Multiple Acronym Math and Audio Plot - MAAPlot * * * * See the file COPYING. * * for details about the copyright. * * * * 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. * * * * MAAplot for Lazarus/fpc * * (C) 2014 Stefan Junghans * ***************************************************************************** } {$mode objfpc}{$H+} interface uses Classes, SysUtils, FPimage, uPlotAxis, uPlotDataTypes, uPlotClass, uPlotUtils, math, Graphics, uPlotStyles; type TFPColorPoint = record Pt: TPoint; FPColor: TFPColor; end; PXYPixelLine = ^TXYPixelLine; TXYPixelLine = array of TFPColorPoint; TExtendedArray = array of Extended; TIpolMode = (imStep, imLinear); TIpolAxisMode = (iamXonly, iamXY); // TODO THiddenPixelMode = (hpmMax, hpmMin, hpmAverage); TCalcAxis = (caX, caY, caZ); TCalcAxes = set of TCalcAxis; THiddenCalcFunction = function(ALine: TExtendedArray; AAxis: TPlotAxisBase): Extended of object; TIpolFunction = function(AScreenPoint: TPoint; AColorValueStart: Extended; AColorValueEnd: Extended; IsLastPoint: Boolean; var AXYPixelLine: TXYPixelLine): Integer of object; { TInterpolator } TInterpolator = class private protected FOwnerSeries: TPlotSeriesBase; public constructor Create(AOwnerSeries: TPlotSeriesBase); virtual; destructor Destroy; override; end; { TInterpolator_Pixel } { Notes: - the pixel interpolator calculates the screen pixels from XYValues - it avoids duplicate pixel drawing if we have more than 1 point per screen pixel - it fills the gaps between Screen points } { TInterpolator_PixelXY } // calculation based on DataImage for fast series TInterpolator_PixelXY = class(TInterpolator) // coloredaxis and axes from ownerseries // axes in CoordAxes are respected, rest is not calcualted private // Z axis disregarded, as PixelXY only takes TXYLines FIpolFunction: TIpolFunction; // either use _Ipol or _IpolStep FIpolMode: TIpolMode; FIpolAxisMode: TIpolAxisMode; // interpolate only X coordinates or XY coordinates FHiddenPixelMode: THiddenPixelMode; // max, min or mean of pixels plottet to the same screen coordinate FCalcAxes: TCalcAxes; // simplify this FHiddenCalcFunc: THiddenCalcFunction; FHiddenLine: TExtendedArray; FLastHiddenPoint: TPoint; //FHideStartIndex: Integer; FXaxis, FYaxis, FZaxis, FColoredAxis: TPlotAxisBase; FColoredDimension: Integer; FZeroYcoord: Boolean; function GetCalcAxes: TCalcAxes; function GetHiddenPixelMode: THiddenPixelMode; function GetIpolAxisMode: TIpolAxisMode; function GetIpolMode: TIpolMode; procedure SetCalcAxes(AValue: TCalcAxes); procedure SetHiddenPixelMode(AValue: THiddenPixelMode); procedure SetIpolAxisMode(AValue: TIpolAxisMode); procedure SetIpolMode(AValue: TIpolMode); procedure SetZeroYcoord(AValue: Boolean); procedure _Hide(AScreenPoint: TPoint; AColorValue: Extended); procedure _UnHide(out AScreenPoint: TPoint; out AColorValue: Extended); function _Ipol(AScreenPoint: TPoint; AColorValueStart: Extended; AColorValueEnd: Extended; IsLastPoint: Boolean; var AXYPixelLine: TXYPixelLine): Integer; function _IpolStep(AScreenPoint: TPoint; AColorValueStart: Extended; AColorValueEnd: Extended; IsLastPoint: Boolean; var AXYPixelLine: TXYPixelLine): Integer; function _ColorValue2FPColor(AColorValue: Extended): TFPColor; // basic work done in AddGetPoints, see below function _AddGetPoints(AScreenPoint: TPoint; AColorValue: Extended; IsLastPoint: Boolean; out AXYPixelLine: TXYPixelLine): Integer; function _ResetGetPoints(out AXYPixelLine: TXYPixelLine): Integer; function _ValuesToScreenPoint(AXaxis, AYaxis, AZaxis: TPlotAxisBase; AXValue, AYValue, AZValue: Extended; out AScrPt: TPoint): Integer; virtual; protected function HiddenCalcMin(ALine: TExtendedArray; AAxis: TPlotAxisBase): Extended; function HiddenCalcMax(ALine: TExtendedArray; AAxis: TPlotAxisBase): Extended; function HiddenCalcMean(ALine: TExtendedArray; AAxis: TPlotAxisBase): Extended; public constructor Create(AOwnerSeries: TPlotSeriesBase); override; destructor Destroy; override; function Interpolate(out AXYPixelLine: TXYPixelLine; Aline: TXYLine): Integer; // main routine called from outside property CalcAxes: TCalcAxes read GetCalcAxes write SetCalcAxes; // needed ? or get from series ? --> try to remove this property HiddenPixelMode: THiddenPixelMode read GetHiddenPixelMode write SetHiddenPixelMode; property IpolAxisMode: TIpolAxisMode read GetIpolAxisMode write SetIpolAxisMode; property IpolMode: TIpolMode read GetIpolMode write SetIpolMode; property ZeroYcoord: Boolean read FZeroYcoord write SetZeroYcoord; // only used for colored spectrograms (2DWF waterfall) end; { TInterpolator_PixelXY_PlotRect } // calculation based on PlotImage for slow standard 2D and 3D series TInterpolator_PixelXY_PlotRect = class(TInterpolator_PixelXY) private function _ValuesToScreenPoint(AXaxis, AYaxis, AZaxis: TPlotAxisBase; AXValue, AYValue, AZValue: Extended; out AScrPt: TPoint): Integer; override; protected public end; implementation uses uPlotSeries; { TInterpolator_PixelXY_PlotRect } function TInterpolator_PixelXY_PlotRect._ValuesToScreenPoint(AXaxis, AYaxis, AZaxis: TPlotAxisBase; AXValue, AYValue, AZValue: Extended; out AScrPt: TPoint ): Integer; begin Result := XYZToScreen(AXaxis, AYaxis, AZaxis, AXValue, AYValue, AZValue, AScrPt); end; { TInterpolator_Pixel } function TInterpolator_PixelXY.GetIpolAxisMode: TIpolAxisMode; begin Result := FIpolAxisMode; end; function TInterpolator_PixelXY.GetIpolMode: TIpolMode; begin Result := FIpolMode; end; procedure TInterpolator_PixelXY.SetCalcAxes(AValue: TCalcAxes); begin IF FCalcAxes = AValue THEN exit; FCalcAxes := AValue; end; function TInterpolator_PixelXY.GetHiddenPixelMode: THiddenPixelMode; begin Result := FHiddenPixelMode; end; function TInterpolator_PixelXY.GetCalcAxes: TCalcAxes; begin Result := FCalcAxes; end; procedure TInterpolator_PixelXY.SetHiddenPixelMode(AValue: THiddenPixelMode); begin IF FHiddenPixelMode = AValue THEN exit; FHiddenPixelMode := AValue; case FHiddenPixelMode of hpmMin: FHiddenCalcFunc := @HiddenCalcMin; hpmMax: FHiddenCalcFunc := @HiddenCalcMax; hpmAverage: FHiddenCalcFunc := @HiddenCalcMean; end; end; procedure TInterpolator_PixelXY.SetIpolAxisMode(AValue: TIpolAxisMode); begin IF FIpolAxisMode = AValue THEN exit; FIpolAxisMode := AValue; end; procedure TInterpolator_PixelXY.SetIpolMode(AValue: TIpolMode); begin IF FIpolMode = AValue THEN exit; FIpolMode := AValue; case FIpolMode of imStep: FIpolFunction := @_IpolStep; imLinear: FIpolFunction := @_Ipol; end; end; procedure TInterpolator_PixelXY.SetZeroYcoord(AValue: Boolean); begin if FZeroYcoord=AValue then Exit; FZeroYcoord:=AValue; end; procedure TInterpolator_PixelXY._Hide(AScreenPoint: TPoint; AColorValue: Extended); begin FLastHiddenPoint := AScreenPoint; if FColoredAxis <> nil then begin setlength(FHiddenLine, length(FHiddenLine)+1); FHiddenLine[length(FHiddenLine)-1] := TPlotAxis(FColoredAxis).ReCalcValue(AColorValue); end else begin setlength(FHiddenLine, 1); FHiddenLine[0] := 0; end; end; procedure TInterpolator_PixelXY._UnHide(out AScreenPoint: TPoint; out AColorValue: Extended); begin if (length(FHiddenLine) < 1) then begin AScreenPoint.X := c_INVALIDCOORDINATE; AScreenPoint.Y := c_INVALIDCOORDINATE; AColorValue := 0; end else begin AScreenPoint := FLastHiddenPoint; if (FColoredAxis <> nil) then AColorValue := FHiddenCalcFunc(FHiddenLine, FColoredAxis) else AColorValue:=0; end; setlength(FHiddenLine, 0); end; function TInterpolator_PixelXY._Ipol(AScreenPoint: TPoint; AColorValueStart: Extended; AColorValueEnd: Extended; IsLastPoint: Boolean; var AXYPixelLine: TXYPixelLine ): Integer; var dx,dy: Integer; vXleading: Boolean; vLoop: Integer; vX1, vX2: Integer; vY1, vY2: Integer; dCol: Extended; //vPoint: TPoint; vSpan: Integer; vDirection: Integer; // interpolates from lowX to highX (direction +1) or inverse (direction -1) vIndex: Integer; begin if length(AXYPixelLine) <> 1 then begin Result := 0; exit; end; vDirection:=1; // AXYPixelLine has 1 element which is the start point for Ipol; // Parameters AScreenPoint and AColorValue are the endpoints; // TODO: correct log color ipol !?? dx := (AScreenPoint.X - AXYPixelLine[0].Pt.X); dy := (AScreenPoint.Y - AXYPixelLine[0].Pt.Y); dCol := AColorValueEnd - AColorValueStart; IF (dx = 0) and (dy = 0 ) THEN begin Result := 1; exit; end; IF ( abs(dx) > abs(dy) ) THEN vXleading := TRUE ELSE vXleading := FALSE; IF (IpolAxisMode = iamXonly) THEN begin vXleading:=TRUE; if dx = 0 then begin Result := 1; exit; end; end; IF vXleading THEN BEGIN IF AXYPixelLine[0].Pt.X > AScreenPoint.X THEN begin vX1 := AScreenPoint.X; vY1 := AScreenPoint.Y; vX2 := AXYPixelLine[0].Pt.X; vDirection:=-1; AColorValueStart:=AColorValueEnd; dCol := -dCol; end else begin vX1 := AXYPixelLine[0].Pt.X; vY1 := AXYPixelLine[0].Pt.Y; vX2 := AScreenPoint.X; end; vSpan := vX2-vX1; setlength(AXYPixelLine, length(AXYPixelLine) + vSpan + 1); for vLoop := vX1 to vX2 do begin vY2 := trunc(dy/dx * (vLoop-vX1)) + vY1; // trunc(dy/dx * (vLoop-vX1) + 1) + vY1; why +1 ???????????????? also in Lazarus bug ? AXYPixelLine[vLoop-vX1+1].Pt.X := vLoop; AXYPixelLine[vLoop-vX1+1].Pt.Y := vY2; AXYPixelLine[vLoop-vX1+1].FPColor := _ColorValue2FPColor( ((vLoop-vX1)/vSpan * dCol) + AColorValueStart ); end; END ELSE BEGIN IF AXYPixelLine[0].Pt.Y > AScreenPoint.Y THEN begin vY1 := AScreenPoint.Y; vX1 := AScreenPoint.X; vY2 := AXYPixelLine[0].Pt.Y; vDirection:=-1; AColorValueStart:=AColorValueEnd; dCol := -dCol; end else begin vY1 := AXYPixelLine[0].Pt.Y; vX1 := AXYPixelLine[0].Pt.X; vY2 := AScreenPoint.Y; end; vSpan := vY2-vY1; setlength(AXYPixelLine, length(AXYPixelLine) + vSpan + 1); for vLoop := vY1 to vY2 do begin vX2 := trunc(dx/dy * (vLoop-vY1)) + vX1; if (vDirection > 0) then vIndex := vLoop-vY1+1 else vIndex := vY2 - vLoop + 1; // fill forward AXYPixelLine[vIndex].Pt.X := vX2; AXYPixelLine[vIndex].Pt.Y := vLoop; AXYPixelLine[vIndex].FPColor := _ColorValue2FPColor( ((vLoop-vY1)/vSpan * dCol) + AColorValueStart ); end; END; if (not IsLastPoint) then setlength(AXYPixelLine, length(AXYPixelLine)-1); // delete last point Result := length(AXYPixelLine); end; function TInterpolator_PixelXY._IpolStep(AScreenPoint: TPoint; AColorValueStart: Extended; AColorValueEnd: Extended; IsLastPoint: Boolean; var AXYPixelLine: TXYPixelLine): Integer; var dx,dy: Integer; vXleading: Boolean; vLoop: Integer; vX1, vX2, vX, vmid: Integer; vY1, vY2, vY: Integer; dCol, vColTemp: Extended; //vPoint: TPoint; vSpan: Integer; vDirection: Integer; // interpolates from lowX to highX (direction +1) or inverse (direction -1) vIndex, vIndexbase: Integer; begin if length(AXYPixelLine) <> 1 then begin Result := 0; exit; end; vDirection:=1; // AXYPixelLine has 1 element which is the start point for Ipol; // Parameters AScreenPoint and AColorValue are the endpoints; // TODO: correct log color ipol !?? dx := (AScreenPoint.X - AXYPixelLine[0].Pt.X); dy := (AScreenPoint.Y - AXYPixelLine[0].Pt.Y); dCol := AColorValueEnd - AColorValueStart; IF (dx = 0) and (dy = 0 ) THEN begin Result := 1; exit; end; IF ( abs(dx) > abs(dy) ) THEN vXleading := TRUE ELSE vXleading := FALSE; IF (IpolAxisMode = iamXonly) THEN begin vXleading:=TRUE; if dx = 0 then begin Result := 1; exit; end; end; // debug if (dx > 3) then vXleading:=true; //if (dy > 0) then vXleading:=false; IF vXleading THEN BEGIN IF AXYPixelLine[0].Pt.X > AScreenPoint.X THEN begin vX1 := AScreenPoint.X; vY1 := AScreenPoint.Y; vX2 := AXYPixelLine[0].Pt.X; vDirection:=-1; vColTemp:=AColorValueStart; AColorValueStart:=AColorValueEnd; AColorValueEnd:=vColTemp; dCol := -dCol; vY2 := AXYPixelLine[0].Pt.Y; end else begin vX1 := AXYPixelLine[0].Pt.X; vY1 := AXYPixelLine[0].Pt.Y; vX2 := AScreenPoint.X; vY2 := AScreenPoint.Y; end; vSpan := vX2-vX1; vmid := vX1 + ((vX2-vX1) DIV 2); setlength(AXYPixelLine, length(AXYPixelLine) + vSpan + 1); for vLoop := vX1 to vX2 do begin if (vLoop <= vmid) then vY := vY1 else vY := vY2; AXYPixelLine[vLoop-vX1+1].Pt.X := vLoop; AXYPixelLine[vLoop-vX1+1].Pt.Y := vY; //vY2; AXYPixelLine[vLoop-vX1+1].FPColor := _ColorValue2FPColor( ((vLoop-vX1)/vSpan * dCol) + AColorValueStart ); end; // add vertical line (X indices not in order !) vSpan := abs(dy)-1; vIndexbase:=length(AXYPixelLine); setlength(AXYPixelLine, length(AXYPixelLine) + vSpan ); for vLoop := min(vY1, vY2)+1 to max(vY1,vY2)-1 do begin AXYPixelLine[vIndexbase + vLoop-min(vY1, vY2)-1].Pt.X := vmid; AXYPixelLine[vIndexbase + vLoop-min(vY1, vY2)-1].Pt.Y := vLoop; //vY2; AXYPixelLine[vIndexbase + vLoop-min(vY1, vY2)-1].FPColor := _ColorValue2FPColor( (0.5 * dCol) + AColorValueStart ) end; END ELSE BEGIN IF AXYPixelLine[0].Pt.Y > AScreenPoint.Y THEN begin vY1 := AScreenPoint.Y; vX1 := AScreenPoint.X; vY2 := AXYPixelLine[0].Pt.Y; vDirection:=-1; vColTemp:=AColorValueStart; AColorValueStart:=AColorValueEnd; AColorValueEnd:=vColTemp; dCol := -dCol; vX2 := AXYPixelLine[0].Pt.X; end else begin vY1 := AXYPixelLine[0].Pt.Y; vX1 := AXYPixelLine[0].Pt.X; vY2 := AScreenPoint.Y; vX2 := AScreenPoint.X; end; vSpan := vY2-vY1; vmid := vY1 + ((vY2-vY1) DIV 2); setlength(AXYPixelLine, length(AXYPixelLine) + vSpan + 1); for vLoop := vY1 to vY2 do begin if (vLoop <= vmid) then vX := vX1 else vX := vX2; if (vDirection > 0) then vIndex := vLoop-vY1+1 else vIndex := vY2 - vLoop + 1; // fill forward AXYPixelLine[vIndex].Pt.X := vX; //vX2; AXYPixelLine[vIndex].Pt.Y := vLoop; AXYPixelLine[vIndex].FPColor := _ColorValue2FPColor( ((vLoop-vY1)/vSpan * dCol) + AColorValueStart ); end; // add horizontal line (X indices not in order !) vSpan := abs(dx)-1; vIndexbase:=length(AXYPixelLine); setlength(AXYPixelLine, length(AXYPixelLine) + vSpan ); for vLoop := min(vX1, vX2)+1 to max(vX1,vX2)-1 do begin AXYPixelLine[vIndexbase + vLoop-min(vX1, vX2)-1].Pt.X := vLoop; AXYPixelLine[vIndexbase + vLoop-min(vX1, vX2)-1].Pt.Y := vmid; //vY2; AXYPixelLine[vIndexbase + vLoop-min(vX1, vX2)-1].FPColor := _ColorValue2FPColor( (0.5 * dCol) + AColorValueStart ); end; END; if (not IsLastPoint) then setlength(AXYPixelLine, length(AXYPixelLine)-1); // delete last point Result := length(AXYPixelLine); end; function TInterpolator_PixelXY._ColorValue2FPColor(AColorValue: Extended ): TFPColor; begin if (FColoredAxis <> nil) then Result := TPlotAxis(FColoredAxis).ValueFPColor[AColorValue] else Result := TColorToFPColor(TPlotStyle(FOwnerSeries.Style).Color); Result.alpha := TPlotSeries(FOwnerSeries).TransParency; if (FOwnerSeries is TXYWFPlotSeries) and (AColorValue < TXYWFPlotSeries(FOwnerSeries).YThreshold) then // TODO: all series Result.alpha := alphaTransparent; end; function TInterpolator_PixelXY._AddGetPoints(AScreenPoint: TPoint; AColorValue: Extended; IsLastPoint: Boolean; out AXYPixelLine: TXYPixelLine ): Integer; var dx, dy: Integer; vColorValue: Extended; begin { Basic function as follows: a) when data points have higher densitiy than pixels (i.e. when these are plotted on top of each other) - When a next point for plotting has same coordinates than the recent one, it will be "hidden" --> _Hide - When the last point is reached or the coordinate of the next point is now different we call _Unhide - _UnHide will use @FHiddenCalcFunc to return one point which is maximum, minimum or mean of the formerly hidden points b) when distance bewteen points is > 1 pixel - @FIpolFunction is called to interpolate the pixels Therefore this function returns - 0 points when the actual point needs to be hidden - 1 point if the coordinate changed by 1 pixel and the latest hidden points are to be drawn now - n points when interpolation occured } Result := 0; setlength(AXYPixelLine, 0); dx := AScreenPoint.X - FLastHiddenPoint.X; dy := AScreenPoint.Y - FLastHiddenPoint.Y; if length(FHiddenLine) = 0 then begin // first point _Hide(AScreenPoint, AColorValue); if IsLastPoint then begin setlength(AXYPixelLine, 1); _UnHide(AXYPixelLine[0].Pt, vColorValue); AXYPixelLine[0].FPColor := _ColorValue2FPColor(vColorValue); end; end else // add hidden if (dx = 0) and (dy = 0) THEN begin _Hide(AScreenPoint, AColorValue); if IsLastPoint then begin setlength(AXYPixelLine, 1); _UnHide(AXYPixelLine[0].Pt, vColorValue); AXYPixelLine[0].FPColor := _ColorValue2FPColor(vColorValue); end; end else begin // unhide, no ipol, distance <=1 setlength(AXYPixelLine, 1); _UnHide(AXYPixelLine[0].Pt, vColorValue); AXYPixelLine[0].FPColor := _ColorValue2FPColor(vColorValue); if (abs(dx) <= 1) and (abs(dy) <= 1) THEN begin end else begin // do ipol Result := FIpolFunction(AScreenPoint, vColorValue, AColorValue, IsLastPoint, AXYPixelLine); end; if (not IsLastPoint) then _Hide(AScreenPoint, AColorValue); end; Result := length(AXYPixelLine); end; function TInterpolator_PixelXY._ResetGetPoints(out AXYPixelLine: TXYPixelLine ): Integer; var vColorValue: Extended; begin if length(FHiddenLine) = 0 then begin setlength(AXYPixelLine, 0); end else begin setlength(AXYPixelLine, 1); _UnHide(AXYPixelLine[0].Pt, vColorValue); AXYPixelLine[0].FPColor := _ColorValue2FPColor(vColorValue); end; Result := length(AXYPixelLine); end; function TInterpolator_PixelXY._ValuesToScreenPoint(AXaxis, AYaxis, AZaxis: TPlotAxisBase; AXValue, AYValue, AZValue: Extended; out AScrPt: TPoint ): Integer; begin Result := XYZToDataImage(AXaxis, AYaxis, AZaxis, AXValue, AYValue, AZValue, AScrPt); end; function TInterpolator_PixelXY.HiddenCalcMin(ALine: TExtendedArray; AAxis: TPlotAxisBase): Extended; begin if (length(ALine) < 1) or (AAxis = nil) THEN BEGIN Result := 0; exit; end; Result := TPlotAxis(AAxis).ReCalcValueInverse( minvalue(ALine) ); end; function TInterpolator_PixelXY.HiddenCalcMax(ALine: TExtendedArray; AAxis: TPlotAxisBase): Extended; begin if (length(ALine) < 1) or (AAxis = nil) THEN BEGIN Result := 0; exit; end; Result := TPlotAxis(AAxis).ReCalcValueInverse( maxvalue(ALine) ); end; function TInterpolator_PixelXY.HiddenCalcMean(ALine: TExtendedArray; AAxis: TPlotAxisBase): Extended; begin if (length(ALine) < 1) or (AAxis = nil) THEN BEGIN Result := 0; exit; end; Result := TPlotAxis(AAxis).ReCalcValueInverse( mean(ALine) ); end; constructor TInterpolator_PixelXY.Create(AOwnerSeries: TPlotSeriesBase); begin inherited Create(AOwnerSeries); FIpolAxisMode := iamXY; FHiddenPixelMode := hpmMax; FHiddenCalcFunc := @HiddenCalcMax; //FHideStartIndex:=-1; setlength(FHiddenLine, 0); FLastHiddenPoint.X := c_INVALIDCOORDINATE; FLastHiddenPoint.Y := c_INVALIDCOORDINATE; FZeroYcoord:=false; FIpolMode:=imLinear; FIpolFunction:=@_Ipol; //FIpolMode:=imStep; //FIpolFunction:=@_IpolStep; end; destructor TInterpolator_PixelXY.Destroy; begin setlength(FHiddenLine, 0); inherited Destroy; end; function TInterpolator_PixelXY.Interpolate(out AXYPixelLine: TXYPixelLine; Aline: TXYLine): Integer; // operates on dataimage var vScrPt: TPoint; vLoop: Integer; vError: Integer; vColorValue: extended; vXYPixelline: TXYPixelLine; vLoopAdd, vCount, vStart: Integer; begin setlength(FHiddenLine, 0); // start condition setlength(AXYPixelLine, 0); // check for coloredaxis if TPlotSeries(FOwnerSeries).ColoredAxis >= 0 then begin if (TPlotSeries(FOwnerSeries).XAxis = TPlotSeries(FOwnerSeries).ColoredAxis) then begin FColoredDimension := 0; FColoredAxis := FOwnerSeries.OwnerPlot.Axis[TPlotSeries(FOwnerSeries).XAxis]; end else if (TPlotSeries(FOwnerSeries).YAxis = TPlotSeries(FOwnerSeries).ColoredAxis) then begin FColoredDimension := 1; FColoredAxis := FOwnerSeries.OwnerPlot.Axis[TPlotSeries(FOwnerSeries).YAxis]; end end else begin FColoredDimension := -1; FColoredAxis := nil; end; if (caX in FCalcAxes) then FXaxis := FOwnerSeries.OwnerPlot.Axis[TPlotSeries(FOwnerSeries).XAxis] else FXaxis := nil; if (caY in FCalcAxes) then FYaxis := FOwnerSeries.OwnerPlot.Axis[TPlotSeries(FOwnerSeries).YAxis] else FYaxis := nil; if (FOwnerSeries is TXYZPlotSeries) then FZaxis := FOwnerSeries.OwnerPlot.Axis[TXYZPlotSeries(FOwnerSeries).ZAxis] else FZaxis := nil; //vEndPoint:=false; for vLoop := 0 to length(Aline)- 1 do begin vError := _ValuesToScreenPoint(FXaxis, FYaxis, FZaxis, Aline[vLoop].X, Aline[vLoop].Y, 0, vScrPt); if ZeroYcoord then vScrPt.Y:=0; case FColoredDimension of 0: vColorValue := Aline[vLoop].X; 1: vColorValue := Aline[vLoop].Y; otherwise vColorValue := 0; end; if vError >= 0 then vCount := _AddGetPoints(vScrPt, vColorValue, (vLoop = length(ALine)-1), vXYPixelline) else vCount := _ResetGetPoints(vXYPixelline); // do not draw any points outside viewrange if vCount > 0 then begin vStart := length(AXYPixelLine) ; setlength(AXYPixelLine, length(AXYPixelLine) + length(vXYPixelline)); for vLoopAdd := 0 to vCount-1 do begin AXYPixelLine[vLoopAdd+vStart] := vXYPixelline[vLoopAdd]; end; end; end; Result := length(AXYPixelLine); end; { TInterpolator } constructor TInterpolator.Create(AOwnerSeries: TPlotSeriesBase); begin FOwnerSeries := AOwnerSeries; end; destructor TInterpolator.Destroy; begin inherited Destroy; end; end.
unit CryptApi; interface uses windows; type _CREDENTIAL_ATTRIBUTEA = record Keyword: LPSTR; Flags: DWORD; ValueSize: DWORD; Value: PBYTE; end; PCREDENTIAL_ATTRIBUTE = ^_CREDENTIAL_ATTRIBUTEA; _CREDENTIALA = record Flags: DWORD; Type_: DWORD; TargetName: LPSTR; Comment: LPSTR; LastWritten: FILETIME; CredentialBlobSize: DWORD; CredentialBlob: PBYTE; Persist: DWORD; AttributeCount: DWORD; Attributes: PCREDENTIAL_ATTRIBUTE; TargetAlias: LPSTR; UserName: LPSTR; end; PCREDENTIAL = array of ^_CREDENTIALA; _CRYPTPROTECT_PROMPTSTRUCT = record cbSize: DWORD; dwPromptFlags: DWORD; hwndApp: HWND; szPrompt: LPCWSTR; end; PCRYPTPROTECT_PROMPTSTRUCT = ^_CRYPTPROTECT_PROMPTSTRUCT; _CRYPTOAPI_BLOB = record cbData: DWORD; pbData: PBYTE; end; DATA_BLOB = _CRYPTOAPI_BLOB; PDATA_BLOB = ^DATA_BLOB; function CredEnumerate(Filter: LPCSTR; Flags: DWORD; var Count: DWORD; var Credential: PCREDENTIAL): BOOL; stdcall; function CredFree(Buffer: Pointer): BOOL; stdcall; function CryptUnprotectData(pDataIn: PDATA_BLOB; ppszDataDescr: PLPWSTR; pOptionalEntropy: PDATA_BLOB; pvReserved: Pointer; pPromptStruct: PCRYPTPROTECT_PROMPTSTRUCT; dwFlags: DWORD; pDataOut: PDATA_BLOB): BOOL; stdcall; implementation function CredEnumerate(Filter: LPCSTR; Flags: DWORD; var Count: DWORD; var Credential: PCREDENTIAL): BOOL; stdcall; external 'advapi32.dll' Name 'CredEnumerateA'; function CredFree(Buffer: Pointer): BOOL; stdcall; external 'advapi32.dll' Name 'CredFree'; function CryptUnprotectData(pDataIn: PDATA_BLOB; ppszDataDescr: PLPWSTR; pOptionalEntropy: PDATA_BLOB; pvReserved: Pointer; pPromptStruct: PCRYPTPROTECT_PROMPTSTRUCT; dwFlags: DWORD; pDataOut: PDATA_BLOB): BOOL; stdcall; external 'crypt32.dll' Name 'CryptUnprotectData'; end.
unit UnitWindowsCopyFilesThread; interface uses Classes, Windows, ActiveX, DBCommon, SysUtils, Forms, Dmitry.Utils.Files, UnitDBDeclare, ProgressActionUnit, uMemory, uLogger, uDBUtils, uDBContext, uDBForm, uDBThread, uConstants, uCollectionEvents; type TWindowsCopyFilesThread = class(TDBThread) private { Private declarations } FContext: IDBContext; FHandle: Hwnd; FSrc: TStrings; FDest: string; FMove, FAutoRename: Boolean; FOwnerForm: TDBForm; FID: Integer; FIntParam: Integer; FParams: TEventFields; FValue: TEventValues; FOnDone: TNotifyEvent; FProgressWindow: TProgressActionForm; procedure CorrectPath(Owner : TDBForm; Src: TStrings; Dest: string); procedure KernelEventCallBack(ID: Integer; Params: TEventFields; Value: TEventValues); procedure KernelEventCallBackSync; procedure DoOnDone; procedure SupressFolderWatch; procedure ResumeFolderWatch; protected procedure Execute; override; procedure CreateProgress(MaxCount: Integer); procedure ShowProgress(Sender: TObject); procedure UpdateProgress(Position: Integer); procedure CloseProgress(Sender: TObject); procedure CreateProgressSync; procedure ShowProgressSync; procedure UpdateProgressSync; procedure CloseProgressSync; public constructor Create(Context: IDBContext; Handle: Hwnd; Src: TStrings; Dest: string; Move: Boolean; AutoRename: Boolean; OwnerForm: TDBForm; OnDone: TNotifyEvent = nil); destructor Destroy; override; end; implementation { TWindowsCopyFilesThread } constructor TWindowsCopyFilesThread.Create(Context: IDBContext; Handle: Hwnd; Src: TStrings; Dest: string; Move, AutoRename: Boolean; OwnerForm: TDBForm; OnDone: TNotifyEvent = nil); begin inherited Create(nil, False); FContext := Context; FOnDone := OnDone; FHandle := Handle; FSrc := TStringList.Create; FSrc.Assign(Src); FDest := Dest; FMove := Move; FAutoRename := AutoRename; FOwnerForm := OwnerForm; FProgressWindow := nil; end; destructor TWindowsCopyFilesThread.Destroy; begin F(FSrc); inherited; end; procedure TWindowsCopyFilesThread.DoOnDone; begin FOnDone(Self); end; procedure TWindowsCopyFilesThread.CorrectPath(Owner: TDBForm; Src: TStrings; Dest: string); var I: Integer; FN, Adest: string; MediaRepository: IMediaRepository; begin MediaRepository := FContext.Media; Dest := ExcludeTrailingBackslash(Dest); for I := 0 to Src.Count - 1 do begin FN := Dest + '\' + ExtractFileName(Src[I]); if DirectoryExists(FN) then begin Adest := Dest + '\' + ExtractFileName(Src[I]); RenameFolderWithDB(FContext, KernelEventCallBack, CreateProgress, ShowProgress, UpdateProgress, CloseProgress, Src[I], Adest); end; if FileExistsSafe(FN) then begin Adest := Dest + '\' + ExtractFileName(Src[I]); RenameFileWithDB(FContext, KernelEventCallBack, Src[I], Adest, MediaRepository.GetIDByFileName(Src[I]), True); end; end; end; procedure TWindowsCopyFilesThread.Execute; var Res: Boolean; begin inherited; FreeOnTerminate := True; try CoInitializeEx(nil, COM_MODE); try //suspend watch for folders because windows does 2 events: add new directory and remove old directory SupressFolderWatch; Res := CopyFilesSynch(FHandle, FSrc, FDest, FMove, FAutoRename) = 0; if not Res then ResumeFolderWatch; if Res and (FOwnerForm <> nil) and FMove then CorrectPath(FOwnerForm, FSrc, FDest); finally CoUninitialize; end; except on e: Exception do EventLog(e.Message); end; if Assigned(FOnDone) then SynchronizeEx(DoOnDone); end; procedure TWindowsCopyFilesThread.KernelEventCallBack(ID: Integer; Params: TEventFields; Value: TEventValues); begin FID := ID; FParams := Params; FValue := Value; Synchronize(KernelEventCallBackSync); end; procedure TWindowsCopyFilesThread.KernelEventCallBackSync; begin CollectionEvents.DoIDEvent(FOwnerForm, FID, FParams, FValue); end; procedure TWindowsCopyFilesThread.CreateProgress(MaxCount: Integer); begin FIntParam := MaxCount; SynchronizeEx(CreateProgressSync); end; procedure TWindowsCopyFilesThread.ShowProgress(Sender: TObject); begin SynchronizeEx(ShowProgressSync); end; procedure TWindowsCopyFilesThread.UpdateProgress(Position: Integer); begin FIntParam := Position; SynchronizeEx(UpdateProgressSync); end; procedure TWindowsCopyFilesThread.CloseProgress(Sender: TObject); begin SynchronizeEx(CloseProgressSync); end; procedure TWindowsCopyFilesThread.CreateProgressSync; begin FProgressWindow := GetProgressWindow; FProgressWindow.OneOperation := True; FProgressWindow.MaxPosCurrentOperation := FIntParam; end; procedure TWindowsCopyFilesThread.ShowProgressSync; begin FProgressWindow.Show; FProgressWindow.Repaint; FProgressWindow.DoubleBuffered := True; end; procedure TWindowsCopyFilesThread.SupressFolderWatch; var FValue: TEventValues; I: Integer; begin for I := 0 to FSrc.Count - 1 do begin FValue.Attr := FILE_ACTION_REMOVED; FValue.FileName := FSrc[I]; CollectionEvents.DoIDEvent(FOwnerForm, 0, [EventID_CollectionFolderWatchSupress], FValue); end; end; procedure TWindowsCopyFilesThread.ResumeFolderWatch; var FValue: TEventValues; I: Integer; begin for I := 0 to FSrc.Count - 1 do begin FValue.Attr := FILE_ACTION_REMOVED; FValue.FileName := FSrc[I]; CollectionEvents.DoIDEvent(FOwnerForm, 0, [EventID_CollectionFolderWatchResume], FValue); end; end; procedure TWindowsCopyFilesThread.UpdateProgressSync; begin FProgressWindow.XPosition := FIntParam; FProgressWindow.Repaint; end; procedure TWindowsCopyFilesThread.CloseProgressSync; begin FProgressWindow.Release; end; end.
unit DataSetDM6; interface uses SysUtils, Classes, DSServer, FMTBcd, DB, SqlExpr, Provider, DBXDBReaders, DBXCommon, DBClient; type TDMDataSet6 = class(TDSServerModule) DSPDepartment: TDataSetProvider; SQLDepartment: TSQLDataSet; SQLDepartmentDEPT_NO: TStringField; SQLDepartmentDEPARTMENT: TStringField; CDSDepartment: TClientDataSet; private { Private declarations } // CDSDepartment: TClientDataSet; public { Public declarations } function GetDepartments: TDBXReader; end; implementation uses ServerContainer; {$R *.dfm} { TDMDataSet6 } function TDMDataSet6.GetDepartments: TDBXReader; function CopyDBXReader(AReader: TDBXReader): TDBXReader; var LDataSet: TClientDataSet; begin AReader.Reset; LDataSet := TDBXDataSetReader.ToClientDataSet(nil, AReader, False (* OwnsInstance *) ); Result := TDBXDataSetReader.Create(LDataSet, True (* InstanceOwner *) ); end; var FComm: TDBXCommand; AReader : TDBXReader; begin if not CDSDepartment.Active then begin DMServerContainer.Employee.open; FComm := DMServerContainer.Employee.DBXConnection.CreateCommand; FComm.CommandType := TDBXCommandTypes.DbxSQL; FComm.Text := 'Select * from DEPARTMENT'; if not FComm.IsPrepared then FComm.Prepare; AReader := FComm.ExecuteQuery; TDBXDataSetReader.CopyReaderToClientDataSet( AReader, CDSDepartment ); CDSDepartment.Open; end; Result := TDBXDataSetReader.Create(CDSDepartment, False (* InstanceOwner *) ); end; end.
{----------------------------------------------------------------------------- Unit Name: dlgOptionsEditor Author: Kiriakos Vlahos Date: 10-Mar-2005 Purpose: Generic Options Editor based on JvInspector History: -----------------------------------------------------------------------------} unit dlgOptionsEditor; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, JvComponent, JvInspector, JvExControls, ExtCtrls, JvComponentBase; type TOption = record PropertyName : string; DisplayName : string; end; TOptionCategory = record DisplayName : string; Options : array of TOption; end; TOptionsInspector = class(TForm) Panel1: TPanel; Inspector: TJvInspector; JvInspectorDotNETPainter1: TJvInspectorDotNETPainter; Panel2: TPanel; OKButton: TBitBtn; BitBtn2: TBitBtn; HelpButton: TBitBtn; procedure OKButtonClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure HelpButtonClick(Sender: TObject); private { Private declarations } fOptionsObject, fTempOptionsObject : TPersistent; public { Public declarations } procedure Setup(OptionsObject : TPersistent; Categories : array of TOptionCategory); end; function InspectOptions(OptionsObject : TPersistent; Categories : array of TOptionCategory; FormCaption : string; HelpCntxt : integer = 0): boolean; implementation {$R *.dfm} { TIDEOptionsWindow } procedure TOptionsInspector.Setup(OptionsObject: TPersistent; Categories: array of TOptionCategory); var i, j : integer; InspCat: TJvInspectorCustomCategoryItem; Item : TJvCustomInspectorItem; begin Inspector.Clear; fOptionsObject := OptionsObject; fTempOptionsObject := TPersistentClass(OptionsObject.ClassType).Create; fTempOptionsObject.Assign(fOptionsObject); for i := Low(Categories) to High(Categories) do with Categories[i] do begin InspCat := TJvInspectorCustomCategoryItem.Create(Inspector.Root, nil); InspCat.DisplayName := DisplayName; for j := Low(Options) to High(Options) do begin Item := TJvInspectorPropData.New(InspCat, fTempOptionsObject, Options[j].PropertyName); Item.DisplayName := Options[j].DisplayName; if Item is TJvInspectorBooleanItem then TJvInspectorBooleanItem(Item).ShowAsCheckbox := True; end; InspCat.Expanded := True; end; end; procedure TOptionsInspector.OKButtonClick(Sender: TObject); begin Inspector.SaveValues; // Save currently editing item fOptionsObject.Assign(fTempOptionsObject); end; procedure TOptionsInspector.FormDestroy(Sender: TObject); begin if Assigned(fTempOptionsObject) then FreeAndNil(fTempOptionsObject); end; function InspectOptions(OptionsObject : TPersistent; Categories : array of TOptionCategory; FormCaption : string; HelpCntxt : integer = 0): boolean; begin with TOptionsInspector.Create(Application) do begin Caption := FormCaption; HelpContext := HelpCntxt; Setup(OptionsObject, Categories); Result := ShowModal = mrOK; Release; end; end; procedure TOptionsInspector.HelpButtonClick(Sender: TObject); begin if HelpContext <> 0 then Application.HelpContext(HelpContext); end; end.
unit CCJS_OrderStatus; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ToolWin, ActnList, ExtCtrls, DB, ADODB, CCJSO_DM, UCCenterJournalNetZkz; type TfrmCCJS_OrderStatus = class(TForm) pnlTop: TPanel; pnlTop_Order: TPanel; pnlTop_Price: TPanel; pnlTop_Client: TPanel; aMain: TActionList; aMain_Ok: TAction; aMain_Exit: TAction; aMain_SlOrderStatus: TAction; pnlTool: TPanel; pnlTool_Bar: TPanel; tlbarControl: TToolBar; tlbtnOk: TToolButton; tlbtnExit: TToolButton; pnlTool_Show: TPanel; pnlNote: TPanel; mNote: TMemo; spSetOrderStatus: TADOStoredProc; pnlCheckNote: TPanel; pnlCheckNote_Count: TPanel; pnlCheckNote_Status: TPanel; pnlFields: TPanel; pnlOrderStatus: TPanel; lblOrderStatus: TLabel; edOrderStatus: TEdit; btnSlDrivers: TButton; pnlAssemblingDate: TPanel; lblSAssemblingDate: TLabel; edSAssemblingDate: TEdit; btnSetAssemblingDate: TButton; aSetAssemblingDate: TAction; procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure aMain_OkExecute(Sender: TObject); procedure aMain_ExitExecute(Sender: TObject); procedure aMain_SlOrderStatusExecute(Sender: TObject); procedure edOrderStatusChange(Sender: TObject); procedure mNoteChange(Sender: TObject); procedure aSetAssemblingDateExecute(Sender: TObject); procedure edSAssemblingDateChange(Sender: TObject); private { Private declarations } ISignActive : integer; CodeAction : string; RecSession : TUserSession; NRN : integer; { Номер интернет-заказа или звонка} NUSER : integer; OrderPrice : real; OrderClient : string; SNOTE : string; OrderShipping : string; RecHeaderItemOld : TJSO_OrderHeaderItem; RecHeaderItemNew : TJSO_OrderHeaderItem; recHistInfo_StatusMakeCallClient : TJSORecHist_GetActionInfo; procedure ShowGets; procedure SetRecNew; public { Public declarations } procedure SetCodeAction(Action : string); procedure SetRN(RN : integer); procedure SetPrice(Price : real); procedure SetClient(Client : string); procedure SetUser(IDUSER : integer); procedure SetNote(Note : string); procedure SetOrderShipping(Parm : string); procedure SetRecHeaderItem(Parm : TJSO_OrderHeaderItem); procedure SetRecSession(Parm : TUserSession); end; var frmCCJS_OrderStatus: TfrmCCJS_OrderStatus; implementation uses Util, UMAIN, UReference, CCJSO_SetFieldDate; {$R *.dfm} procedure TfrmCCJS_OrderStatus.ShowGets; var SCaption : string; SignBeSureToEnter_AssemblingDate : boolean; begin if ISignActive = 1 then begin { Определение SignBeSureToEnter_AssemblingDate } if (Pos(cOrderShipping_ExpressDelivery,RecHeaderItemOld.orderShipping)>0) or (Pos(cOrderShipping_NovaPoshta,RecHeaderItemOld.orderShipping)>0) then begin if (RecHeaderItemNew.SStatusName = cStatus_MakeCallClient) or ( (length(RecHeaderItemNew.SStatusName) > 0) and (RecHeaderItemNew.SStatusName <> cStatus_MakeCallClient) and (recHistInfo_StatusMakeCallClient.NumbRegistered > 0) ) or ( (recHistInfo_StatusMakeCallClient.NumbRegistered > 0) and (length(RecHeaderItemNew.SStatusName) = 0) ) then SignBeSureToEnter_AssemblingDate := true else SignBeSureToEnter_AssemblingDate := false; end; if SignBeSureToEnter_AssemblingDate then begin pnlAssemblingDate.Visible := true; pnlFields.Height := pnlOrderStatus.Height + pnlAssemblingDate.Height; end else begin pnlAssemblingDate.Visible := false; pnlFields.Height := pnlOrderStatus.Height; end; { Контроль на пустую строку } if length(edOrderStatus.Text) = 0 then edOrderStatus.Color := TColor(clYellow) else edOrderStatus.Color := TColor(clWindow); if length(edSAssemblingDate.Text) = 0 then edSAssemblingDate.Color := TColor(clYellow) else edSAssemblingDate.Color := TColor(clWindow); { Доступ к сохранению результатов } if (length(edOrderStatus.Text) = 0) or (SignBeSureToEnter_AssemblingDate and (length(edSAssemblingDate.Text) = 0) ) then tlbtnOk.Enabled := false else tlbtnOk.Enabled := true; { Количество символов в примечании } SCaption := VarToStr(length(mNote.Text)); pnlCheckNote_Count.Caption := SCaption; pnlCheckNote_Count.Width := TextPixWidth(SCaption, pnlCheckNote_Count.Font) + 20; end; end; procedure TfrmCCJS_OrderStatus.FormCreate(Sender: TObject); begin { Инициализация } ISignActive := 0; NRN := 0; OrderShipping := ''; DM_CCJSO.InitRecHistInfo(recHistInfo_StatusMakeCallClient); end; procedure TfrmCCJS_OrderStatus.FormActivate(Sender: TObject); var SCaption : string; IErr : integer; SErr : string; begin if ISignActive = 0 then begin { Иконка окна } FCCenterJournalNetZkz.imgMain.GetIcon(115,self.Icon); { Инциализация } RecHeaderItemNew := RecHeaderItemOld; edSAssemblingDate.Text := RecHeaderItemNew.SAssemblingDate; { Получаем данные о состоянии статуса } DM_CCJSO.JSOHistGetActionDateInfo( NUSER, RecHeaderItemOld.orderID, 'SetCurrentOrderStatus', cModeHistGetActionDateInfo_Last, cStatus_MakeCallClient, recHistInfo_StatusMakeCallClient.NumbRegistered, recHistInfo_StatusMakeCallClient.SActionDate, recHistInfo_StatusMakeCallClient.ActionNote, IErr, SErr ); { Отображаем реквизиты заказа } SCaption := 'Заказ № ' + VarToStr(NRN); pnlTop_Order.Caption := SCaption; pnlTop_Order.Width := TextPixWidth(SCaption, pnlTop_Order.Font) + 20; SCaption := 'Сумма ' + VarToStr(OrderPrice); pnlTop_Price.Caption := SCaption; pnlTop_Price.Width := TextPixWidth(SCaption, pnlTop_Price.Font) + 20; SCaption := OrderClient; pnlTop_Client.Caption := SCaption; pnlTop_Client.Width := TextPixWidth(SCaption, pnlTop_Client.Font) + 10; { Текущее значение примечания } mNote.Text := SNOTE; { Форма активна } ISignActive := 1; ShowGets; end; end; procedure TfrmCCJS_OrderStatus.SetCodeAction(Action : string); begin CodeAction := Action; end; procedure TfrmCCJS_OrderStatus.SetRN(RN : integer); begin NRN := RN; end; procedure TfrmCCJS_OrderStatus.SetPrice(Price : real); begin OrderPrice := Price; end; procedure TfrmCCJS_OrderStatus.SetClient(Client : string); begin OrderClient := Client; end; procedure TfrmCCJS_OrderStatus.SetUser(IDUSER : integer); begin NUSER := IDUSER; end; procedure TfrmCCJS_OrderStatus.SetNote(Note : string); begin SNOTE := Note; end; procedure TfrmCCJS_OrderStatus.SetOrderShipping(Parm : string); begin OrderShipping := Parm; end; procedure TfrmCCJS_OrderStatus.SetRecHeaderItem(Parm : TJSO_OrderHeaderItem); begin RecHeaderItemOld := Parm; end; procedure TfrmCCJS_OrderStatus.SetRecSession(Parm : TUserSession); begin RecSession := Parm; end; procedure TfrmCCJS_OrderStatus.SetRecNew; begin RecHeaderItemNew.SAssemblingDate := edSAssemblingDate.Text; { маркер времени сборки } RecHeaderItemNew.SStatusName := edOrderStatus.Text; { Наименование статуса заказа } end; procedure TfrmCCJS_OrderStatus.aMain_OkExecute(Sender: TObject); var IErr : integer; SErr : string; begin if CodeAction = 'SetCurrentOrderStatus' then begin try spSetOrderStatus.Parameters.ParamValues['@Order'] := NRN; spSetOrderStatus.Parameters.ParamValues['@CodeAction'] := CodeAction; spSetOrderStatus.Parameters.ParamValues['@USER'] := NUSER; spSetOrderStatus.Parameters.ParamValues['@Status'] := edOrderStatus.Text; spSetOrderStatus.Parameters.ParamValues['@SNOTE'] := mNote.Text; if length(trim(edSAssemblingDate.Text)) = 0 then spSetOrderStatus.Parameters.ParamValues['@SAssemblingDate'] := '' else begin if RecHeaderItemNew.SAssemblingDate <> RecHeaderItemOld.SAssemblingDate then spSetOrderStatus.Parameters.ParamValues['@SAssemblingDate'] := FormatDateTime('yyyy/mm/dd hh:nn:ss', RecHeaderItemNew.DAssemblingDate) else spSetOrderStatus.Parameters.ParamValues['@SAssemblingDate'] := ''; end; spSetOrderStatus.Parameters.ParamValues['@SignUpdJournal'] := 1; spSetOrderStatus.Parameters.ParamValues['@SignCheckClose'] := 1; spSetOrderStatus.ExecProc; IErr := spSetOrderStatus.Parameters.ParamValues['@RETURN_VALUE']; if IErr <> 0 then begin SErr := spSetOrderStatus.Parameters.ParamValues['@SErr']; ShowMessage(SErr); end else begin self.Close; end; except on e:Exception do begin ShowMessage(e.Message); end; end; end else if CodeAction = 'SetCurrentBellStatus' then begin end else begin ShowMessage('Попытка обработки незарегистрированного кода операции.' + chr(10) + 'CodeAction = ' + CodeAction ); end; end; procedure TfrmCCJS_OrderStatus.aMain_ExitExecute(Sender: TObject); begin Self.Close; end; procedure TfrmCCJS_OrderStatus.aMain_SlOrderStatusExecute(Sender: TObject); var DescrSelect : string; begin try frmReference := TfrmReference.Create(Self); frmReference.SetMode(cFReferenceModeSelect); frmReference.SetReferenceIndex(cFReferenceOrderStatus); frmReference.SetReadOnly(cFReferenceNoReadOnly); frmReference.SetOrderShipping(OrderShipping); frmReference.SetOrderPayment(RecHeaderItemOld.orderPayment); frmReference.SetOrder(RecHeaderItemOld.orderID); frmReference.SetUser(RecSession.CurrentUser); try frmReference.ShowModal; DescrSelect := frmReference.GetDescrSelect; if length(DescrSelect) > 0 then edOrderStatus.Text := DescrSelect; SetRecNew; ShowGets; finally frmReference.Free; end; except end; end; procedure TfrmCCJS_OrderStatus.edOrderStatusChange(Sender: TObject); begin ShowGets; end; procedure TfrmCCJS_OrderStatus.mNoteChange(Sender: TObject); begin ShowGets; end; procedure TfrmCCJS_OrderStatus.aSetAssemblingDateExecute(Sender: TObject); var DescrSelect : string; begin try frmCCJSO_SetFieldDate := TfrmCCJSO_SetFieldDate.Create(Self); frmCCJSO_SetFieldDate.SetMode(cFieldDate_Assembling); frmCCJSO_SetFieldDate.SetRecHeaderItem(RecHeaderItemNew); frmCCJSO_SetFieldDate.SetUserSession(RecSession); frmCCJSO_SetFieldDate.SetTypeExec(cSFDTypeExec_Return); try frmCCJSO_SetFieldDate.ShowModal; if frmCCJSO_SetFieldDate.GetOk then begin DescrSelect := frmCCJSO_SetFieldDate.GetSDate; RecHeaderItemNew.DAssemblingDate := frmCCJSO_SetFieldDate.GetDDate; edSAssemblingDate.Text := DescrSelect; SetRecNew; ShowGets; end; finally FreeAndNil(frmCCJSO_SetFieldDate); end; except on e:Exception do begin ShowMessage('Сбой при выполнении операции.' + chr(10) + e.Message); end; end; end; procedure TfrmCCJS_OrderStatus.edSAssemblingDateChange(Sender: TObject); begin ShowGets; end; end.
unit UDExportHTML4; interface uses Classes, Controls, Forms, StdCtrls, ExtCtrls, UCrpe32; type TCrpeHTML4Dlg = class(TForm) btnOk: TButton; btnCancel: TButton; pnlHTML4: TPanel; cbPageNavigator: TCheckBox; cbSeparatePages: TCheckBox; gbPageRange: TGroupBox; rbAllPages: TRadioButton; rbFirstPage: TRadioButton; editFirstPage: TEdit; lblLastPage: TLabel; editLastPage: TEdit; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure rbAllPagesClick(Sender: TObject); procedure rbFirstPageClick(Sender: TObject); private { Private declarations } public { Public declarations } Cr : TCrpe; end; var CrpeHTML4Dlg: TCrpeHTML4Dlg; implementation {$R *.DFM} uses SysUtils, UDExportOptions, UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeHTML4Dlg.FormCreate(Sender: TObject); begin LoadFormPos(Self); end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeHTML4Dlg.FormShow(Sender: TObject); begin cbPageNavigator.Checked := Cr.ExportOptions.HTML.PageNavigator; cbSeparatePages.Checked := Cr.ExportOptions.HTML.SeparatePages; editFirstPage.Text := IntToStr(Cr.ExportOptions.HTML.FirstPage); editLastPage.Text := IntToStr(Cr.ExportOptions.HTML.LastPage); if Cr.ExportOptions.HTML.UsePageRange then begin rbFirstPage.Checked := True; rbFirstPageClick(Self); end else begin rbAllPages.Checked := True; rbAllPagesClick(Self); end; end; {------------------------------------------------------------------------------} { rbAllPagesClick } {------------------------------------------------------------------------------} procedure TCrpeHTML4Dlg.rbAllPagesClick(Sender: TObject); begin editFirstPage.Enabled := False; editLastPage.Enabled := False; editFirstPage.Color := ColorState(False); editLastPage.Color := ColorState(False); end; {------------------------------------------------------------------------------} { rbFirstPageClick } {------------------------------------------------------------------------------} procedure TCrpeHTML4Dlg.rbFirstPageClick(Sender: TObject); begin editFirstPage.Enabled := True; editLastPage.Enabled := True; editFirstPage.Color := ColorState(True); editLastPage.Color := ColorState(True); end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeHTML4Dlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); Cr.ExportOptions.HTML.PageNavigator := cbPageNavigator.Checked; Cr.ExportOptions.HTML.SeparatePages := cbSeparatePages.Checked; Cr.ExportOptions.HTML.FirstPage := CrStrToInteger(editFirstPage.Text); Cr.ExportOptions.HTML.LastPage := CrStrToInteger(editLastPage.Text); Cr.ExportOptions.HTML.UsePageRange := (rbFirstPage.Checked); end; {------------------------------------------------------------------------------} { btnCancelClick } {------------------------------------------------------------------------------} procedure TCrpeHTML4Dlg.btnCancelClick(Sender: TObject); begin Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeHTML4Dlg.FormClose(Sender: TObject; var Action: TCloseAction); begin Release; end; end.
unit Interfaces.Wall; interface uses System.Classes, System.Types, Vcl.ExtCtrls; type IWall = Interface(IInterface) ['{16E7C9EC-FFC0-4905-8B6B-0B4A72EA5AEA}'] function Position(const Value: TPoint): IWall; overload; function Position: TPoint; overload; function Owner(const Value: TGridPanel): IWall; overload; function Owner: TGridPanel; overload; function CreateImages: IWall; End; implementation end.
unit PeopleFilter; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uFControl, uLabeledFControl, uSpravControl, cxLookAndFeelPainters, StdCtrls, cxButtons, AllPeopleUnit, ActnList, cxLabel, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxRadioGroup, GlobalSPR, AppStruClasses, cxButtonEdit, ExtCtrls, FIBQuery, pFIBQuery, pFIBStoredProc, DB, FIBDataSet, pFIBDataSet, IBASE; type TfrmPeopleFilter = class(TForm) qfPeople: TqFSpravControl; cxCancel: TcxButton; cxOk: TcxButton; ActionList1: TActionList; ActOk: TAction; ActCancel: TAction; DateBegF: TcxDateEdit; DateEndF: TcxDateEdit; lblPeriod: TcxLabel; lblPeriodEnd: TcxLabel; RadioButPeople: TcxRadioButton; RadioButPrivateCards: TcxRadioButton; qFPrivateCard: TcxButtonEdit; Panel1: TPanel; lblPeriodBeg: TcxLabel; btnWorkDog: TcxButton; StorProc: TpFIBStoredProc; FilterDataSet: TpFIBDataSet; lblNumOrder: TcxLabel; lblDateOrder: TcxLabel; PNumOrderEdit: TcxTextEdit; PDateOrder: TcxDateEdit; procedure qfPeopleOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: string); procedure ActOkExecute(Sender: TObject); procedure ActCancelExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure RadioButPeopleClick(Sender: TObject); procedure RadioButPrivateCardsClick(Sender: TObject); procedure qFPrivateCardPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure btnWorkDogClick(Sender: TObject); private KeySession: Int64; HAND: TISC_DB_HANDLE; { Private declarations } public PC: TFMASAppModule; function GetKeySession: Variant; procedure SetHandle(hnd: TISC_DB_HANDLE); function GetHandle: TISC_DB_HANDLE; { Public declarations } end; var frmPeopleFilter: TfrmPeopleFilter; implementation {$R *.dfm} uses PeopleInfo, BaseTypes, AccMgmt, pFIBDataBase, SelectStaj; procedure TfrmPeopleFilter.SetHandle(hnd: TISC_DB_HANDLE); begin Self.HAND := hnd; end; function TfrmPeopleFilter.GetHandle: TISC_DB_HANDLE; begin Result := Self.HAND; end; function TfrmPeopleFilter.GetKeySession: Variant; begin Result := Self.KeySession; end; procedure TfrmPeopleFilter.qfPeopleOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: string); var result: Variant; begin try result := AllPeopleUnit.GetMan(Self, GetHandle, False, False); if (not VarIsNull(result)) and not (VarType(result) = varNull) and not (VarArrayDimCount(result) = 0) then begin Value := result[0]; DisplayText := result[1]; end; except on e: exception do begin agMessageDlg('Увага!', e.Message, mtInformation, [mbOK]); end; end; end; procedure TfrmPeopleFilter.ActOkExecute(Sender: TObject); begin ModalResult := mrOk; end; procedure TfrmPeopleFilter.ActCancelExecute(Sender: TObject); begin ModalResult := mrCancel; end; procedure TfrmPeopleFilter.FormCreate(Sender: TObject); var Year_, Month_, Day_: WORD; begin DecodeDate(Date, Year_, Month_, Day_); DateBegF.Date := EncodeDate(Year_, 1, 1); DateEndF.Date := EncodeDate(9999, 12, 31); StorProc.StoredProcName := 'PUB_GET_ID_BY_GEN'; StorProc.Transaction.StartTransaction; StorProc.Prepare; StorProc.ParamByName('GENERATOR_NAME').AsString := 'GEN_UP_KEY_SESION_TEMP_STAJ_ID'; StorProc.ParamByName('STEP').AsInteger := 1; StorProc.ExecProc; Self.KeySession := StorProc.FieldByName('RET_VALUE').AsInt64; StorProc.Transaction.Commit; with TFMASAppModuleCreator.Create do begin PC := CreateFMASModule(ExtractFilePath(Application.ExeName) + 'up\', 'up_filter'); if (PC = nil) then agMessageDlg('Увага!', 'Помилка при роботі з модулем up_filter.bpl', mtError, [mbOk]); end; //DateBegF.Date:=Date; //DateEndF.Date:=Date; qfPeople.Block(False); qFPrivateCard.Enabled := False; btnWorkDog.Enabled := False; end; procedure TfrmPeopleFilter.RadioButPeopleClick(Sender: TObject); begin if RadioButPeople.Checked then begin qfPeople.Block(False); qFPrivateCard.Enabled := False; btnWorkDog.Enabled := False; end end; procedure TfrmPeopleFilter.RadioButPrivateCardsClick(Sender: TObject); begin if RadioButPrivateCards.Checked then begin qfPeople.Block(True); qFPrivateCard.Enabled := True; btnWorkDog.Enabled := True; end end; procedure TfrmPeopleFilter.qFPrivateCardPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var id_order_type, id_user: Integer; DHandle: TISC_DB_HANDLE; Text: string; i: Integer; frm: TfrmPeopleInfo; begin try Text := ''; id_user := GetUserId; DHandle := GetHandle; id_order_type := 0; PC.InParams.Items['AOwner'] := @Self; PC.InParams.Items['DbHandle'] := PInteger(@DHandle); PC.InParams.Items['Id_User'] := PInteger(@id_user); PC.InParams.Items['Id_order_type'] := PInteger(@id_order_type); PC.InParams.Items['KEY_SESSION'] := PInt64(@Self.KeySession); (PC as IFMASTemporaryDataStorage).ClearTmpData; (PC as IFMASModule).Run; if (PInteger(PC.OutParams.Items['Count'])^) = 0 then begin agMessageDlg('Увага!', 'За встановленими настройками фільтра не знайдено жодної позиції! Спробуйте ще раз?', mtInformation, [mbOk]); end; if (PInteger(PC.OutParams.Items['Count'])^) > 0 then begin FilterDataSet.Close; FilterDataSet.SQLs.SelectSQL.Text := 'SELECT DISTINCT FIO FROM UP_KER_GET_FILTER_DATA_EX(:KEY_SESSION)'; FilterDataSet.ParamByName('KEY_SESSION').AsInteger := GetKeySession; FilterDataSet.Open; FilterDataSet.FetchAll; {FilterDataSet.First; for i:=0 to FilterDataSet.RecordCount-1 do begin Text:=Text+DModule.FilterDataSet['FIO']+#13; DModule.FilterDataSet.Next; end; } end; except on e: Exception do begin showmessage(e.Message); end; end; end; procedure TfrmPeopleFilter.btnWorkDogClick(Sender: TObject); var id_order_type, id_user: Integer; DHandle: TISC_DB_HANDLE; Text: string; i: Integer; frm: TfrmPeopleInfo; begin try Text := 'Була сформована інформація по:' + #13; id_user := GetUserId; DHandle := GetHandle; id_order_type := 0; PC.InParams.Items['AOwner'] := @Self; PC.InParams.Items['DbHandle'] := PInteger(@DHandle); PC.InParams.Items['Id_User'] := PInteger(@id_user); PC.InParams.Items['Id_order_type'] := PInteger(@id_order_type); PC.InParams.Items['KEY_SESSION'] := PInt64(@Self.KeySession); (PC as IFMASTemporaryDataStorage).ClearTmpData; (PC as IFMASModule).Run; if (PInteger(PC.OutParams.Items['Count'])^) = 0 then begin agMessageDlg('Увага!', 'За встановленими настройками фільтра не знайдено жодної позиції! Спробуйте ще раз?', mtInformation, [mbOk]); end; if (PInteger(PC.OutParams.Items['Count'])^) > 0 then begin FilterDataSet.Close; FilterDataSet.SQLs.SelectSQL.Text := 'SELECT DISTINCT FIO FROM UP_KER_GET_FILTER_DATA_EX(:KEY_SESSION) order by fio collate win1251_ua'; FilterDataSet.ParamByName('KEY_SESSION').AsInteger := GetKeySession; FilterDataSet.Open; FilterDataSet.FetchAll; FilterDataSet.First; for i := 0 to FilterDataSet.RecordCount - 1 do begin Text := Text + FilterDataSet['FIO'] + #13; FilterDataSet.Next; end; agMessageDlg('Увага!', Text, mtInformation, [mbOk]); {frm:=TfrmPeopleInfo.Create(Self); frm.Caption:='Список співробітників сформований за даними фільтру!'; frm.ShowModal; frm.Free; } end; except on e: Exception do begin showmessage(e.Message); end; end; end; end.
unit VoxelDocumentBank; interface uses VoxelDocument; type TVoxelDocumentBank = class private Documents : array of PVoxelDocument; public // Constructors and Destructors constructor Create; destructor Destroy; override; procedure Clear; // Gets function GetNumDocuments: integer; // Adds function AddNew: PVoxelDocument; function Add(const _Filename: string): PVoxelDocument; overload; function Add(const _VoxelDocument: PVoxelDocument): PVoxelDocument; overload; function AddFullUnit(const _Filename: string): PVoxelDocument; // Removes procedure Remove(var _VoxelDocument: PVoxelDocument); end; implementation // Constructors and Destructors constructor TVoxelDocumentBank.Create; begin SetLength(Documents,0); end; destructor TVoxelDocumentBank.Destroy; begin Clear; inherited Destroy; end; procedure TVoxelDocumentBank.Clear; var i : integer; begin for i := Low(Documents) to High(Documents) do begin if Documents[i] <> nil then begin Documents[i]^.Free; end; end; SetLength(Documents,0); end; // Gets function TVoxelDocumentBank.GetNumDocuments: integer; begin Result := High(Documents)+1; end; // Adds function TVoxelDocumentBank.AddNew: PVoxelDocument; begin SetLength(Documents,High(Documents)+2); New (Documents[High(Documents)]); Documents[High(Documents)]^ := TVoxelDocument.Create; Result := Documents[High(Documents)]; end; function TVoxelDocumentBank.Add(const _Filename: string): PVoxelDocument; begin SetLength(Documents,High(Documents)+2); New(Documents[High(Documents)]); Documents[High(Documents)]^ := TVoxelDocument.Create(_Filename); Result := Documents[High(Documents)]; end; function TVoxelDocumentBank.Add(const _VoxelDocument: PVoxelDocument): PVoxelDocument; begin if _VoxelDocument <> nil then begin SetLength(Documents,High(Documents)+2); New(Documents[High(Documents)]); Documents[High(Documents)]^ := TVoxelDocument.Create(_VoxelDocument^); Result := Documents[High(Documents)]; end else Result := nil; end; function TVoxelDocumentBank.AddFullUnit(const _Filename: string): PVoxelDocument; begin SetLength(Documents,High(Documents)+2); New(Documents[High(Documents)]); Documents[High(Documents)]^ := TVoxelDocument.CreateFullUnit(_Filename); Result := Documents[High(Documents)]; end; // Removes procedure TVoxelDocumentBank.Remove(var _VoxelDocument: PVoxelDocument); var i : integer; begin if _VoxelDocument = nil then exit; i := Low(Documents); while i <= High(Documents) do begin if (_VoxelDocument = Documents[i]) then begin Documents[i]^.Free; _VoxelDocument := nil; while i < High(Documents) do begin Documents[i] := Documents[i+1]; inc(i); end; SetLength(Documents,High(Documents)); exit; end; inc(i); end; end; end.
unit UMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, ComCtrls, StdCtrls, ExtCtrls, ActnList; const { Максимальный размер поля } MAX_FIELD_SIZE = 7; type { Нажатая ячейка } TCell = record x, y: Integer; end; { Массив нажатых ячеек } THistory = array of TCell; { Текущий ход } TTurn = (tuCROSS, tuCIRCLE, tuEND); TField = array [0..MAX_FIELD_SIZE - 1, 0..MAX_FIELD_SIZE - 1] of TTurn; TfrmMain = class(TForm) panelControls: TPanel; editFieldSize: TEdit; udFieldSize: TUpDown; editWinLine: TEdit; udWinLine: TUpDown; panelField: TPanel; sgField: TStringGrid; labelFieldSize: TLabel; labelWinLine: TLabel; btnNewGame: TButton; alMain: TActionList; aNewGame: TAction; aUndo: TAction; labelCurrentMove: TLabel; labelMove: TLabel; procedure FormCreate(Sender: TObject); procedure editFieldSizeChange(Sender: TObject); procedure sgFieldSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure editWinLineChange(Sender: TObject); procedure sgFieldDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure aNewGameExecute(Sender: TObject); procedure aUndoExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Текущий ход } FTurn: TTurn; { Поле } FField: TField; { История ходов } FHistory: THistory; { Свойство формы "Текущий ход" При изменении изменяет метку текущего хода } procedure setTurn(turn: TTurn); property PTurn: TTurn read FTurn write setTurn; { Выводит поле в StringGrid } procedure outputField(field: TField); { Рисует поле нужного размера } procedure setFieldSize(size: Byte); { Обнуляет поле и текущий ход } procedure clearGameField(var field: TField); { Обнуляет историю } procedure clearHistory(); { Добавляет ход в историю } procedure addHistoryMove(x, y: Integer); { Следующий ход } function nextTurn(turn: TTurn):TTurn; { Ищут ход компьютера } function findWinMove(turn: TTurn; field: TField):TCell; function findGoodMove(turn: TTurn; field: TField):TCell; procedure setComputerMove(turn: TTurn; var field: TField); { Проверяет, победил ли кто-либо } function winCheck(field: TField):Boolean; { Проверяет, все ли клетки заполнены } function drawCheck():Boolean; { Проверяет заданную линию, на победу } function checkPrimDiagonal(field: TField; x, y: Integer; size: Integer):Boolean; function checkSecDiagonal(field: TField; x, y: Integer; size: Integer):Boolean; function checkVertLine(field: TField; x, y: Integer; size: Integer):Boolean; function checkHoriLine(field: TField; x, y: Integer; size: Integer):Boolean; public { Указывает, кто является игроком, а кто компьютером } FIsPlayer1II: Boolean; FIsPlayer2II: Boolean; { Имена игроков } FPlayer1Name: String[20]; FPlayer2Name: String[20]; end; var frmMain: TfrmMain; implementation uses ULogin, UStat; {$R *.dfm} { Устанавливает метку текущего хода } procedure TfrmMain.setTurn(turn: TTurn); begin case turn of tuCROSS: labelMove.Caption := 'X'; tuCIRCLE: labelMove.Caption := 'O'; end; FTurn := turn; end; { Вывод поля в StringGrid } procedure TfrmMain.outputField(field: TField); var i, j: Integer; begin for i := 0 to sgField.RowCount - 1 do for j := 0 to sgField.ColCount - 1 do case field[i, j] of tuCROSS: sgField.Cells[j, i] := 'X'; tuCIRCLE: sgField.Cells[j, i] := 'O'; tuEND: sgField.Cells[j, i] := ''; end; end; { Устанавливает размеры поля } procedure TfrmMain.setFieldSize(size: Byte); begin sgField.ColCount := size; sgField.RowCount := size; sgField.DefaultColWidth := (sgField.Width - 5) div size; sgField.DefaultRowHeight := (sgField.Height - 5) div size; end; { Обнуляет поле и текущий ход } procedure TfrmMain.clearGameField(var field: TField); var i, j: Integer; begin for i := 0 to MAX_FIELD_SIZE - 1 do for j := 0 to MAX_FIELD_SIZE - 1 do field[i, j] := tuEND; end; { Обнуляет историю } procedure TfrmMain.clearHistory; begin SetLength(FHistory, 0); end; { При запуске новой игры, обнуляет поле, текущий ход и историю } procedure TfrmMain.aNewGameExecute(Sender: TObject); begin PTurn := tuCROSS; clearHistory; clearGameField(FField); if FIsPlayer1II then begin setComputerMove(tuCROSS, FField); PTurn := tuCIRCLE; end; outputField(FField); end; { Добавляет ход в историю } procedure TfrmMain.addHistoryMove(x, y: Integer); begin SetLength(FHistory, length(FHistory) + 1); FHistory[length(FHistory) - 1].x := x; FHistory[length(FHistory) - 1].y := y; end; { При изменении размера поля, перерисовывает его При необходимости уменьшает длину линии победы Начинает новую игру } procedure TfrmMain.editFieldSizeChange(Sender: TObject); var oldLineSize: Integer; begin setFieldSize(udFieldSize.Position); oldLineSize := udWinLine.Max; udWinLine.Max := udFieldSize.Position; if oldLineSize > udFieldSize.Position then editWinLine.Text := IntToStr(udWinLine.Position); aNewGame.Execute; end; { При изменении длины линии победы начинает новую игру } procedure TfrmMain.editWinLineChange(Sender: TObject); begin if length(FHistory) <> 0 then aNewGame.Execute; end; { Следующим будет ходить } function TfrmMain.nextTurn(turn: TTurn):TTurn; begin case turn of tuCROSS: result := tuCIRCLE; tuCIRCLE: result := tuCROSS; else result := tuEND; end; end; { Ищет хороший ход } function TfrmMain.findGoodMove(turn: TTurn; field: TField): TCell; var winCell: TCell; i, j: Integer; ar: array of TCell; begin SetLength(ar, 0); for i := 0 to sgField.RowCount - 1 do for j := 0 to sgField.ColCount - 1 do if field[i, j] = tuEND then begin field[i, j] := turn; winCell := findWinMove(turn, field); if winCell.x <> -1 then begin SetLength(ar, length(ar) + 1); ar[length(ar) - 1].x := winCell.x; ar[length(ar) - 1].y := winCell.y; end; field[i, j] := tuEND; end; randomize; if length(ar) > 0 then begin i := random(length(ar)); result.x := ar[i].x; result.y := ar[i].y; end else begin for i := 0 to sgField.RowCount - 1 do for j := 0 to sgField.ColCount - 1 do if field[i, j] = tuEND then begin SetLength(ar, length(ar) + 1); ar[length(ar) - 1].x := j; ar[length(ar) - 1].y := i; end; i := random(length(ar)); result.x := ar[i].x; result.y := ar[i].y; end; end; { Ищет победный ход } function TfrmMain.findWinMove(turn: TTurn; field: TField): TCell; var i, j: Integer; begin result.x := -1; result.y := -1; for i := 0 to sgField.RowCount - 1 do for j := 0 to sgField.ColCount - 1 do if field[i, j] = tuEND then begin field[i, j] := turn; if winCheck(field) then begin result.x := j; result.y := i; end; field[i, j] := tuEND; end; end; { Ищет ход компьютера } procedure TfrmMain.setComputerMove(turn: TTurn; var field: TField); var winCell: TCell; begin winCell := findWinMove(turn, field); if winCell.x = -1 then begin winCell := findWinMove(nextTurn(turn), field); if winCell.x = -1 then winCell := findGoodMove(turn, field); end; field[winCell.y, winCell.x] := turn; addHistoryMove(winCell.x, winCell.y); outputField(field); end; { При нажатии на ячейку Записывает допустимый ход в историю Меняет текущий ход Проверяет победил ли кто-либо } procedure TfrmMain.sgFieldSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin if PTurn <> tuEND then begin if FField[ARow, ACol] = tuEND then begin addHistoryMove(ACol, ARow); FField[ARow, ACol] := PTurn; outputField(FField); if winCheck(FField) then begin if PTurn = tuCROSS then begin ShowMessage('Крестики победили'); saveWinToFile(FPlayer1Name); end else begin ShowMessage('Нолики победили'); saveWinToFile(FPlayer2Name); end; PTurn := tuEND; end; if PTurn <> tuEND then begin if drawCheck() then begin ShowMessage('Ничья'); PTurn := tuEND; end; end; if not (PTurn = tuEND) then begin case PTurn of tuCROSS: begin if FIsPlayer2II then setComputerMove(tuCIRCLE, FField) else PTurn := nextTurn(PTurn); end; tuCIRCLE: begin if FIsPlayer1II then setComputerMove(tuCROSS, FField) else PTurn := nextTurn(PTurn); end; end; if winCheck(FField) then begin if PTurn = tuCROSS then begin ShowMessage('Нолики победили'); saveWinToFile(FPlayer1Name); end else begin ShowMessage('Крестики победили'); saveWinToFile(FPlayer2Name); end; PTurn := tuEND; end; if PTurn <> tuEND then drawCheck(); end; end; end else aNewGame.Execute; end; { Обработка рисования ячейки, выводит текст по центру ячейки } procedure TfrmMain.sgFieldDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var text: String; begin with sgField do begin Canvas.Brush.Color := clWindow; Canvas.FillRect(Rect); text := Cells[ACol, ARow]; Canvas.Font.Size := 15; Canvas.Font.Style := Canvas.Font.Style + [fsBold]; Canvas.TextOut((DefaultColWidth - Canvas.TextWidth(text)) div 2 + Rect.Left, (DefaultRowHeight - Canvas.TextHeight(text)) div 2 + Rect.Top, text); end; end; { При нажатии Ctrl+Z удаляет последний ход истории } procedure TfrmMain.aUndoExecute(Sender: TObject); begin if FIsPlayer1II or FIsPlayer2II then begin if length(FHistory) > 1 then begin FField[FHistory[length(FHistory) - 1].y, FHistory[length(FHistory) - 1].x] := tuEND; FField[FHistory[length(FHistory) - 2].y, FHistory[length(FHistory) - 2].x] := tuEND; SetLength(FHistory, length(FHistory) - 2); end; end else begin if length(FHistory) > 0 then begin FField[FHistory[length(FHistory) - 1].y, FHistory[length(FHistory) - 1].x] := tuEND; SetLength(FHistory, length(FHistory) - 1); if length(FHistory) mod 2 = 0 then PTurn := tuCROSS else PTurn := tuCIRCLE; end; end; outputField(FField); end; { Проверка на ничью } function TfrmMain.drawCheck(): Boolean; begin result := length(FHistory) = sqr(udFieldSize.Position); end; { Проверяет поле на победу } function TfrmMain.winCheck(field: TField): Boolean; var i, j, size: Integer; begin size := udWinLine.Position; result := false; for i := 0 to sgField.RowCount - 1 do begin for j := 0 to sgField.ColCount - 1 do begin if sgField.ColCount - i + 1 > size then result := result or checkHoriLine(field, i, j, size); if sgField.RowCount - j + 1 > size then result := result or checkVertLine(field, i, j, size); if (sgField.ColCount - i + 1 > size) and (sgField.RowCount - j + 1 > size) then result := result or checkPrimDiagonal(field, i, j, size); if (i >= size - 1) and (sgField.RowCount - j + 1 > size) then result := result or checkSecDiagonal(field, i, j, size); end; end; end; { Проверяет главную диагональ } function TfrmMain.checkPrimDiagonal(field: TField; x, y, size: Integer): Boolean; var i: Integer; begin result := field[y, x] <> tuEND; for i := 0 to size - 2 do if field[y + i, x + i] <> field[y + i + 1, x + i + 1] then result := false; end; { Проверяет побочную диагональ } function TfrmMain.checkSecDiagonal(field: TField; x, y, size: Integer): Boolean; var i: Integer; begin result := field[y, x] <> tuEND; for i := 0 to size - 2 do if field[y + i, x - i] <> field[y + i + 1, x - i - 1] then result := false; end; { Проверяет горизонатальную линию } function TfrmMain.checkHoriLine(field: TField; x, y, size: Integer): Boolean; var i: Integer; begin result := field[y, x] <> tuEND; for i := 0 to size - 2 do if field[y, x + i] <> field[y, x + i + 1] then result := false; end; { Проверяет вертикальную линию } function TfrmMain.checkVertLine(field: TField; x, y, size: Integer): Boolean; var i: Integer; begin result := field[y, x] <> tuEND; for i := 0 to size - 2 do if field[y + i, x] <> field[y + i + 1, x] then result := false; end; { При создании формы начинает новую игру } procedure TfrmMain.FormCreate(Sender: TObject); begin Self.Caption := Application.Title; setFieldSize(3); aNewGame.Execute; end; { При выходе показывать форму входа } procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction); begin frmLogin.Show; end; end.
// Copyright (c) 2009, ConTEXT Project Ltd // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. unit regexpo; interface {$I ConTEXT.inc} uses winprocs, wintypes, registry, classes, sysutils, dialogs; {$I-} procedure ExportRegSettings; implementation uses uCommon; function dblBackSlash(t: string): string; var k: longint; begin result := t; {Strings are not allowed to have} for k := length(t) downto 1 do {single backslashes} if result[k] = '\' then insert('\', result, k); end; procedure ExportBranch(rootsection: DWord; regroot: string; filename: string); var reg: tregistry; f: textfile; p: PCHAR; procedure ProcessBranch(root: string); {recursive sub-procedure} var values, keys: tstringlist; i, j, k: longint; s, t: string; {longstrings are on the heap, not on the stack!} begin Writeln(f); {write blank line} case rootsection of HKEY_CLASSES_ROOT: s := 'HKEY_CLASSES_ROOT'; HKEY_CURRENT_USER: s := 'HKEY_CURRENT_USER'; HKEY_LOCAL_MACHINE: s := 'HKEY_LOCAL_MACHINE'; HKEY_USERS: s := 'HKEY_USERS'; HKEY_PERFORMANCE_DATA: s := 'HKEY_PERFORMANCE_DATA'; HKEY_CURRENT_CONFIG: s := 'HKEY_CURRENT_CONFIG'; HKEY_DYN_DATA: s := 'HKEY_DYN_DATA'; end; Writeln(f, '[' + s + '\' + root + ']'); {write section name in brackets} reg.OpenKey(root, false); values := tstringlist.create; keys := tstringlist.create; keys.clear; values.clear; reg.getvaluenames(values); {get all value names} reg.getkeynames(keys); {get all sub-branches} for i := 0 to values.count - 1 do {write all the values first} begin s := values[i]; t := s; {s=value name} if s = '' then s := '@' {empty means "default value", write as @} else s := '"' + s + '"'; {else put in quotes} write(f, dblbackslash(s) + '='); {write the name of the key to the file} case reg.Getdatatype(t) of {What type of data is it?} rdString, rdExpandString: {String-type} Writeln(f, '"' + dblbackslash(reg.readstring(t) + '"')); rdInteger: {32-bit unsigned long integer} Writeln(f, 'dword:' + inttohex(reg.readinteger(t), 8)); {write an array of hex bytes if data is "binary." Perform a line feed after approx. 25 numbers so the line length stays within limits} rdBinary: begin write(f, 'hex:'); j := reg.getdatasize(t); {determine size} getmem(p, j); {Allocate memory} reg.ReadBinaryData(t, p^, J); {read in the data, treat as pchar} for k := 0 to j - 1 do begin Write(f, inttohex(byte(p[k]), 2)); {Write byte as hex} if k <> j - 1 then {not yet last byte?} begin write(f, ','); {then write Comma} if (k > 0) and ((k mod 25) = 0) {line too long?} then writeln(f, '\'); {then write Backslash + lf} end; {if} end; {for} freemem(p, j); {free the memory} writeln(f); {Linefeed} end; else writeln(f, '""'); {write an empty string if datatype illegal/unknown} end; {case} end; {for} reg.closekey; {value names all done, no longer needed} values.free; {Now al values are written, we process all subkeys} {Perform this process RECURSIVELY...} for i := 0 to keys.count - 1 do ProcessBranch(root + '\' + keys[i]); keys.free; {this branch is ready} end; begin if regroot[length(regroot)] = '\' then {No trailing backslash} setlength(regroot, length(regroot) - 1); Assignfile(f, filename); {create a text file} rewrite(f); if ioresult <> 0 then EXIT; Writeln(f, 'REGEDIT4'); {"magic key" for regedit} reg := tregistry.create; try reg.rootkey := rootsection; ProcessBranch(regroot); {Call the function that writes the branch and all subbranches} finally reg.free; {ready} close(f); end; end; procedure ExportRegSettings; var dlgSave: TSaveDialog; s: string; begin dlgSave := TSaveDialog.Create(nil); try dlgSave.DefaultExt := 'reg'; dlgSave.Filter := 'Registry files (*.reg)|*.reg|All files (*.*)|*.*'; dlgSave.Options := dlgSave.Options + [ofOverwritePrompt]; if (dlgSave.Execute) then begin s := CONTEXT_REG_KEY; if s[1] = '\' then Delete(s, 1, 1); ExportBranch(HKEY_CURRENT_USER, s, dlgSave.FileName); end; finally dlgSave.Free; end; end; end.
unit brotli; interface uses sysutils; // Returns FALSE on error. function BrotliDecompress( const compressedData: TBytes; decompressedSize: SizeInt; out decompressedData: TBytes): Boolean; implementation {$LINKLIB brotlidec-static} {$LINKLIB brotlicommon-static} uses ctypes; type // TBrotliDecoderResult is a enum in the C header. TBrotliDecoderResult = cint; const // BrotliDecoderDecompress() returns either // BROTLI_DECODER_RESULT_SUCCESS or BROTLI_DECODER_RESULT_ERROR, so // we can't make a useful message for an exception. That's why our // BrotliDecompress() wrapper returns a boolean. BROTLI_DECODER_RESULT_SUCCESS = 1; function BrotliDecoderDecompress( encodedSize: csize_t; const encodedBuffer: Pointer; decodedSize: pcsize_t; decodedBuffer: Pointer): TBrotliDecoderResult; cdecl; external; function BrotliDecompress( const compressedData: TBytes; decompressedSize: SizeInt; out decompressedData: TBytes): Boolean; var brotliDecompressedSize: csize_t; brotliDecoderResult: TBrotliDecoderResult; begin if decompressedSize < 0 then exit(FALSE); SetLength(decompressedData, decompressedSize); brotliDecompressedSize := csize_t(decompressedSize); brotliDecoderResult := BrotliDecoderDecompress( Length(compressedData), Pointer(compressedData), @brotliDecompressedSize, Pointer(decompressedData)); result := (brotliDecoderResult = BROTLI_DECODER_RESULT_SUCCESS) and (brotliDecompressedSize = csize_t(decompressedSize)); end; end.
// RemObjects CS to Pascal 0.1 namespace UT3Bots.UTItems; interface uses System, System.Collections.Generic, System.Linq, System.Text, UT3Bots.Communications; type UTBotState = public abstract class(UTObject) protected //Common State variables var _rotation: UTVector; var _velocity: UTVector; var _name: String; var _health: Integer; var _armor: Integer; var _weapon: WeaponType := WeaponType.None; var _firingType: FireType; var _mesh: BotMesh; var _colour: BotColor; method UpdateState(playerMessage: Message);virtual; public //Constructor constructor (); constructor (Id: UTIdentifier; Location: UTVector; Rotation: UTVector; Velocity: UTVector; Name: String; Health: Integer; Armor: Integer; Weapon: WeaponType; Firing: FireType; Mesh: BotMesh; Color: BotColor); /// <summary> /// The actual name of this bot /// </summary> property Name: String read get_Name write set_Name; method get_Name: String; method set_Name(value: String); /// <summary> /// The amount of health this bot has (Between 0 and 200) /// </summary> property Health: Integer read get_Health write set_Health; method get_Health: Integer; method set_Health(value: Integer); /// <summary> /// The amount of armor this bot has /// </summary> property ArmorStrength: Integer read get_ArmorStrength write set_ArmorStrength; method get_ArmorStrength: Integer; method set_ArmorStrength(value: Integer); /// <summary> /// The 3D Vector of which way this bot is facing (X, Y, Z = Yaw, Pitch, Roll) /// </summary> property Rotation: UTVector read get_Rotation write set_Rotation; method get_Rotation: UTVector; method set_Rotation(value: UTVector); /// <summary> /// The Angle in degrees of which way this bot is facing from a top down view /// </summary> property RotationAngle: Double read get_RotationAngle; method get_RotationAngle: Double; /// <summary> /// The 3D Vector of which direction and how fast this bot is moving /// </summary> property Velocity: UTVector read get_Velocity; method get_Velocity: UTVector; /// <summary> /// The skinned colour of this bot /// </summary> property Color: BotColor read get_Color; method get_Color: BotColor; /// <summary> /// The mesh of this bot /// </summary> property Mesh: BotMesh read get_Mesh; method get_Mesh: BotMesh; /// <summary> /// The weapon currently selected by this bot /// </summary> property Weapon: WeaponType read get_Weapon; method get_Weapon: WeaponType; /// <summary> /// Whether this bot is currently not firing, firing or alt-firing /// </summary> property FiringType: FireType read get_FiringType write set_FiringType; method get_FiringType: FireType; method set_FiringType(value: FireType); /// <summary> /// Is the bot firing /// </summary> property IsFiring: Boolean read get_IsFiring; method get_IsFiring: Boolean; end; implementation method UTBotState.UpdateState(playerMessage: Message); begin if ((playerMessage <> nil) and ((playerMessage.Info = InfoMessage.PLAYER_INFO) or (playerMessage.Info = InfoMessage.SELF_INFO))) then begin Self._id := new UTIdentifier(playerMessage.Arguments[0]); Self._location := UTVector.Parse(playerMessage.Arguments[1]); Self._rotation := UTVector.Parse(playerMessage.Arguments[2]); Self._velocity := UTVector.Parse(playerMessage.Arguments[3]); Self._name := playerMessage.Arguments[4]; Self._health := Integer.Parse(playerMessage.Arguments[5]); Self._armor := Integer.Parse(playerMessage.Arguments[6]); Self._weapon := playerMessage.Arguments[7].GetAsWeaponType(); Self._firingType := FireType((Integer.Parse(playerMessage.Arguments[8]))); Self._mesh := BotMesh((Integer.Parse(playerMessage.Arguments[9]))); Self._colour := BotColor((Integer.Parse(playerMessage.Arguments[10]))); end; end; constructor UTBotState(); begin inherited constructor(nil, nil); end; constructor UTBotState(Id: UTIdentifier; Location: UTVector; Rotation: UTVector; Velocity: UTVector; Name: String; Health: Integer; Armor: Integer; Weapon: WeaponType; Firing: FireType; Mesh: BotMesh; Color: BotColor); begin inherited constructor(Id, Location); Self._rotation := Rotation; Self._velocity := Velocity; Self._name := Name; Self._health := Health; Self._armor := Armor; Self._weapon := Weapon; Self._firingType := Firing; Self._mesh := Mesh; Self._colour := Color; end; method UTBotState.get_Name: String; begin Result := Self._name; end; method UTBotState.set_Name(value: String); begin Self._name := value; OnPropertyChanged('Name') end; method UTBotState.get_Health: Integer; begin Result := Self._health; end; method UTBotState.set_Health(value: Integer); begin Self._health := value; OnPropertyChanged('Health') end; method UTBotState.get_ArmorStrength: Integer; begin Result := Self._armor; end; method UTBotState.set_ArmorStrength(value: Integer); begin Self._armor := value; OnPropertyChanged('ArmorStrength') end; method UTBotState.get_Rotation: UTVector; begin Result := Self._rotation; end; method UTBotState.set_Rotation(value: UTVector); begin Self._rotation := value; OnPropertyChanged('Rotation'); OnPropertyChanged('RotationAngle') end; method UTBotState.get_RotationAngle: Double; begin Result := (Self._rotation.Y / 65535) * 360; end; method UTBotState.get_Velocity: UTVector; begin Result := Self._velocity; end; method UTBotState.get_Color: BotColor; begin Result := Self._colour; end; method UTBotState.get_Mesh: BotMesh; begin Result := Self._mesh; end; method UTBotState.get_Weapon: WeaponType; begin Result := Self._weapon; end; method UTBotState.get_FiringType: FireType; begin Result := Self._firingType; end; method UTBotState.set_FiringType(value: FireType); begin Self._firingType := value; OnPropertyChanged('FiringType'); OnPropertyChanged('IsFiring'); end; method UTBotState.get_IsFiring: Boolean; begin Result := (Self._firingType <> FireType.None); end; end.
begin write('Hello world!', ''#10'') end.
unit appconfig; interface uses Classes, Windows, SysUtils, Forms, IniFiles, Registry, Vcl.DBGrids, Grids.Helper, strtools; type TAppParams = class public class function Exists(ParamNames: array of string): boolean; end; TAppConfig = class(TComponent) private F: TObject; FActive: boolean; FAutoOpen: boolean; FFilename: string; FOnChangeState: TNotifyEvent; protected procedure SetActive(AActive: boolean); procedure SetFilename(const AFilename: string); procedure DoOnChangeState; procedure DoOpen; virtual; abstract; procedure DoClose; virtual; function GetDefFilename: string; virtual; abstract; function DoReadString(const Section, Ident: string; const Def: string): string; virtual; abstract; procedure DoWriteString(const Section, Ident: string; const Value: string); virtual; abstract; function Check(const Section, Ident: string): boolean; function CheckObject(const Def: Vcl.DBGrids.TDBGrid): boolean; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Open(const AFilename: string): boolean; overload; function Open: boolean; overload; procedure Close; procedure Write(const Section, Ident: string; const Value: boolean); overload; procedure Write(const Section, Ident: string; const Value: string); overload; procedure Write(const Section, Ident: string; const Value: Longint); overload; virtual; abstract; procedure Write(const Section, Ident: string; const Value: TDateTime); overload; virtual; abstract; procedure Write(const Section, Ident: string; const Value: TForm); overload; procedure Write(const Section, Ident: string; const Value: TGridFields); overload; procedure Write(const Section, Ident: string; const Value: Vcl.DBGrids.TDBGrid); overload; function Read(const Section, Ident: string; const Def: boolean): boolean; overload; function Read(const Section, Ident: string; const Def: string): string; overload; function Read(const Section, Ident: string; const Def: Longint): Longint; overload; virtual; abstract; function Read(const Section, Ident: string; const Def: TDateTime): TDateTime; overload; virtual; abstract; function Read(const Section, Ident: string; const Def: TForm): TForm; overload; function Read(const Section, Ident: string; const Def: TGridFields): TGridFields overload; function Read(const Section, Ident: string; const Def: Vcl.DBGrids.TDBGrid): Vcl.DBGrids.TDBGrid; overload; published property Active: boolean read FActive write SetActive; property AutoOpen: boolean read FAutoOpen write FAutoOpen; property Filename: string read FFilename write SetFilename; property DefFilename: string read GetDefFilename; property OnChangeState: TNotifyEvent read FOnChangeState write FOnChangeState; end; TFileConfig = class(TAppConfig) private F: TIniFile; protected procedure DoOpen; override; function GetDefFilename: string; override; function DoReadString(const Section, Ident: string; const Def: string): string; override; procedure DoWriteString(const Section, Ident: string; const Value: string); override; public procedure Write(const Section, Ident: string; const Value: Longint); overload; override; procedure Write(const Section, Ident: string; const Value: TDateTime); overload; override; function Read(const Section, Ident: string; const Def: Longint): Longint; overload; override; function Read(const Section, Ident: string; const Def: TDateTime): TDateTime; overload; override; end; TRegIniFile = class(Registry.TRegIniFile) public procedure DoWriteBuffer(const Section, Ident: string; Buffer: Pointer; BufSize: Integer; RegData: TRegDataType); procedure DoReadBuffer(const Section, Ident: string; Buffer: Pointer; BufSize: Integer; RegData: TRegDataType); end; TRegConfig = class(TAppConfig) private F: TRegIniFile; protected procedure DoOpen; override; function GetDefFilename: string; override; function DoReadString(const Section, Ident: string; const Def: string): string; override; procedure DoWriteString(const Section, Ident: string; const Value: string); override; public procedure Write(const Section, Ident: string; const Value: Longint); overload; override; procedure Write(const Section, Ident: string; const Value: TDateTime); overload; override; function Read(const Section, Ident: string; const Def: Longint): Longint; overload; override; function Read(const Section, Ident: string; const Def: TDateTime): TDateTime; overload; override; end; implementation const cbool: array[boolean]of Longint = (0,1); // TAppParams class function TAppParams.Exists(ParamNames: array of string): boolean; var j, n: Integer; lparam: string; begin Result := false; for j := 1 to ParamCount do begin lparam := AnsiLowerCase(getname(Paramstr(j))); if lparam <> '' then begin if CharInSet(lparam[1], ['-', '\', '/']) then lparam := copy(lparam, 2); for n := 0 to Length(ParamNames) - 1 do if lparam = AnsiLowerCase(ParamNames[n]) then begin Result := true; exit; end; end; end; end; // TAppConfig constructor TAppConfig.Create(AOwner: TComponent); begin inherited Create(AOwner); FAutoOpen := true; FActive := false; FFilename := DefFilename; F := nil; FOnChangeState := nil; end; destructor TAppConfig.Destroy; begin FOnChangeState := nil; Close; inherited Destroy; end; procedure TAppConfig.SetActive(AActive: boolean); begin if AActive then Open else Close; end; procedure TAppConfig.SetFilename(const AFilename: string); var lname: string; begin lname := AnsiLowerCase(Trim(AFilename)); if lname<>'' then if lname <> AnsiLowerCase(Filename) then begin Close; FFilename := Trim(AFilename); end; end; procedure TAppConfig.DoOnChangeState; begin if Assigned(FOnChangeState) then FOnChangeState(Self); end; function TAppConfig.Open(const AFilename: string): boolean; begin SetFilename(AFilename); Result := Open; end; function TAppConfig.Open: boolean; begin if not FActive then begin DoOpen; end; Result := FActive; end; procedure TAppConfig.Close; begin if not FActive then begin DoClose; end; end; procedure TAppConfig.DoClose; begin if Assigned(F) then begin F.Free; F := nil; FActive := false; DoOnChangeState; end; end; function TAppConfig.Check(const Section, Ident: string): boolean; begin Result := false; if FActive then begin Result := (Section <> '') and (Ident <> ''); end else if FAutoOpen then if Open then begin Result := (Section <> '') and (Ident <> ''); end; end; function TAppConfig.CheckObject(const Def: Vcl.DBGrids.TDBGrid): boolean; begin Result := false; if Assigned(Def) then if Assigned(Def.DataSource) then if Assigned(Def.DataSource.DataSet) then if Def.DataSource.DataSet.Active then Result := true; end; // read function TAppConfig.Read(const Section, Ident: string; const Def: boolean): boolean; begin Result := Read(Section, Ident, cbool[Def])=cbool[true]; end; function TAppConfig.Read(const Section, Ident: string; const Def: string): string; begin if Check(Section, Ident) then begin Result := DoReadString(Section, Ident, Def); end else begin Result := Def; end; end; function TAppConfig.Read(const Section, Ident: string; const Def: TForm): TForm; var buff: string; fpos: array [0 .. 4] of Integer; begin if Check(Section, Ident) then begin buff := DoReadString(Section, Ident, ''); fpos[0] := Def.Left; fpos[1] := Def.Top; fpos[2] := Def.Width; fpos[3] := Def.Height; fpos[4] := Integer(Def.WindowState); if expand4int(buff, @fpos[0], 4) > 3 then begin Def.Left := fpos[0]; Def.Top := fpos[1]; Def.Width := fpos[2]; Def.Height := fpos[3]; Def.WindowState := TWindowState(fpos[4]); end; end; Result := Def; end; function TAppConfig.Read(const Section, Ident: string; const Def: TGridFields): TGridFields; var fld: TGridField; buff: string; fpos: array [0 .. 1] of Integer; j: Integer; begin Result := Def; if Check(Section, Ident) then begin Def.DisableControls; for j := 0 to Def.Count - 1 do begin fld := Def[j]; buff := DoReadString(Section + '\' + Ident, fld.Name, ''); fpos[0] := fld.Column; fpos[1] := fld.Width; if expand4int(buff, @fpos[0], 2) > 1 then begin fld.Column := fpos[0]; fld.Width := fpos[1]; end; end; Def.EnableControls; end; end; function TAppConfig.Read(const Section, Ident: string; const Def: Vcl.DBGrids.TDBGrid): Vcl.DBGrids.TDBGrid; var col: TColumn; j, w: Integer; begin Result := Def; if CheckObject(Def) then if Check(Section, Ident) then begin for j := 0 to Def.Columns.Count - 1 do begin col := Def.Columns[j]; w := Read(Section + '\' + Ident, col.FieldName, col.Width); if w > (Def.Width - 40) then w := (Def.Width - 40); col.Width := w; end; end; end; // write procedure TAppConfig.Write(const Section, Ident: string; const Value: boolean); begin Write(Section, Ident, cbool[Value]); end; procedure TAppConfig.Write(const Section, Ident: string; const Value: string); begin if Check(Section, Ident) then begin DoWriteString(Section, Ident, Value); end; end; procedure TAppConfig.Write(const Section, Ident: string; const Value: TForm); var buff: string; fpos: array [0 .. 4] of Integer; begin if Check(Section, Ident) then begin if Value.WindowState = wsNormal then begin buff := Format('%d:%d:%d:%d:%d', [Value.Left, Value.Top, Value.Width, Value.Height, Integer(Value.WindowState)]); DoWriteString(Section, Ident, buff); end else begin buff := TIniFile(F).ReadString(Section, Ident, ''); if expand4int(buff, @fpos[0], 5) > 3 then begin buff := Format('%d:%d:%d:%d:%d', [fpos[0], fpos[1], fpos[2], fpos[3], Integer(Value.WindowState)]); DoWriteString(Section, Ident, buff); end; end; end; end; procedure TAppConfig.Write(const Section, Ident: string; const Value: TGridFields); var fld: TGridField; j: Integer; begin if Check(Section, Ident) then begin Value.Realign; for j := 0 to Value.Count - 1 do begin fld := Value[j]; Write(Section + '\' + Ident, fld.Name, Format('%d:%d', [fld.Column, fld.Width])); end; end; end; procedure TAppConfig.Write(const Section, Ident: string; const Value: Vcl.DBGrids.TDBGrid); var col: TColumn; j: Integer; begin if CheckObject(Value) then if Check(Section, Ident) then begin for j := 0 to Value.Columns.Count - 1 do begin col := Value.Columns[j]; Write(Section + '\' + Ident, col.FieldName, col.Width); end; end; end; // TFileConfig procedure TFileConfig.DoOpen; begin DoClose; if FFilename <> '' then begin F := TIniFile.Create(FFilename); FActive := true; DoOnChangeState; end; end; function TFileConfig.GetDefFilename: string; begin Result := ChangeFileExt(Paramstr(0), '.conf'); end; function TFileConfig.DoReadString(const Section, Ident: string; const Def: string): string; begin Result := TIniFile(F).ReadString(Section, Ident, Def); end; procedure TFileConfig.DoWriteString(const Section, Ident: string; const Value: string); begin TIniFile(F).WriteString(Section, Ident, Value); end; procedure TFileConfig.Write(const Section, Ident: string; const Value: Longint); begin if Check(Section, Ident) then begin TIniFile(F).WriteInteger(Section, Ident, Value); end; end; procedure TFileConfig.Write(const Section, Ident: string; const Value: TDateTime); begin if Check(Section, Ident) then begin TIniFile(F).WriteDateTime(Section, Ident, Value); end; end; function TFileConfig.Read(const Section, Ident: string; const Def: Longint): Longint; begin if Check(Section, Ident) then begin Result := TIniFile(F).ReadInteger(Section, Ident, Def); end else begin Result := Def; end; end; function TFileConfig.Read(const Section, Ident: string; const Def: TDateTime): TDateTime; begin if Check(Section, Ident) then begin Result := TIniFile(F).ReadDateTime(Section, Ident, Def); end else begin Result := Def; end; end; // TRegIniFile procedure TRegIniFile.DoWriteBuffer(const Section, Ident: string; Buffer: Pointer; BufSize: Integer; RegData: TRegDataType); var Key, OldKey: HKEY; begin CreateKey(Section); Key := GetKey(Section); if Key <> 0 then try OldKey := CurrentKey; SetCurrentKey(Key); try PutData(Ident, Buffer, BufSize, RegData); finally SetCurrentKey(OldKey); end; finally RegCloseKey(Key); end; end; procedure TRegIniFile.DoReadBuffer(const Section, Ident: string; Buffer: Pointer; BufSize: Integer; RegData: TRegDataType); var Key, OldKey: HKEY; begin CreateKey(Section); Key := GetKey(Section); if Key <> 0 then try OldKey := CurrentKey; SetCurrentKey(Key); try GetData(Ident, Buffer, BufSize, RegData); finally SetCurrentKey(OldKey); end; finally RegCloseKey(Key); end; end; // TRegConfig procedure TRegConfig.DoOpen; begin DoClose; if FFilename <> '' then begin F := TRegIniFile.Create(FFilename); FActive := true; DoOnChangeState; end; end; function TRegConfig.GetDefFilename: string; begin Result := 'Software\' + ChangeFileExt(ExtractFilename(Paramstr(0)), ''); end; function TRegConfig.DoReadString(const Section, Ident: string; const Def: string): string; begin Result := TRegIniFile(F).ReadString(Section, Ident, Def); end; procedure TRegConfig.DoWriteString(const Section, Ident: string; const Value: string); begin TRegIniFile(F).WriteString(Section, Ident, Value); end; procedure TRegConfig.Write(const Section, Ident: string; const Value: Longint); begin if Check(Section, Ident) then begin TRegIniFile(F).WriteInteger(Section, Ident, Value); end; end; procedure TRegConfig.Write(const Section, Ident: string; const Value: TDateTime); begin if Check(Section, Ident) then begin TRegIniFile(F).DoWriteBuffer(Section, Ident, @Value, SizeOf(TDateTime), rdBinary); end; end; function TRegConfig.Read(const Section, Ident: string; const Def: Longint): Longint; begin if Check(Section, Ident) then begin Result := TRegIniFile(F).ReadInteger(Section, Ident, Def); end else begin Result := Def; end; end; function TRegConfig.Read(const Section, Ident: string; const Def: TDateTime): TDateTime; begin Result := Def; if Check(Section, Ident) then begin TRegIniFile(F).DoReadBuffer(Section, Ident, @Result, SizeOf(TDateTime), rdBinary); end; end; end.
unit uCDMappingTypes; interface uses System.Types, System.Classes, System.SysUtils, System.StrUtils, uProgramStatInfo, uMemory; const TCD_CLASS_TAG_NONE = 0; TCD_CLASS_TAG_NO_QUESTION = 1; C_CD_MAP_FILE = 'DBCDMap.map'; type // File strusts////////////////////////////////////// TCDIndexFileHeader = record ID: string[20]; Version: Byte; DBVersion: Integer; end; TCDIndexFileHeaderV1 = record CDLabel: string[255]; Date: TDateTime; end; TCDIndexInfo = record CDLabel: string[255]; Date: TDateTime; DBVersion: Integer; Loaded: Boolean; end; // DB Structs///////////////////////////////////////// TCDDataArrayItem = record Name: string[255]; CDRelativePath: string; end; TCDDataArray = record CDName: string; Data: array of TCDDataArrayItem; end; TCDIndexMappingDirectory = class private FFiles: TList; function GetFileByIndex(FileIndex: Integer): TCDIndexMappingDirectory; function GetCount: Integer; public Name: string; IsFile: Boolean; Parent: TCDIndexMappingDirectory; IsReal: Boolean; RealFileName: string; DB_ID: Integer; FileSize: Int64; constructor Create; destructor Destroy; override; function Add(Item: TCDIndexMappingDirectory): Integer; property Items[FileIndex: Integer]: TCDIndexMappingDirectory read GetFileByIndex; default; property Count: Integer read GetCount; procedure Remove(var Item : TCDIndexMappingDirectory); procedure Delete(Index: Integer); property Files: TList read FFiles; end; TDBFilePath = record FileName: string; ID: Integer; end; TDBFilePathArray = array of TDBFilePath; type TCDClass = class(TObject) public Name: string; Path: string; Tag: Integer; end; TCDDBMapping = class(TObject) private CDLoadedList: TList; CDFindedList: TList; public constructor Create; destructor Destroy; override; function GetCDByName(CDName: string): TCDClass; function GetCDByNameInternal(CDName: string): TCDClass; procedure DoProcessPath(var FileName: string; CanUserNotify: Boolean = False); function ProcessPath(FileName: string; CanUserNotify: Boolean = False): string; procedure AddCDMapping(CDName: string; Path: string; Permanent: Boolean); procedure RemoveCDMapping(CDName: string); function GetFindedCDList: TList; procedure SetCDWithNOQuestion(CDName: string); procedure UnProcessPath(var Path: string); end; TCheckCDFunction = function(CDName: string) : Boolean; var CheckCDFunction: TCheckCDFunction = nil; function CDMapper: TCDDBMapping; function ProcessPath(FileName: string; CanUserNotify: Boolean = False): string; procedure DoProcessPath(var FileName: string; CanUserNotify: Boolean = False); procedure UnProcessPath(var FileName: string); function StaticPath(FileName: string): Boolean; implementation var FCDMapper: TCDDBMapping = nil; function CDMapper: TCDDBMapping; begin if FCDMapper = nil then FCDMapper := TCDDBMapping.Create; Result := FCDMapper; end; function StaticPath(FileName: string): Boolean; begin Result := True; if Copy(FileName, 1, 2) = '::' then if PosEx('::', FileName, 3) > 0 then Result := False; end; procedure DoProcessPath(var FileName: string; CanUserNotify: Boolean = False); begin CDMapper.DoProcessPath(FileName, CanUserNotify); end; procedure UnProcessPath(var FileName: string); begin CDMapper.UnProcessPath(FileName); end; function ProcessPath(FileName: string; CanUserNotify: Boolean = False): string; begin Result := CDMapper.ProcessPath(FileName, CanUserNotify); end; { TCDIndexMappingDirectory } function TCDIndexMappingDirectory.Add( Item: TCDIndexMappingDirectory): Integer; begin Result := FFiles.Add(Item); end; constructor TCDIndexMappingDirectory.Create; begin FFiles := TList.Create; Parent := nil; end; procedure TCDIndexMappingDirectory.Delete(Index: Integer); begin Items[Index].Free; FFiles.Delete(Index); end; destructor TCDIndexMappingDirectory.Destroy; begin FreeList(FFiles); inherited; end; function TCDIndexMappingDirectory.GetCount: Integer; begin Result := FFiles.Count; end; function TCDIndexMappingDirectory.GetFileByIndex( FileIndex: Integer): TCDIndexMappingDirectory; begin Result := FFiles[FileIndex]; end; procedure TCDIndexMappingDirectory.Remove(var Item: TCDIndexMappingDirectory); begin FFiles.Remove(Item); F(Item); end; { TCDDBMapping } procedure TCDDBMapping.AddCDMapping(CDName, Path: string; Permanent: boolean); var CD: TCDClass; begin CD := GetCDByName(CDName); if CD <> nil then begin CD.Path := Path; Exit; end; ProgramStatistics.CDMappingUsed; CD := TCDClass.Create; CD.Name := CDName; CD.Tag := TCD_CLASS_TAG_NONE; CD.Path := Path; CDLoadedList.Add(CD); if GetCDByNameInternal(CDName) = nil then begin CD := TCDClass.Create; CD.Name := CDName; CD.Tag := TCD_CLASS_TAG_NONE; CD.Path := Path; CDFindedList.Add(CD); end; end; constructor TCDDBMapping.Create; begin CDLoadedList := TList.Create; CDFindedList := TList.Create; end; destructor TCDDBMapping.Destroy; begin FreeList(CDLoadedList); FreeList(CDFindedList); inherited; end; procedure TCDDBMapping.DoProcessPath(var FileName: string; CanUserNotify: boolean); var P: Integer; MapResult: Boolean; CD: TCDClass; CDName: string; begin if Copy(FileName, 1, 2) = '::' then begin P := PosEx('::', FileName, 3); if P > 0 then begin CDName := Copy(FileName, 3, P - 3); CD := GetCDByName(CDName); if CD <> nil then begin Delete(FileName, 1, P + 2); FileName := CD.Path + FileName; end else begin CD := GetCDByNameInternal(CDName); if CD = nil then begin CD := TCDClass.Create; CD.name := CDName; CD.Tag := TCD_CLASS_TAG_NONE; CD.Path := ''; CDFindedList.Add(CD); end; if CanUserNotify then begin CD := GetCDByNameInternal(CDName); if CD.Tag <> TCD_CLASS_TAG_NO_QUESTION then begin MapResult := CheckCDFunction(CDName); if MapResult then DoProcessPath(FileName, CanUserNotify); end; end; end; end; end; end; function TCDDBMapping.GetCDByName(CDName: string): TCDClass; var I: Integer; CD : TCDClass; begin Result := nil; for I := 0 to CDLoadedList.Count - 1 do begin CD := TCDClass(CDLoadedList[I]); if AnsiLowerCase(CD.Name) = AnsiLowerCase(CDName) then begin Result := CD; Break; end; end; end; function TCDDBMapping.GetCDByNameInternal(CDName: string): TCDClass; var I: Integer; CD : TCDClass; begin Result := nil; for I := 0 to CDFindedList.Count - 1 do begin CD := TCDClass(CDFindedList[I]); if AnsiLowerCase(CD.Name) = AnsiLowerCase(CDName) then begin Result := CD; Break; end; end; end; function TCDDBMapping.GetFindedCDList: TList; begin Result := CDFindedList; end; function TCDDBMapping.ProcessPath(FileName: string; CanUserNotify: boolean): string; begin Result := FileName; DoProcessPath(Result, CanUserNotify); end; procedure TCDDBMapping.RemoveCDMapping(CDName: string); var CD: TCDClass; begin CD := GetCDByName(CDName); if CD <> nil then begin CDLoadedList.Remove(CD); F(CD); end; end; procedure TCDDBMapping.SetCDWithNOQuestion(CDName: string); var CD: TCDClass; begin CD := GetCDByNameInternal(CDName); if CD <> nil then CD.Tag := TCD_CLASS_TAG_NO_QUESTION; end; procedure TCDDBMapping.UnProcessPath(var Path: string); var I: Integer; CDPath: string; CD: TCDClass; begin for I := 0 to CDLoadedList.Count - 1 do begin CD := TCDClass(CDLoadedList[I]); if CD.Path <> '' then begin CDPath := ExcludeTrailingBackslash(CD.Path); if AnsiLowerCase(Copy(Path, 1, Length(CDPath))) = AnsiLowerCase(CDPath) then begin Delete(Path, 1, Length(CDPath)); Path := AnsiLowerCase('::' + CD.name + '::' + Path); end; end; end; end; initialization finalization F(FCDMapper); end.
unit cxmycombobox; interface uses Windows, Classes, SysUtils, StrUtils, cxVariants, dxMessages, cxFilterControlUtils, cxContainer, cxEdit, cxTextEdit, cxControls, cxDropDownEdit, cxEditRepositoryItems; type tcxMyComboBox = class; TOnBeforeGetItems = procedure(Sender: TObject; SearchWord: string; Items: TStrings) of object; TcxMyComboBoxProperties = class(cxDropDownEdit.TcxComboBoxProperties) private FWordMode: Boolean; fSpacer,fSeparator,fIsolator:String; fOnBeforeGetItems: TOnBeforeGetItems; public constructor Create(AOwner: TPersistent); override; procedure Assign(Source: TPersistent); override; class function GetContainerClass: TcxContainerClass; override; property WordMode: Boolean read FWordMode write FWordMode default false; property Spacer: String read fSpacer write fSpacer; property Separator: String read fSeparator write fSeparator; property Isolator: String read fIsolator write fIsolator; property OnBeforeGetItems: TOnBeforeGetItems read fOnBeforeGetItems write fOnBeforeGetItems; end; TcxMyEditRepositoryComboBoxItem = class(cxEditRepositoryItems.TcxEditRepositoryComboBoxItem) private function GetProperties: TcxMyComboBoxProperties; procedure SetProperties(Value: TcxMyComboBoxProperties); public class function GetEditPropertiesClass: TcxCustomEditPropertiesClass; override; published property Properties: TcxMyComboBoxProperties read GetProperties write SetProperties; end; TcxCustomTextEditProperties = class(cxTextEdit.TcxCustomTextEditProperties); tcxMyComboBox = class(cxDropDownEdit.TcxComboBox) private fSelectedFromList: Boolean; function GetActiveProperties: TcxMyComboBoxProperties; function GetProperties: TcxMyComboBoxProperties; procedure SetProperties(Value: TcxMyComboBoxProperties); protected function GetWord(s: string; var sstart: integer; slen: integer; full: boolean = false): string; function ChangeWord(wrd: string; includesep: boolean = false): integer; procedure HandleSelectItem(Sender: TObject); override; procedure DoEditKeyPress(var Key: Char); override; procedure MaskEditPressKey(var Key: Char); procedure TextEditPressKey(var Key: Char); public class function GetPropertiesClass: TcxCustomEditPropertiesClass; override; property ActiveProperties: TcxMyComboBoxProperties read GetActiveProperties; property Properties: TcxMyComboBoxProperties read GetProperties write SetProperties; end; TcxMyFilterComboBoxHelper = class(TcxFilterDropDownEditHelper) public class function GetFilterEditClass: TcxCustomEditClass; override; class procedure InitializeProperties(AProperties, AEditProperties: TcxCustomEditProperties; AHasButtons: Boolean); override; end; implementation constructor TcxMyComboBoxProperties.Create(AOwner: TPersistent); begin inherited; fSpacer := '_'; fSeparator := ' '; fIsolator := ''; end; procedure TcxMyComboBoxProperties.Assign(Source: TPersistent); begin if Source is TcxMyComboBoxProperties then begin BeginUpdate; try inherited Assign(Source); with Source as TcxMyComboBoxProperties do begin Self.WordMode := WordMode; Self.Spacer := Spacer; Self.Separator := Separator; Self.Isolator := Isolator; Self.OnBeforeGetItems := OnBeforeGetItems; // Self.DropDownListStyle := DropDownListStyle; // Self.DropDownRows := DropDownRows; // Self.ItemHeight := ItemHeight; // Self.Revertable := Revertable; // // Self.OnDrawItem := OnDrawItem; // Self.OnMeasureItem := OnMeasureItem; end; finally EndUpdate; end end else inherited Assign(Source); end; class function TcxMyComboBoxProperties.GetContainerClass: TcxContainerClass; begin result := tcxMyComboBox; end; function TcxMyEditRepositoryComboBoxItem.GetProperties: TcxMyComboBoxProperties; begin Result := inherited Properties as TcxMyComboBoxProperties; end; procedure TcxMyEditRepositoryComboBoxItem.SetProperties(Value: TcxMyComboBoxProperties); begin inherited Properties := Value; end; class function TcxMyEditRepositoryComboBoxItem.GetEditPropertiesClass: TcxCustomEditPropertiesClass; begin Result := TcxMyComboBoxProperties; end; class function TcxMyComboBox.GetPropertiesClass: TcxCustomEditPropertiesClass; begin result := tcxMyComboBoxProperties; end; function TcxMyComboBox.GetActiveProperties: TcxMyComboBoxProperties; begin Result := TcxMyComboBoxProperties(InternalGetActiveProperties); end; function TcxMyComboBox.GetProperties: TcxMyComboBoxProperties; begin Result := TcxMyComboBoxProperties(FProperties); end; procedure TcxMyComboBox.SetProperties(Value: TcxMyComboBoxProperties); begin FProperties.Assign(Value); end; function tcxMyComboBox.GetWord(s: string; var sstart: integer; slen: integer; full: boolean = false): string; var n,i,j,astart,aend,ssStart: integer; begin if not properties.WordMode then begin result := s; Exit; end; // s := DisplayValue; if SelLength < 0 then n := sstart + slen + 1 else n := sstart + 1; ssStart := 1; astart := 1; aend := 0; if Properties.Isolator <> '' then begin j := PosEx(Properties.Isolator,s); while j > 0 do begin if j < n then astart := j + 1; j := PosEx(Properties.Isolator,s,j + 1); if j = 0 then begin j := 1; Break; end else if j < n then begin ssStart := j + 1; j := PosEx(Properties.Isolator,s,j + 1); end else begin aend := j; Break; end; end; end else j := 0; if j = 0 then begin i := PosEx(properties.Separator,s,ssStart); if i > 0 then while i > 0 do begin if i < n then astart := i + 1 else begin aend := i; Break; end; i := PosEx(properties.Separator,s,i + 1); end; end; if aend = 0 then if full then aend := length(s) + 1 else begin if s[sstart] <> properties.Isolator then aend := sstart + 1 else aend := sstart; end; { if aend > SelStart then aend := SelStart + SelLength; } if (slen > 0) and (aend > sstart) then aend := sstart + 1; result := copy(s,astart,aend-astart); sStart := sStart - aStart + 1; //InternalEditValue := copy(s,1,astart) + wrd + copy(s,aend,length(Text)-aend+1); //result := astart + length(wrd); end; function tcxMyComboBox.ChangeWord(wrd: string; includesep: boolean = false): integer; var s: string; n,i,j,astart,aend,sStart: integer; begin wrd := Properties.Isolator + wrd + Properties.Isolator; s := DisplayValue; if SelLength < 0 then n := SelStart + SelLength + 1 else n := SelStart + 1; sStart := 1; aStart := 0; aEnd := 0; if Properties.Isolator <> '' then begin j := PosEx(Properties.Isolator,s); while j > 0 do begin if j < n then astart := j - 1; j := PosEx(Properties.Isolator,s,j + 1); if j = 0 then begin j := 1; Break; end else if j < n then begin sStart := j + 1; j := PosEx(Properties.Isolator,s,j + 1); end else begin aend := j + 1; Break; end; end; end else j := 0; if j = 0 then begin i := PosEx(Properties.Separator,s,sStart); if i > 0 then while i > 0 do begin if i < n then astart := i else begin aend := i; Break; end; i := PosEx(Properties.Separator,s,i + 1); end; end; if aend = 0 then aend := length(DisplayValue) + 1; { if astart<>aend then result := trim(Copy(s,astart,aend-astart)) + ' ' else result := ''; } if includesep then begin DataBinding.DisplayValue := copy(s,1,astart) + wrd + copy(s,aend,length(s)-aend+1) + Properties.Separator; result := astart + length(wrd) + length(Properties.Separator); end else begin DataBinding.DisplayValue := copy(s,1,astart) + wrd + copy(s,aend,length(s)-aend+1); result := astart + length(wrd); end; end; procedure tcxMyComboBox.HandleSelectItem(Sender: TObject); //override; var ANewEditValue: TcxEditValue; AEditValueChanged: Boolean; n: integer; sStart: integer; s: string; begin if (Properties.DropDownListStyle <> lsEditList) or not properties.WordMode then begin inherited; Exit; end; //if ModifiedAfterEnter then // Exit; ANewEditValue := LookupKeyToEditValue(ILookupData.CurrentKey); sStart := SelStart + SelLength; s := GetWord(DisplayValue,sStart,0); AEditValueChanged := not VarEqualsExact(s, ANewEditValue); if FLookupDataTextChangedLocked and not AEditValueChanged then Exit; //if FSelectedFromList then //begin // FSelectedFromList := false; // Exit; //end; if AEditValueChanged and not DoEditing then Exit; SaveModified; LockLookupDataTextChanged; try n := ChangeWord(ANewEditValue, true); fSelectedFromList := true; finally UnlockLookupDataTextChanged; RestoreModified; end; if AEditValueChanged then ModifiedAfterEnter := True; SelStart := n; ShortRefreshContainer(False); end; procedure tcxMyComboBox.TextEditPressKey(var Key: Char); function FillFromList(var AFindText: string): Boolean; var ATail: string; L: Integer; S: string; begin S := AFindText; if InnerTextEdit.ImeLastChar <> #0 then S := S + InnerTextEdit.ImeLastChar; if Assigned(Properties.OnBeforeGetItems) then Properties.OnBeforeGetItems(Self,S,Properties.Items); { if S = '' then begin Result := false; FindSelection := false; Exit; end; } Result := ILookupData.Locate(S, ATail, False); if Result then begin AFindText := S; if InnerTextEdit.ImeLastChar <> #0 then begin L := Length(AFindText); Insert(Copy(AFindText, L, 1), ATail, 1); Delete(AFindText, L, 1); end; end; FindSelection := Result; if AFindText = '' then begin if (TcxCustomTextEditProperties(ActiveProperties).EditingStyle <> esFixedList) and not Properties.WordMode then InternalSetDisplayValue(''); FindSelection := False; end; if Result then begin L := ChangeWord(AFindText + ATail); //DataBinding.DisplayValue := AFindText + ATail; SelStart := L - length(ATail) - length(Properties.fIsolator);//Length(AFindText); SelLength := Length(ATail) + length(Properties.fIsolator); end; UpdateDrawValue; end; function CanContinueIncrementalSearch: Boolean; begin Result := TcxCustomTextEditProperties(ActiveProperties).EditingStyle in [esEditList, esFixedList]; if not Result then Result := (SelLength = 0) {and (SelStart = Length(DisplayValue))} or FindSelection or (SelLength > 0); end; var AEditingStyle: TcxEditEditingStyle; AFindText: string; AFound: Boolean; APrevCurrentKey: TcxEditValue; APrevFindSelection: Boolean; sStart: integer; begin AEditingStyle := TcxCustomTextEditProperties(ActiveProperties).EditingStyle; InnerTextEdit.InternalUpdating := True; ValidateKeyPress(Key); if (Key = #0) then exit; //else if (AEditingStyle <> esEditList) //and properties.WordMode and (Key = properties.Spacer) then //begin // DroppedDown := false; // Exit; //end; UnlockLookupDataTextChanged; KeyboardAction := True; if AEditingStyle = esFixedList then case Key of #8: if not TcxCustomTextEditProperties(ActiveProperties).FixedListSelection then begin Key := #0; FindSelection := False; end; end; APrevCurrentKey := ILookupData.CurrentKey; APrevFindSelection := FindSelection; AFound := False; LockClick(True); try if Key = #8 then begin if TcxCustomTextEditProperties(ActiveProperties).UseLookupData then begin if TcxCustomTextEditProperties(ActiveProperties).CanIncrementalSearch then begin if ((AEditingStyle = esEditList) or (AEditingStyle = esEdit) and Properties.WordMode) and (Length(DisplayValue) > 0) and not FindSelection then begin //SelLength := Length(DisplayValue) - SelStart; FindSelection := True; end; if FindSelection then begin sStart := SelStart; AFindText := GetWord(DisplayValue,sStart,SelLength);//Copy(DisplayValue, 1, Length(DisplayValue) - SelLength); SetLength(AFindText, Length(AFindText) - Length(AnsiLastChar(AFindText))); LockLookupDataTextChanged; AFound := FillFromList(AFindText); end; if AEditingStyle = esFixedList then Key := #0; end else if Assigned(Properties.OnBeforeGetItems) then begin AFindText := DisplayValue; sStart := SelStart; if SelLength > 0 then begin Delete(AFindText,SelStart+1,SelLength); Properties.OnBeforeGetItems(Self,GetWord(AFindText,sStart,0),Properties.Items); end else begin Delete(AFindText,SelStart,1); dec(sStart,1 + length(Properties.Isolator)); Properties.OnBeforeGetItems(Self,GetWord(AFindText,sStart,0),Properties.Items); end; end; end; end else if IsTextChar(Key) then begin if TcxCustomTextEditProperties(ActiveProperties).UseLookupData then begin if TcxCustomTextEditProperties(ActiveProperties).CanIncrementalSearch and CanContinueIncrementalSearch then begin LockLookupDataTextChanged; AFound := False; AFindText := DisplayValue; sStart := SelStart; if SelLength > 0 then AFindText := GetWord(AFindText,sStart,SelLength){Copy(AFindText, 1, SelStart)} + Key else if AEditingStyle = esFixedList then if FindSelection then begin AFindText := AFindText + Key; AFound := FillFromList(AFindText); if not AFound then AFindText := Key; end else AFindText := Key else Insert(Key, AFindText, SelStart + 1); if not AFound then begin inc(sStart); AFindText := GetWord(AFindText,sStart, 0); AFound := FillFromList(AFindText); end; if (AEditingStyle = esFixedList) and not TcxCustomTextEditProperties(ActiveProperties).FixedListSelection and not AFound then begin AFindText := Key; AFound := FillFromList(AFindText); end; end else if Assigned(Properties.OnBeforeGetItems) then begin sStart := SelStart; AFindText := GetWord(DisplayValue,sStart,SelLength); Insert(Key,AFindText,SelStart+1); Properties.OnBeforeGetItems(Self,AFindText,Properties.Items); end; if (AEditingStyle in [esEditList, esFixedList]) and not AFound then begin Key := #0; if (AEditingStyle = esEditList) and (DisplayValue <> '') or (AEditingStyle = esFixedList) and TcxCustomTextEditProperties(ActiveProperties).FixedListSelection and APrevFindSelection then FindSelection := True; end; end; end; finally LockClick(False); KeyboardAction := False; if TcxCustomTextEditProperties(ActiveProperties).UseLookupData and not VarEqualsExact(APrevCurrentKey, ILookupData.CurrentKey) then DoClick; end; if AFound then Key := #0; if Key <> #0 then InnerTextEdit.InternalUpdating := False; end; procedure tcxMyComboBox.MaskEditPressKey(var Key: Char); begin if not ActiveProperties.IsMasked then begin TextEditPressKey(Key); Exit; end; if (Key = #9) or (Key = #27) then Key := #0 else if not ValidateKeyPress(Key) then Key := #0 else begin if Key <> #13 then begin if not ActiveProperties.IsMasked then TextEditPressKey(Key) else begin if (Key = #3) or (Key = #22) or (Key = #24) then // ^c ^v ^x begin TextEditPressKey(Key) end else begin if Key = #8 then // Backspace begin if not Mode.PressBackSpace then Key := #0; end else if not Mode.PressSymbol(Key) then Key := #0; end; end; end; end; end; procedure tcxMyComboBox.DoEditKeyPress(var Key: Char); var lastkey: char; begin if (Properties.DropDownListStyle <> lsEditList) or not properties.WordMode then begin inherited; Exit; end; lastkey := key; if IsTextChar(Key) and ActiveProperties.ImmediateDropDownWhenKeyPressed and not HasPopupWindow then begin //DroppedDown := True; if TcxMyComboBoxProperties(ActiveProperties).PopupWindowCapturesFocus and (TranslateKey(Word(Key)) <> VK_RETURN) and CanDropDown and (GetPopupFocusedControl <> nil) then begin PostMessage(PopupWindow.Handle, DXM_POPUPCONTROLKEY, Integer(Key), 0); Key := #0; end; end; if Key <> #0 then MaskEditPressKey(Key); if (IsTextChar(lastkey) or properties.WordMode and (lastkey = #8)) and ActiveProperties.ImmediateDropDownWhenKeyPressed and not HasPopupWindow then DroppedDown := true else if HasPopupWindow and (Properties.Items.Count = 0) then DroppedDown := false; end; class function TcxMyFilterComboBoxHelper.GetFilterEditClass: TcxCustomEditClass; begin Result := TcxMyComboBox; end; class procedure TcxMyFilterComboBoxHelper.InitializeProperties(AProperties, AEditProperties: TcxCustomEditProperties; AHasButtons: Boolean); begin inherited InitializeProperties(AProperties, AEditProperties, AHasButtons); with TcxCustomComboBoxProperties(AProperties) do begin ButtonGlyph := nil; DropDownRows := 8; DropDownListStyle := lsEditList; ImmediateDropDownWhenKeyPressed := False; PopupAlignment := taLeftJustify; Revertable := False; end; end; initialization FilterEditsController.Register(TcxMyComboBoxProperties, TcxMyFilterComboBoxHelper); finalization FilterEditsController.Unregister(TcxMyComboBoxProperties, TcxMyFilterComboBoxHelper); end.
unit SDUi18n; // Description: Internationalization (i18n) Functions // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // // This unit implements i18n related code. // For now, it largely wraps the dxGetText library atm, but can be used for // projects built without dxGetText (in which case, this unit does // nothing - for now) // Define "_DXGETTEXT" to use dxGetText for translation // Leave this undefined for default behaviour interface uses Classes, ComCtrls, StdCtrls,Forms; const ISO639_ALPHA2_ENGLISH = 'en'; //{$IFNDEF _DXGETTEXT} function _(msg: unicodestring): unicodestring; //{$ENDIF} function SDUTranslate(msg: unicodestring): unicodestring; procedure SDUTranslateComp(var c: TRichEdit); OVERLOAD; procedure SDUTranslateComp(var c: TLabel); OVERLOAD; function SDUPluralMsg(n: Integer; singleMsg: WideString; pluralMsg: WideString): WideString; OVERLOAD; function SDUPluralMsg(n: Integer; msgs: array of WideString): WideString; OVERLOAD; procedure SDUSetLanguage(lang: String); procedure SDUTranslateComponent(Comp: TComponent); procedure SDURetranslateComponent(Comp: TComponent); procedure SDUGetLanguageCodes(langCodes: TStringList); function SDUGetCurrentLanguageCode(): String; function SDUGetTranslatorName(): WideString; function SDUGetTranslatorNameAndEmail(): WideString; procedure SDUTP_GlobalIgnoreClass(IgnClass: TClass); procedure SDUTP_GlobalIgnoreClassProperty(IgnClass: TClass; const propertyname: String); // Returns TRUE/FALSE if English // (e.g. US English, British English) // WARNING: If '' supplied, this will return FALSE function SDUIsLanguageCodeEnglish(code: String): Boolean; implementation uses {$IFDEF _DXGETTEXT} gnugettext, {$ENDIF} ActnList, Controls, ExtCtrls, Graphics, SysUtils; function _(msg: unicodestring): unicodestring; begin Result := SDUTranslate(msg); end; function SDUTranslate(msg: unicodestring): unicodestring; begin {$IFDEF _DXGETTEXT} Result := gnugettext._(msg); {$ELSE} Result := msg; {$ENDIF} end; procedure SDUTranslateComp(var c: TRichEdit); OVERLOAD; begin //tag is used as flag if translated already if c.tag = 0 then c.Text := SDUTranslate(c.Text); c.tag := 1; end; procedure SDUTranslateComp(var c: TLabel); OVERLOAD; begin //tag is used as flag if translated already if c.tag = 0 then c.Caption := SDUTranslate(c.Caption); c.tag := 1; end; function SDUPluralMsg(n: Integer; singleMsg: WideString; pluralMsg: WideString): WideString; begin Result := SDUPluralMsg(n, [singleMsg, pluralMsg]); end; // Note: n must be 1 or greater function SDUPluralMsg(n: Integer; msgs: array of WideString): WideString; OVERLOAD; begin Result := ''; if (length(msgs) > 0) then begin if (n > length(msgs)) then begin n := length(msgs); end else if (n < 1) then begin n := 1; end; // -1 as array indexes from zero Result := msgs[n - 1]; end; end; procedure SDUTranslateComponent(Comp: TComponent); begin {$IFDEF _DXGETTEXT} TranslateComponent(comp); {$ENDIF} end; procedure SDURetranslateComponent(Comp: TComponent); begin {$IFDEF _DXGETTEXT} if Comp.FindComponent('GNUgettextMarker') <> nil then RetranslateComponent(comp) else TranslateComponent(comp); {$ENDIF} end; procedure SDUSetLanguage(lang: String); begin {$IFDEF _DXGETTEXT} UseLanguage(lang); {$ENDIF} end; procedure SDUTP_GlobalIgnoreClass(IgnClass: TClass); begin {$IFDEF _DXGETTEXT} TP_GlobalIgnoreClass(IgnClass); {$ENDIF} end; procedure SDUTP_GlobalIgnoreClassProperty(IgnClass: TClass; const propertyname: String); begin {$IFDEF _DXGETTEXT} TP_GlobalIgnoreClassProperty(IgnClass, propertyname); {$ENDIF} end; procedure SDUGetLanguageCodes(langCodes: TStringList); begin {$IFDEF _DXGETTEXT} DefaultInstance.GetListOfLanguages('default', langCodes); {$ENDIF} end; function SDUGetCurrentLanguageCode(): String; begin {$IFDEF _DXGETTEXT} Result := GetCurrentLanguage(); {$ELSE} Result := ''; {$ENDIF} end; function SDUGetTranslatorName(): WideString; begin Result := SDUGetTranslatorNameAndEmail(); //aaa := 'aa <b@c.d>'; //aaa := '<b@c.d> aa'; //aaa := 'aaa'; //aaa := '<b@c.d>'; //aaa := 'b@c.d'; if ((Pos('<', Result) > 0) and (Pos('@', Result) > Pos('<', Result)) and // Sanity, in case of "<Berty>" - not an email addr (Pos('>', Result) > Pos('@', Result)) // Sanity, in case of "<Berty>" - not an email addr ) then begin // Trivial version; only handles stuff like "Fred <bert@domain.com>" // Really should be able to handle "<ME!> <myaddr@domain.com" Result := copy(Result, 1, (Pos('<', Result) - 1)); Result := Trim(Result); end; end; function SDUGetTranslatorNameAndEmail(): WideString; begin {$IFDEF _DXGETTEXT} Result := GetTranslatorNameAndEmail(); {$ELSE} Result := ''; {$ENDIF} end; function SDUIsLanguageCodeEnglish(code: String): Boolean; begin Result := (Pos(ISO639_ALPHA2_ENGLISH, code) = 1); end; initialization // This is the list of ignores. The list of ignores has to come before the // first call to TranslateComponent(). // Note: Many of these are commented out; including them all would require // the "uses" clause to include all the units that define the classes // listed // VCL, important ones SDUTP_GlobalIgnoreClassProperty(TAction, 'Category'); SDUTP_GlobalIgnoreClassProperty(TControl, 'HelpKeyword'); SDUTP_GlobalIgnoreClassProperty(TNotebook, 'Pages'); // VCL, not so important SDUTP_GlobalIgnoreClassProperty(TControl, 'ImeName'); SDUTP_GlobalIgnoreClass(TFont); // Database (DB unit) // SDUTP_GlobalIgnoreClassProperty(TField, 'DefaultExpression'); // SDUTP_GlobalIgnoreClassProperty(TField, 'FieldName'); // SDUTP_GlobalIgnoreClassProperty(TField, 'KeyFields'); // SDUTP_GlobalIgnoreClassProperty(TField, 'DisplayName'); // SDUTP_GlobalIgnoreClassProperty(TField, 'LookupKeyFields'); // SDUTP_GlobalIgnoreClassProperty(TField, 'LookupResultField'); // SDUTP_GlobalIgnoreClassProperty(TField, 'Origin'); // SDUTP_GlobalIgnoreClass(TParam); // SDUTP_GlobalIgnoreClassProperty(TFieldDef, 'Name'); // MIDAS/Datasnap // SDUTP_GlobalIgnoreClassProperty(TClientDataset, 'CommandText'); // SDUTP_GlobalIgnoreClassProperty(TClientDataset, 'Filename'); // SDUTP_GlobalIgnoreClassProperty(TClientDataset, 'Filter'); // SDUTP_GlobalIgnoreClassProperty(TClientDataset, 'IndexFieldnames'); // SDUTP_GlobalIgnoreClassProperty(TClientDataset, 'IndexName'); // SDUTP_GlobalIgnoreClassProperty(TClientDataset, 'MasterFields'); // SDUTP_GlobalIgnoreClassProperty(TClientDataset, 'Params'); // SDUTP_GlobalIgnoreClassProperty(TClientDataset, 'ProviderName'); // Database controls // SDUTP_GlobalIgnoreClassProperty(TDBComboBox, 'DataField'); // SDUTP_GlobalIgnoreClassProperty(TDBCheckBox, 'DataField'); // SDUTP_GlobalIgnoreClassProperty(TDBEdit, 'DataField'); // SDUTP_GlobalIgnoreClassProperty(TDBImage, 'DataField'); // SDUTP_GlobalIgnoreClassProperty(TDBListBox, 'DataField'); // SDUTP_GlobalIgnoreClassProperty(TDBLookupControl, 'DataField'); // SDUTP_GlobalIgnoreClassProperty(TDBLookupControl, 'KeyField'); // SDUTP_GlobalIgnoreClassProperty(TDBLookupControl, 'ListField'); // SDUTP_GlobalIgnoreClassProperty(TDBMemo, 'DataField'); // SDUTP_GlobalIgnoreClassProperty(TDBRadioGroup, 'DataField'); // SDUTP_GlobalIgnoreClassProperty(TDBRichEdit, 'DataField'); // SDUTP_GlobalIgnoreClassProperty(TDBText, 'DataField'); // Interbase Express (IBX) // SDUTP_GlobalIgnoreClass(TIBDatabase); // SDUTP_GlobalIgnoreClass(TIBDatabase); // SDUTP_GlobalIgnoreClass(TIBTransaction); // SDUTP_GlobalIgnoreClassProperty(TIBSQL, 'UniqueRelationName'); // Borland Database Engine (BDE) // SDUTP_GlobalIgnoreClass(TSession); // SDUTP_GlobalIgnoreClass(TDatabase); // ADO components // SDUTP_GlobalIgnoreClass (TADOConnection); // SDUTP_GlobalIgnoreClassProperty(TADOQuery, 'CommandText'); // SDUTP_GlobalIgnoreClassProperty(TADOQuery, 'ConnectionString'); // SDUTP_GlobalIgnoreClassProperty(TADOQuery, 'DatasetField'); // SDUTP_GlobalIgnoreClassProperty(TADOQuery, 'Filter'); // SDUTP_GlobalIgnoreClassProperty(TADOQuery, 'IndexFieldNames'); // SDUTP_GlobalIgnoreClassProperty(TADOQuery, 'IndexName'); // SDUTP_GlobalIgnoreClassProperty(TADOQuery, 'MasterFields'); // SDUTP_GlobalIgnoreClassProperty(TADOTable, 'IndexFieldNames'); // SDUTP_GlobalIgnoreClassProperty(TADOTable, 'IndexName'); // SDUTP_GlobalIgnoreClassProperty(TADOTable, 'MasterFields'); // SDUTP_GlobalIgnoreClassProperty(TADOTable, 'TableName'); // SDUTP_GlobalIgnoreClassProperty(TADODataset, 'CommandText'); // SDUTP_GlobalIgnoreClassProperty(TADODataset, 'ConnectionString'); // SDUTP_GlobalIgnoreClassProperty(TADODataset, 'DatasetField'); // SDUTP_GlobalIgnoreClassProperty(TADODataset, 'Filter'); // SDUTP_GlobalIgnoreClassProperty(TADODataset, 'IndexFieldNames'); // SDUTP_GlobalIgnoreClassProperty(TADODataset, 'IndexName'); // SDUTP_GlobalIgnoreClassProperty(TADODataset, 'MasterFields'); // ActiveX stuff // SDUTP_GlobalIgnoreClass(TWebBrowser); end.
(* * FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV * * * 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 uLoadImage; interface uses LCLIntf, LCLType, SysUtils, Classes, Graphics , // Inserted by me dialogs, IntfGraphics, GraphType, FPimage, Types, uMAPGraphic; function loadImageFile( var bmp_dst : TMAPGraphic; filename : string ) : boolean; procedure getProportionalSize( var bmp_src : TBitMap; var newWidth, newHeight: integer ); implementation procedure getProportionalSize( var bmp_src : TBitMap; var newWidth, newHeight: integer ); var width, height : integer; begin width := newWidth; height := newHeight; if bmp_src <> nil then begin if bmp_src.Width > bmp_src.Height then begin height := (bmp_src.Height * newWidth) div bmp_src.Width; end else begin width := (bmp_src.Width * newHeight) div bmp_src.Height; end; newWidth:=width; newHeight:=height; end; end; function getBPP(var image :TBitmap) : Integer; begin getBPP:= PIXELFORMAT_BPP[image.PixelFormat]; end; function getBPP(var picture :TPicture) : Integer; var tmp_pic : TPicture; begin tmp_pic := TPicture.Create; tmp_pic.PNG:= TPortableNetworkGraphic.Create; if picture.Graphic.MimeType = tmp_pic.Graphic.MimeType then begin getBPP:= picture.PNG.RawImage.Description.Depth; end else begin getBPP:= picture.Bitmap.RawImage.Description.Depth; end; tmp_pic.Free; end; procedure loadInBitmap(var bitmap: TBitmap; fileName : String); var AImage: TLazIntfImage; begin // create a TLazIntfImage with 32 bits per pixel, alpha 8bit, red 8 bit, green 8bit, blue 8bit, // Bits In Order: bit 0 is pixel 0, Top To Bottom: line 0 is top AImage := TLazIntfImage.Create(0,0); AImage.DataDescription:=GetDescriptionFromDevice(0); try // Load an image from disk. // It uses the file extension to select the right registered image reader. // The AImage will be resized to the width, height of the loaded image. AImage.LoadFromFile(fileName); Bitmap.LoadFromIntfImage(AImage); finally AImage.Free; end; end; procedure copyMaskToBitmap32(var bmp: TBitmap; icon: TIcon); var tmpBMP : TBitmap; lazBmp : TLazIntfImage; lazMask: TLazIntfImage; ico_mask: TBitmap; k,j : integer; curColor : TFPColor; maskPtr : PRGBTriple; begin lazBmp:= bmp.CreateIntfImage; tmpBMP := TBitmap.Create; tmpBMP.Handle:=icon.MaskHandle; ico_mask := TBitmap.Create; ico_mask.PixelFormat:=pf24bit; ico_mask.SetSize(bmp.width,bmp.height); ico_mask.canvas.Draw(0,0,tmpBMP); lazMask:= ico_mask.CreateIntfImage; for k := 0 to lazBmp.height - 1 do begin maskPtr:=lazMask.GetDataLineStart(k); for j := 0 to lazBmp.width - 1 do begin curColor:=lazBmp.Colors[j,k]; curColor.alpha:= (255-maskPtr[j].rgbtBlue) shl 8; lazBmp.Colors[j,k]:=curColor; end; end; bmp.LoadFromIntfImage(lazBmp); lazBmp.free; lazMask.free; end; function loadImageFile( var bmp_dst : TMAPGraphic; filename : string ) : boolean; var temp_pic : TPicture; bpp_src :integer; begin result := false; if AnsiLowerCase(ExtractFileExt(Filename)) = '.map' then begin bmp_dst.LoadFromFile(Filename); end else begin temp_pic:= TPicture.Create; try temp_pic.LoadFromFile(Filename); Except exit; end; if temp_pic.Graphic.ClassType = TIcon.ClassType then begin temp_pic.Icon.Current:= temp_pic.Icon.GetBestIndexForSize(Size(600,600)) ; bpp_src:= PIXELFORMAT_BPP[temp_pic.Icon.PixelFormat]; if bpp_src<32 then begin bmp_dst.PixelFormat:=pf32bit; bmp_dst.SetSize(temp_pic.Width,temp_pic.Height); bmp_dst.Canvas.Draw(0,0,temp_pic.Icon); copyMaskToBitmap32(TBitmap(bmp_dst),temp_pic.Icon); end else begin bmp_dst.LoadFromBitmapHandles(temp_pic.Icon.BitmapHandle,temp_pic.Icon.MaskHandle); // bmp_src.LoadFromIntfImage(bmp_src.CreateIntfImage); end; end else begin bmp_dst.Assign(temp_pic.bitmap); end; temp_pic.free; end; // Copiamos imagen if ((bmp_dst.Width <> 0) and (bmp_dst.Height <> 0)) then begin result := true; end end; end.
unit XED.OperandElementXtypeEnum; {$Z4} interface type TXED_Operand_Element_Xtype_Enum = ( XED_OPERAND_XTYPE_INVALID, XED_OPERAND_XTYPE_2F16, XED_OPERAND_XTYPE_B80, XED_OPERAND_XTYPE_BF16, XED_OPERAND_XTYPE_F16, XED_OPERAND_XTYPE_F32, XED_OPERAND_XTYPE_F64, XED_OPERAND_XTYPE_F80, XED_OPERAND_XTYPE_I1, XED_OPERAND_XTYPE_I16, XED_OPERAND_XTYPE_I32, XED_OPERAND_XTYPE_I64, XED_OPERAND_XTYPE_I8, XED_OPERAND_XTYPE_INT, XED_OPERAND_XTYPE_STRUCT, XED_OPERAND_XTYPE_U128, XED_OPERAND_XTYPE_U16, XED_OPERAND_XTYPE_U256, XED_OPERAND_XTYPE_U32, XED_OPERAND_XTYPE_U64, XED_OPERAND_XTYPE_U8, XED_OPERAND_XTYPE_UINT, XED_OPERAND_XTYPE_VAR, XED_OPERAND_XTYPE_LAST); /// This converts strings to #xed_operand_element_xtype_enum_t types. /// @param s A C-string. /// @return #xed_operand_element_xtype_enum_t /// @ingroup ENUM function str2xed_operand_element_xtype_enum_t(s: PAnsiChar): TXED_Operand_Element_Xtype_Enum; cdecl; external 'xed.dll'; /// This converts strings to #xed_operand_element_xtype_enum_t types. /// @param p An enumeration element of type xed_operand_element_xtype_enum_t. /// @return string /// @ingroup ENUM function xed_operand_element_xtype_enum_t2str(const p: TXED_Operand_Element_Xtype_Enum): PAnsiChar; cdecl; external 'xed.dll'; /// Returns the last element of the enumeration /// @return xed_operand_element_xtype_enum_t The last element of the enumeration. /// @ingroup ENUM function xed_operand_element_xtype_enum_t_last:TXED_Operand_Element_Xtype_Enum;cdecl; external 'xed.dll'; implementation end.
{ Clever Internet Suite Version 6.2 Copyright (C) 1999 - 2006 Clever Components www.CleverComponents.com } unit clFtpServer; interface {$I clVer.inc} {$IFDEF DELPHI6} {$WARN SYMBOL_PLATFORM OFF} {$ENDIF} {$IFDEF DELPHI7} {$WARN UNSAFE_CODE OFF} {$WARN UNSAFE_TYPE OFF} {$WARN UNSAFE_CAST OFF} {$ENDIF} uses Classes, Windows, SysUtils, WinSock, clUtils, clTcpServer, clSocket, clFtpUtils, clUserMgr, SyncObjs; type TclFtpUserAccountItem = class(TclUserAccountItem) private FRootDir: string; FReadOnlyAccess: Boolean; procedure SetRootDir(const Value: string); public procedure Assign(Source: TPersistent); override; published property ReadOnlyAccess: Boolean read FReadOnlyAccess write FReadOnlyAccess; property RootDir: string read FRootDir write SetRootDir; end; TclFtpFileItem = class(TCollectionItem) private FInfo: TclFtpFileInfo; public constructor Create(Collection: TCollection); override; destructor Destroy; override; property Info: TclFtpFileInfo read FInfo; end; TclFtpFileList = class(TCollection) private function GetItem(Index: Integer): TclFtpFileItem; procedure SetItem(Index: Integer; const Value: TclFtpFileItem); public function Add: TclFtpFileItem; property Items[Index: Integer]: TclFtpFileItem read GetItem write SetItem; default; end; TclFtpCommandConnection = class(TclCommandConnection) private FIsAuthorized: Boolean; FCurrentDir: string; FDataPosition: Int64; FCurrentName: string; FDataConnection: TclSyncConnection; FDataConnectionAccess: TCriticalSection; FTransferMode: TclFtpTransferMode; FTransferStructure: TclFtpTransferStructure; FTransferType: TclFtpTransferType; FUserName: string; FTempUserName: string; FReadOnlyAccess: Boolean; FRootDir: string; FDataPort: Integer; FDataIP: string; FPassiveMode: Boolean; FDataProtection: Boolean; procedure AssignDataConnection(AConnection: TclSyncConnection); protected procedure DoDestroy; override; public constructor Create; procedure InitParams; property IsAuthorized: Boolean read FIsAuthorized; property CurrentDir: string read FCurrentDir; property RootDir: string read FRootDir; property DataPosition: Int64 read FDataPosition; property CurrentName: string read FCurrentName; property DataConnection: TclSyncConnection read FDataConnection; property TransferMode: TclFtpTransferMode read FTransferMode; property TransferStructure: TclFtpTransferStructure read FTransferStructure; property TransferType: TclFtpTransferType read FTransferType; property UserName: string read FUserName; property ReadOnlyAccess: Boolean read FReadOnlyAccess; property DataIP: string read FDataIP; property DataPort: Integer read FDataPort; property PassiveMode: Boolean read FPassiveMode; property DataProtection: Boolean read FDataProtection; end; TclFtpCommandHandler = procedure (AConnection: TclFtpCommandConnection; const ACommand, AParams: string) of object; TclFtpCommandInfo = class(TclTcpCommandInfo) private FHandler: TclFtpCommandHandler; FIsOOB: Boolean; protected procedure Execute(AConnection: TclCommandConnection; AParams: TclTcpCommandParams); override; end; TclFtpHelpCommandEvent = procedure (Sender: TObject; AConnection: TclFtpCommandConnection; const AParams: string; AHelpText: TStrings) of object; TclFtpAuthenticateEvent = procedure (Sender: TObject; AConnection: TclFtpCommandConnection; Account: TclFtpUserAccountItem; const APassword: string; var IsAuthorized, Handled: Boolean) of object; TclFtpNameEvent = procedure (Sender: TObject; AConnection: TclFtpCommandConnection; const AName: string; var Success: Boolean; var AErrorMessage: string) of object; TclFtpRenameEvent = procedure (Sender: TObject; AConnection: TclFtpCommandConnection; const ACurrentName, ANewName: string; var Success: Boolean; var AErrorMessage: string) of object; TclFtpFileInfoEvent = procedure (Sender: TObject; AConnection: TclFtpCommandConnection; const AName: string; AInfo: TclFtpFileInfo; var Success: Boolean; var AErrorMessage: string) of object; TclFtpPutFileEvent = procedure (Sender: TObject; AConnection: TclFtpCommandConnection; const AFileName: string; AOverwrite: Boolean; var ADestination: TStream; var Success: Boolean; var AErrorMessage: string) of object; TclFtpGetFileEvent = procedure (Sender: TObject; AConnection: TclFtpCommandConnection; const AFileName: string; var ASource: TStream; var Success: Boolean; var AErrorMessage: string) of object; TclFtpFileListEvent = procedure (Sender: TObject; AConnection: TclFtpCommandConnection; const APathName: string; AIncludeHidden: Boolean; AFileList: TclFtpFileList) of object; TclFtpConnectionEvent = procedure (Sender: TObject; AConnection: TclFtpCommandConnection) of object; TclFtpServer = class(TclTcpCommandServer) private FRootDir: string; FUserAccounts: TclUserAccountList; FAllowAnonymousAccess: Boolean; FDirListingStyle: TclDirListingStyle; FOnHelpCommand: TclFtpHelpCommandEvent; FOnAuthenticate: TclFtpAuthenticateEvent; FOnCreateDir: TclFtpNameEvent; FOnDelete: TclFtpNameEvent; FOnRename: TclFtpRenameEvent; FOnGetFileInfo: TclFtpFileInfoEvent; FOnPutFile: TclFtpPutFileEvent; FOnGetFile: TclFtpGetFileEvent; FOnGetFileList: TclFtpFileListEvent; FTclFtpConnectionEvent: TclFtpConnectionEvent; procedure HandleQUIT(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleUSER(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandlePASS(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleMODE(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleSTRU(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleTYPE(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleREST(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandlePORT(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandlePASV(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleLIST(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleNLST(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleMKD(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandlePWD(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleCWD(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleCDUP(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleRMD(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleSTOR(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleAPPE(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleSTOU(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleSIZE(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleRNFR(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleRNTO(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleDELE(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleRETR(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleSITE(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleNOOP(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleHELP(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleREIN(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleSTAT(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleSYST(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleABOR(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandlePBSZ(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandlePROT(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleAUTH(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure HandleNullCommand(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure SetRootDir(const Value: string); procedure CollectDirList(AConnection: TclFtpCommandConnection; AList: TStrings; const APathName: string; ADetails: Boolean); function GetFullPath(AConnection: TclFtpCommandConnection; const APathName: string): string; procedure RaiseFileAccessError(const ACommand, AFileName, AMessage: string); procedure RaiseArgumentError(const ACommand: string); procedure RaiseDataConnectionError(const ACommand: string); procedure SetUserAccounts(const Value: TclUserAccountList); function GetCaseInsensitive: Boolean; procedure SetCaseInsensitive(const Value: Boolean); procedure InternalHandleList(AConnection: TclFtpCommandConnection; const ACommand, AParams: string; ADetails: Boolean); procedure InternalHandleStor(AConnection: TclFtpCommandConnection; const ACommand, AParams: string; Append, ACreateUnique: Boolean); procedure InternalHandleDelete(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); procedure InternalHandleCwd(AConnection: TclFtpCommandConnection; const ACommand, ACurDir: string); function Authenticate(AConnection: TclFtpCommandConnection; Account: TclUserAccountItem; const APassword: string): Boolean; function IsAnonymousUser(const AUserName: string): Boolean; function IsFileExists(AConnection: TclFtpCommandConnection; const ACommand, AFileName: string): Boolean; procedure CheckAuthorized(AConnection: TclFtpCommandConnection; const ACommand: string); procedure CheckAccessRights(AConnection: TclFtpCommandConnection; const ACommand, AName: string); procedure CheckTlsMode(AConnection: TclFtpCommandConnection; const ACommand: string); function GetFileInfo(AConnection: TclFtpCommandConnection; const ACommand, AName: string): TclFtpFileInfo; procedure InitDataConnection(AConnection: TclFtpCommandConnection; ADataConnection: TclSyncConnection); protected procedure OpenDataConnection(AConnection: TclFtpCommandConnection; const ACommand: string); virtual; procedure AddFtpCommand(const ACommand: string; AHandler: TclFtpCommandHandler; IsOOB: Boolean = False); procedure RegisterCommands; override; function GetNullCommand(const ACommand: string): TclTcpCommandInfo; override; procedure ProcessUnhandledError(AConnection: TclCommandConnection; AParams: TclTcpCommandParams; E: Exception); override; procedure DoProcessCommand(AConnection: TclCommandConnection; AInfo: TclTcpCommandInfo; AParams: TclTcpCommandParams); override; procedure DoAcceptConnection(AConnection: TclCommandConnection); override; function CreateDefaultConnection: TclCommandConnection; override; procedure DoDestroy; override; procedure DoHelpCommand(AConnection: TclFtpCommandConnection; const AParams: string; AHelpText: TStrings); virtual; procedure DoAuthenticate(AConnection: TclFtpCommandConnection; Account: TclFtpUserAccountItem; const APassword: string; var IsAuthorized, Handled: Boolean); virtual; procedure DoCreateDir(AConnection: TclFtpCommandConnection; const AName: string; var Success: Boolean; var AErrorMessage: string); virtual; procedure DoDelete(AConnection: TclFtpCommandConnection; const AName: string; var Success: Boolean; var AErrorMessage: string); virtual; procedure DoRename(AConnection: TclFtpCommandConnection; const ACurrentName, ANewName: string; var Success: Boolean; var AErrorMessage: string); virtual; procedure DoGetFileInfo(AConnection: TclFtpCommandConnection; const AName: string; AInfo: TclFtpFileInfo; var Success: Boolean; var AErrorMessage: string); virtual; procedure DoPutFile(AConnection: TclFtpCommandConnection; const AFileName: string; AOverwrite: Boolean; var ADestination: TStream; var Success: Boolean; var AErrorMessage: string); virtual; procedure DoGetFile(AConnection: TclFtpCommandConnection; const AFileName: string; var ASource: TStream; var Success: Boolean; var AErrorMessage: string); virtual; procedure DoGetFileList(AConnection: TclFtpCommandConnection; const APathName: string; AIncludeHidden: Boolean; AFileList: TclFtpFileList); virtual; procedure DoInitDataConnection(AConnection: TclFtpCommandConnection); virtual; public constructor Create(AOwner: TComponent); override; published property RootDir: string read FRootDir write SetRootDir; property Port default cDefaultFtpPort; property UserAccounts: TclUserAccountList read FUserAccounts write SetUserAccounts; property CaseInsensitive: Boolean read GetCaseInsensitive write SetCaseInsensitive default False; property AllowAnonymousAccess: Boolean read FAllowAnonymousAccess write FAllowAnonymousAccess default False; property DirListingStyle: TclDirListingStyle read FDirListingStyle write FDirListingStyle default lsMsDos; property OnHelpCommand: TclFtpHelpCommandEvent read FOnHelpCommand write FOnHelpCommand; property OnAuthenticate: TclFtpAuthenticateEvent read FOnAuthenticate write FOnAuthenticate; property OnCreateDir: TclFtpNameEvent read FOnCreateDir write FOnCreateDir; property OnDelete: TclFtpNameEvent read FOnDelete write FOnDelete; property OnRename: TclFtpRenameEvent read FOnRename write FOnRename; property OnGetFileInfo: TclFtpFileInfoEvent read FOnGetFileInfo write FOnGetFileInfo; property OnPutFile: TclFtpPutFileEvent read FOnPutFile write FOnPutFile; property OnGetFile: TclFtpGetFileEvent read FOnGetFile write FOnGetFile; property OnGetFileList: TclFtpFileListEvent read FOnGetFileList write FOnGetFileList; property OnInitDataConnection: TclFtpConnectionEvent read FTclFtpConnectionEvent write FTclFtpConnectionEvent; end; procedure RaiseFtpError(const ACommand, AMessage: string; ACode: Integer); implementation uses clTlsSocket; const cTransferResult: array[Boolean] of string = ('Transfer complete', 'Transfer aborted'); procedure RaiseFtpError(const ACommand, AMessage: string; ACode: Integer); begin raise EclTcpCommandError.Create(ACommand, Format('%d %s', [ACode, AMessage]), ACode); end; { TclFtpServer } procedure TclFtpServer.DoAcceptConnection(AConnection: TclCommandConnection); begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end; {$ENDIF} {$ENDIF} inherited DoAcceptConnection(AConnection); SendResponse(AConnection, '', '220 ' + ServerName); end; procedure TclFtpServer.AddFtpCommand(const ACommand: string; AHandler: TclFtpCommandHandler; IsOOB: Boolean); var info: TclFtpCommandInfo; begin info := TclFtpCommandInfo.Create(); AddCommand(info); info.Name := ACommand; info.FHandler := AHandler; info.FIsOOB := IsOOB; end; procedure TclFtpServer.RegisterCommands; begin AddFtpCommand('USER', HandleUSER); AddFtpCommand('PASS', HandlePASS); AddFtpCommand('QUIT', HandleQUIT); AddFtpCommand('MODE', HandleMODE); AddFtpCommand('STRU', HandleSTRU); AddFtpCommand('TYPE', HandleTYPE); AddFtpCommand('REST', HandleREST); AddFtpCommand('PORT', HandlePORT); AddFtpCommand('PASV', HandlePASV); AddFtpCommand('P@SW', HandlePASV); AddFtpCommand('LIST', HandleLIST); AddFtpCommand('NLST', HandleNLST); AddFtpCommand('MKD', HandleMKD); AddFtpCommand('PWD', HandlePWD); AddFtpCommand('CWD', HandleCWD); AddFtpCommand('CDUP', HandleCDUP); AddFtpCommand('RMD', HandleRMD); AddFtpCommand('STOR', HandleSTOR); AddFtpCommand('APPE', HandleAPPE); AddFtpCommand('STOU', HandleSTOU); AddFtpCommand('SIZE', HandleSIZE); AddFtpCommand('RNFR', HandleRNFR); AddFtpCommand('RNTO', HandleRNTO); AddFtpCommand('DELE', HandleDELE); AddFtpCommand('RETR', HandleRETR); AddFtpCommand('XMKD', HandleMKD); AddFtpCommand('XPWD', HandlePWD); AddFtpCommand('XCWD', HandleCWD); AddFtpCommand('XCUP', HandleCDUP); AddFtpCommand('XRMD', HandleRMD); AddFtpCommand('SITE', HandleSITE); AddFtpCommand('NOOP', HandleNOOP); AddFtpCommand('ALLO', HandleNOOP); AddFtpCommand('HELP', HandleHELP); AddFtpCommand('REIN', HandleREIN); AddFtpCommand('STAT', HandleSTAT); AddFtpCommand('SYST', HandleSYST); AddFtpCommand('ABOR', HandleABOR, True); AddFtpCommand(#$FF#$F4#$FF#$FF'ABOR', HandleABOR, True); AddFtpCommand(#$FF#$F4#$F2'ABOR', HandleABOR, True); AddFtpCommand('PBSZ', HandlePBSZ); AddFtpCommand('PROT', HandlePROT); AddFtpCommand('AUTH', HandleAUTH); end; constructor TclFtpServer.Create(AOwner: TComponent); begin inherited Create(AOwner); FUserAccounts := TclUserAccountList.Create(Self, TclFtpUserAccountItem); Port := cDefaultFtpPort; CaseInsensitive := False; FAllowAnonymousAccess := False; FDirListingStyle := lsMsDos; ServerName := 'Clever Internet Suite FTP service'; end; function TclFtpServer.CreateDefaultConnection: TclCommandConnection; begin Result := TclFtpCommandConnection.Create(); end; procedure TclFtpServer.SetRootDir(const Value: string); begin if (FRootDir <> Value) then begin FRootDir := Value; if (FRootDir <> '') and (FRootDir[Length(FRootDir)] = '\') then begin Delete(FRootDir, Length(FRootDir), 1); end; end; end; procedure TclFtpServer.CollectDirList(AConnection: TclFtpCommandConnection; AList: TStrings; const APathName: string; ADetails: Boolean); var i: Integer; path: string; includeHidden: Boolean; fileList: TclFtpFileList; begin includeHidden := False; path := APathName; if (LowerCase(path) = '-al') then begin path := ''; includeHidden := True; end; fileList := TclFtpFileList.Create(TclFtpFileItem); try DoGetFileList(AConnection, GetFullPath(AConnection, path), includeHidden, fileList); AList.Clear(); for i := 0 to fileList.Count - 1 do begin if ADetails then begin AList.Add(fileList[i].Info.Build(DirListingStyle)); end else begin AList.Add(fileList[i].Info.FileName); end; end; finally fileList.Free(); end; end; procedure TclFtpServer.DoGetFileList(AConnection: TclFtpCommandConnection; const APathName: string; AIncludeHidden: Boolean; AFileList: TclFtpFileList); begin if Assigned(OnGetFileList) then begin OnGetFileList(Self, AConnection, APathName, AIncludeHidden, AFileList); end; end; function TclFtpServer.GetFullPath(AConnection: TclFtpCommandConnection; const APathName: string): string; function NormalizePath(const APath: string): string; begin Result := StringReplace(APath, '/', '\', [rfReplaceAll]); if (Result <> '') and (Result[1] <> '\') then begin Result := '\' + Result; end; if (Result <> '') and (Result[Length(Result)] = '\') then begin Delete(Result, Length(Result), 1); end; end; begin Result := NormalizePath(APathName); if not (TextPos('\', Result, 2) > 1) then begin Result := NormalizePath(AConnection.CurrentDir) + Result; end; if (AConnection.RootDir <> '') then begin Result := AConnection.RootDir + Result; end else begin Result := RootDir + Result; end; Assert(system.Pos('..', Result) = 0); Assert(system.Pos('\\', Result) = 0); end; procedure TclFtpServer.HandleQUIT(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); begin try SendResponse(AConnection, ACommand, '221 Bye Bye.'); AConnection.Close(False); except on EclSocketError do ; end; end; procedure TclFtpServer.HandleUSER(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); begin CheckTlsMode(AConnection, ACommand); AConnection.InitParams(); AConnection.FTempUserName := Trim(AParams); if AllowAnonymousAccess and IsAnonymousUser(AConnection.FTempUserName) then begin SendResponse(AConnection, ACommand, '331 Anonymous access allowed, send identity (e-mail name) as password.'); end else begin SendResponse(AConnection, ACommand, '331 Password required for %s.', [AConnection.FTempUserName]); end; end; procedure TclFtpServer.DoAuthenticate(AConnection: TclFtpCommandConnection; Account: TclFtpUserAccountItem; const APassword: string; var IsAuthorized, Handled: Boolean); begin if Assigned(OnAuthenticate) then begin OnAuthenticate(Self, AConnection, Account, APassword, IsAuthorized, handled); end; end; function TclFtpServer.Authenticate(AConnection: TclFtpCommandConnection; Account: TclUserAccountItem; const APassword: string): Boolean; var handled: Boolean; begin handled := False; Result := False; DoAuthenticate(AConnection, TclFtpUserAccountItem(Account), APassword, Result, handled); if (not handled) and (Account <> nil) then begin Result := Account.Authenticate(APassword); end; end; procedure TclFtpServer.HandlePASS(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); var account: TclUserAccountItem; begin CheckTlsMode(AConnection, ACommand); if (AConnection.FTempUserName = '') then begin RaiseFtpError(ACommand, 'Login with USER first.', 503); end; AConnection.FUserName := AConnection.FTempUserName; AConnection.FTempUserName := ''; AConnection.FIsAuthorized := False; if AllowAnonymousAccess and IsAnonymousUser(AConnection.UserName) then begin if (Trim(AParams) = '') then begin RaiseFtpError(ACommand, Format('User %s cannot log in.', [AConnection.UserName]), 530); end; AConnection.FReadOnlyAccess := True; AConnection.FRootDir := RootDir; AConnection.FIsAuthorized := True; SendResponse(AConnection, ACommand, '230 Anonymous user logged in.'); end else begin account := UserAccounts.AccountByUserName(AConnection.UserName); if not Authenticate(AConnection, account, Trim(AParams)) then begin RaiseFtpError(ACommand, Format('User %s cannot log in.', [AConnection.UserName]), 530); end; if (account <> nil) then begin AConnection.FReadOnlyAccess := (account as TclFtpUserAccountItem).ReadOnlyAccess; AConnection.FRootDir := (account as TclFtpUserAccountItem).RootDir; end; AConnection.FIsAuthorized := True; SendResponse(AConnection, ACommand, '230 User %s logged in.', [AConnection.UserName]); end; end; function TclFtpServer.IsAnonymousUser(const AUserName: string): Boolean; begin if CaseInsensitive then begin Result := SameText('anonymous', AUserName); end else begin Result := ('Anonymous' = AUserName); end; end; procedure TclFtpServer.HandleMODE(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); var s: string; begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); s := UpperCase(Trim(AParams)); if (Length(s) <> 1) then begin RaiseArgumentError(ACommand); end; case s[1] of 'B': AConnection.FTransferMode := tmBlock; 'C': AConnection.FTransferMode := tmCompressed; 'S': AConnection.FTransferMode := tmStream; 'Z': AConnection.FTransferMode := tmDeflate else RaiseArgumentError(ACommand); end; SendResponse(AConnection, ACommand, '200 Mode %s ok.', [s]); end; procedure TclFtpServer.HandleSTRU(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); var s: string; begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); s := UpperCase(Trim(AParams)); if (Length(s) <> 1) then begin RaiseArgumentError(ACommand); end; case s[1] of 'F': AConnection.FTransferStructure := tsFile; 'R': AConnection.FTransferStructure := tsRecord; 'P': AConnection.FTransferStructure := tsPage else RaiseArgumentError(ACommand); end; SendResponse(AConnection, ACommand, '200 STRU %s ok.', [s]); end; procedure TclFtpServer.HandleTYPE(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); var s: string; begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); s := UpperCase(Trim(AParams)); if (Length(s) <> 1) then begin RaiseArgumentError(ACommand); end; case s[1] of 'A': AConnection.FTransferType := ttAscii; 'I': AConnection.FTransferType := ttBinary else RaiseArgumentError(ACommand); end; SendResponse(AConnection, ACommand, '200 Type %s ok.', [s]); end; procedure TclFtpServer.HandleREST(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); AConnection.FDataPosition := StrToIntDef(Trim(AParams), 0); SendResponse(AConnection, ACommand, '350 Restarting at %d.', [AConnection.FDataPosition]); end; procedure TclFtpServer.InitDataConnection(AConnection: TclFtpCommandConnection; ADataConnection: TclSyncConnection); begin AConnection.AssignDataConnection(ADataConnection); if (UseTLS <> stNone) and AConnection.DataProtection then begin ADataConnection.NetworkStream := TclTlsNetworkStream.Create(); TclTlsNetworkStream(ADataConnection.NetworkStream).OnGetCertificate := GetCertificate; TclTlsNetworkStream(ADataConnection.NetworkStream).TLSFlags := TLSFlags; TclTlsNetworkStream(ADataConnection.NetworkStream).RequireClientCertificate := False; end else begin ADataConnection.NetworkStream := TclNetworkStream.Create(); end; AConnection.FDataConnection.TimeOut := TimeOut; AConnection.FDataConnection.BatchSize := BatchSize; AConnection.FDataConnection.IsReadUntilClose := True; AConnection.FDataConnection.BitsPerSec := BitsPerSec; DoInitDataConnection(AConnection); end; procedure TclFtpServer.DoInitDataConnection(AConnection: TclFtpCommandConnection); begin if Assigned(OnInitDataConnection) then begin OnInitDataConnection(Self, AConnection); end; end; procedure TclFtpServer.HandlePORT(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); var parameter: string; begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); AConnection.FPassiveMode := False; parameter := Trim(AParams); if (parameter = '') or (WordCount(parameter, [',']) < 6) then begin RaiseArgumentError(ACommand); end; ParseFtpHostStr(parameter, AConnection.FDataIP, AConnection.FDataPort); InitDataConnection(AConnection, TclTcpClientConnection.Create()); SendResponse(AConnection, ACommand, '200 PORT command successful.'); end; procedure TclFtpServer.HandlePASV(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); var dataConnection: TclTcpServerConnection; begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); AConnection.FPassiveMode := True; dataConnection := TclTcpServerConnection.Create(); InitDataConnection(AConnection, dataConnection); AConnection.FDataIP := ''; AConnection.FDataPort := dataConnection.Open(0); SendResponse(AConnection, ACommand, '227 Entering Passive Mode (%s).', [GetFtpHostStr(GetFtpLocalHostStr(AConnection.PeerName), AConnection.DataPort)]); end; procedure TclFtpServer.InternalHandleList(AConnection: TclFtpCommandConnection; const ACommand, AParams: string; ADetails: Boolean); var list: TStrings; isAborted: Boolean; begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); list := TStringList.Create(); try CollectDirList(AConnection, list, Trim(AParams), ADetails); OpenDataConnection(AConnection, ACommand); SendResponse(AConnection, ACommand, '150 Opening data connection.'); try AConnection.FDataConnection.WriteString(list.Text); except on EclSocketError do begin AConnection.FDataConnection.Abort(); end; end; isAborted := AConnection.FDataConnection.IsAborted; AConnection.AssignDataConnection(nil); if isAborted then begin SendResponse(AConnection, ACommand, '426 Connection closed, transfer aborted.'); end; SendResponse(AConnection, ACommand, '226 %s.', [cTransferResult[isAborted]]); finally list.Free(); end; end; procedure TclFtpServer.HandleLIST(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); begin InternalHandleList(AConnection, ACommand, AParams, True); end; procedure TclFtpServer.HandleMKD(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); var s: string; success: Boolean; error: string; begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); s := Trim(AParams); if (s = '') then begin RaiseArgumentError(ACommand); end; CheckAccessRights(AConnection, ACommand, s); success := True; error := ''; DoCreateDir(AConnection, GetFullPath(AConnection, s), success, error); if not success then begin RaiseFileAccessError(ACommand, s, error); end; SendResponse(AConnection, ACommand, '257 %s directory created.', [s]); end; procedure TclFtpServer.DoCreateDir(AConnection: TclFtpCommandConnection; const AName: string; var Success: Boolean; var AErrorMessage: string); begin if Assigned(OnCreateDir) then begin OnCreateDir(Self, AConnection, AName, Success, AErrorMessage); end; end; procedure TclFtpServer.InternalHandleCwd(AConnection: TclFtpCommandConnection; const ACommand, ACurDir: string); var ind: Integer; curDir, newDir: string; info: TclFtpFileInfo; begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); curDir := Trim(ACurDir); if (Length(curDir) > 1) and (curDir[Length(curDir)] = '/') then begin Delete(curDir, Length(curDir), 1); end; if (curDir = '..') then begin ind := RTextPos('/', AConnection.FCurrentDir); if (ind > 1) then begin AConnection.FCurrentDir := Copy(AConnection.FCurrentDir, 1, ind - 1); end else if (ind = 1) then begin AConnection.FCurrentDir := '/'; end; end else if (curDir = '/') then begin AConnection.FCurrentDir := '/'; end else begin if (curDir = '') then begin curDir := '/'; end; if (AConnection.FCurrentDir <> '') and (AConnection.FCurrentDir[Length(AConnection.FCurrentDir)] = '/') then begin system.Delete(AConnection.FCurrentDir, Length(AConnection.FCurrentDir), 1); end; if (curDir <> '') and (curDir[1] = '/') then begin newDir := curDir; end else begin if (curDir <> '') and (curDir[1] <> '/') then begin curDir := '/' + curDir; end; newDir := AConnection.FCurrentDir + curDir; end; info := GetFileInfo(AConnection, ACommand, newDir); try if not info.IsDirectory then begin RaiseFileAccessError(ACommand, newDir, 'No such file or directory.'); end; AConnection.FCurrentDir := newDir; finally info.Free(); end; end; SendResponse(AConnection, ACommand, '250 CWD command successful.'); end; procedure TclFtpServer.HandleCDUP(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); begin InternalHandleCwd(AConnection, ACommand, '..'); end; procedure TclFtpServer.HandleCWD(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); begin InternalHandleCwd(AConnection, ACommand, AParams); end; procedure TclFtpServer.HandlePWD(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); var s: string; begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); s := AConnection.FCurrentDir; if (s = '') then begin s := '/'; end; SendResponse(AConnection, ACommand, '257 "%s" is current directory.', [s]); end; procedure TclFtpServer.HandleRMD(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); begin InternalHandleDelete(AConnection, ACommand, AParams); end; procedure TclFtpServer.InternalHandleDelete(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); var s: string; success: Boolean; error: string; begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); s := Trim(AParams); if (s = '') then begin RaiseArgumentError(ACommand); end; CheckAccessRights(AConnection, ACommand, s); success := True; error := ''; DoDelete(AConnection, GetFullPath(AConnection, s), success, error); if not success then begin RaiseFileAccessError(ACommand, s, error); end; SendResponse(AConnection, ACommand, '250 %s command successful.', [ACommand]); end; procedure TclFtpServer.DoDelete(AConnection: TclFtpCommandConnection; const AName: string; var Success: Boolean; var AErrorMessage: string); begin if Assigned(OnDelete) then begin OnDelete(Self, AConnection, AName, Success, AErrorMessage); end; end; procedure TclFtpServer.HandleSTOR(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); begin InternalHandleStor(AConnection, ACommand, AParams, False, False); end; procedure TclFtpServer.HandleSIZE(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); var s: string; info: TclFtpFileInfo; begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); s := Trim(AParams); if (s = '') then begin RaiseArgumentError(ACommand); end; info := GetFileInfo(AConnection, ACommand, s); try SendResponse(AConnection, ACommand, '213 %d', [info.Size]); finally info.Free(); end end; procedure TclFtpServer.HandleRNFR(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); var s: string; info: TclFtpFileInfo; begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); s := Trim(AParams); if (s = '') then begin RaiseArgumentError(ACommand); end; CheckAccessRights(AConnection, ACommand, s); AConnection.FCurrentName := s; info := GetFileInfo(AConnection, ACommand, AConnection.FCurrentName); try SendResponse(AConnection, ACommand, '350 File exists, ready for destination name'); finally info.Free(); end end; procedure TclFtpServer.HandleRNTO(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); var curName, newName: string; success: Boolean; error: string; begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); if (AConnection.FCurrentName = '') then begin RaiseFtpError(ACommand, 'Bad sequence of commands.', 503); end; curName := AConnection.FCurrentName; newName := Trim(AParams); if (newName = '') then begin RaiseArgumentError(ACommand); end; CheckAccessRights(AConnection, ACommand, newName); success := True; error := ''; DoRename(AConnection, GetFullPath(AConnection, curName), GetFullPath(AConnection, newName), success, error); if not success then begin RaiseFileAccessError(ACommand, newName, error); end; SendResponse(AConnection, ACommand, '250 RNTO command successful.'); end; procedure TclFtpServer.DoRename(AConnection: TclFtpCommandConnection; const ACurrentName, ANewName: string; var Success: Boolean; var AErrorMessage: string); begin if Assigned(OnRename) then begin OnRename(Self, AConnection, ACurrentName, ANewName, Success, AErrorMessage); end; end; procedure TclFtpServer.HandleNLST(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); begin InternalHandleList(AConnection, ACommand, AParams, False); end; procedure TclFtpServer.HandleDELE(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); begin InternalHandleDelete(AConnection, ACommand, AParams); end; procedure TclFtpServer.HandleRETR(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); var stream: TStream; fileName, error: string; isAborted, success: Boolean; begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); fileName := GetFullPath(AConnection, Trim(AParams)); if (fileName = '') then begin RaiseArgumentError(ACommand); end; stream := nil; try success := True; error := ''; DoGetFile(AConnection, fileName, stream, success, error); if (not success) or (stream = nil) then begin RaiseFileAccessError(ACommand, ExtractFileName(fileName), error); end; if (AConnection.FDataPosition > 0) and (AConnection.FDataPosition < stream.Size) then begin stream.Position := AConnection.FDataPosition; end; OpenDataConnection(AConnection, ACommand); SendResponse(AConnection, ACommand, '150 Opening data connection for %s(%d bytes).', [ExtractFileName(fileName), stream.Size]); try AConnection.FDataConnection.WriteData(stream); except on EclSocketError do begin AConnection.FDataConnection.Abort(); end; end; finally stream.Free(); end; isAborted := AConnection.FDataConnection.IsAborted; AConnection.AssignDataConnection(nil); if isAborted then begin SendResponse(AConnection, ACommand, '426 Connection closed, transfer aborted.'); end; SendResponse(AConnection, ACommand, '226 %s.', [cTransferResult[isAborted]]); end; procedure TclFtpServer.DoGetFile(AConnection: TclFtpCommandConnection; const AFileName: string; var ASource: TStream; var Success: Boolean; var AErrorMessage: string); begin if Assigned(OnGetFile) then begin OnGetFile(Self, AConnection, AFileName, ASource, Success, AErrorMessage); end; end; procedure TclFtpServer.RaiseFileAccessError(const ACommand, AFileName, AMessage: string); var msg: string; begin msg := AMessage; if (msg = '') then begin msg := 'failed'; end; RaiseFtpError(ACommand, AFileName + ': ' + msg, 550); end; procedure TclFtpServer.RaiseArgumentError(const ACommand: string); begin RaiseFtpError(ACommand, 'invalid argument', 501); end; procedure TclFtpServer.RaiseDataConnectionError(const ACommand: string); begin RaiseFtpError(ACommand, 'Can not open data connection', 425); end; procedure TclFtpServer.SetUserAccounts(const Value: TclUserAccountList); begin FUserAccounts.Assign(Value); end; function TclFtpServer.GetCaseInsensitive: Boolean; begin Result := FUserAccounts.CaseInsensitive; end; procedure TclFtpServer.SetCaseInsensitive(const Value: Boolean); begin FUserAccounts.CaseInsensitive := Value; end; procedure TclFtpServer.HandleSITE(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); var list: TStrings; begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); list := TStringList.Create(); AddMultipleLines(AConnection, list); list.Add('214-The following SITE commands are recognized.'); SendMultipleLines(AConnection, '214 HELP command successful.', True); end; procedure TclFtpServer.HandleNOOP(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); SendResponse(AConnection, ACommand, '200 NOOP command successful.'); end; procedure TclFtpServer.DoHelpCommand(AConnection: TclFtpCommandConnection; const AParams: string; AHelpText: TStrings); begin if Assigned(OnHelpCommand) then begin OnHelpCommand(Self, AConnection, AParams, AHelpText); end; end; procedure TclFtpServer.HandleHELP(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); var list: TStrings; begin list := TStringList.Create(); AddMultipleLines(AConnection, list); DoHelpCommand(AConnection, AParams, list); if (list.Count = 0) then begin list.Add('The following commands are recognized'); end; list[0] := '214-' + list[0]; SendMultipleLines(AConnection, '214 HELP command successful.', True); end; procedure TclFtpServer.HandleREIN(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); begin AConnection.InitParams(); SendResponse(AConnection, ACommand, '220 Service ready for new user.'); end; procedure TclFtpServer.HandleSTAT(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); const TransferTypes: array[TclFtpTransferType] of string = ('ASCII', 'BINARY'); TransferForms: array[TclFtpTransferType] of string = ('Print', 'Nonprint'); TransferStructs: array[TclFtpTransferStructure] of string = ('File', 'Record', 'Page'); TransferModes: array[TclFtpTransferMode] of string = ('BLOCK', 'COMPRESSED', 'STREAM', 'DEFLATE'); var list: TStrings; begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); list := TStringList.Create(); AddMultipleLines(AConnection, list); list.Add('211-FTP Service status:'); list.Add(' Connected to ' + AConnection.PeerName); list.Add(' Logged in as ' + AConnection.UserName); list.Add(Format(' TYPE: %s, FORM: %s; STRUcture: %s; transfer MODE: %s', [ TransferTypes[AConnection.TransferType], TransferForms[AConnection.TransferType], TransferStructs[AConnection.TransferStructure], TransferModes[AConnection.TransferMode] ])); if (AConnection.DataConnection = nil) then begin list.Add(' No data connection'); end; SendMultipleLines(AConnection, '211 End of status.', True); end; procedure TclFtpServer.HandleSYST(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); SendResponse(AConnection, ACommand, '215 Windows 9x/NT.'); end; procedure TclFtpServer.HandleAPPE(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); begin InternalHandleStor(AConnection, ACommand, AParams, True, False); end; function TclFtpServer.IsFileExists(AConnection: TclFtpCommandConnection; const ACommand, AFileName: string): Boolean; begin if not Assigned(OnGetFileInfo) then begin RaiseFileAccessError(ACommand, ExtractFileName(AFileName), ''); end; try GetFileInfo(AConnection, ACommand, AFileName).Free(); Result := True; except on EclSocketError do begin Result := False; end; end; end; procedure TclFtpServer.OpenDataConnection(AConnection: TclFtpCommandConnection; const ACommand: string); begin if (AConnection.FDataConnection = nil) then begin RaiseDataConnectionError(ACommand); end; if AConnection.PassiveMode then begin TclTcpServerConnection(AConnection.FDataConnection).AcceptConnection(); end else begin TclTcpClientConnection(AConnection.FDataConnection).Open(AConnection.DataIP, AConnection.DataPort); end; end; procedure TclFtpServer.InternalHandleStor(AConnection: TclFtpCommandConnection; const ACommand, AParams: string; Append, ACreateUnique: Boolean); var i: Integer; stream: TStream; fileName, error: string; success, isAppend, isAborted: Boolean; begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); if ACreateUnique then begin i := 1; repeat fileName := GetFullPath(AConnection, Format('FTP%d.TMP', [i])); Inc(i); until not IsFileExists(AConnection, ACommand, fileName); end else begin fileName := GetFullPath(AConnection, Trim(AParams)); if (fileName = '') then begin RaiseArgumentError(ACommand); end; end; CheckAccessRights(AConnection, ACommand, ExtractFileName(fileName)); OpenDataConnection(AConnection, ACommand); SendResponse(AConnection, ACommand, '150 Opening data connection for %s.', [ExtractFileName(fileName)]); stream := nil; try isAppend := (AConnection.FDataPosition > 0) or Append; success := True; error := ''; DoPutFile(AConnection, fileName, not isAppend, stream, success, error); if (not success) or (stream = nil) then begin RaiseFileAccessError(ACommand, ExtractFileName(fileName), error); end; if isAppend then begin if (AConnection.FDataPosition > 0) and (AConnection.FDataPosition < stream.Size) then begin stream.Position := AConnection.FDataPosition; end else begin stream.Position := stream.Size; end; end; try AConnection.FDataConnection.ReadData(stream); except on EclSocketError do begin AConnection.FDataConnection.Abort(); end; end; finally stream.Free(); end; isAborted := AConnection.FDataConnection.IsAborted; AConnection.AssignDataConnection(nil); if isAborted then begin SendResponse(AConnection, ACommand, '426 Connection closed, transfer aborted.'); end; SendResponse(AConnection, ACommand, '226 %s.', [cTransferResult[isAborted]]); end; procedure TclFtpServer.DoPutFile(AConnection: TclFtpCommandConnection; const AFileName: string; AOverwrite: Boolean; var ADestination: TStream; var Success: Boolean; var AErrorMessage: string); begin if Assigned(OnPutFile) then begin OnPutFile(Self, AConnection, AFileName, AOverwrite, ADestination, Success, AErrorMessage); end; end; procedure TclFtpServer.HandleSTOU(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); begin AConnection.FDataPosition := 0; InternalHandleStor(AConnection, ACommand, AParams, False, True); end; procedure TclFtpServer.HandleABOR(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); begin CheckTlsMode(AConnection, ACommand); CheckAuthorized(AConnection, ACommand); AConnection.FDataConnectionAccess.Enter(); try if (AConnection.FDataConnection = nil) then begin // SendResponse(AConnection, ACommand, '225 ABOR command successful.'); end else begin AConnection.FDataConnection.Abort(); end; finally AConnection.FDataConnectionAccess.Leave(); end; end; procedure TclFtpServer.DoDestroy; begin FUserAccounts.Free(); inherited DoDestroy(); end; function TclFtpServer.GetNullCommand(const ACommand: string): TclTcpCommandInfo; var info: TclFtpCommandInfo; begin info := TclFtpCommandInfo.Create(); info.Name := ACommand; info.FHandler := HandleNullCommand; Result := info; end; procedure TclFtpServer.HandleNullCommand(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); begin RaiseFtpError(ACommand, 'Command not implemented.', 502); end; procedure TclFtpServer.ProcessUnhandledError(AConnection: TclCommandConnection; AParams: TclTcpCommandParams; E: Exception); begin SendResponse(AConnection, AParams.Command, '451 Requested action aborted: ' + Trim(E.Message)); end; procedure TclFtpServer.CheckAuthorized(AConnection: TclFtpCommandConnection; const ACommand: string); begin if not AConnection.IsAuthorized then begin RaiseFtpError(ACommand, 'Not logged in.', 530); end; end; procedure TclFtpServer.CheckAccessRights(AConnection: TclFtpCommandConnection; const ACommand, AName: string); begin if AConnection.ReadOnlyAccess then begin RaiseFtpError(ACommand, Format('%s: Access is denied.', [AName]), 550); end; end; function TclFtpServer.GetFileInfo(AConnection: TclFtpCommandConnection; const ACommand, AName: string): TclFtpFileInfo; var success: Boolean; error: string; begin Result := TclFtpFileInfo.Create(); try success := True; error := ''; DoGetFileInfo(AConnection, GetFullPath(AConnection, AName), Result, success, error); if not success then begin RaiseFileAccessError(ACommand, AName, error); end; except Result.Free(); raise; end; end; procedure TclFtpServer.DoGetFileInfo(AConnection: TclFtpCommandConnection; const AName: string; AInfo: TclFtpFileInfo; var Success: Boolean; var AErrorMessage: string); begin if Assigned(OnGetFileInfo) then begin OnGetFileInfo(Self, AConnection, AName, AInfo, Success, AErrorMessage); end; end; procedure TclFtpServer.DoProcessCommand(AConnection: TclCommandConnection; AInfo: TclTcpCommandInfo; AParams: TclTcpCommandParams); begin if TclFtpCommandInfo(AInfo).FIsOOB then begin inherited DoProcessCommand(AConnection, AInfo, AParams); end else begin AConnection.BeginWork(); try inherited DoProcessCommand(AConnection, AInfo, AParams); finally AConnection.EndWork(); end; end; end; procedure TclFtpServer.HandlePBSZ(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); begin SendResponse(AConnection, ACommand, '200 Protection buffer size set to 0'); end; procedure TclFtpServer.HandlePROT(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); var s: string; begin s := UpperCase(Trim(AParams)); case s[1] of 'C': begin AConnection.FDataProtection := False; SendResponse(AConnection, ACommand, '200 Data channel will be clear text'); end; 'P': begin AConnection.FDataProtection := True; SendResponse(AConnection, ACommand, '200 Data channel will be encrypted'); end; else RaiseFtpError(ACommand, 'Unsupported option', 536); end; end; procedure TclFtpServer.HandleAUTH(AConnection: TclFtpCommandConnection; const ACommand, AParams: string); var s: string; begin if (UseTLS = stNone) then begin RaiseFtpError(ACommand, 'SSL encryption disabled', 500); end; if (UseTLS = stImplicit) then begin RaiseFtpError(ACommand, 'Secure mode is already started.', 500); end; s := UpperCase(Trim(AParams)); if (s <> 'TLS') then begin RaiseFtpError(ACommand, 'Unknown auth method ' + s, 504); end; SendResponse(AConnection, ACommand, '234 Enabling SSL'); StartTls(AConnection); end; procedure TclFtpServer.CheckTlsMode(AConnection: TclFtpCommandConnection; const ACommand: string); begin if (UseTLS = stExplicitRequire) and (not AConnection.IsTls) then begin RaiseFtpError(ACommand, 'Sorry SSL encryption is required', 500); end; end; { TclFtpCommandConnection } procedure TclFtpCommandConnection.AssignDataConnection(AConnection: TclSyncConnection); begin FDataConnectionAccess.Enter(); try if (FDataConnection <> nil) then begin FDataConnection.Close(False); FDataConnection.Free(); end; FDataConnection := AConnection; FDataPosition := 0; finally FDataConnectionAccess.Leave(); end; end; constructor TclFtpCommandConnection.Create; begin inherited Create(); FDataConnectionAccess := TCriticalSection.Create(); InitParams(); end; procedure TclFtpCommandConnection.InitParams; begin FTransferMode := tmStream; FTransferStructure := tsFile; FTransferType := ttAscii; FCurrentDir := '/'; FIsAuthorized := False; FReadOnlyAccess := False; FDataPosition := 0; FCurrentName := ''; FUserName := ''; FRootDir := ''; FDataPort := 0; FDataIP := ''; FPassiveMode := False; FDataProtection := False; end; procedure TclFtpCommandConnection.DoDestroy; begin BeginWork(); try AssignDataConnection(nil); finally EndWork(); end; FDataConnectionAccess.Free(); inherited DoDestroy(); end; { TclFtpUserAccountItem } procedure TclFtpUserAccountItem.Assign(Source: TPersistent); var account: TclFtpUserAccountItem; begin inherited Assign(Source); if (Source is TclFtpUserAccountItem) then begin account := (Source as TclFtpUserAccountItem); FReadOnlyAccess := account.ReadOnlyAccess; FRootDir := account.RootDir; end; end; procedure TclFtpUserAccountItem.SetRootDir(const Value: string); begin if (FRootDir <> Value) then begin FRootDir := Value; if (FRootDir <> '') and (FRootDir[Length(FRootDir)] = '\') then begin Delete(FRootDir, Length(FRootDir), 1); end; end; end; { TclFtpCommandInfo } procedure TclFtpCommandInfo.Execute(AConnection: TclCommandConnection; AParams: TclTcpCommandParams); begin FHandler(AConnection as TclFtpCommandConnection, Name, AParams.Params); end; { TclFtpFileItem } constructor TclFtpFileItem.Create(Collection: TCollection); begin inherited Create(Collection); FInfo := TclFtpFileInfo.Create(); end; destructor TclFtpFileItem.Destroy; begin FInfo.Free(); inherited Destroy(); end; { TclFtpFileList } function TclFtpFileList.Add: TclFtpFileItem; begin Result := TclFtpFileItem(inherited Add()); end; function TclFtpFileList.GetItem(Index: Integer): TclFtpFileItem; begin Result := TclFtpFileItem(inherited GetItem(Index)); end; procedure TclFtpFileList.SetItem(Index: Integer; const Value: TclFtpFileItem); begin inherited SetItem(Index, Value); end; end.
unit DSA.Graph.BellmanFord; interface uses System.SysUtils, System.Rtti, DSA.Interfaces.DataStructure, DSA.Interfaces.Comparer, DSA.Graph.Edge, DSA.List_Stack_Queue.ArrayList, DSA.List_Stack_Queue.LinkedListStack; type TBellmanFord<T> = class private type TEdge_T = TEdge<T>; TList_Edge = TArrayList<TEdge_T>; TArrEdge = TArray<TEdge_T>; TWeightGraph_T = TWeightGraph<T>; TCmp_T = TComparer<T>; TStack_Edge = TLinkedListStack<TEdge_T>; var __g: TWeightGraph_T; __s: integer; // 起始点 __distTo: array of T; // distTo[i]存储从起始点s到i的最短路径长度 __from: TArrEdge; // from[i]记录最短路径中, 到达i点的边是哪一条,可以用来恢复整个最短路径 __hasNegativeCycle: boolean; // 标记图中是否有负权环 /// <summary> 判断图中是否有负权环 </summary> function __detectNegativeCycle: boolean; function __add_T(a, b: T): T; public constructor Create(g: TWeightGraph_T; s: integer); destructor Destroy; override; /// <summary> // 返回图中是否有负权环 </summary> function NegativeCycle: boolean; /// <summary> 返回从a点到b点的最短路径长度 </summary> function ShortestPathTo(b: integer): T; /// <summary> 判断从a点到b点是否联通 </summary> function HasPathTo(b: integer): boolean; /// <summary> 寻找从a到b的最短路径, 将整个路径经过的边存放在vec中 </summary> function ShortestPath(b: integer): TList_Edge; /// <summary> 打印出从a点到b点的路径 </summary> procedure ShowPath(b: integer); end; procedure Main; implementation uses DSA.Graph.SparseWeightedGraph, DSA.Utils; type TSparseWeightedGraph_int = TSparseWeightedGraph<integer>; TBellmanFord_int = TBellmanFord<integer>; TReadGraphWeight_int = TReadGraphWeight<integer>; procedure Main; var g: TSparseWeightedGraph_int; b: TBellmanFord_int; fileName: string; i, v, s: integer; begin //fileName := WEIGHT_GRAPH_FILE_NAME_6; fileName := WEIGHTGRAPH_NEGATIVE_CIRCLE_FILE_NAME; v := 5; g := TSparseWeightedGraph_int.Create(v, True); TReadGraphWeight_int.Execute(g, FILE_PATH + fileName); WriteLn('Test Bellman-Ford:'); s := 0; b := TBellmanFord_int.Create(g, s); if b.NegativeCycle then WriteLn('The graph contain negative cycle!') else begin for i := 0 to g.Vertex - 1 do begin if i = s then Continue; if b.HasPathTo(i) then begin WriteLn('Shortest Path to ', i, ' : ', b.ShortestPathTo(i)); b.ShowPath(i); end else WriteLn('No Path to ', i); WriteLn('----------'); end; end; end; { TBellmanFord<T> } constructor TBellmanFord<T>.Create(g: TWeightGraph_T; s: integer); var bool, pass, i: integer; e: TEdge_T; cmp: TCmp_T; begin __s := s; __g := g; SetLength(__distTo, g.Vertex); SetLength(__from, g.Vertex); cmp := TCmp_T.Default; // 初始化所有的节点s都不可达, 由from数组来表示 for i := 0 to g.Vertex - 1 do __from[i] := nil; // 设置distTo[s] = 0, 并且让from[s]不为 nil, 表示初始s节点可达且距离为 0 __distTo[s] := Default (T); __from[s] := TEdge_T.Create(s, s, Default (T)); // Bellman-Ford的过程 // 进行V-1次循环, 每一次循环求出从起点到其余所有点, 最多使用pass步可到达的最短距离 for pass := 1 to g.Vertex - 1 do begin // 每次循环中对所有的边进行一遍松弛操作 // 遍历所有边的方式是先遍历所有的顶点, 然后遍历和所有顶点相邻的所有边 for i := 0 to g.Vertex - 1 do begin // 使用我们实现的邻边迭代器遍历和所有顶点相邻的所有边 for e in g.AdjIterator(i) do begin // 对于每一个边首先判断e->v()可达 // 之后看如果e->w()以前没有到达过, 显然我们可以更新distTo[e->w()] // 或者e->w()以前虽然到达过, 但是通过这个e我们可以获得一个更短的距离, // 即可以进行一次松弛操作, 我们也可以更新distTo[e->w()] bool := cmp.Compare(__add_T(__distTo[e.VertexA], e.Weight), __distTo[e.VertexB]); if (__from[e.VertexA] <> nil) and ((__from[e.VertexB] = nil) or (bool < 0)) then begin __distTo[e.VertexB] := __add_T(__distTo[e.VertexA], e.Weight); __from[e.VertexB] := e; end; end; end; end; __hasNegativeCycle := __detectNegativeCycle; end; destructor TBellmanFord<T>.Destroy; begin inherited Destroy; end; function TBellmanFord<T>.HasPathTo(b: integer): boolean; begin Assert((b >= 0) and (b < __g.Vertex)); Result := __from[b] <> nil; end; function TBellmanFord<T>.NegativeCycle: boolean; begin Result := __hasNegativeCycle; end; function TBellmanFord<T>.ShortestPath(b: integer): TList_Edge; var stack: TStack_Edge; e: TEdge_T; ret: TList_Edge; begin Assert((b >= 0) and (b < __g.Vertex)); Assert(not __hasNegativeCycle); Assert(HasPathTo(b)); // 通过from数组逆向查找到从s到w的路径, 存放到栈中 stack := TStack_Edge.Create; e := __from[b]; while e.VertexA <> __s do begin stack.Push(e); e := __from[e.VertexA]; end; stack.Push(e); ret := TList_Edge.Create; // 从栈中依次取出元素, 获得顺序的从s到w的路径 while not stack.IsEmpty do begin e := stack.Pop; ret.AddLast(e); end; Result := ret; end; function TBellmanFord<T>.ShortestPathTo(b: integer): T; begin Assert((b >= 0) and (b < __g.Vertex)); Assert(not __hasNegativeCycle); Assert(HasPathTo(b)); Result := __distTo[b]; end; procedure TBellmanFord<T>.ShowPath(b: integer); var list: TList_Edge; i: integer; begin Assert((b >= 0) and (b < __g.Vertex)); Assert(not __hasNegativeCycle); Assert(HasPathTo(b)); list := ShortestPath(b); for i := 0 to list.GetSize - 1 do begin Write(list[i].VertexA, ' -> '); if i = list.GetSize - 1 then WriteLn(list[i].VertexB); end; end; function TBellmanFord<T>.__add_T(a, b: T): T; var v1, v2: Variant; ret: T; begin v1 := TValue.From<T>(a).AsVariant; v2 := TValue.From<T>(b).AsVariant; TValue.FromVariant(v1 + v2).ExtractRawData(@ret); Result := ret; end; function TBellmanFord<T>.__detectNegativeCycle: boolean; var i: integer; e: TEdge_T; cmp: TCmp_T; bool: integer; begin cmp := TCmp_T.Default; Result := False; for i := 0 to __g.Vertex - 1 do begin for e in __g.AdjIterator(i) do begin bool := cmp.Compare(__add_T(__distTo[e.VertexA], e.Weight), __distTo[e.VertexB]); if (__from[e.VertexA] <> nil) and (bool < 0) then begin Result := True; Exit; end; end; end; end; end.
unit ReplaceUtlForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ActnList, Menus, ComCtrls, IniFiles, Mask, MaskUtils, FileCtrl; type TForm1 = class(TForm) PageControl1: TPageControl; tsRules: TTabSheet; Memo2: TMemo; tsReplace: TTabSheet; Panel1: TPanel; MainMenu1: TMainMenu; miSchema: TMenuItem; Load1: TMenuItem; N1: TMenuItem; Exit1: TMenuItem; ActionList1: TActionList; acSchemaLoad: TAction; acSchemaExit: TAction; acSchemaSave: TAction; acSchemaSaveAs: TAction; Save1: TMenuItem; SaveAs1: TMenuItem; miRules: TMenuItem; AutoCreate1: TMenuItem; tsFiles: TTabSheet; Memo1: TMemo; miReplace: TMenuItem; acReplaceDoIt: TAction; DoIt1: TMenuItem; acSchemaNew: TAction; acRulesAddRules: TAction; New1: TMenuItem; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; Panel2: TPanel; ProgressBar1: TProgressBar; Files1: TMenuItem; acFilesAddFilesTypes: TAction; AddFilesTypes1: TMenuItem; acFilesDelFileType: TAction; acRulesDeleteRule: TAction; PageControl2: TPageControl; tsFilesTypes: TTabSheet; tsFilesList: TTabSheet; Panel3: TPanel; chbScanSubFolders: TCheckBox; ledRootPath: TLabeledEdit; lbFilesTypes: TListBox; DeleteType1: TMenuItem; DeleteRule1: TMenuItem; N2: TMenuItem; acFilesAddFiles: TAction; acFilesDeleteFile: TAction; acFilesAddFile1: TMenuItem; acFilesDeleteFile1: TMenuItem; btnBrowse: TButton; pmFilesTypes: TPopupMenu; AddFilesTypes2: TMenuItem; DeleteType2: TMenuItem; lbFiles: TListBox; pmFilesList: TPopupMenu; AddFiles1: TMenuItem; DeleteFile1: TMenuItem; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure acSchemaLoadExecute(Sender: TObject); procedure acSchemaExitExecute(Sender: TObject); procedure acSchemaNewExecute(Sender: TObject); procedure DoSchemaChange(Sender: TObject); procedure acSchemaSaveExecute(Sender: TObject); procedure acSchemaSaveAsExecute(Sender: TObject); procedure acRulesAddRulesExecute(Sender: TObject); procedure acReplaceDoItExecute(Sender: TObject); procedure acFilesAddFilesTypesExecute(Sender: TObject); procedure acRulesDeleteRuleExecute(Sender: TObject); procedure btnBrowseClick(Sender: TObject); procedure acFilesDelFileTypeExecute(Sender: TObject); procedure acFilesAddFilesExecute(Sender: TObject); procedure acFilesDeleteFileExecute(Sender: TObject); private { Private declarations } fl: TStringList; AllowList: TStringList; DenyList: TStringList; SchemaChanged: Boolean; SchemaName: String; public procedure SchemaLoadFromFile(FileName: String); procedure SchemaSaveToFile(FileName: String); procedure SchemaClear; procedure FormatCaption; { Public declarations } end; var Form1: TForm1; implementation uses RuleFrm, Math, FilesList, StrUtils; {$R *.dfm} function ReplaceStr(Str, s1, s2: String): String; var i: Integer; s: String; begin s := str; Result := ''; i := Pos(s1, Str); while i > 0 do begin Result := Result + Copy(Str, 1, i - 1) + s2; Delete(Str, 1, i-1+Length(s1)); i := Pos(s1, Str); end; Result := Result + Str; end; procedure TForm1.FormCreate(Sender: TObject); begin // Edit1.Text := 'B'+ 'T'; // Edit2.Text := 'S'+ 'H'; PageControl1.ActivePage := tsFiles; PageControl2.ActivePage := tsFilesTypes; fl := TStringList.Create; AllowList := TStringList.Create; DenyList := TStringList.Create; fl.Add('.pas'); fl.Add('.dfm'); fl.Add('.dpr'); fl.Add('.cfg'); fl.Add('.bpg'); acSchemaNew.Execute; end; procedure TForm1.FormDestroy(Sender: TObject); begin fl.Free; AllowList.Free; DenyList.Free; end; procedure TForm1.Button1Click(Sender: TObject); (* function ReplaceLine(Str, s1, s2: String): String; var i,k, ind: Integer; s: String; leks: TStringList; begin Result := Str; // Если нечего менять - не тратим время k := Pos(s1, Str); if k = 0 then Exit; // иначе leks := TStringList.Create; try // разбиваем на лексемы s := ''; for i := 1 to Length(Str) do begin if (Str[i] in ['A'..'Z','a'..'z','А'..'Я','а'..'я','_']) then s := s + Str[i] else if s <> '' then begin leks.Add(s); s := ''; end end; if s <> '' then leks.Add(s); // проверяем каждую лексему на наличие искомого шаблона for i := 0 to leks.Count - 1 do begin if Pos(s1, leks[i]) = 0 then Continue; if DenyList.IndexOfName(leks[i]) = -1 then begin ind := AllowList.IndexOfName(leks[i]); if ind = -1 then begin if CheckBox2.Checked then ind := AllowList.Add(leks[i]+'='+ReplaceStr(leks[i], s1, s2)) else // Запросить возможность автозамены case Application.MessageBox(PChar(Format('Разрешить автозамену "%s" -> "%s" ?',[leks[i], ReplaceStr(leks[i], s1, s2)])), 'Создание правила автозамены', MB_YESNOCANCEL) of IDYES: ind := AllowList.Add(leks[i]+'='+ReplaceStr(leks[i], s1, s2)); IDNO: DenyList.Add(leks[i]+'='+ReplaceStr(leks[i], s1, s2)); IDCANCEL: Abort; end; end; if (ind <> -1) and (not CheckBox2.Checked) then Result := ReplaceStr(Result, AllowList.Names[ind], AllowList.Values[AllowList.Names[ind]]); end; end; finally leks.Free; end; end; procedure ReplaceDirFiles(DirPath, Mask: String; Recursive: Boolean); var sr: TSearchRec; res, i: Integer; sl: TStringList; FileChanged: Boolean; _s: String; begin sl := TStringList.Create; try res := FindFirst(DirPath + Mask, faAnyFile, sr); while res = 0 do begin if (sr.Name <> '.') and (sr.Name <> '..') then begin if (sr.Attr and faDirectory) = faDirectory then begin if Recursive then ReplaceDirFiles(DirPath + sr.Name + '\', Mask, Recursive); end else begin if fl.IndexOf(LowerCase(ExtractFileExt(sr.Name))) <> -1 then begin sl.LoadFromFile(DirPath + sr.Name); { Алгоритм Каждую строку разбивать на лексемы (слова) если слово содержит элемент замены } // разбивать строку на стринги, // ввести списки разрещенных и запрещенных замен FileChanged := False; for i := 0 to sl.Count - 1 do begin _s := ReplaceLine(sl[i], Edit1.Text, Edit2.Text); if (_s <> sl[i]) and (not CheckBox2.Checked) then begin sl[i] := _s; FileChanged := True; end; end; if (not CheckBox2.Checked) and FileChanged then begin sl.SaveToFile(DirPath + sr.Name); Memo1.Lines.Add('файл перезаписан '+DirPath + sr.Name); end else Memo1.Lines.Add('файл обработан '+DirPath + sr.Name); end; if ReplaceStr(sr.Name, Edit1.Text, Edit2.Text) <> sr.Name then begin RenameFile(DirPath + sr.Name, DirPath + ReplaceStr(sr.Name, Edit1.Text, Edit2.Text)); Memo1.Lines.Add('файл переименован '+sr.Name+ ' -> ' + ReplaceStr(sr.Name, Edit1.Text, Edit2.Text)); end; end; end; res := FindNext(sr); end; FindClose(sr); finally sl.Free; end; end; *) begin (* if FileExists('AllowList.txt') then AllowList.LoadFromFile('AllowList.txt'); if FileExists('DenyList.txt') then DenyList.LoadFromFile('DenyList.txt'); ReplaceDirFiles(ledRootPath.Text, '*.*', chbScanSubFolders.Checked); AllowList.Sort; AllowList.SaveToFile('AllowList.txt'); DenyList.Sort; DenyList.SaveToFile('DenyList.txt');*) end; procedure TForm1.FormatCaption; begin if not SchemaChanged then begin if SchemaName <> '' then Caption := Application.Title + ' - ' + SchemaName else Caption := Application.Title; end else begin if SchemaName <> '' then Caption := Application.Title + ' - ' + SchemaName + '(Unsaved)' else Caption := Application.Title + ' - (Unsaved)' end end; procedure TForm1.acSchemaNewExecute(Sender: TObject); var Cap: String; begin if SchemaName = '' then Cap := 'Save changes to schema ?' else Cap := 'Save changes to schema ' + SchemaName + '?'; // Новая схема - удалить старую схему, если изменялась if SchemaChanged then case Application.MessageBox(PAnsiChar(Cap), 'Confirm', MB_YESNOCANCEL) of IDYES: acSchemaSave.Execute; IDCANCEL: Abort; end; SchemaClear; end; procedure TForm1.acSchemaLoadExecute(Sender: TObject); begin // Загрузка схемы (inifile) OpenDialog1.InitialDir := ExtractFileDir(Application.ExeName); if OpenDialog1.Execute then SchemaLoadFromFile(OpenDialog1.FileName); end; procedure TForm1.DoSchemaChange(Sender: TObject); begin SchemaChanged := True; FormatCaption; end; procedure TForm1.acSchemaSaveExecute(Sender: TObject); begin // if SchemaName = '' then acSchemaSaveAs.Execute else SchemaSaveToFile(ExtractFileDir(Application.ExeName)+'\' + SchemaName); end; procedure TForm1.acSchemaSaveAsExecute(Sender: TObject); begin // Сохранение схемы SaveDialog1.InitialDir := ExtractFileDir(Application.ExeName); if SaveDialog1.Execute then SchemaSaveToFile(SaveDialog1.FileName); end; procedure TForm1.acRulesAddRulesExecute(Sender: TObject); function FindAndCreateRule(Str, s1, s2: String; Strings: TStrings): String; var i,k, ind: Integer; s: String; leks: TStringList; begin Result := Str; // Если нечего менять - не тратим время k := Pos(s1, Str); if k = 0 then Exit; // иначе leks := TStringList.Create; try // разбиваем на лексемы s := ''; for i := 1 to Length(Str) do begin if (Str[i] in ['A'..'Z','a'..'z','А'..'Я','а'..'я','_']) then s := s + Str[i] else if s <> '' then begin leks.Add(s); s := ''; end end; if s <> '' then leks.Add(s); // проверяем каждую лексему на наличие искомого шаблона for i := 0 to leks.Count - 1 do begin if Pos(s1, leks[i]) = 0 then Continue; ind := Strings.IndexOfName(leks[i]); if ind = -1 then Strings.Add(leks[i]+'='+ReplaceStr(leks[i], s1, s2)) end; finally leks.Free; end; end; var _From, _To, _s: string; _WholeWords: Boolean; sl: TStringList; i, j: Integer; begin // Создание правил замены {Алгоритм Пользователь вводит шаблоны поиска и замены } PageControl1.ActivePage := tsRules; if GetRuleDef(_From, _To, _WholeWords) then begin if _WholeWords then begin If Memo2.Lines.IndexOfName(_From) = -1 then Memo2.Lines.Add(_From + '=' + _To) else raise Exception.Create('Rule for replace from '''+_From+''' already exists!'); end else begin // проверить задан ли путь для сканирования if lbFiles.Items.Count = 0 then raise Exception.Create('Files List is Empty!'); sl := TStringList.Create; try for i := 0 to lbFiles.Items.Count - 1 do begin sl.LoadFromFile(lbFiles.Items[i]); for j := 0 to sl.Count - 1 do _s := FindAndCreateRule(sl[j], _From, _To, Memo2.Lines); end; sl.Assign(Memo2.Lines); sl.Sort; Memo2.Lines.Assign(sl); finally sl.Free; end; end; end; end; procedure TForm1.acSchemaExitExecute(Sender: TObject); begin // Выход из программы acSchemaNew.Execute; Close; end; procedure TForm1.SchemaLoadFromFile(FileName: String); var ini: TIniFile; i: Integer; sl: TStringList; begin ini := TIniFile.Create(FileName); try ledRootPath.Text := ini.ReadString('Paths', 'RootPath', ''); chbScanSubFolders.Checked := ini.ReadBool('Paths', 'ScanSubFolders', False); ini.ReadSectionValues('AllowList', Memo2.Lines); { with lbFiles do begin ReadSectionValues('Files', Items); for i := 0 to Items.Count - 1 do Items[i] := Copy(Items[i], 1, Length(Items[i])-1); end;} sl := TStringList.Create; try lbFiles.Clear; sl.LoadFromFile(FileName); i := sl.IndexOf('[Files]'); if i > -1 then begin Inc(i); while (i < sl.Count) and (sl[i][1] <> '[') and (sl[i][1] <> ' ') do begin lbFiles.Items.Add(Copy(sl[i], 1, Length(sl[i])-1)); Inc(i); end; end; finally sl.Free; end; with lbFilesTypes do begin ini.ReadSectionValues('FileTypes', Items); for i := 0 to Items.Count - 1 do Items[i] := Copy(Items[i], 1, Length(Items[i])-1); end; PageControl1.ActivePage := tsFiles; PageControl2.ActivePage := tsFilesTypes; finally ini.Free; end; SchemaName := ExtractFileName(FileName); SchemaChanged := False; FormatCaption; end; procedure TForm1.SchemaSaveToFile(FileName: String); var ini: TIniFile; i: Integer; begin ini := TIniFile.Create(FileName); try ini.WriteString('Paths', 'RootPath', ledRootPath.Text); ini.WriteBool('Paths', 'ScanSubFolders', chbScanSubFolders.Checked); ini.EraseSection('AllowList'); ProgressBar1.Max := Memo2.Lines.Count; ProgressBar1.Min := 0; Panel2.Visible := True; for i := 0 to Memo2.Lines.Count - 1 do begin ini.WriteString('AllowList', Memo2.Lines.Names[i], Copy(Memo2.Lines[i], Length(Memo2.Lines.Names[i])+2, 255)); ProgressBar1.Position := i+1; Application.ProcessMessages; end; ini.EraseSection('FileTypes'); ProgressBar1.Max := lbFilesTypes.Items.Count; ProgressBar1.Min := 0; Panel2.Visible := True; for i := 0 to lbFilesTypes.Items.Count - 1 do begin ini.WriteString('FileTypes', lbFilesTypes.Items[i], ''); ProgressBar1.Position := i+1; Application.ProcessMessages; end; ini.EraseSection('Files'); ProgressBar1.Max := lbFiles.Items.Count; ProgressBar1.Min := 0; Panel2.Visible := True; for i := 0 to lbFiles.Items.Count - 1 do begin ini.WriteString('Files', lbFiles.Items[i], ''); ProgressBar1.Position := i+1; Application.ProcessMessages; end; finally ini.Free; Panel2.Visible := False; end; SchemaChanged := False; SchemaName := ExtractFileName(FileName); FormatCaption; end; procedure TForm1.SchemaClear; begin Memo1.Clear; Memo2.Clear; lbFilesTypes.Clear; lbFiles.Clear; ledRootPath.Clear; chbScanSubFolders.Checked := False; PageControl1.ActivePageIndex := 0; SchemaChanged := False; SchemaName := ''; FormatCaption; end; procedure TForm1.acFilesAddFilesTypesExecute(Sender: TObject); function AddFileTypes(FilesList: TFilesList; Strings: TStrings): Integer; var i: Integer; FileExt: String; begin Result := 0; for i := 0 to FilesList.FilesCount - 1 do begin FileExt := AnsiLowerCase(ExtractFileExt(FilesList[i].Name)); if Strings.IndexOf(FileExt) = -1 then begin Strings.Add(FileExt); Result := Result + 1; end; end; for i := 0 to FilesList.FoldersCount - 1 do Result := Result + AddFileTypes(FilesList.Folders[i], Strings); end; var FilesList: TFilesList; begin // сканирование типов файлов // просканировать путь (если задано - то рекурсивно) FilesList := TFilesList.Create; try FilesList.Scan(ledRootPath.Text, '*.*', chbScanSubFolders.Checked); if AddFileTypes(FilesList, lbFilesTypes.Items) > 0 then begin SchemaChanged := True; FormatCaption; end; finally FilesList.Free; end; end; procedure TForm1.acRulesDeleteRuleExecute(Sender: TObject); begin // Delete rule end; procedure TForm1.btnBrowseClick(Sender: TObject); var Dir: String; begin if SelectDirectory('', '', Dir) then begin if Copy(Dir, Length(Dir), 1) <> '\' then Dir := Dir + '\'; ledRootPath.Text := Dir; end; end; procedure TForm1.acFilesDelFileTypeExecute(Sender: TObject); var Index: Integer; begin // with lbFilesTypes do begin Index := ItemIndex; if Index = -1 then Exit; Items.Delete(Index); if Count > Index then ItemIndex := Index else ItemIndex := Index - 1; end; SchemaChanged := True; FormatCaption; end; procedure TForm1.acFilesAddFilesExecute(Sender: TObject); function AddFiles(FilesList: TFilesList; Strings, Strings2: TStrings): Integer; var i: Integer; FileExt: String; begin Result := 0; for i := 0 to FilesList.FilesCount - 1 do begin FileExt := AnsiLowerCase(ExtractFileExt(FilesList[i].Name)); if (Strings2.IndexOf(FileExt) <> -1) or (Strings2.Count = 0) then if Strings.IndexOf(FilesList[i].FullPath) = -1 then begin Strings.Add(FilesList[i].FullPath); Result := Result + 1; end; end; for i := 0 to FilesList.FoldersCount - 1 do Result := Result + AddFiles(FilesList.Folders[i], Strings, Strings2); end; var FilesList: TFilesList; begin // Добавляем файлы PageControl2.ActivePage := tsFilesList; // сканируем все файлы FilesList := TFilesList.Create; try FilesList.Scan(ledRootPath.Text, '*.*', chbScanSubFolders.Checked); if AddFiles(FilesList, lbFiles.Items, lbFilesTypes.Items) > 0 then begin SchemaChanged := True; FormatCaption; end; finally FilesList.Free; end; end; procedure TForm1.acFilesDeleteFileExecute(Sender: TObject); var Index: Integer; begin with lbFiles do begin Index := ItemIndex; if Index = -1 then Exit; Items.Delete(Index); if Count > Index then ItemIndex := Index else ItemIndex := Index - 1; end; SchemaChanged := True; FormatCaption; end; procedure TForm1.acReplaceDoItExecute(Sender: TObject); function FindAndReplace(Strings, Rules: TStrings): Boolean; var i,j,k: Integer; s: String; begin Result := False; for i := 0 to Strings.Count - 1 do begin for j := 0 to Rules.Count - 1 do begin k := Pos(Rules.Names[j], Strings[i]); if k <> 0 then begin // s := AnsiReplaceText(Strings[i], Rules.Names[j], Rules.Values[Rules.Names[j]]); // case ignore function s := AnsiReplaceStr(Strings[i], Rules.Names[j], Rules.Values[Rules.Names[j]]); if CompareStr(Strings[i], s) <> 0 then begin Strings[i] := s; Result := True; end; end; end; end; end; var i: Integer; sl: TStringList; begin // Замена по всем файлам из списка PageControl1.ActivePage := tsReplace; ProgressBar1.Position := 0; ProgressBar1.Max := lbFiles.Items.Count; Panel2.Visible := True; sl := TStringList.Create; try for i := 0 to lbFiles.Items.Count - 1 do begin sl.LoadFromFile(lbFiles.Items[i]); // автозамена по ранее заготовленным шаблонам if FindAndReplace(sl, Memo2.Lines) then begin sl.SaveToFile(lbFiles.Items[i]); // добавить запись в лог о сохранении файла Memo1.Lines.Add(Format('File %s changed and saved',[lbFiles.Items[i]])); end; ProgressBar1.Position := ProgressBar1.Position + 1; Application.ProcessMessages; end; finally sl.Free; Panel2.Visible := False; end; end; end.
unit uBufferString; interface resourcestring sqlGetIDTransaction = 'SELECT ID_TRANSACTION FROM GET_ID_TRANSACTION'; sqlGetIDPBKey = 'SELECT Id_PbKey FROM Buffer_Get_Id_PBKey'; sqlAddBufTran = 'INSERT INTO BUFF_TRAN(ID_TRANSACTION, ID_PBKEY, DATE_IN, ' + 'BUFFER_NAME, IB_BUFFER_NAME, Id_System) VALUES(:Id_Transaction, :Id_PBKey, '+ 'CURRENT_DATE, :Buffer, :IB_Buffer, :Id_System)'; sqlGetTranData = 'SELECT * FROM BUFF_GET_TRANSACTION_RECORDS(:Id_Transaction)'; sqlDelIBBuffer = 'DELETE FROM :IB_Buffer_Name WHERE Id_PBKey = :Id_PBKey'; sqlDelBufTran = 'EXECUTE PROCEDURE BUFF_TRANSACTION_RECORDS_DELETE(:Id_Transaction)'; sqlGetAllTran= 'SELECT * FROM BUFF_TRAN WHERE Id_System = :Id_System'; sqlDelRecBufTran = 'DELETE FROM BUFF_TRAN WHERE Id_Transaction = ' + ':Id_Transaction AND Id_PBKey = :Id_PBKey'; sqlGetData = 'SELECT * FROM :IB_Buffer WHERE Id_PBKey = :Id_PBKey'; errBufTransactionActive = 'BufTran.Start: Транзакция буфера уже начата'; errARBufTransactionNotActive = 'BufTran.AddRecord: Транзакция буфера не запущена'; errRBBufTransactionNotActive = 'BufTran.Rollback: Транзакция буфера не запущена'; errCBufTransactionNotActive = 'BufTran.Commit: Транзакция буфера не запущена'; errRollbackAll = 'BufTran.RollbackAll: Під час роботи системи запису даних у dbf виникла проблема: '; implementation end.
unit Odontologia.Modelo.Ciudad.Interfaces; interface uses Data.DB, SimpleInterface, Odontologia.Modelo.Entidades.Ciudad, Odontologia.Modelo.Departamento.Interfaces; type iModelCiudad = interface ['{89B9EBC9-DD50-466E-B032-6C59B574BD5E}'] function Entidad : TDCIUDAD; overload; function Entidad(aEntidad: TDCIUDAD) : iModelCiudad; overload; function DAO : iSimpleDAO<TDCIUDAD>; function DataSource(aDataSource: TDataSource) : iModelCiudad; function Departamento : iModelDepartamento; end; implementation end.
unit UAssembler; interface uses SysUtils, Windows; type TProc_AddByteArrays = procedure (Tab1,Tab2,Tab3:pointer; Size:Integer); // Tab3 := Tab2 + Tab1 procedure AddByteArrays(Tab1,Tab2,Tab3:pointer; Size:Integer); procedure AddByteArrays_pointer(Tab1,Tab2,Tab3:pointer; Size:Integer); procedure AddByteArrays_mmx(Tab1,Tab2,Tab3:pointer; Size:Integer); function Test_AddByteArrays(p_size: Integer; p_proc: TProc_AddByteArrays; mmx: Boolean = false ): string; implementation //GetMem wrapper that aligns the pointer on a 16 bit boundry procedure GetMemA(var P: Pointer; const Size: DWORD); inline; var OriginalAddress : Pointer; begin P := nil; GetMem(OriginalAddress,Size + 32); //Allocate users size plus extra for storage If OriginalAddress = nil Then Exit; //If not enough memory then exit P := PByte(OriginalAddress) + 4; //We want at least enough room for storage DWORD(P) := (DWORD(P) + (15)) And (Not(15)); //align the pointer If DWORD(P) < DWORD(OriginalAddress) Then Inc(PByte(P),16); //If we went into storage goto next boundry Dec(PDWORD(P)); //Move back 4 bytes so we can save original pointer PDWORD(P)^ := DWORD(OriginalAddress); //Save original pointer Inc(PDWORD(P)); //Back to the boundry end; //Freemem wrapper to free aligned memory procedure FreeMemA(P: Pointer); inline; begin Dec(PDWORD(P)); //Move back to where we saved the original pointer DWORD(P) := PDWORD(P)^; //Set P back to the original FreeMem(P); //Free the memory end; procedure AddByteArrays(Tab1,Tab2,Tab3:pointer; Size:Integer); var i: Integer; t1: PByteArray absolute Tab1; t2: PByteArray absolute Tab2; t3: PByteArray absolute Tab3; begin for I := 0 to Size - 1 do begin t3^[i] := t1^[i] + t2^[i] end; end; procedure AddByteArrays_pointer(Tab1,Tab2,Tab3:pointer; Size:Integer); var i: Integer; t1: PByte ; t2: PByte ; t3: PByte ; begin t1 := PByte(Tab1); t2 := PByte(Tab2); t3 := PByte(Tab3); for I := 0 to Size - 1 do begin t3^ := t1^ + t2^; Inc(t1); Inc(t2); Inc(t3); end; end; procedure AddByteArrays_mmx(Tab1,Tab2,Tab3:pointer; Size:Integer); begin asm push eax //Save ebx // tab1 push ebx //Save edx // tab2 push ecx //Save edx // tab3 push edx //Save edx // licznik petli mov edx, Size // ustawiam licznik petli mov eax, tab1 //Set eax to tab1 mov ebx, tab2 //Set ebx to tab2 mov ecx, tab3 //Set ecx to tab3 @@InnerLoop: //[wersja 2] movaps xmm1, [eax] //Move 16 bytes from eax xmm0 register paddb xmm1, [ebx] // wykonuje dodawanie movaps [ecx], xmm1 //Put the data to ecx // przesuwam wskaznik add eax, 16 // tab1 add ebx, 16 // tab2 add ecx, 16 // tab3 // sub edx, 16 // zmniejszam licznik petli JNZ @@InnerLoop pop edx //Restore ecx pop ecx //Restore ecx pop ebx //Restore ebx pop eax //Restore eax end; end; function Test_AddByteArrays(p_size: Integer; p_proc: TProc_AddByteArrays; mmx: Boolean = false): string; var t1,t2,t3: Pointer; var StartTick, EndTick, Frequency : Int64; i: integer; begin if mmx = true then begin GetMemA(t1,p_size); GetMemA(t2,p_size); GetMemA(t3,p_size); end else begin GetMem(t1,p_size); GetMem(t2,p_size); GetMem(t3,p_size); end; QueryPerformanceFrequency(Frequency); QueryPerformanceCounter(StartTick); // for I := 0 to 1000 - 1 do p_proc(t1,t2,t3,p_size); // QueryPerformanceCounter(EndTick); result := (Format('Time = %.2f ms'+sLineBreak + 'Transfer = %.2f MB/s',[((EndTick - StartTick) / Frequency) * 1000, (p_size/(1024*1024)) / ((EndTick - StartTick) / Frequency) ])); if mmx = true then begin FreeMemA(t1); FreeMemA(t2); FreeMemA(t3); end else begin FreeMem(t1); FreeMem(t2); FreeMem(t3); end; end; end.
unit CPrintOpAgent; (******************************************************************************* * CLASE: TPrintOpAgent * * FECHA CREACION: 08-2001 * * PROGRAMADOR: Saulo Alvarado Mateos * * DESCRIPCIÓN: * * * Agente encargado de gestionar la impresión de un registro concreto, * * mostrando el resultado en una ventana. * * * * FECHA MODIFICACIÓN: 08-05-2002 * * PROGRAMADOR: Saulo Alvarado Mateos (CINCA) * * DESCRIPCIÓN: * * Se añade una opción para que el usuario pueda elegir el número de co- * * pias a imprimir de una sola vez. Esto evita la molestia de tener que leer * * el registro para imprimirlo N veces. Se pone un tope máximo (a nivel del * * propio control en tiempo de diseño) de 99. * *******************************************************************************) interface uses SysUtils, Classes, Controls, COpDivSystemRecord, VShowListadoText; type TPrintOpAgent = class(TObject) protected FOperation: TOpDivSystemRecord; FPrnStrings: TStringList; FShowPrint: TShowListadoTextForm; FNumCopias: Integer; // procedimientos asociados a eventos en la vista procedure onChangeNumCopias(Sender: TObject); procedure onClickImprimirBtn(Sender: TObject); procedure doPrintRec; virtual; procedure doShowPrint; virtual; public constructor Create; virtual; destructor Destroy; override; procedure Execute(anOp: TOpDivSystemRecord); end; implementation uses StdCtrls, Printers; (****************** MÉTODOS PROTEGIDOS ******************) procedure TPrintOpAgent.onChangeNumCopias(Sender: TObject); begin FNumCopias := StrToInt(TEdit( Sender ).Text); end; procedure TPrintOpAgent.onClickImprimirBtn(Sender: TObject); begin doPrintRec(); end; procedure TPrintOpAgent.doPrintRec; var // Impresion: TEXT; iLine: Integer; xPos, yPos: Integer; // 08.05.02 - se pueden imprimir N copias de una vez numCopia: Integer; begin (* $ 5/11/2001 -- a partir de ahora, se manipula la impresión "pintando" en vez de enviando las líneas. AssignPrn(Impresion); Rewrite(Impresion); // ponemos un tipo de letra que sea FIXED // Printer.Canvas.Font.Name := 'Courier New'; // Printer.Canvas.Font.Size := 9; for iLine := 0 to FPrnStrings.Count - 1 do WriteLn(Impresion, FPrnStrings.Strings[iLine]); CloseFile(Impresion); *) for numCopia := 1 to FNumCopias do begin Printer.BeginDoc(); printer.Title := 'Operaciones diversas. Tipo ' + FOperation.RecType; // establecemos fuente y tamaño Printer.Canvas.Font.Name := 'Courier New'; Printer.Canvas.Font.Size := 10; // dejamos un margen de x píxeles y empezamos en y... xPos := 15; yPos := 65; for iLine := 0 to FPrnStrings.Count - 1 do begin Printer.Canvas.TextOut(xPos, yPos, FPrnStrings.Strings[iLine]); yPos := yPos + Printer.Canvas.TextHeight('0123456789abcdefghijklmnñopqrstuvwxzyABCDEFGHIJKLMNÑOPQRSTUVWXYZ_') + 3; end; Printer.EndDoc(); end; // además, después de impreso se cierra la ventana FShowPrint.ModalResult := mrOK; end; procedure TPrintOpAgent.doShowPrint; // var // showPrint: TShowListadoTextForm; begin FShowPrint := TShowListadoTextForm.Create(nil); try FShowPrint.listadoMemo.Lines.Assign(FPrnStrings); // 08.05.02 - se asocia el cambio de copias para tener "actualizado" el valor interno. FShowPrint.numCopiasEdit.OnChange := onChangeNumCopias; // se debe asociar el botón "imprimir"... FShowPrint.imprimirButton.OnClick := onClickImprimirBtn; FShowPrint.ShowModal(); finally FShowPrint.Free(); end; end; (**************** MÉTODOS PÚBLICOS ****************) // -- creación, destrucción constructor TPrintOpAgent.Create; begin inherited; FPrnStrings := TStringList.Create(); FNumCopias := 0; end; destructor TPrintOpAgent.Destroy; begin FPrnStrings.Free(); inherited; end; // -- de utilidad procedure TPrintOpAgent.Execute(anOp: TOpDivSystemRecord); begin FPrnStrings.Clear(); FOperation := anOp; anOp.getDataAsPrintedRecord(FPrnStrings); doShowPrint(); end; end.
unit frmAboutU; interface uses WinApi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.Controls, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Imaging.pngimage; type TfrmAbout = class(TForm) Panel1: TPanel; Comments: TLabel; Panel2: TPanel; OKButton: TButton; Panel3: TPanel; Panel4: TPanel; Panel5: TPanel; ProgramIcon: TImage; ProductName: TLabel; CompanyName: TLabel; Bevel1: TBevel; Version: TLabel; memoCredits: TMemo; procedure FormCreate(Sender: TObject); private procedure UpdateProductInformation; public { Public declarations } end; implementation {$R *.dfm} uses FileVersionInformationU; procedure TfrmAbout.FormCreate(Sender: TObject); begin ProductName.Font.Size := ProductName.Font.Size * 2; CompanyName.Font.Size := CompanyName.Font.Size + 2; UpdateProductInformation; end; procedure TfrmAbout.UpdateProductInformation; var LFileVersionInformation: TFileVersionInformation; begin LFileVersionInformation := TFileVersionInformation.Create; try try LFileVersionInformation.FileName := ParamStr(0); ProductName.Caption := LFileVersionInformation.ProductName; Version.Caption := LFileVersionInformation.FileVersion; CompanyName.Caption := LFileVersionInformation.CompanyName; Comments.Caption := LFileVersionInformation.Comments; except end; finally FreeAndNil(LFileVersionInformation); end; end; end.
unit ExDataT2; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask; type TfrmAddTrigger = class(TForm) btnOk: TButton; btnCancel: TButton; GroupBox1: TGroupBox; Label1: TLabel; edtTriggerString: TEdit; Label2: TLabel; edtPacketSize: TMaskEdit; Label3: TLabel; edtTimeout: TMaskEdit; chkIncludeStrings: TCheckBox; chkIgnoreCase: TCheckBox; chkEnabled: TCheckBox; procedure FormActivate(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); public TriggerString : string; PacketSize : Integer; Timeout : Integer; IncludeStrings : Boolean; IgnoreCase : Boolean; TriggerEnabled : Boolean; end; var frmAddTrigger: TfrmAddTrigger; implementation {$R *.DFM} procedure TfrmAddTrigger.FormActivate(Sender: TObject); begin edtTriggerString.Text := ''; edtPacketSize.Text := '0'; edtTimeout.Text := '0'; chkIncludeStrings.Checked := True; chkIgnoreCase.Checked := True; chkEnabled.Checked := True; end; procedure TfrmAddTrigger.btnOkClick(Sender: TObject); begin TriggerString := edtTriggerString.Text; PacketSize := StrToIntDef(edtPacketSize.Text, 0); Timeout := StrToIntDef(edtTimeout.Text, 0); IncludeStrings := chkIncludeStrings.Checked; IgnoreCase := chkIgnoreCase.Checked; TriggerEnabled := chkEnabled.Checked; ModalResult := mrOk; end; procedure TfrmAddTrigger.btnCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; end.
unit o_mitarbeiter; interface uses IBX.IBDatabase, SysUtils, IBX.IBQuery, Classes, contnrs, o_optima, o_mitarbeitergruppe, o_vertreter, f_optima, o_maeinstellungen, c_Types, o_berechtigungobj; type TMitarbeiter = class(TOptima) private Login: string; MitarbeiterName: string; Tel: string; Fax: string; Mail: string; Passwort: string; Signatur: string; Anfragen: boolean; Geschaeftsbereich: integer; Aussendienst: boolean; Vertreter: TVertreter; NurEigene: boolean; Gesperrt: boolean; PWNeverExpires: boolean; PWChangeOwn: boolean; PWChanged: TDateTime; PWExpiresAfter: integer; IstAktiv: boolean; Admin: boolean; Gruppe: integer; NurZeitbuchung: boolean; _Geschlecht: TGeschlecht; _EBNotifikation : boolean; // _IMAP_User: string; // _IMAP_Passwort: string; Hash: string; Salt: string; Gruppen: TObjectList; function getAnfragen: boolean; procedure setAnfragen(value: boolean); procedure setGeschlecht(const Value: TGeschlecht); // procedure setIMAP_Passwort(const Value: string); // procedure setIMAP_User(const Value: string); // function getIMAP_Passwort: string; protected function getGeneratorName: string; override; function getTablePrefix: string; override; public Einstellung: TMAEinstellungen; Berechtigung: TBerechtigungObj; function delete: boolean; override; constructor Create(aOwner: TComponent; aLogin: string; aStammdaten: pointer; aTransaction: TIBTransaction); overload; destructor Destroy; override; function getTableName: string; override; procedure loadFromQuery(aQuery: TIBQuery); override; procedure saveToDB; override; function getLogin: string; function getMitarbeiterName: string; function getTel: string; function getFax: string; function getMail: string; function getPasswort: string; function getSignatur: string; function getGeschaeftsbereich: integer; function isGesperrt: boolean; function getPWNeverExpires: boolean; function getPWChangeOwn: boolean; function getPWChanged: TDateTime; function getPWExpiresAfter: integer; function getGruppen: TObjectList; function getAdmin: boolean; function getGruppe: integer; function getImageFile: string; function getNurZeibuchung: boolean; function getHash: string; function getSalt: string; procedure setLogin(const aLogin: string); procedure setMitarbeiterName(aMitarbeiterName: string); procedure setTel(aTel: string); procedure setFax(aFax: string); procedure setMail(aMail: string); procedure setPasswort(aPasswort: string); procedure setSignatur(aSignatur: string); procedure setGeschaeftsbereich(aGeschaeftsbereich: integer); procedure setGesperrt(aGesperrt: boolean); procedure setPWNeverExpires(aValue: boolean); procedure setPWChangeOwn(aValue: boolean); procedure setPWChanged(aDate: TDateTime); procedure setPWExpiresAfter(aDays: integer); procedure setGruppe(aWert: integer); procedure setNurZeitbuchung(aWert: boolean); procedure setHash(const aHash: string); procedure setSalt(const aSalt: string); procedure neueGruppe(aGruppeID: integer); procedure GruppenAufheben; function isInGruppe(aGruppe: TMitarbeitergruppe): boolean; property isAnfragen: boolean read getAnfragen write setAnfragen; procedure setEBNotifikation(awert : boolean); procedure setIstAktiv(aWert: boolean); procedure setVertreter(aVertreter: TVertreter); procedure setNurEigene(aWert: boolean); procedure setAussendienst(aWert: boolean); function getVertreter: TVertreter; function getNurEigene: boolean; function getAussendienst: boolean; function getIstAktiv: boolean; function getKommunikationMail: string; function getGBKommunikationID: integer; function getMAKommunikationID: integer; function getStandardKommunikationsprofil: pointer; function getGB_Bev_KommunikationID: integer; function isGruppe: boolean; function isLogin: boolean; function getKey: string; property Geschlecht: TGeschlecht read _Geschlecht write setGeschlecht; property EBNotifikation: boolean read _EBNotifikation write setEBNotifikation; // property IMAP_User: string read _IMAP_User write setIMAP_User; // property IMAP_Passwort: string read getIMAP_Passwort write setIMAP_Passwort; class function loadForGruppe(aOwner: TComponent; aGruppenId: integer; aStammdaten: pointer; aTransaction: TIBTransaction): TMitarbeiter; procedure InitNew; override; end; const cAussendienst = 10; implementation uses o_makommunikation, o_optimaSimpleQueryBuilder, o_optimaFactory, IdHTTP, IdHash, IdHashMessageDigest, o_nf, o_MaGruppe, o_Geschaeftsbereich, math, o_debuglist, o_Stammdaten; constructor TMitarbeiter.Create(aOwner: TComponent; aLogin: string; aStammdaten: pointer; aTransaction: TIBTransaction); var ReadQuery: TIBQuery; Lower_Login: string; Login_Length: Integer; begin inherited Create(aOwner); Transaction := aTransaction; ReadQuery := TIBQuery.Create(self); with ReadQuery do begin Lower_Login := SqlCaseSensitiv(aLogin); Transaction := self.Transaction; OpenTransaction; Login_Length := f_optima.FieldSize('MA_LOGIN', 'MITARBEITER', Transaction); Lower_Login := Copy(Lower_Login, 1, Login_Length); SQL.Clear; SQL.Add('select * from MITARBEITER where lower(MA_LOGIN) = lower(:Login) and MA_DELETE != "T" and MA_AKTIV = "T" '); ParamByName('Login').asString := Lower_Login; Open; loadFromQuery(ReadQuery); Close; CommitTransaction; Free; end; end; function TMitarbeiter.getLogin: string; begin result := Login; end; function TMitarbeiter.getMitarbeiterName: string; begin result := MitarbeiterName; end; function TMitarbeiter.getPasswort: string; var KryptPass: string; KryptChar: char; x: integer; begin KryptPass := ''; for x := 1 to length(Passwort) do begin KryptChar := Passwort[x]; KryptChar := chr(ord(KryptChar) xor ord('A')); KryptPass := KryptPass + KryptChar; end; result := KryptPass; end; function TMitarbeiter.getAdmin: boolean; begin result := Admin; end; function TMitarbeiter.getSignatur: string; begin result := Signatur; end; function TMitarbeiter.getStandardKommunikationsprofil: pointer; var stdID: integer; begin result := nil; stdID := getMAKommunikationID; if stdID > 0 then result := TMAKommunikation.Create(self, stdID, StammdatenX, Transaction); end; function TMitarbeiter.getGeschaeftsbereich: integer; begin result := Geschaeftsbereich; end; function TMitarbeiter.getAnfragen: boolean; begin result := Anfragen; end; procedure TMitarbeiter.saveToDB; var WriteQuery: TIBQuery; x: integer; begin if ((not Update) and (not Neu) and (not Del)) or (Neu and Del) then Exit; WriteQuery := TIBQuery.Create(self); // Mitarbeitergruppen speichern with WriteQuery do begin Transaction := self.Transaction; OpenTransaction; // TODO: Macht das Sinn bei jedem Speichern des Mitarbeiters die // gesamten Gruppenzuordnungen zu löschen und neu anzulegen?! SQL.Clear; SQL.Add('UPDATE MA_MG SET MA_MG_DELETE = "T" WHERE MA_MG_MA_ID = :ID'); ParamByName('ID').AsInteger := ID; ExecSQL; SQL.Clear; SQL.Add('INSERT INTO MA_MG ( ' + 'MA_MG_ID, MA_MG_MA_ID, MA_MG_MG_ID, MA_MG_UPDATE, MA_MG_DELETE ' + ') VALUES ( ' + 'GEN_ID(MA_MG_ID, 1), :Mitarbeiter, :Gruppe, "T", "F" ' + ') '); for x := 0 to self.getGruppen.Count - 1 do begin ParamByName('Mitarbeiter').AsInteger := ID; ParamByName('Gruppe').AsInteger := TMitarbeitergruppe(self.getGruppen.Items[x]).getID; ExecSQL; end; SQL.Clear; if not Neu then SQL.Add('update MITARBEITER set ' + 'MA_NAME = :MA_Name, ' + 'MA_LOGIN = :Login, ' + 'MA_PASSWORD = :Pass, ' + 'MA_TEL = :Tel, ' + 'MA_FAX = :Fax, ' + 'MA_MAIL = :Mail, ' + 'MA_SIGNATUR = :Signatur, ' + 'MA_ANFRAGEN = :Anfragen, ' + 'MA_GB_ID = :GBereich, ' + 'MA_VERTRETER = :Vertreter, ' + 'MA_NUREIGENE = :NurEIgene, ' + 'MA_AUSSENDIENST = :Aussendienst, ' + 'MA_UPDATE = :Upd, ' + 'MA_DELETE = :Del, ' + 'MA_PW_NEVER_EXPIRE = :PWNeverExpire, ' + 'MA_PW_CHANGE_OWN = :PWChangeOwn, ' + 'MA_GESPERRT = :Gesperrt, ' + 'MA_PW_CHANGED = :PWChanged, ' + 'MA_TEL_NORM = :TelNorm, ' + 'MA_AKTIV = :IstAktiv, ' + 'MA_PW_EXPIRES_AFTER = :PWExpiresAfter, ' + 'MA_GESCHLECHT = :Geschlecht, ' + 'MA_EB_NOTIFICATION = :EBNotifikation, ' + 'MA_NURZEITBUCHUNG = :NurZeitbuchung, ' + // 'MA_IMAP_USER = :IMAPUser, ' + // 'MA_IMAP_PASSWORT = :IMAPPasswort, ' + 'MA_GRUPPE = :Gruppe, ' + 'MA_HASH = :Hash, ' + 'MA_SALT = :Salt ' + 'where MA_ID = :ID') else SQL.Add('insert into MITARBEITER( ' + 'MA_ID, MA_NAME, MA_LOGIN, MA_PASSWORD, MA_TEL, MA_FAX, MA_MAIL, MA_SIGNATUR, ' + 'MA_ANFRAGEN, MA_GB_ID, MA_VERTRETER, MA_NUREIGENE, MA_AUSSENDIENST, MA_UPDATE, ' + 'MA_DELETE, MA_AKTIV, MA_PW_NEVER_EXPIRE, MA_PW_CHANGE_OWN, MA_GESPERRT, ' + 'MA_PW_CHANGED, MA_PW_EXPIRES_AFTER, MA_TEL_NORM, ' + 'MA_GRUPPE, MA_GESCHLECHT, MA_EB_NOTIFICATION, MA_NURZEITBUCHUNG, ' + // 'MA_IMAP_USER, MA_IMAP_PASSWORT, ' + 'MA_HASH, MA_SALT ' + ') values ( ' + ':ID, :MA_Name, :Login, :Pass, :Tel, :Fax, :Mail, :Signatur, :Anfragen, ' + ':GBereich, :Vertreter, :NurEigene, :Aussendienst, :Upd, :Del, :IstAktiv, ' + ':PWNeverExpire, :PWChangeOwn, :Gesperrt, :PWChanged, :PWExpiresAfter, ' + ':TelNorm, :Gruppe, :Geschlecht, :EBNotifikation, :NurZeitbuchung, ' + // ':IMAPUser, :IMAPPasswort, ' + ':Hash, :Salt)'); ParamByName('ID').AsInteger := ID; ParamByName('MA_Name').asString := MitarbeiterName; ParamByName('Tel').asString := Tel; ParamByName('Fax').asString := Fax; ParamByName('Mail').asString := Mail; ParamByName('Login').asString := Login; ParamByName('Pass').asString := Passwort; ParamByName('Signatur').asString := Signatur; ParamByName('Anfragen').asString := BoolToStr(Anfragen); ParamByName('GBereich').AsInteger := Geschaeftsbereich; ParamByName('Upd').asString := 'T'; ParamByName('Del').asString := BoolToStr(Del); if Vertreter = nil then ParamByName('Vertreter').AsInteger := 0 else ParamByName('Vertreter').AsInteger := Vertreter.getID; ParamByName('NurEigene').asString := BoolToStr(NurEigene); ParamByName('Aussendienst').asString := BoolToStr(Aussendienst); ParamByName('PWNeverExpire').asString := BoolToStr(PWNeverExpires); ParamByName('PWChangeOwn').asString := BoolToStr(PWChangeOwn); ParamByName('Gesperrt').asString := BoolToStr(Gesperrt); ParamByName('PWChanged').AsDateTime := PWChanged; ParamByName('PWExpiresAfter').AsInteger := PWExpiresAfter; ParamByName('TelNorm').asString := normalisieren(Tel); ParamByName('IstAktiv').asString := BoolToStr(IstAktiv); ParamByName('Gruppe').AsInteger := Gruppe; ParamByName('Geschlecht').AsInteger := ord(Geschlecht); ParamByName('EBNotifikation').asString := BoolToStr(_EBNotifikation); ParamByName('NurZeitbuchung').AsString := BoolToStr(NurZeitbuchung); // ParamByName('IMAPUser').AsString := _IMAP_User; // ParamByName('IMAPPasswort').AsString := _IMAP_Passwort; ParamByName('Hash').AsString := Hash; ParamByName('Salt').AsString := Salt; ExecSQL; CommitTransaction; Free; Update := false; Neu := false; end; end; procedure TMitarbeiter.setAnfragen(value: boolean); begin if value <> Anfragen then begin Anfragen := value; Update := true; end; end; class function TMitarbeiter.loadForGruppe(aOwner: TComponent; aGruppenId: integer; aStammdaten: pointer; aTransaction: TIBTransaction): TMitarbeiter; var queryBuilder: TOptimaSimpleQueryBuilder; begin queryBuilder := TOptimaSimpleQueryBuilder.Create; queryBuilder.select.from('MITARBEITER').where('MA_GRUPPE = :Gruppe').param('Gruppe', aGruppenId).where('MA_DELETE != "T"'); result := TOptimaFactory.FindFirst(TMitarbeiter, queryBuilder, aOwner, aTransaction) as TMitarbeiter; queryBuilder.Free; end; procedure TMitarbeiter.loadFromQuery(aQuery: TIBQuery); begin with aQuery do begin ID := FieldByName('MA_ID').AsInteger; MitarbeiterName := FieldByName('MA_NAME').asString; Tel := FieldByName('MA_TEL').asString; Fax := FieldByName('MA_FAX').asString; Mail := FieldByName('MA_MAIL').asString; Login := FieldByName('MA_LOGIN').asString; Passwort := FieldByName('MA_PASSWORD').asString; Signatur := FieldByName('MA_SIGNATUR').asString; Anfragen := (FieldByName('MA_ANFRAGEN').asString = 'T'); Geschaeftsbereich := FieldByName('MA_GB_ID').AsInteger; if FieldByName('MA_VERTRETER').AsInteger = 0 then Vertreter := nil else Vertreter := TVertreter.Create(self, FieldByName('MA_Vertreter').AsInteger, StammdatenX, self.Transaction); NurEigene := FieldByName('MA_NUREIGENE').asString = 'T'; Aussendienst := FieldByName('MA_AUSSENDIENST').asString = 'T'; Gesperrt := (FieldByName('MA_GESPERRT').asString = 'T'); PWNeverExpires := (FieldByName('MA_PW_NEVER_EXPIRE').asString = 'T'); PWChangeOwn := (FieldByName('MA_PW_CHANGE_OWN').asString = 'T'); PWChanged := FieldByName('MA_PW_CHANGED').AsDateTime; PWExpiresAfter := FieldByName('MA_PW_EXPIRES_AFTER').AsInteger; IstAktiv := FieldByName('MA_AKTIV').asString = 'T'; Admin := FieldByName('MA_ADMIN').asString = 'T'; Gruppe := FieldByName('MA_GRUPPE').AsInteger; Einstellung := TMAEinstellungen.Create(self, ID, aQuery.Transaction.DefaultDatabase); Berechtigung := TBerechtigungObj.Create(Id, aQuery.Transaction); Geschlecht := TGeschlecht(FieldByName('MA_GESCHLECHT').AsInteger); NurZeitbuchung := FieldByName('MA_NURZEITBUCHUNG').AsString = 'T'; _EBNotifikation := FieldByName('MA_EB_NOTIFICATION').asString = 'T'; // _IMAP_User := FieldByName('MA_IMAP_USER').AsString; // _IMAP_Passwort := FieldByName('MA_IMAP_PASSWORT').AsString; Hash := FieldByName('MA_HASH').asString; Salt := FieldByName('MA_SALT').asString; end; end; procedure TMitarbeiter.setGeschaeftsbereich(aGeschaeftsbereich: integer); begin UpdateV(Geschaeftsbereich, aGeschaeftsbereich); end; procedure TMitarbeiter.setGeschlecht(const Value: TGeschlecht); begin if _Geschlecht <> Value then begin _Geschlecht := Value; Aktual; end; //UpdateV(ord(_Geschlecht), ord(Value)); end; procedure TMitarbeiter.setLogin(const aLogin: string); begin UpdateV(Login, aLogin); end; procedure TMitarbeiter.setMitarbeiterName(aMitarbeiterName: string); begin UpdateV(MitarbeiterName, aMitarbeiterName); end; procedure TMitarbeiter.setPasswort(aPasswort: string); var KryptPass: string; KryptChar: char; x: integer; begin KryptPass := ''; for x := 1 to length(aPasswort) do begin KryptChar := aPasswort[x]; KryptChar := chr(ord(KryptChar) xor ord('A')); KryptPass := KryptPass + KryptChar; end; UpdateV(Passwort, KryptPass); end; procedure TMitarbeiter.setSignatur(aSignatur: string); begin UpdateV(Signatur, aSignatur); end; procedure TMitarbeiter.neueGruppe(aGruppeID: integer); begin self.getGruppen.Add(TMitarbeitergruppe.Create(self, aGruppeID, StammdatenX, Transaction)); Update := true; end; procedure TMitarbeiter.GruppenAufheben; begin self.getGruppen.Clear; Update := true; end; function TMitarbeiter.isInGruppe(aGruppe: TMitarbeitergruppe): boolean; var x: integer; begin result := false; for x := 0 to self.getGruppen.Count - 1 do begin if TMitarbeitergruppe(self.getGruppen.Items[x]).getID = aGruppe.getID then begin result := true; Exit; end; end; end; function TMitarbeiter.isLogin: boolean; begin result := Gruppe = 0; end; function TMitarbeiter.getVertreter: TVertreter; begin result := Vertreter; end; procedure TMitarbeiter.setVertreter(aVertreter: TVertreter); begin if (Vertreter = nil) or (aVertreter = nil) or (Vertreter.getID <> aVertreter.getID) then begin Vertreter := aVertreter; Update := true; end; end; function TMitarbeiter.getNurEigene: boolean; begin result := NurEigene; end; function TMitarbeiter.getNurZeibuchung: boolean; begin result := NurZeitbuchung; end; procedure TMitarbeiter.setNurEigene(aWert: boolean); begin UpdateV(NurEigene, aWert); end; procedure TMitarbeiter.setNurZeitbuchung(aWert: boolean); begin updateV(NurZeitbuchung, aWert); end; function TMitarbeiter.getAussendienst: boolean; begin result := Aussendienst; end; procedure TMitarbeiter.setAussendienst(aWert: boolean); begin UpdateV(Aussendienst, aWert); end; function TMitarbeiter.getPWChanged: TDateTime; begin result := PWChanged; end; function TMitarbeiter.getPWChangeOwn: boolean; begin result := PWChangeOwn; end; function TMitarbeiter.getPWExpiresAfter: integer; begin result := PWExpiresAfter; end; function TMitarbeiter.getPWNeverExpires: boolean; begin result := PWNeverExpires; end; function TMitarbeiter.isGesperrt: boolean; begin result := Gesperrt; end; function TMitarbeiter.isGruppe: boolean; begin result := Gruppe > 0; end; procedure TMitarbeiter.setGesperrt(aGesperrt: boolean); begin UpdateV(Gesperrt, aGesperrt); end; procedure TMitarbeiter.setGruppe(aWert: integer); begin UpdateV(Gruppe, aWert); end; { procedure TMitarbeiter.setIMAP_Passwort(const Value: string); begin UpdateV(_IMAP_Passwort, PasswortVerschluesseln(Value, getKey)); end; procedure TMitarbeiter.setIMAP_User(const Value: string); begin UpdateV(_IMAP_User, Value); end; } procedure TMitarbeiter.setIstAktiv(aWert: boolean); begin UpdateV(IstAktiv, aWert); end; procedure TMitarbeiter.setHash(const aHash: string); begin UpdateV(Hash, aHash); end; function TMitarbeiter.getHash: string; begin result := Hash; end; procedure TMitarbeiter.setSalt(const aSalt: string); begin UpdateV(Salt, aSalt); end; function TMitarbeiter.getSalt: string; begin result := Salt; end; procedure TMitarbeiter.setPWChanged(aDate: TDateTime); begin UpdateV(PWChanged, aDate); end; procedure TMitarbeiter.setPWChangeOwn(aValue: boolean); begin UpdateV(PWChangeOwn, aValue); end; procedure TMitarbeiter.setPWExpiresAfter(aDays: integer); begin UpdateV(PWExpiresAfter, aDays); end; procedure TMitarbeiter.setPWNeverExpires(aValue: boolean); begin UpdateV(PWNeverExpires, aValue); end; function TMitarbeiter.getGeneratorName: string; begin result := 'MA_ID'; end; function TMitarbeiter.getTableName: string; begin result := 'MITARBEITER'; end; function TMitarbeiter.getTablePrefix: string; begin result := 'MA'; end; function TMitarbeiter.getKey: string; var eKey: Extended; begin eKey := power(getID, 2); Result := 'O$p"t!m$' + FloatToStr(eKey) + 'n2wß-f*r#o€n<t>i&e@r=s'; end; function TMitarbeiter.getKommunikationMail: string; var Query: TIBQuery; WasOpen: boolean; begin Query := TIBQuery.Create(self); with Query do begin Transaction := self.Transaction; WasOpen := Transaction.inTransaction; if not WasOpen then Transaction.StartTransaction; SQL.Add('select MK_MAIL from MAKOMMUNIKATION ' + 'where ' + 'MK_DELETE != "T" and ' + 'MK_MA_ID = :ID and ' + 'MK_STANDARD = "T" '); ParamByName('ID').AsInteger := self.getID; Open; result := Fields[0].asString; Close; if not WasOpen then Transaction.Rollback; Free; end; end; function TMitarbeiter.getGruppe: integer; begin result := Gruppe; end; function TMitarbeiter.getGruppen: TObjectList; var ReadQuery: TIBQuery; begin if Gruppen = nil then begin Gruppen := TObjectList.Create; ReadQuery := TIBQuery.Create(self); with ReadQuery do begin Transaction := self.Transaction; OpenTransaction; SQL.Clear; SQL.Add('SELECT * FROM MA_MG WHERE MA_MG_MA_ID = :ID AND MA_MG_DELETE <> "T"'); ParamByName('ID').AsInteger := ID; Open; while not eof do begin Gruppen.Add(TMitarbeitergruppe.Create(self, FieldByName('MA_MG_MG_ID').AsInteger, StammdatenX, self.Transaction)); next; end; Close; CommitTransaction; end; freeAndNil(ReadQuery); end; result := Gruppen; end; function TMitarbeiter.getImageFile: string; var Mail, hash: string; fileStream: TFileStream; md5: TIdHashMessageDigest5; http: TIdHttp; DebugList: TDebugList; begin // TODO: In eigene Klasse packen // TODO: TTL implementieren // TODO: In ein Temp-Verzeichnis speichern result := ''; DebugList := TDebugList.Create('c:\temp\log.txt'); try DebugList.Log('TMitarbeiter.getImageFile', '***START***'); if getStandardKommunikationsprofil = nil then begin DebugList.Log('TMitarbeiter.getImageFile', 'Kein Standardprofil gefunden.'); Exit; end; Mail := TMAKommunikation(getStandardKommunikationsprofil).getMail; DebugList.Log('TMitarbeiter.getImageFile', Mail); md5 := TIdHashMessageDigest5.Create; hash := LowerCase(md5.HashStringAsHex(LowerCase(Mail))); md5.Free; DebugList.Log('TMitarbeiter.getImageFile', Hash); result := Tnf.GetInstance.System.GetTempPath + hash + '.jpg'; DebugList.Log('TMitarbeiter.getImageFile', Result); if (not FileExists(result)) then begin DebugList.Log('TMitarbeiter.getImageFile', 'Datei nicht gefunden'); fileStream := TFileStream.Create(result, fmCreate); http := TIdHttp.Create(self); http.Get('http://www.gravatar.com/avatar/' + hash + '?s=32&d=mm', fileStream); DebugList.Log('TMitarbeiter.getImageFile', 'Get'); http.Free; fileStream.Free; end; DebugList.Log('TMitarbeiter.getImageFile', '***ENDE***'); finally FreeAndNil(DebugList); end; end; { function TMitarbeiter.getIMAP_Passwort: string; begin Result := PasswortEntschluesseln(_IMAP_Passwort, getKey); end; } function TMitarbeiter.getIstAktiv: boolean; begin result := IstAktiv; end; destructor TMitarbeiter.Destroy; begin if (Vertreter <> nil) and (Vertreter.Owner = self) then freeAndNil(Vertreter); if (Gruppen <> nil) then freeAndNil(Gruppen); if (Berechtigung <> nil) then FreeAndNil(Berechtigung); inherited; end; function TMitarbeiter.getFax: string; begin result := Fax; end; function TMitarbeiter.getMail: string; begin result := Mail; end; function TMitarbeiter.getMAKommunikationID: integer; var Query: TIBQuery; WasOpen: boolean; begin result := -1; Query := TIBQuery.Create(self); with Query do begin Transaction := self.Transaction; WasOpen := Transaction.inTransaction; if not WasOpen then Transaction.StartTransaction; SQL.Add('select MK_ID from MAKOMMUNIKATION ' + 'where ' + 'MK_DELETE != "T" and ' + 'MK_MA_ID = :ID and ' + 'MK_STANDARD = "T" '); ParamByName('ID').AsInteger := self.getID; Open; if Fields[0].AsInteger > 0 then result := Fields[0].AsInteger; Close; if not WasOpen then Transaction.Rollback; Free; end; end; function TMitarbeiter.getGBKommunikationID: integer; var Query: TIBQuery; WasOpen: boolean; begin result := -1; Query := TIBQuery.Create(self); try Query.Transaction := self.Transaction; WasOpen := self.Transaction.Active; if not WasOpen then self.Transaction.StartTransaction; Query.SQL.Add('select MK_ID from MAKOMMUNIKATION ' + 'where ' + 'MK_DELETE != "T" and ' + 'MK_MA_ID = :ID and ' + 'MK_GB_ID = :GBID '); Query.ParamByName('ID').AsInteger := self.getID; Query.ParamByName('GBID').AsInteger := StammdatenX.getAktGB; Query.Open; if Query.Fields[0].AsInteger > 0 then result := Query.Fields[0].AsInteger; Query.Close; if not WasOpen then Transaction.Rollback; finally freeAndNil(Query); end; end; function TMitarbeiter.getGB_Bev_KommunikationID: integer; var Query: TIBQuery; WasOpen: boolean; begin result := -1; Query := TIBQuery.Create(self); try Query.Transaction := self.Transaction; WasOpen := self.Transaction.Active; if not WasOpen then self.Transaction.StartTransaction; Query.SQL.Add('select MK_ID from MAKOMMUNIKATION ' + 'where ' + 'MK_DELETE != "T" and ' + 'MK_GB_BEVORZUGT = "T" and ' + 'MK_MA_ID = :ID and ' + 'MK_GB_ID = :GBID '); Query.ParamByName('ID').AsInteger := self.getID; Query.ParamByName('GBID').AsInteger := StammdatenX.getAktGB; Query.Open; if Query.Fields[0].AsInteger > 0 then result := Query.Fields[0].AsInteger; Query.Close; if not WasOpen then Transaction.Rollback; finally freeAndNil(Query); end; end; function TMitarbeiter.getTel: string; begin result := Tel; end; procedure TMitarbeiter.setFax(aFax: string); begin UpdateV(Fax, aFax); end; procedure TMitarbeiter.setMail(aMail: string); begin UpdateV(Mail, aMail); end; procedure TMitarbeiter.setTel(aTel: string); begin UpdateV(Tel, aTel); end; function TMitarbeiter.delete: boolean; begin DelQueries := TStringList.Create; DelQueries.Add('select count(*) from MAHNUNGEN where (MA_MITARBEITER =:Param)'); DelQueries.Add('select count(*) from JOURNAL where (JO_MITARBEITER =:Param) and (JO_DELETE != "T")'); DelQueries.Add('select count(*) from VORGANG where (VO_MITARBEITER =:Param) and (VO_DELETE != "T")'); DelQueries.Add('select count(*) from AUFTRAGSSTEUERUNG where (AU_MA_ID =:Param) and (AU_DELETE != "T")'); DelQueries.Add('select count(*) from CHARGE where (CH_MA_ID =:Param) and (CH_DELETE != "T")'); DelQueries.Add('select count(*) from SERIENNUMMERN where (SN_MA_ID =:Param) and (SN_DELETE != "T")'); DelQueries.Add('select count(*) from EXTDOKUMENTE where (ED_MA_ID =:Param) and (ED_DELETE != "T")'); DelQueries.Add('select count(*) from ZAHLUNGEN where (ZA_MA_ID =:Param)'); DelQueries.Add('select count(*) from MAILS where (ML_MA_ID =:Param) and (ML_DELETE != "T")'); DelQueries.Add('select count(*) from T_PROZESS where (PZ_MA_ID =:Param) and (PZ_DELETE != "T")'); DelQueries.Add('select count(*) from T_ARBEITSAUFTRAEGE where (AA_MA_ID =:Param) or (AA_AKT_MA_ID =:Param) and (AA_DELETE != "T")'); DelQueries.Add('select count(*) from SENDUNGEN where (SE_MA_ID =:Param) and (SE_DELETE != "T")'); DelQueries.Add('select count(*) from KUNDENAKTIVITAET where (KA_MA_ID =:Param) and (KA_DELETE != "T")'); DelQueries.Add('select count(*) from ANSPRECHPARTNER where (AS_KONTAKTER =:Param) and (AS_DELETE != "T")'); DelQueries.Add('select count(*) from PERSON where (PP_MA_ID =:Param) and (PP_DELETE != "T")'); DelMessages := TStringList.Create; DelMessages.Add('den Mahnungen'); DelMessages.Add('dem Journal'); DelMessages.Add('aktiven Vorgängen'); DelMessages.Add('den Service-Aufträgen'); DelMessages.Add('den Chargen'); DelMessages.Add('den Seriennummern'); DelMessages.Add('den externen Dokumenten'); DelMessages.Add('den Zahlungen'); DelMessages.Add('den Mails'); DelMessages.Add('den Tickets'); DelMessages.Add('den Arbeitsauftraegen'); DelMessages.Add('den Sendungen'); DelMessages.Add('den Kundenaktivitäten'); DelMessages.Add('den Ansprechpartnern'); DelMessages.Add('den Personen'); if AllowDelete then begin inherited delete; TMAGruppe.DeleteParent(getId, Transaction); result := true; end else result := false; FreeAndNil(DelQueries); FreeAndNil(DelMessages); end; procedure TMitarbeiter.InitNew; begin inherited; Geschaeftsbereich := StammdatenX.getAktGB; end; procedure TMitarbeiter.setEBNotifikation(awert: boolean); begin UpdateV(_EBNotifikation, awert); end; end.
unit MessagesFrm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, BaseFrm; type TMessagesForm = class(TBaseForm) StaticLabel: TLabel; RuntimeLabel: TLabel; SingularLabel: TLabel; FewLabel: TLabel; ManyLabel: TLabel; OtherLabel: TLabel; DynamicLabel: TLabel; Dynamic2Label: TLabel; GenderLabel: TLabel; SelectLabel: TLabel; procedure FormCreate(Sender: TObject); public procedure UpdateStrings; end; var MessagesForm: TMessagesForm; implementation {$R *.dfm} uses NtPattern; procedure TMessagesForm.FormCreate(Sender: TObject); begin UpdateStrings; end; procedure TMessagesForm.UpdateStrings; resourcestring SRuntime = 'Runtime message'; //loc Message text SDynamic = 'Hello %s!'; //loc 0: Name of the user SDynamic2 = 'Hello %s and %s!'; //loc 0: Name of the first user, 1: Name of the second user SMessagePlural = '{plural, one {%d file} other {%d files}}'; //loc 0: File count SMessageGender = '{gender, male {%s will bring his bicycle} female {%s will bring her bicycle}}'; //loc 0: Name of a person SMessageSelect = '{select, soccer {%s is the best soccer player} hockey {%s is the best ice hockey player} basketball {%s is the best basketball player}}'; //loc 0: Name of the player var str, str2, player: String; begin str := 'John'; str2 := 'Jill'; player := 'Wayne Gretzky'; // Runtime messages RuntimeLabel.Caption := SRuntime; DynamicLabel.Caption := Format(SDynamic, [str]); Dynamic2Label.Caption := Format(SDynamic2, [str, str2]); // Plural enabled messages SingularLabel.Caption := TMultiPattern.Format(SMessagePlural, 1); FewLabel.Caption := TMultiPattern.Format(SMessagePlural, 2); ManyLabel.Caption := TMultiPattern.Format(SMessagePlural, 5); OtherLabel.Caption := TMultiPattern.Format(SMessagePlural, 10); // Gender enabled messages GenderLabel.Caption := TMultiPattern.Format(SMessageGender, 'male', [str]); // Select enabled messages SelectLabel.Caption := TMultiPattern.Format(SMessageSelect, 'hockey', [player]); end; end.
unit LIB.Lattice.D2; interface //#################################################################### ■ uses System.UITypes, FMX.Graphics, LIB; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TMap2D<_TYPE_> TMap2D<_TYPE_> = class private ///// メソッド procedure InitMap; protected _Map :TArray2<_TYPE_>; _SizeX :Integer; _SizeY :Integer; ///// アクセス procedure SetSizeX( const SizeX_:Integer ); procedure SetSizeY( const SizeY_:Integer ); public constructor Create; overload; constructor Create( const SizeX_,SizeY_:Integer ); overload; virtual; ///// プロパティ property SizeX :Integer read _SizeX write SetSizeX; property SizeY :Integer read _SizeY write SetSizeY; ///// メソッド procedure SetSize( const SizeX_,SizeY_:Integer ); procedure Clear( const Value_:_TYPE_ ); procedure LoadFromFile( const FileName_:String ); virtual; abstract; procedure SaveToFile( const FileName_:String ); virtual; abstract; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TColorMap2D TColorMap2D = class( TMap2D<TAlphaColorF> ) private protected public ///// メソッド procedure LoadFromFile( const FileName_:String ); override; procedure SaveToFile( const FileName_:String ); override; procedure ImportFrom( const BMP_:TBitmap ); procedure ExportTo( const BMP_:TBitmap ); function Interp( const X_,Y_:Single ) :TAlphaColorF; end; //const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ uses System.Math, System.Threading, System.Classes; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TMap2D<_TYPE_> //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private /////////////////////////////////////////////////////////////////////// メソッド procedure TMap2D<_TYPE_>.InitMap; begin SetLength( _Map, _SizeY, _SizeX ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス procedure TMap2D<_TYPE_>.SetSizeX( const SizeX_:Integer ); begin _SizeX := SizeX_; InitMap; end; procedure TMap2D<_TYPE_>.SetSizeY( const SizeY_:Integer ); begin _SizeY := SizeY_; InitMap; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TMap2D<_TYPE_>.Create; begin Create( 0, 0 ); end; constructor TMap2D<_TYPE_>.Create( const SizeX_,SizeY_:Integer ); begin inherited Create; SetSize( SizeX_, SizeY_ ); end; /////////////////////////////////////////////////////////////////////// メソッド procedure TMap2D<_TYPE_>.SetSize( const SizeX_,SizeY_:Integer ); begin _SizeX := SizeX_; _SizeY := SizeY_; InitMap; end; //------------------------------------------------------------------------------ procedure TMap2D<_TYPE_>.Clear( const Value_:_TYPE_ ); var X, Y :Integer; begin for Y := 0 to _SizeY-1 do begin for X := 0 to _SizeX-1 do _Map[ Y, X ] := Value_; end; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TColorMap2D //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public /////////////////////////////////////////////////////////////////////// メソッド procedure TColorMap2D.LoadFromFile( const FileName_:String ); var B :TBitmap; begin B := TBitmap.Create; B.LoadFromFile( FileName_ ); ImportFrom( B ); B.DisposeOf; end; procedure TColorMap2D.SaveToFile( const FileName_:String ); var B :TBitmap; begin B := TBitmap.Create; ExportTo( B ); B.SaveToFile( FileName_ ); B.DisposeOf; end; //------------------------------------------------------------------------------ procedure TColorMap2D.ImportFrom( const BMP_:TBitmap ); var B :TBitmapData; X, Y :Integer; P :PAlphaColor; begin SetSize( BMP_.Width, BMP_.Height ); BMP_.Map( TMapAccess.Read, B ); for Y := 0 to _SizeY-1 do begin P := B.GetScanline( Y ); for X := 0 to _SizeX-1 do begin _Map[ Y, X ] := TAlphaColorF.Create( P^ ); Inc( P ); end; end; BMP_.Unmap( B ); end; procedure TColorMap2D.ExportTo( const BMP_:TBitmap ); var B :TBitmapData; X, Y :Integer; P :PAlphaColor; begin BMP_.SetSize( _SizeX, _SizeY ); BMP_.Map( TMapAccess.Write, B ); for Y := 0 to _SizeY-1 do begin P := B.GetScanline( Y ); for X := 0 to _SizeX-1 do begin P^ := _Map[ Y, X ].ToAlphaColor; Inc( P ); end; end; BMP_.Unmap( B ); end; //------------------------------------------------------------------------------ function TColorMap2D.Interp( const X_,Y_:Single ) :TAlphaColorF; var Xi, Yi :Integer; begin Xi := Clamp( Floor( _SizeX * X_ ), 0, _SizeX-1 ); Yi := Clamp( Floor( _SizeY * Y_ ), 0, _SizeY-1 ); Result := _Map[ Xi, Yi ]; end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 //############################################################################## □ initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化 finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化 end. //######################################################################### ■
unit ogl3dview_engine; {$INCLUDE Global_Conditionals.inc} interface uses Geometry,Windows,SysUtils,Graphics,dglOpenGL,forms,Voxel,BasicDataTypes, Voxel_Engine,math,dialogs,HVA, math3d; { type TVector3f = record X, Y, Z : single; end; } type TVoxelBox = record Color, Normal: integer; Position: TVector3f; Faces: array [1..6] of boolean; end; TVoxelBoxSection = record Box : array of TVoxelBox; List, ID : integer; end; TVoxelBoxGroup = record Section : array of TVoxelBoxSection; NumBoxes : integer; end; TVector3b = record R,G,B : Byte; end; TVector4f = record X,Y,Z,W : Single; end; THVAMATRIXLISTDATA = record First : TVector4f; Second : TVector4f; Third : TVector4f; end; var oglloaded : boolean = false; RebuildLists : boolean = false; XRotB,YRotB, SSM, SSO : boolean; BGColor,FontColor : TVector3f; oldw,oldh : integer; Size,FPS : single; VoxelBoxGroup: TVoxelBoxGroup; VoxelBox_No : integer; base : GLuint; // Base Display List For The Font Set dc : HDC; // Device Context FFrequency : int64; FoldTime : int64; // last system time rc : HGLRC; // Rendering Context RemapColour : TVector3f; ElapsedTime, DemoStart, LastTime : DWord; YRot, XRot, XRot2, YRot2 : glFloat; // Y Rotation Depth : glFloat; Xcoord, Ycoord, Zcoord : Integer; MouseButton : Integer; WireFrame : Boolean; RemapColourMap : array [0..8] of TVector3b = ( ( //DarkRed R : 146; G : 3; B : 3; ), ( //DarkBlue R : 9; G : 32; B : 140; ), ( //DarkGreen R : 13; G : 136; B : 16; ), ( //White R : 160; G : 160; B : 160; ), ( //Orange R : 146; G : 92; B : 3; ), ( //Magenta R : 104; G : 43; B : 73; ), ( //Purple R : 137; G : 12; B : 134; ), ( //Gold R : 149; G : 119; B : 0; ), ( //DarkSky R : 13; G : 102; B : 136; ) ); light0_position:TGLArrayf4=( 5.0, 0.0, 10.0, 0.0); ambient: TGLArrayf4=( 0.0, 0.0, 0.0, 1); Light0_Light: TGLArrayf4=( 1, 1, 1, 1); Light0_Spec: TGLArrayf4=( 1, 0.5, 0, 0); function SetVector(x, y, z : single) : TVector3f; function SetVectori(x, y, z : integer) : TVector3i; Function TColorToTVector3f(Color : TColor) : TVector3f; Function TVector3fToTColor(Vector3f : TVector3f) : TColor; procedure Update3dViewWithNormals(Vxl : TVoxelSection); procedure glDraw(); procedure Update3dView(Vxl : TVoxelSection); procedure BuildFont; Function CleanVCCol(Color : TColor) : TVector3f; function CleanV3fCol(Color: TVector3f): TVector3f; function GetCorrectColour(Color: integer; RemapColour : TVector3f): TVector3f; function GetPosWithSize(Position: TVector3f; Size: single): TVector3f; procedure GetScaleWithMinBounds(const _Vxl: TVoxelSection; var _Scale,_MinBounds: TVector3f); function ScreenShot_BitmapResult : TBitmap; function checkface(Vxl : TVoxelSection; x,y,z : integer) : boolean; procedure ClearVoxelBoxes(var _VoxelBoxGroup : TVoxelBoxGroup); procedure Update3dViewVOXEL(Vxl : TVoxel); procedure DrawBox(VoxelPosition, Color: TVector3f; Size: TVector3f; VoxelBox: TVoxelBox); //procedure Update3dViewWithRGBTEST; implementation uses Palette,FormMain,FTGifAnimate, GIFImage, normals, GlobalVars; procedure BuildFont; // Build Our Bitmap Font var font: HFONT; // Windows Font ID begin base := glGenLists(256); // Storage For 96 Characters font := 0; SelectObject(DC, font); // Selects The Font We Want font := CreateFont(9, 0,0,0, FW_NORMAL, 0, 0, 0, OEM_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY , FF_DONTCARE + DEFAULT_PITCH, 'Terminal'); SelectObject(DC, font); wglUseFontBitmaps(DC, 0, 127, base); end; procedure KillFont; // Delete The Font begin glDeleteLists(base, 256); // Delete All 96 Characters end; procedure glPrint(text : pchar); // Custom GL "Print" Routine begin if (text = '') then // If There's No Text Exit; // Do Nothing glPushAttrib(GL_LIST_BIT); // Pushes The Display List Bits glListBase(base); // Sets The Base Character glCallLists(length(text), GL_UNSIGNED_BYTE, text); // Draws The Display List Text glPopAttrib(); // Pops The Display List Bits end; function SetVector(x, y, z : single) : TVector3f; begin result.x := x; result.y := y; result.z := z; end; function SetVectori(x, y, z : integer) : TVector3i; begin result.x := x; result.y := y; result.z := z; end; Function TColorToTVector3f(Color : TColor) : TVector3f; begin Result.X := GetRValue(Color) / 255; Result.Y := GetGValue(Color) / 255; Result.Z := GetBValue(Color) / 255; end; Function TVector3fToTColor(Vector3f : TVector3f) : TColor; begin Result := RGB(trunc(Vector3f.X*255),trunc(Vector3f.Y*255),trunc(Vector3f.Z*255)); end; procedure ScreenShot(Filename : string); var i: integer; t, FN, FN2, FN3 : string; SSDir : string; begin // create the scrnshots directory if it doesn't exist SSDir := extractfiledir(Paramstr(0))+'\ScreenShots\'; FN2 := extractfilename(Filename); FN2 := copy(FN2,1,length(FN2)-length(Extractfileext(FN2))); // sys_mkdir {$I-} CreateDir(SSDir); // MkDir(SSDir); {$I+} FN := SSDir+FN2; for i := 0 to 999 do begin t := inttostr(i); if length(t) < 3 then t := '00'+t else if length(t) < 2 then t := '0'+t; if not fileexists(FN+'_'+t+'.bmp') then begin FN3 := FN+'_'+t+'.bmp'; break; end; end; if FN3 = '' then begin exit; end; ScreenShot_BitmapResult.SaveToFile(FN3); end; procedure ScreenShotGIF(GIFIMAGE : TGIFImage; Filename : string); var i: integer; t, FN, FN2, FN3 : string; SSDir : string; begin // create the scrnshots directory if it doesn't exist SSDir := extractfiledir(Paramstr(0))+'\ScreenShots\'; FN2 := extractfilename(Filename); FN2 := copy(FN2,1,length(FN2)-length(Extractfileext(FN2))); // sys_mkdir {$I-} CreateDir(SSDir); // MkDir(SSDir); {$I+} FN := SSDir+FN2; for i := 0 to 999 do begin t := inttostr(i); if length(t) < 3 then t := '00'+t else if length(t) < 2 then t := '0'+t; if not fileexists(FN+'_'+t+'.gif') then begin FN3 := FN+'_'+t+'.gif'; break; end; end; if FN3 = '' then begin exit; end; GIFImage.SaveToFile(FN3); end; function ScreenShot_BitmapResult : TBitmap; var buffer: array of byte; x,y, i: integer; Bitmap : TBitmap; begin SetLength(buffer, (FrmMain.OGL3DPreview.Width * FrmMain.OGL3DPreview.Height * 3 + 18) + 1); glReadPixels(0, 0, FrmMain.OGL3DPreview.Width, FrmMain.OGL3DPreview.Height, GL_RGB, GL_UNSIGNED_BYTE, Pointer(Cardinal(buffer) {+ 18})); i := 0; Bitmap := TBitmap.Create; Bitmap.Canvas.Brush.Color := TVector3fToTColor(BGColor); Bitmap.Width := FrmMain.OGL3DPreview.Width+2; Bitmap.Height := FrmMain.OGL3DPreview.Height+2; for y := 0 to FrmMain.OGL3DPreview.Height-1 do for x := 0 to FrmMain.OGL3DPreview.Width do begin if (x <> FrmMain.OGL3DPreview.Width) and (FrmMain.OGL3DPreview.Height-y-1 > 0) then Bitmap.Canvas.Pixels[x,FrmMain.OGL3DPreview.Height-y-2] := RGB(buffer[(i*3){+18}],buffer[(i*3){+18}+1],buffer[(i*3){+18}+2]); inc(i); end; Bitmap.width := Bitmap.width -2; Bitmap.Height := Bitmap.Height -4; SetLength(buffer,0); finalize(buffer); Result := Bitmap; end; procedure DoNormals(Normal: integer); var N: integer; NormalVector : TVector3f; begin N := Normal; if N < 0 then begin glNormal3f(0, 0, 0); exit; end; NormalVector := FrmMain.Document.ActiveSection^.Normals[trunc(N)]; glNormal3f(NormalVector.X * 1.2, NormalVector.Y * 1.2, NormalVector.Z * 1.2); end; // 1.3: Now with Hyper Speed! Kirov at 59/60fps :D procedure DrawBox(VoxelPosition, Color: TVector3f; Size: TVector3f; VoxelBox: TVoxelBox); var East,West,South,North,Floor,Ceil : single; begin East := VoxelPosition.X + Size.X; West := VoxelPosition.X; Ceil := VoxelPosition.Y + Size.Y; Floor := VoxelPosition.Y; North := VoxelPosition.Z + Size.Z; South := VoxelPosition.Z; glBegin(GL_QUADS); begin glColor3f(Color.X, Color.Y, Color.Z); // Set The Color DoNormals(VoxelBox.Normal); if VoxelBox.Faces[1] then begin glVertex3f(East, Ceil, South); // Top Right Of The Quad (Top) glVertex3f(West, Ceil, South); // Top Left Of The Quad (Top) glVertex3f(West, Ceil, North); // Bottom Left Of The Quad (Top) glVertex3f(East, Ceil, North); // Bottom Right Of The Quad (Top) end; if VoxelBox.Faces[2] then begin glVertex3f(East, Floor, North); // Top Right Of The Quad (Bottom) glVertex3f(West, Floor, North); // Top Left Of The Quad (Bottom) glVertex3f(West, Floor, South); // Bottom Left Of The Quad (Bottom) glVertex3f(East, Floor, South); // Bottom Right Of The Quad (Bottom) end; if VoxelBox.Faces[3] then begin glVertex3f(East, Ceil, North); // Top Right Of The Quad (Front) glVertex3f(West, Ceil, North); // Top Left Of The Quad (Front) glVertex3f(West, Floor, North); // Bottom Left Of The Quad (Front) glVertex3f(East, Floor, North); // Bottom Right Of The Quad (Front) end; if VoxelBox.Faces[4] then begin glVertex3f(East, Floor, South); // Bottom Left Of The Quad (Back) glVertex3f(West, Floor, South); // Bottom Right Of The Quad (Back) glVertex3f(West, Ceil, South); // Top Right Of The Quad (Back) glVertex3f(East, Ceil, South); // Top Left Of The Quad (Back) end; if VoxelBox.Faces[5] then begin glVertex3f(West, Ceil, North); // Top Right Of The Quad (Left) glVertex3f(West, Ceil, South); // Top Left Of The Quad (Left) glVertex3f(West, Floor, South); // Bottom Left Of The Quad (Left) glVertex3f(West, Floor, North); // Bottom Right Of The Quad (Left) end; if VoxelBox.Faces[6] then begin glVertex3f(East, Ceil, South); // Top Right Of The Quad (Right) glVertex3f(East, Ceil, North); // Top Left Of The Quad (Right) glVertex3f(East, Floor, North); // Bottom Left Of The Quad (Right) glVertex3f(East, Floor, South); // Bottom Right Of The Quad (Right) end; end; glEnd(); end; function GetPosWithSize(Position: TVector3f; Size: single): TVector3f; begin Result.X := Position.X * Size; Result.Y := Position.Y * Size; Result.Z := Position.Z * Size; end; function CleanVCCol(Color: TColor): TVector3f; begin Result.X := GetRValue(Color); Result.Y := GetGValue(Color); Result.Z := GetBValue(Color); if Result.X > 255 then Result.X := 255 else if Result.X < 0 then Result.X := 0; if Result.Y > 255 then Result.Y := 255 else if Result.Y < 0 then Result.Y := 0; if Result.Z > 255 then Result.Z := 255 else if Result.Z < 0 then Result.Z := 0; Result.X := Result.X / 255; Result.Y := Result.Y / 255; Result.Z := Result.Z / 255; end; function CleanV3fCol(Color: TVector3f): TVector3f; begin Result.X := Color.X; Result.Y := Color.Y; Result.Z := Color.Z; if Result.X > 255 then Result.X := 255 else if Result.X < 0 then Result.X := 0; if Result.Y > 255 then Result.Y := 255 else if Result.Y < 0 then Result.Y := 0; if Result.Z > 255 then Result.Z := 255 else if Result.Z < 0 then Result.Z := 0; Result.X := Result.X / 255; Result.Y := Result.Y / 255; Result.Z := Result.Z / 255; end; function GetCorrectColour(Color: integer; RemapColour : TVector3f): TVector3f; var T: TVector3f; begin if (Color > 15) and (Color < 32) then begin T.X := RemapColour.X * ((32 - Color) / 16); T.Y := RemapColour.Y * ((32 - Color) / 16); T.Z := RemapColour.Z * ((32 - Color) / 16); Result := T; //CleanV3fCol(T); end else Result := TColorToTVector3f(FrmMain.Document.Palette^[Color]); end; function GetVXLColor(Color, Normal: integer): TVector3f; begin if SpectrumMode = ModeColours then Result := GetCorrectColour(color, RemapColour) else Result := SetVector(0.5, 0.5, 0.5); end; {------------------------------------------------------------------} { Function to draw the actual scene } {------------------------------------------------------------------} procedure glDraw(); var x : integer; Scale,MinBounds : TVector3f; begin glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer glClearColor(BGColor.X, BGColor.Y, BGColor.Z, 1.0); // Black Background // 1.2: Removed: This is already checked in the function that calls glDraw; // if FrmMain.Display3dView1.Checked then exit; if (not VoxelOpen) then exit; // If it's set to auto-rotate to X, we increase XRot with // adition/subtraction factor XRot2. Ugly name for it. if XRotB then XRot := XRot + XRot2; // If it's set to auto-rotate to Y, we increase YRot with // adition/subtraction factor YRot2. Ugly name for it. if YRotB then YRot := YRot + YRot2; // Here we make sure XRot and YRot are between 0 and 360. XRot := CleanAngle(XRot); YRot := CleanAngle(YRot); glEnable(GL_LIGHT0); glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); // We'll only render anything if there is a voxel to render. if VoxelBoxGroup.NumBoxes > 0 then begin // Here we make the OpenGL list to speed up the render. glLoadIdentity(); // Reset The View GetScaleWithMinBounds(FrmMain.Document.ActiveVoxel^.Section[VoxelBoxGroup.Section[0].ID],Scale,MinBounds); if (VoxelBoxGroup.Section[0].List < 1) or RebuildLists then begin if (VoxelBoxGroup.Section[0].List > 0) then glDeleteLists(VoxelBoxGroup.Section[0].List,1); VoxelBoxGroup.Section[0].List := glGenLists(1); glNewList(VoxelBoxGroup.Section[0].List, GL_COMPILE); // Now, we hunt all voxel boxes... glPushMatrix; for x := Low(VoxelBoxGroup.Section[0].Box) to High(VoxelBoxGroup.Section[0].Box) do begin DrawBox(VoxelBoxGroup.Section[0].Box[x].Position, GetVXLColor(VoxelBoxGroup.Section[0].Box[x].Color, VoxelBoxGroup.Section[0].Box[x].Normal), Scale, VoxelBoxGroup.Section[0].Box[x]); end; glPopMatrix; glEndList; RebuildLists := false; end; // The final voxel rendering part. glPushMatrix; glTranslatef(0, 0, Depth); glRotatef(XRot, 1, 0, 0); glRotatef(YRot, 0, 0, 1); glCallList(VoxelBoxGroup.Section[0].List); glPopMatrix; // End of the final voxel rendering part. glDisable(GL_TEXTURE_2D); glLoadIdentity; glDisable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glPushMatrix; glLoadIdentity; glOrtho(0, FrmMain.OGL3DPreview.Width, 0, FrmMain.OGL3DPreview.Height, -1, 1); glMatrixMode(GL_MODELVIEW); glPushMatrix; glLoadIdentity; glDisable(GL_LIGHT0); glDisable(GL_LIGHTING); glDisable(GL_COLOR_MATERIAL); glColor3f(FontColor.X, FontColor.Y, FontColor.Z); glRasterPos2i(1, 2); glPrint(PChar('Voxels Used: ' + IntToStr(VoxelBox_No))); if (not ssm) and (not SSO) then begin glRasterPos2i(1, 13); glPrint(PChar('Depth: ' + IntToStr(trunc(Depth)))); glRasterPos2i(1, FrmMain.OGL3DPreview.Height - 9); glPrint(PChar('FPS: ' + IntToStr(trunc(FPS)))); if FrmMain.DebugMode1.Checked then begin glRasterPos2i(1, FrmMain.OGL3DPreview.Height - 19); glPrint(PChar('DEBUG - XRot:' + floattostr(XRot) + ' YRot:' + floattostr(YRot))); end; end; glMatrixMode(GL_PROJECTION); glPopMatrix; glMatrixMode(GL_MODELVIEW); glPopMatrix; glEnable(GL_DEPTH_TEST); if SSO then begin ScreenShot(VXLFilename); SSO := False; end; if ssm then begin GifAnimateAddImage(ScreenShot_BitmapResult, False, 10); if (YRot = 360) and ssm then begin ssm := False; FrmMain.btn3DRotateY.Down := False; ScreenShotGIF(GifAnimateEndGif, VXLFilename); FrmMain.btn3DRotateY.Enabled := True; FrmMain.btn3DRotateY2.Enabled := True; FrmMain.btn3DRotateX.Enabled := True; FrmMain.btn3DRotateX2.Enabled := True; FrmMain.spin3Djmp.Enabled := True; FrmMain.SpeedButton1.Enabled := True; FrmMain.SpeedButton2.Enabled := True; YRot := 225; XRotB := False; YRotB := False; end; end; end; end; procedure ClearVoxelBoxes(var _VoxelBoxGroup : TVoxelBoxGroup); var Section : integer; begin if High(_VoxelBoxGroup.Section) >= 0 then begin for Section := Low(_VoxelBoxGroup.Section) to High(_VoxelBoxGroup.Section) do begin if (_VoxelBoxGroup.Section[Section].List > 0) then begin glDeleteLists(_VoxelBoxGroup.Section[Section].List,1); _VoxelBoxGroup.Section[Section].List := 0; end; SetLength(_VoxelBoxGroup.Section[Section].Box,0); end; end; SetLength(_VoxelBoxGroup.Section,0); _VoxelBoxGroup.NumBoxes := 0; end; function CheckFace(Vxl : TVoxelSection; x,y,z : integer) : boolean; var v: TVoxelUnpacked; begin Result := true; if (X < 0) or (X >= Vxl.Tailer.XSize) then Exit; if (Y < 0) or (Y >= Vxl.Tailer.YSize) then Exit; if (Z < 0) or (Z >= Vxl.Tailer.ZSize) then Exit; Vxl.GetVoxel(x,y,z,v); if v.Used then Result := false; end; procedure GetScaleWithMinBounds(const _Vxl: TVoxelSection; var _Scale,_MinBounds: TVector3f); begin _Scale.X := ((_Vxl.Tailer.MaxBounds[1] - _Vxl.Tailer.MinBounds[1]) / _Vxl.Tailer.XSize) * Size; _Scale.Y := ((_Vxl.Tailer.MaxBounds[2] - _Vxl.Tailer.MinBounds[2]) / _Vxl.Tailer.YSize) * Size; _Scale.Z := ((_Vxl.Tailer.MaxBounds[3] - _Vxl.Tailer.MinBounds[3]) / _Vxl.Tailer.ZSize) * Size; _MinBounds.X := _Vxl.Tailer.MinBounds[1] * Size; _MinBounds.Y := _Vxl.Tailer.MinBounds[2] * Size; _MinBounds.Z := _Vxl.Tailer.MinBounds[3] * Size; end; procedure Update3dView(Vxl: TVoxelSection); var x, y, z: byte; v: TVoxelUnpacked; Scale,MinBounds : TVector3f; begin if not IsEditable then exit; if FrmMain.Display3dView1.Checked then exit; {$ifdef DEBUG_FILE} FrmMain.DebugFile.Add('OpenGL3DViewEngine: Update3DView'); {$endif} // Shutup 3d view for setup purposes. FrmMain.Display3dView1.Checked := true; VoxelBox_No := 0; ClearVoxelBoxes(VoxelBoxGroup); GetScaleWithMinBounds(Vxl,Scale,MinBounds); SetLength(VoxelBoxGroup.Section,1); for z := 0 to (Vxl.Tailer.zSize - 1) do begin for y := 0 to (Vxl.Tailer.YSize - 1) do begin for x := 0 to (Vxl.Tailer.xSize - 1) do begin Vxl.GetVoxel(x, y, z, v); if v.Used = True then begin SetLength(VoxelBoxGroup.Section[0].Box, VoxelBox_No+1); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Faces[1] := CheckFace(Vxl, x, y + 1, z); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Faces[2] := CheckFace(Vxl, x, y - 1, z); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Faces[3] := CheckFace(Vxl, x, y, z + 1); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Faces[4] := CheckFace(Vxl, x, y, z - 1); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Faces[5] := CheckFace(Vxl, x - 1, y, z); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Faces[6] := CheckFace(Vxl, x + 1, y, z); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Position.X := (MinBounds.X + (X * Scale.X)); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Position.Y := (MinBounds.Y + (Y * Scale.Y)); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Position.Z := (MinBounds.Z + (Z * Scale.Z)); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Color := v.Colour; VoxelBoxGroup.Section[0].Box[VoxelBox_No].Normal := v.Normal; Inc(VoxelBox_No); end; end; end; end; VoxelBoxGroup.NumBoxes := VoxelBox_No; RebuildLists := true; // Wake up 3d view, since everything is ready. FrmMain.Display3dView1.Checked := false; end; procedure Update3dViewVOXEL(Vxl: TVoxel); var x, y, z, i: byte; v: TVoxelUnpacked; Scale,MinBounds : TVector3f; begin if FrmMain.Display3dView1.Checked then exit; {$ifdef DEBUG_FILE} FrmMain.DebugFile.Add('OpenGL3DViewEngine: Update3DViewVoxel'); {$endif} // Shutup 3d view for setup purposes. FrmMain.Display3dView1.Checked := true; VoxelBoxGroup.NumBoxes := 0; ClearVoxelBoxes(VoxelBoxGroup); SetLength(VoxelBoxGroup.Section,VXL.Header.NumSections); for i := Low(VoxelBoxGroup.Section) to High(VoxelBoxGroup.Section) do begin VoxelBox_No := 0; GetScaleWithMinBounds(Vxl.Section[i],Scale,MinBounds); for z := 0 to (Vxl.Section[i].Tailer.zSize - 1) do begin for y := 0 to (Vxl.Section[i].Tailer.YSize - 1) do begin for x := 0 to (Vxl.Section[i].Tailer.xSize - 1) do begin Vxl.Section[i].GetVoxel(x, y, z, v); if v.Used = True then begin SetLength(VoxelBoxGroup.Section[i].Box, VoxelBox_No+1); VoxelBoxGroup.Section[i].Box[VoxelBox_No].Faces[1] := CheckFace(Vxl.Section[i], x, y + 1, z); VoxelBoxGroup.Section[i].Box[VoxelBox_No].Faces[2] := CheckFace(Vxl.Section[i], x, y - 1, z); VoxelBoxGroup.Section[i].Box[VoxelBox_No].Faces[3] := CheckFace(Vxl.Section[i], x, y, z + 1); VoxelBoxGroup.Section[i].Box[VoxelBox_No].Faces[4] := CheckFace(Vxl.Section[i], x, y, z - 1); VoxelBoxGroup.Section[i].Box[VoxelBox_No].Faces[5] := CheckFace(Vxl.Section[i], x - 1, y, z); VoxelBoxGroup.Section[i].Box[VoxelBox_No].Faces[6] := CheckFace(Vxl.Section[i], x + 1, y, z); VoxelBoxGroup.Section[i].Box[VoxelBox_No].Position.X := (Vxl.Section[i].Tailer.Transform[1][3] + MinBounds.X + (X * Scale.X)); VoxelBoxGroup.Section[i].Box[VoxelBox_No].Position.Y := (Vxl.Section[i].Tailer.Transform[2][3] + MinBounds.Y + (Y * Scale.Y)); VoxelBoxGroup.Section[i].Box[VoxelBox_No].Position.Z := (Vxl.Section[i].Tailer.Transform[3][3] + MinBounds.Z + (Z * Scale.Z)); VoxelBoxGroup.Section[i].Box[VoxelBox_No].Color := v.Colour; VoxelBoxGroup.Section[i].Box[VoxelBox_No].Normal := v.Normal; Inc(VoxelBox_No); Inc(VoxelBoxGroup.NumBoxes); end; end; end; end; end; RebuildLists := true; // Wake up 3d view, since everything is ready. FrmMain.Display3dView1.Checked := false; end; procedure Update3dViewWithNormals(Vxl: TVoxelSection); var x,num: byte; Normal : TVector3f; begin if FrmMain.Display3dView1.Checked then exit; {$ifdef DEBUG_FILE} FrmMain.DebugFile.Add('OpenGL3DViewEngine: Update3DViewWithNormals'); {$endif} // Shutup 3d view for setup purposes. FrmMain.Display3dView1.Checked := true; VoxelBox_No := 0; ClearVoxelBoxes(VoxelBoxGroup); if Vxl.Tailer.Unknown = 2 then num := 35 else num := 243; SetLength(VoxelBoxGroup.Section,1); for x := 0 to Vxl.Normals.GetLastID() do begin Normal := Vxl.Normals[x]; SetLength(VoxelBoxGroup.Section[0].Box, VoxelBox_No+1); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Faces[1] := CheckFace(Vxl, trunc(Normal.x * 30.5), trunc(Normal.y * 30.5) + 1, trunc(Normal.z * 30.5)); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Faces[2] := CheckFace(Vxl, trunc(Normal.x * 30.5), trunc(Normal.y * 30.5) - 1, trunc(Normal.z * 30.5)); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Faces[3] := CheckFace(Vxl, trunc(Normal.x * 30.5), trunc(Normal.y * 30.5), trunc(Normal.z * 30.5) + 1); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Faces[4] := CheckFace(Vxl, trunc(Normal.x * 30.5), trunc(Normal.y * 30.5), trunc(Normal.z * 30.5) - 1); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Faces[5] := CheckFace(Vxl, trunc(Normal.x * 30.5) - 1, trunc(Normal.y * 30.5), trunc(Normal.z * 30.5)); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Faces[6] := CheckFace(Vxl, trunc(Normal.x * 30.5) + 1, trunc(Normal.y * 30.5), trunc(Normal.z * 30.5)); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Position.X := trunc(Normal.x * 30.5); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Position.Y := trunc(Normal.y * 30.5); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Position.Z := trunc(Normal.z * 30.5); VoxelBoxGroup.Section[0].Box[VoxelBox_No].Color := 15; VoxelBoxGroup.Section[0].Box[VoxelBox_No].Normal := 0; Inc(VoxelBox_No); end; RebuildLists := true; VoxelBoxGroup.NumBoxes := VoxelBox_No; // Wake 3d view, since everything is ready. FrmMain.Display3dView1.Checked := false; end; end.
unit uRFD8500; interface uses SysUtils, System.Classes, System.StrUtils, System.Types, uRFIDBase; type TOperation = (FLAG_ALERT = 1000, FLAG_CONNECTION = 1000, FLAG_INVENTORY = 1001, FLAG_BATTERY = 1002, FLAG_SET = 1004, FLAG_READ = 1005, FLAG_GETBUFFER = 1006, FLAG_CLEARBUFFER = 1007, FLAG_MASK = 1008, FLAG_GEN2 = 1009, FLAG_POWER = 1010, FLAG_DUTY = 1011, FLAG_BEEP = 1012, FLAG_WRITE = 1013, FLAG_LOCK = 1014, FLAG_DISCO = 1015, FLAG_FINDER = 1016, FLAG_DEFAULT = 9999); type TRFD8500 = class(TRFIDBase) private fOperation: TOperation; fInProgress: boolean; fTX_POWER: integer; fSESSION: integer; fTARGET: integer; fPOPULATION: Extended; public constructor Create; destructor Destroy; override; procedure OpenInterface; procedure CloseInterface; procedure DeviceConfigure; procedure InventoryStart; procedure InventoryStop; procedure InventoryClear; procedure ExecuteTagFinder(sTag2Locate: string); procedure StopTagFinder; procedure ProcessResult(const Data: string); override; property Operation: TOperation read fOperation write fOperation; property InProgress: boolean read fInProgress write fInProgress; property TX_POWER: integer read fTX_POWER write fTX_POWER; property SESSION: integer read fSESSION write fSESSION; property TARGET: integer read fTARGET write fTARGET; property POPULATION: Extended read fPOPULATION write fPOPULATION; end; implementation { TRFIDReader } constructor TRFD8500.Create; begin inherited Create; fInProgress := False; fOperation := TOperation.FLAG_DEFAULT; end; destructor TRFD8500.Destroy; begin inherited; end; procedure TRFD8500.OpenInterface; begin if DoConnection then begin fOperation := TOperation.FLAG_CONNECTION; ExecuteSender('connect'); Sleep(SleepTime); end; end; procedure TRFD8500.CloseInterface; begin if IsConnected then begin fOperation := TOperation.FLAG_DISCO; ExecuteSender('disconnect'); Sleep(SleepTime); Disconnect; end; end; procedure TRFD8500.DeviceConfigure; var sCommand: string; begin fOperation := TOperation.FLAG_SET; // qp .e 0 .i 0 .j 0 .y 100 fOperation := TOperation.FLAG_SET; sCommand := 'qp' + ' .e 0' + ' .i ' + fSESSION.ToString + ' .j ' + fTARGET.ToString + ' .y ' + fPOPULATION.ToString; ExecuteSender(sCommand); // rc .ez .el .ec .er .ek .eh .es fOperation := TOperation.FLAG_SET; sCommand := 'rc .ez .el .ec .er .ek .eh .es'; ExecuteSender(sCommand); // ac .p 270 .lx 0 fOperation := TOperation.FLAG_POWER; sCommand := 'ac' + ' .p ' + fTX_POWER.ToString + ' .lx 0'; ExecuteSender(sCommand); end; procedure TRFD8500.InventoryStart; begin fOperation := TOperation.FLAG_INVENTORY; ExecuteSender('in'); fInProgress := True; end; procedure TRFD8500.InventoryStop; begin fOperation := TOperation.FLAG_DEFAULT; ExecuteSender('a'); fInProgress := False; end; procedure TRFD8500.InventoryClear; begin fOperation := TOperation.FLAG_CLEARBUFFER; ExecuteSender('tp'); end; procedure TRFD8500.ExecuteTagFinder(sTag2Locate: string); begin fOperation := TOperation.FLAG_FINDER; ExecuteSender('lt .ep ' + sTag2Locate); end; procedure TRFD8500.StopTagFinder; begin fOperation := TOperation.FLAG_DEFAULT; ExecuteSender('a'); end; procedure TRFD8500.ProcessResult(const Data: string); begin case fOperation of TOperation.FLAG_INVENTORY: begin // your code here... end; TOperation.FLAG_FINDER: begin // your code here... end; end; end; end.
unit arduinohw; {$mode objfpc}{$H+} interface uses Classes, SysUtils, basehw, msgstr, Synaser, utilfunc; type { TArduinoHardware } TArduinoHardware = class(TBaseHardware) private FDevOpened: boolean; FStrError: string; FSerial: TBlockSerial; FCOMPort: string; public constructor Create; destructor Destroy; override; function GetLastError: string; override; function DevOpen: boolean; override; procedure DevClose; override; //spi function SPIRead(CS: byte; BufferLen: integer; var buffer: array of byte): integer; override; function SPIWrite(CS: byte; BufferLen: integer; buffer: array of byte): integer; override; function SPIInit(speed: integer): boolean; override; procedure SPIDeinit; override; //I2C procedure I2CInit; override; procedure I2CDeinit; override; function I2CReadWrite(DevAddr: byte; WBufferLen: integer; WBuffer: array of byte; RBufferLen: integer; var RBuffer: array of byte): integer; override; procedure I2CStart; override; procedure I2CStop; override; function I2CReadByte(ack: boolean): byte; override; function I2CWriteByte(data: byte): boolean; override; //return ack //MICROWIRE function MWInit(speed: integer): boolean; override; procedure MWDeinit; override; function MWRead(CS: byte; BufferLen: integer; var buffer: array of byte): integer; override; function MWWrite(CS: byte; BitsWrite: byte; buffer: array of byte): integer; override; function MWIsBusy: boolean; override; end; implementation uses main; const SrtErr_CmdNoAck = 'Data not accepted!'; StrErr_CmdErr = 'Command not accepted!'; TIMEOUT = 2000; FUNC_SPI_INIT = 7; FUNC_SPI_DEINIT = 8; FUNC_SPI_READ = 10; FUNC_SPI_WRITE = 11; FUNC_I2C_INIT = 20; FUNC_I2C_READ = 21; FUNC_I2C_WRITE = 22; FUNC_I2C_START = 23; FUNC_I2C_STOP = 24; FUNC_I2C_READBYTE = 25; FUNC_I2C_WRITEBYTE = 26; FUNC_MW_READ = 30; FUNC_MW_WRITE = 31; FUNC_MW_BUSY = 32; FUNC_MW_INIT = 33; FUNC_MW_DEINIT = 34; ACK = 81; ERROR_RECV = 99; ERROR_NO_CMD = 100; constructor TArduinoHardware.Create; begin FHardwareName := 'Arduino'; FHardwareID := CHW_ARDUINO; FSerial := TBlockSerial.Create; end; destructor TArduinoHardware.Destroy; begin DevClose; FSerial.Free; end; function TArduinoHardware.GetLastError: string; begin result := FSerial.LastErrorDesc; if FSerial.LastError = 0 then result := FStrError; end; function TArduinoHardware.DevOpen: boolean; var buff: byte; speed: cardinal; begin if FDevOpened then DevClose; FDevOpened := false; FCOMPort := main.Arduino_COMPort; speed := main.Arduino_BaudRate; if FCOMPort = '' then begin FStrError:= 'No port selected!'; Exit(false); end; {if Fserial.InstanceActive then begin FSerial.Purge; FDevOpened := true; Exit(true); end;} FSerial.Connect(FCOMPort); if FSerial.LastError <> 0 then begin FStrError := FSerial.LastErrorDesc; Exit(false); end; FSerial.Config(speed, 8, 'N', SB1, false, false); FSerial.Purge; sleep(2000); //Задержка пока отработает загрузчик ардуины //FSerial.RaiseExcept:= true; FDevOpened := true; Result := true; end; procedure TArduinoHardware.DevClose; begin FDevOpened := false; FSerial.CloseSocket(); end; //SPI___________________________________________________________________________ function TArduinoHardware.SPIInit(speed: integer): boolean; var buff: byte; begin if not FDevOpened then Exit(false); FSerial.SendByte(FUNC_SPI_INIT); FSerial.SendByte(speed); FSerial.Flush; buff := FSerial.RecvByte(TIMEOUT); if FSerial.LastError <> 0 then LogPrint(FSerial.LastErrorDesc); if buff <> FUNC_SPI_INIT then begin LogPrint(StrErr_CmdErr + IntToStr(buff)); Exit(false); end; Result := true; end; procedure TArduinoHardware.SPIDeinit; var buff: byte; begin if not FDevOpened then Exit; buff := FUNC_SPI_DEINIT; FSerial.SendByte(FUNC_SPI_DEINIT); FSerial.Flush; buff := FSerial.RecvByte(TIMEOUT); if FSerial.LastError <> 0 then LogPrint(FSerial.LastErrorDesc); if buff <> FUNC_SPI_DEINIT then begin LogPrint(StrErr_CmdErr + IntToStr(buff)); Exit; end; end; function TArduinoHardware.SPIRead(CS: byte; BufferLen: integer; var buffer: array of byte): integer; var buff: byte; bytes: integer; const chunk = 64; begin if not FDevOpened then Exit(-1); result := 0; FSerial.SendByte(FUNC_SPI_READ); FSerial.SendByte(CS); FSerial.SendByte(hi(lo(BufferLen))); FSerial.SendByte(lo(lo(BufferLen))); FSerial.Flush; buff := FSerial.RecvByte(TIMEOUT); if buff <> FUNC_SPI_READ then begin LogPrint(StrErr_CmdErr + IntToStr(buff)); Exit(-1); end; bytes := 0; while bytes < BufferLen do begin if BufferLen - bytes > chunk-1 then begin result := result + FSerial.RecvBufferEx(@buffer[bytes], chunk, TIMEOUT); Inc(bytes, chunk); end else begin result := result + FSerial.RecvBufferEx(@buffer[bytes], BufferLen - bytes, TIMEOUT); Inc(bytes, BufferLen - bytes); end; if FSerial.LastError <> 0 then LogPrint(FSerial.LastErrorDesc); FSerial.SendByte(ACK); FSerial.Flush; end; end; function TArduinoHardware.SPIWrite(CS: byte; BufferLen: integer; buffer: array of byte): integer; var buff: byte; bytes: integer; const chunk = 256; begin if not FDevOpened then Exit(-1); result := 0; FSerial.SendByte(FUNC_SPI_WRITE); FSerial.SendByte(CS); FSerial.SendByte(hi(lo(BufferLen))); FSerial.SendByte(lo(lo(BufferLen))); FSerial.Flush; buff := FSerial.RecvByte(TIMEOUT); if buff <> FUNC_SPI_WRITE then begin LogPrint(StrErr_CmdErr + IntToStr(buff)); Exit(-1); end; //Нужна запись пачками чтобы не переполнять буфер ардуинки bytes := 0; while bytes < BufferLen do begin if BufferLen - bytes > chunk-1 then begin result := result + FSerial.SendBuffer(@buffer[bytes], chunk); Inc(bytes, chunk); end else begin result := result + FSerial.SendBuffer(@buffer[bytes], BufferLen - bytes); Inc(bytes, BufferLen - bytes); end; buff := FSerial.RecvByte(TIMEOUT); if buff <> ACK then begin LogPrint(SrtErr_CmdNoAck + IntToStr(buff)); Exit(-1); end; end; end; //i2c___________________________________________________________________________ procedure TArduinoHardware.I2CInit; var buff: byte; begin if not FDevOpened then Exit; FSerial.SendByte(FUNC_I2C_INIT); FSerial.Flush; buff := FSerial.RecvByte(TIMEOUT); if buff <> FUNC_I2C_INIT then begin LogPrint(StrErr_CmdErr + IntToStr(buff)); Exit; end; end; procedure TArduinoHardware.I2CDeinit; begin if not FDevOpened then Exit; end; function TArduinoHardware.I2CReadWrite(DevAddr: byte; WBufferLen: integer; WBuffer: array of byte; RBufferLen: integer; var RBuffer: array of byte): integer; var StopAfterWrite: byte; buff: byte; bytes: integer; const rchunk = 64; wchunk = 256; begin if not FDevOpened then Exit(-1); result := 0; StopAfterWrite := 1; if WBufferLen > 0 then begin if RBufferLen > 0 then StopAfterWrite := 0; FSerial.SendByte(FUNC_I2C_WRITE); FSerial.SendByte(DevAddr); FSerial.SendByte(StopAfterWrite); FSerial.SendByte(hi(lo(WBufferLen))); FSerial.SendByte(lo(lo(WBufferLen))); FSerial.Flush; buff := FSerial.RecvByte(TIMEOUT); if buff <> FUNC_I2C_WRITE then begin LogPrint(StrErr_CmdErr + IntToStr(buff)); Exit(-1); end; bytes := 0; while bytes < WBufferLen do begin if WBufferLen - bytes > wchunk-1 then begin result := result + FSerial.SendBuffer(@Wbuffer[bytes], wchunk); Inc(bytes, wchunk); end else begin result := result + FSerial.SendBuffer(@Wbuffer[bytes], WBufferLen - bytes); Inc(bytes, WBufferLen - bytes); end; buff := FSerial.RecvByte(TIMEOUT); if buff <> ACK then begin LogPrint(SrtErr_CmdNoAck + IntToStr(buff)); Exit(-1); end; end; end; if RBufferLen > 0 then begin FSerial.SendByte(FUNC_I2C_READ); FSerial.SendByte(DevAddr); FSerial.SendByte(hi(lo(RBufferLen))); FSerial.SendByte(lo(lo(RBufferLen))); FSerial.Flush; buff := FSerial.RecvByte(TIMEOUT); if buff <> FUNC_I2C_READ then begin LogPrint(StrErr_CmdErr + IntToStr(buff)); Exit(-1); end; bytes := 0; while bytes < RBufferLen do begin if RBufferLen - bytes > rchunk-1 then begin result := result + FSerial.RecvBufferEx(@Rbuffer[bytes], rchunk, TIMEOUT); Inc(bytes, rchunk); end else begin result := result + FSerial.RecvBufferEx(@Rbuffer[bytes], RBufferLen - bytes, TIMEOUT); Inc(bytes, RBufferLen - bytes); end; if FSerial.LastError <> 0 then LogPrint(FSerial.LastErrorDesc); FSerial.SendByte(ACK); FSerial.Flush; end; end; end; procedure TArduinoHardware.I2CStart; begin if not FDevOpened then Exit; FSerial.SendByte(FUNC_I2C_START); FSerial.Flush; end; procedure TArduinoHardware.I2CStop; begin if not FDevOpened then Exit; FSerial.SendByte(FUNC_I2C_STOP); FSerial.Flush; end; function TArduinoHardware.I2CReadByte(ack: boolean): byte; var Status: byte; begin if not FDevOpened then Exit; FSerial.SendByte(FUNC_I2C_READBYTE); FSerial.SendByte(Byte(ack)); FSerial.Flush; Status := FSerial.RecvByte(TIMEOUT); if Status <> FUNC_I2C_READBYTE then begin LogPrint(StrErr_CmdErr + IntToStr(Status)); Exit; end; Status := FSerial.RecvByte(TIMEOUT); Result := Status; end; function TArduinoHardware.I2CWriteByte(data: byte): boolean; var Status: byte; begin Status := 1; if not FDevOpened then Exit; FSerial.SendByte(FUNC_I2C_WRITEBYTE); FSerial.SendByte(data); FSerial.Flush; Status := FSerial.RecvByte(TIMEOUT); if Status <> FUNC_I2C_WRITEBYTE then begin LogPrint(StrErr_CmdErr + IntToStr(Status)); Exit(false); end; Status := FSerial.RecvByte(TIMEOUT); Result := Boolean(Status); end; //MICROWIRE_____________________________________________________________________ function TArduinoHardware.MWInit(speed: integer): boolean; var buff: byte; begin if not FDevOpened then Exit(false); FSerial.SendByte(FUNC_MW_INIT); FSerial.Flush; buff := FSerial.RecvByte(TIMEOUT); if buff <> FUNC_MW_INIT then begin LogPrint(StrErr_CmdErr + IntToStr(buff)); Exit(false); end; Result := true; end; procedure TArduinoHardware.MWDeInit; var buff: byte; begin if not FDevOpened then Exit; FSerial.SendByte(FUNC_MW_DEINIT); FSerial.Flush; buff := FSerial.RecvByte(TIMEOUT); if buff <> FUNC_MW_DEINIT then begin LogPrint(StrErr_CmdErr + IntToStr(buff)); Exit; end; end; function TArduinoHardware.MWRead(CS: byte; BufferLen: integer; var buffer: array of byte): integer; var buff: byte; bytes: integer; const chunk = 64; begin if not FDevOpened then Exit(-1); result := 0; FSerial.SendByte(FUNC_MW_READ); FSerial.SendByte(CS); FSerial.SendByte(hi(lo(BufferLen))); FSerial.SendByte(lo(lo(BufferLen))); FSerial.Flush; buff := FSerial.RecvByte(TIMEOUT); if buff <> FUNC_MW_READ then begin LogPrint(StrErr_CmdErr + IntToStr(buff)); Exit(-1); end; bytes := 0; while bytes < BufferLen do begin if BufferLen - bytes > chunk-1 then begin result := result + FSerial.RecvBufferEx(@buffer[bytes], chunk, TIMEOUT); Inc(bytes, chunk); end else begin result := result + FSerial.RecvBufferEx(@buffer[bytes], BufferLen - bytes, TIMEOUT); Inc(bytes, BufferLen - bytes); end; if FSerial.LastError <> 0 then LogPrint(FSerial.LastErrorDesc); FSerial.SendByte(ACK); FSerial.Flush; end; end; function TArduinoHardware.MWWrite(CS: byte; BitsWrite: byte; buffer: array of byte): integer; var buff: byte; bytes: byte; const chunk = 32; begin if not FDevOpened then Exit(-1); result := 0; bytes := ByteNum(BitsWrite); FSerial.SendByte(FUNC_MW_WRITE); FSerial.SendByte(CS); FSerial.SendByte(BitsWrite); FSerial.SendByte(0); FSerial.SendByte(bytes); FSerial.Flush; buff := FSerial.RecvByte(TIMEOUT); if buff <> FUNC_MW_WRITE then begin LogPrint(StrErr_CmdErr + IntToStr(buff)); Exit(-1); end; //Максимум 32 байта result := FSerial.SendBuffer(@buffer[0], bytes); buff := FSerial.RecvByte(TIMEOUT); if buff <> ACK then begin LogPrint(SrtErr_CmdNoAck + IntToStr(buff)); Exit(-1); end; if result = bytes then result := BitsWrite; end; function TArduinoHardware.MWIsBusy: boolean; var buff: byte; begin buff := 0; result := False; FSerial.SendByte(FUNC_MW_BUSY); FSerial.Flush; buff := FSerial.RecvByte(TIMEOUT); if buff <> FUNC_MW_BUSY then begin LogPrint(StrErr_CmdErr + IntToStr(buff)); Exit; end; buff := FSerial.RecvByte(TIMEOUT); Result := Boolean(buff); end; end.
{$I-,Q-,R-,S-} {30þ El nuevo juguete de Melany Korea 2002 ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ Melany es una ni¤a inteligente y traviesa. Sus padres le han comprado un nuevo juguete que consiste en un puzzle de N piezas. Se sabe que una pieza encaja con al menos otra pieza del mismo puzzle, y que unir estas dos piezas le lleva a Melany algun M tiempo. Tarea: Confeccione un programa para dada la cantidad de piezas del nuevo juguete, las piezasa que pueden unirse y el tiempo M que demora Melany en unirlas, determine el menor tiempo en que ella armara su puzzle y la configuracion del mismo. Entrada: La entrada es mediante el fichero texto MELY.IN con la siguiente estructura: . Primera linea: dos numeros enteros N y K, el primero representa la cantidad de piezas que tiene el puzzle y el segundo la cantidad de parejas de piezas que pueden unirse (4 <= N <= 100). . 2..K+1 linea: tres enteros A, B y M donde A y B representan numeros de dos piezas que pueden unirse y M el tiempo que demora Melany en unirlas (0 <= M <= 255). Salida: La salida se realizara hacia el fichero texto MELY.OUT: . Primera linea: un entero que significa el tiempo que demora Melany en armar su puzzle. . A partir de la segunda linea la configuracion del puzzle, la primera pieza y a continuacion todas las que Melany une a esta, separados por un espacio en blanco. ÚÄÄÄÄÄÄÄ¿ ÚÄÄÄÄÄÄÄÄ¿ ³MELY.IN³ ³MELY.OUT³ ÃÄÄÄÄÄÄÄ´ ÃÄÄÄÄÄÄÄÄ´ ³6 10 ³ ³16 ³ ³1 2 7 ³ ³1 2 3 4 ³ ³1 6 6 ³ ³3 6 5 ³ ³4 1 2 ³ ÀÄÄÄÄÄÄÄÄÙ ³2 4 8 ³ ³3 1 2 ³ ³5 4 7 ³ ³3 4 3 ³ ³5 3 4 ³ ³6 3 1 ³ ³6 5 5 ³ ÀÄÄÄÄÄÄÄÙ } const mx = 101; maxlong = 2139062143; var fe,fs : text; n,m,sol : longint; tab : array[1..mx,1..mx] of longint; mk : array[1..mx] of boolean; sav : array[1..mx] of longint; link : array[1..mx,1..mx] of boolean; procedure open; var i,a,b,c : longint; begin assign(fe,'mely.in'); reset(fe); assign(fs,'mely.out'); rewrite(fs); readln(fe,n,m); fillchar(tab,sizeof(tab),127); for i:=1 to m do begin readln(fe,a,b,c); tab[a,b]:=c; tab[b,a]:=c; end; close(fe); end; procedure work; var i,j,k,max,act,piv : longint; begin sav[1]:=1; mk[1]:=true; sol:=0; for i:=2 to n do begin max:=maxlong; for j:=1 to i-1 do begin for k:=1 to n do if (not mk[k]) and (tab[sav[j],k] < max) then begin max:=tab[sav[j],k]; piv:=k; act:=sav[j]; end; end; sav[i]:=piv; mk[piv]:=true; link[act,piv]:=true; sol:=sol + tab[act,piv]; end; end; procedure closer; var i,j : longint; ok : boolean; begin writeln(fs,sol); for i:=1 to n do begin ok:=false; for j:=1 to n do if link[i,j] then begin if not ok then begin ok:=true; write(fs,i,' ',j,' '); link[i,j]:=false; end else begin write(fs,j,' '); link[i,j]:=false; end; end; if ok then writeln(fs); end; close(fs); end; begin open; work; closer; end.
unit FHIRDataStore; { Copyright (c) 2001-2013, Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses SysUtils, Classes, IniFiles, kCritSct, DateSupport, kDate, DateAndTime, StringSupport, GuidSupport, ParseMap, AdvNames, AdvIntegerObjectMatches, AdvObjects, AdvStringObjectMatches, AdvStringMatches, AdvExclusiveCriticalSections, KDBManager, KDBDialects, FHIRAtomFeed, FHIRResources, FHIRBase, FHIRTypes, FHIRComponents, FHIRParser, FHIRParserBase, FHIRConstants, FHIRTags, FHIRValueSetExpander, FHIRValidator, FHIRIndexManagers, FHIRSupport, FHIRUtilities, {$IFNDEF FHIR-DSTU} FHIRSubscriptionManager, {$ENDIF} TerminologyServer; const OAUTH_LOGIN_PREFIX = 'os9z4tw9HdmR-'; OAUTH_SESSION_PREFIX = 'b35b7vX3KTAe-'; IMPL_COOKIE_PREFIX = 'implicit-'; Type TFhirTag = class (TAdvName) private FKey : integer; FLabel : String; FScheme: String; FTerm: String; function combine : String; public property Key : integer read FKey write FKey; property Scheme : String read FScheme write FScheme; property Term : String read FTerm write FTerm; property Label_ : String read FLabel write FLabel; end; TFHIRResourceConfig = record key : integer; Supported : Boolean; IdGuids : Boolean; IdClient : Boolean; IdServer : Boolean; cmdUpdate : Boolean; cmdDelete : Boolean; cmdValidate : Boolean; cmdHistoryInstance : Boolean; cmdHistoryType : Boolean; cmdSearch : Boolean; cmdCreate : Boolean; versionUpdates : Boolean; end; TConfigArray = Array [TFHIRResourceType] of TFHIRResourceConfig; TFHIRDataStore = class (TAdvObject) private FDB : TKDBManager; FTerminologyServer : TTerminologyServer; FSourceFolder : String; // folder in which the FHIR specification itself is found FSessions : TStringList; FTags : TAdvNameList; FTagsByKey : TAdvIntegerObjectMatch; FLock : TCriticalSection; FLastSessionKey : integer; FLastSearchKey : integer; FLastVersionKey : integer; FLastTagVersionKey : integer; FLastTagKey : integer; FLastResourceKey : Integer; FLastEntryKey : Integer; FLastCompartmentKey : Integer; FProfiles : TAdvStringMatch; FUserIds : TAdvStringObjectMatch; FUserLogins : TAdvStringObjectMatch; FValidator : TFHIRValidator; FResConfig : TConfigArray; FSupportTransaction : Boolean; FDoAudit : Boolean; FSupportSystemHistory : Boolean; FBases : TStringList; FTotalResourceCount: integer; FFormalURL: String; FOwnerName: String; {$IFNDEF FHIR-DSTU} FSubscriptionManager : TSubscriptionManager; {$ENDIF} procedure LoadExistingResources(conn : TKDBConnection); procedure SaveSecurityEvent(se : TFhirSecurityEvent); procedure RecordFhirSession(session: TFhirSession); procedure CloseFhirSession(key: integer); procedure DoExecuteOperation(request : TFHIRRequest; response : TFHIRResponse; bWantSession : boolean); function DoExecuteSearch (typekey : integer; compartmentId, compartments : String; params : TParseMap; conn : TKDBConnection): String; function getTypeForKey(key : integer) : TFhirResourceType; public constructor Create(DB : TKDBManager; SourceFolder, WebFolder : String; terminologyServer : TTerminologyServer; ini : TIniFile); Destructor Destroy; Override; Function Link : TFHIRDataStore; virtual; procedure CloseAll; function GetSession(sCookie : String; var session : TFhirSession; var check : boolean) : boolean; function GetSessionByToken(outerToken : String; var session : TFhirSession) : boolean; Function CreateImplicitSession(clientInfo : String) : TFhirSession; Procedure EndSession(sCookie, ip : String); function RegisterSession(provider: TFHIRAuthProvider; innerToken, outerToken, id, name, email, original, expires, ip, rights: String): TFhirSession; procedure MarkSessionChecked(sCookie, sName : String); function ProfilesAsOptionList : String; function GetFhirUser(namespace, name :String) : TFHIRUser; function GetFhirUserStructure(namespace, name :String) : TFHIRUserStructure; function NextVersionKey : Integer; function NextTagVersionKey : Integer; function NextSearchKey : Integer; function NextResourceKey : Integer; function NextEntryKey : Integer; function NextCompartmentKey : Integer; Function GetNextKey(keytype : TKeyType): Integer; procedure RegisterTag(tag : TFHIRAtomCategory; conn : TKDBConnection); overload; procedure registerTag(tag: TFhirTag); overload; procedure SeeResource(key, vkey : Integer; id : string; resource : TFHIRResource; conn : TKDBConnection; reload : boolean; session : TFhirSession); procedure DropResource(key, vkey : Integer; id : string; aType : TFhirResourceType; indexer : TFhirIndexManager); function KeyForTag(scheme, term : String) : Integer; Property Validator : TFHIRValidator read FValidator; function GetTagByKey(key : integer): TFhirTag; Property DB : TKDBManager read FDB; Property ResConfig : TConfigArray read FResConfig; Property SupportTransaction : Boolean read FSupportTransaction; Property DoAudit : Boolean read FDoAudit; Property SupportSystemHistory : Boolean read FSupportSystemHistory; Property Bases : TStringList read FBases; Property TotalResourceCount : integer read FTotalResourceCount; Property TerminologyServer : TTerminologyServer read FTerminologyServer; procedure Sweep; property FormalURL : String read FFormalURL write FFormalURL; function ResourceTypeKeyForName(name : String) : integer; procedure ProcessSubscriptions; function DefaultRights : String; Property OwnerName : String read FOwnerName write FOwnerName; end; implementation uses FHIROperation, SearchProcessor; function TagCombine(scheme, term : String): String; begin result := scheme+#1+term; end; { TFHIRRepository } procedure TFHIRDataStore.CloseAll; var i : integer; session : TFhirSession; begin FLock.Lock('close all'); try for i := FSessions.Count - 1 downto 0 do begin session := TFhirSession(FSessions.Objects[i]); session.free; FSessions.Delete(i); end; finally FLock.Unlock; end; end; constructor TFHIRDataStore.Create(DB : TKDBManager; SourceFolder, WebFolder : String; terminologyServer : TTerminologyServer; ini : TIniFile); var i : integer; conn : TKDBConnection; tag : TFhirTag; a : TFHIRResourceType; begin inherited Create; FBases := TStringList.create; FBases.add('http://localhost/'); for a := low(TFHIRResourceType) to high(TFHIRResourceType) do FResConfig[a].Supported := false; FDb := db; FSourceFolder := SourceFolder; FSessions := TStringList.create; FTags := TAdvNameList.Create; FLock := TCriticalSection.Create('fhir-store'); {$IFNDEF FHIR-DSTU} FSubscriptionManager := TSubscriptionManager.Create; FSubscriptionManager.dataBase := FDB; FSubscriptionManager.SMTPHost := ini.ReadString('email', 'Host', ''); FSubscriptionManager.SMTPPort := ini.ReadString('email', 'Port' ,''); FSubscriptionManager.SMTPUsername := ini.readString('email', 'Username' ,''); FSubscriptionManager.SMTPPassword := ini.readString('email', 'Password' ,''); FSubscriptionManager.SMTPUseTLS := ini.ReadBool('email', 'Secure', false); FSubscriptionManager.SMTPSender := ini.readString('email', 'Sender' ,''); FSubscriptionManager.OnExecuteOperation := DoExecuteOperation; FSubscriptionManager.OnExecuteSearch := DoExecuteSearch; {$ENDIF} conn := FDB.GetConnection('setup'); try FLastSessionKey := conn.CountSQL('Select max(SessionKey) from Sessions'); FLastVersionKey := conn.CountSQL('Select Max(ResourceVersionKey) from Versions'); FLastTagVersionKey := conn.CountSQL('Select Max(ResourceTagKey) from VersionTags'); FLastSearchKey := conn.CountSQL('Select Max(SearchKey) from Searches'); FLastTagKey := conn.CountSQL('Select Max(TagKey) from Tags'); FLastResourceKey := conn.CountSQL('select Max(ResourceKey) from Ids'); FLastEntryKey := conn.CountSQL('select max(EntryKey) from indexEntries'); FLastCompartmentKey := conn.CountSQL('select max(ResourceCompartmentKey) from Compartments'); conn.execSQL('Update Sessions set Closed = '+DBGetDate(conn.Owner.Platform)+' where Closed = null'); conn.SQL := 'Select TagKey, SchemeUri, TermURI, Label from Tags'; conn.Prepare; conn.Execute; while conn.FetchNext do begin tag := TFhirTag.create; try tag.Term := conn.ColStringByName['TermURI']; tag.Scheme := conn.ColStringByName['SchemeURI']; tag.Label_ := conn.ColStringByName['Label']; tag.Key := conn.ColIntegerByName['TagKey']; tag.Name := tag.combine; FTags.add(tag.Link); finally tag.free; end; end; conn.terminate; conn.SQL := 'Select * from Config'; conn.Prepare; conn.Execute; while conn.FetchNext do if conn.ColIntegerByName['ConfigKey'] = 1 then FSupportTransaction := conn.ColStringByName['Value'] = '1' else if conn.ColIntegerByName['ConfigKey'] = 2 then FBases.add(conn.ColStringByName['Value']) else if conn.ColIntegerByName['ConfigKey'] = 3 then FSupportSystemHistory := conn.ColStringByName['Value'] = '1' else if conn.ColIntegerByName['ConfigKey'] = 4 then FDoAudit := conn.ColStringByName['Value'] = '1'; conn.Terminate; conn.SQL := 'Select * from Types'; conn.Prepare; conn.Execute; While conn.FetchNext do begin a := TFHIRResourceType(StringArrayIndexOfSensitive(CODES_TFHIRResourceType, conn.ColStringByName['ResourceName'])); FResConfig[a].Key := conn.ColIntegerByName['ResourceTypeKey']; FResConfig[a].Supported := conn.ColStringByName['Supported'] = '1'; FResConfig[a].IdGuids := conn.ColStringByName['IdGuids'] = '1'; FResConfig[a].IdClient := conn.ColStringByName['IdClient'] = '1'; FResConfig[a].IdServer := conn.ColStringByName['IdServer'] = '1'; FResConfig[a].cmdUpdate := conn.ColStringByName['cmdUpdate'] = '1'; FResConfig[a].cmdDelete := conn.ColStringByName['cmdDelete'] = '1'; FResConfig[a].cmdValidate := conn.ColStringByName['cmdValidate'] = '1'; FResConfig[a].cmdHistoryInstance := conn.ColStringByName['cmdHistoryInstance'] = '1'; FResConfig[a].cmdHistoryType := conn.ColStringByName['cmdHistoryType'] = '1'; FResConfig[a].cmdSearch := conn.ColStringByName['cmdSearch'] = '1'; FResConfig[a].cmdCreate := conn.ColStringByName['cmdCreate'] = '1'; FResConfig[a].versionUpdates := conn.ColStringByName['versionUpdates'] = '1'; end; conn.Terminate; FTags.SortedByName; FTagsByKey := TAdvIntegerObjectMatch.create; for i := 0 to FTags.count - 1 do FTagsBykey.Add(TFhirTag(FTags[i]).Key, FTags[i].Link); // the expander is tied to what's on the system FTerminologyServer := terminologyServer; FProfiles := TAdvStringMatch.create; FProfiles.Forced := true; FUserIds := TAdvStringObjectMatch.create; FUserIds.PreventDuplicates; FUserIds.Forced := true; FUserLogins := TAdvStringObjectMatch.create; FUserLogins.PreventDuplicates; FUserLogins.Forced := true; FValidator := TFHIRValidator.create; FValidator.SchematronSource := WebFolder; FValidator.TerminologyServer := terminologyServer.Link; // the order here is important: specification resources must be loaded prior to stored resources FValidator.LoadFromDefinitions(IncludeTrailingPathDelimiter(FSourceFolder)+'validation.zip'); LoadExistingResources(Conn); {$IFNDEF FHIR-DSTU} FSubscriptionManager.LoadQueue(Conn); {$ENDIF} conn.Release; except on e:exception do begin conn.Error(e); raise; end; end; end; function TFHIRDataStore.CreateImplicitSession(clientInfo: String): TFhirSession; var session : TFhirSession; dummy : boolean; new : boolean; se : TFhirSecurityEvent; C : TFhirCoding; p : TFhirSecurityEventParticipant; begin new := false; FLock.Lock('CreateImplicitSession'); try if not GetSession(IMPL_COOKIE_PREFIX+clientInfo, result, dummy) then begin new := true; session := TFhirSession.create; try inc(FLastSessionKey); session.Key := FLastSessionKey; session.Id := ''; session.Name := ClientInfo; session.Expires := UniversalDateTime + DATETIME_SECOND_ONE * 60*60; // 1 hour session.Cookie := ''; session.Provider := apNone; session.originalUrl := ''; session.email := ''; session.User := GetFhirUserStructure(USER_SCHEME_IMPLICIT, clientInfo); if Session.user <> nil then session.Name := Session.User.Resource.Name +' ('+clientInfo+')'; se := TFhirSecurityEvent.create; try se.event := TFhirSecurityEventEvent.create; se.event.type_ := TFhirCodeableConcept.create; c := se.event.type_.codingList.Append; c.codeST := '110114'; c.systemST := 'http://nema.org/dicom/dcid'; c.displayST := 'User Authentication'; c := se.event.subtypeList.append.codingList.Append; c.codeST := '110122'; c.systemST := 'http://nema.org/dicom/dcid'; c.displayST := 'Login'; se.event.actionST := SecurityEventActionE; se.event.outcomeST := SecurityEventOutcome0; se.event.dateTimeST := NowUTC; se.source := TFhirSecurityEventSource.create; se.source.siteST := 'Cloud'; se.source.identifierST := FOwnerName; c := se.source.type_List.Append; c.codeST := '3'; c.displayST := 'Web Server'; c.systemST := 'http://hl7.org/fhir/security-source-type'; // participant - the web browser / user proxy p := se.participantList.Append; p.userIdST := clientInfo; p.network := TFhirSecurityEventParticipantNetwork.create; p.network.identifierST := clientInfo; p.network.type_ST := NetworkType2; SaveSecurityEvent(se); finally se.free; end; FSessions.AddObject(IMPL_COOKIE_PREFIX+clientInfo, session.Link); result := session.Link as TFhirSession; finally session.free; end; end; finally FLock.UnLock; end; if new then RecordFhirSession(result); end; procedure TFHIRDataStore.RecordFhirSession(session: TFhirSession); var conn : TKDBConnection; begin conn := FDB.GetConnection('fhir'); try conn.SQL := 'insert into Sessions (SessionKey, Provider, Id, Name, Email, Expiry) values (:sk, :p, :i, :n, :e, :ex)'; conn.Prepare; conn.BindInteger('sk', Session.Key); conn.BindInteger('p', Integer(Session.Provider)); conn.BindString('i', session.Id); conn.BindString('n', session.Name); conn.BindString('e', session.Email); conn.BindTimeStamp('ex', DateTimeToTS(session.Expires)); conn.Execute; conn.Terminate; conn.Release; except on e:exception do begin conn.Error(e); raise; end; end; end; function TFHIRDataStore.DefaultRights: String; begin result := 'read,write,user'; end; destructor TFHIRDataStore.Destroy; begin FBases.free; FUserIds.free; FUserLogins.free; FProfiles.free; FTagsByKey.free; FSessions.free; FTags.Free; {$IFNDEF FHIR-DSTU} FSubscriptionManager.Free; {$ENDIF} FLock.Free; FValidator.Free; FTerminologyServer.Free; inherited; end; procedure TFHIRDataStore.DoExecuteOperation(request: TFHIRRequest; response: TFHIRResponse; bWantSession : boolean); var storage : TFhirOperation; begin if bWantSession then request.Session := CreateImplicitSession('server'); storage := TFhirOperation.create('en', self.Link); try storage.OwnerName := OwnerName; storage.Connection := FDB.GetConnection('fhir'); storage.PreCheck(request, response); storage.Connection.StartTransact; try storage.Execute(request, response); storage.Connection.Commit; storage.Connection.Release; except on e : exception do begin storage.Connection.Rollback; storage.Connection.Error(e); raise; end; end; finally storage.Free; end; end; function TFHIRDataStore.DoExecuteSearch(typekey: integer; compartmentId, compartments: String; params: TParseMap; conn : TKDBConnection): String; var sp : TSearchProcessor; spaces : TFHIRIndexSpaces; begin spaces := TFHIRIndexSpaces.Create(conn); try sp := TSearchProcessor.create; try sp.typekey := typekey; sp.type_ := getTypeForKey(typeKey); sp.compartmentId := compartmentId; sp.compartments := compartments; sp.baseURL := FFormalURL; // todo: what? sp.lang := 'en'; sp.params := params; sp.indexer := TFhirIndexManager.Create(spaces); sp.Indexer.Ucum := TerminologyServer.Ucum.Link; sp.Indexer.Bases := Bases; sp.Indexer.KeyEvent := GetNextKey; sp.repository := self.Link; sp.build; result := sp.filter; finally sp.free; end; finally spaces.Free; end; end; procedure TFHIRDataStore.EndSession(sCookie, ip: String); var i : integer; session : TFhirSession; se : TFhirSecurityEvent; C : TFhirCoding; p : TFhirSecurityEventParticipant; key : integer; begin key := 0; FLock.Lock('EndSession'); try i := FSessions.IndexOf(sCookie); if i > -1 then begin session := TFhirSession(FSessions.Objects[i]); try se := TFhirSecurityEvent.create; try se.event := TFhirSecurityEventEvent.create; se.event.type_ := TFhirCodeableConcept.create; c := se.event.type_.codingList.Append; c.codeST := '110114'; c.systemST := 'http://nema.org/dicom/dcid'; c.displayST := 'User Authentication'; c := se.event.subtypeList.append.codingList.Append; c.codeST := '110123'; c.systemST := 'http://nema.org/dicom/dcid'; c.displayST := 'Logout'; se.event.actionST := SecurityEventActionE; se.event.outcomeST := SecurityEventOutcome0; se.event.dateTimeST := NowUTC; se.source := TFhirSecurityEventSource.create; se.source.siteST := 'Cloud'; se.source.identifierST := ''+FOwnerName+''; c := se.source.type_List.Append; c.codeST := '3'; c.displayST := 'Web Server'; c.systemST := 'http://hl7.org/fhir/security-source-type'; // participant - the web browser / user proxy p := se.participantList.Append; p.userIdST := inttostr(session.Key); p.altIdST := session.Id; p.nameST := session.Name; if (ip <> '') then begin p.network := TFhirSecurityEventParticipantNetwork.create; p.network.identifierST := ip; p.network.type_ST := NetworkType2; p.requestorST := true; end; SaveSecurityEvent(se); finally se.free; end; key := session.key; FSessions.Delete(i); finally session.free; end; end; finally FLock.Unlock; end; if key > 0 then CloseFhirSession(key); end; procedure TFHIRDataStore.CloseFhirSession(key : integer); var conn : TKDBConnection; begin conn := FDB.GetConnection('fhir'); try conn.SQL := 'Update Sessions set closed = :d where SessionKey = '+inttostr(key); conn.Prepare; conn.BindTimeStamp('d', DateTimeToTS(UniversalDateTime)); conn.Execute; conn.Terminate; conn.Release; except on e:exception do begin conn.Error(e); raise; end; end; end; function TFHIRDataStore.GetSession(sCookie: String; var session: TFhirSession; var check : boolean): boolean; var key, i : integer; begin key := 0; FLock.Lock('GetSession'); try i := FSessions.IndexOf(sCookie); result := i > -1; if result then begin session := TFhirSession(FSessions.Objects[i]); session.useCount := session.useCount + 1; if session.Expires > UniversalDateTime then begin session.link; check := (session.Provider in [apFacebook, apGoogle]) and (session.NextTokenCheck < UniversalDateTime); end else begin result := false; try Key := Session.key; FSessions.Delete(i); finally session.free; end; end; end; finally FLock.Unlock; end; if key > 0 then CloseFhirSession(key); end; function TFHIRDataStore.GetSessionByToken(outerToken : String; var session: TFhirSession): boolean; var key, i : integer; begin result := false; session := nil; FLock.Lock('GetSessionByToken'); try for i := 0 to FSessions.count - 1 do if (TFhirSession(FSessions.Objects[i]).Outertoken = outerToken) or (TFhirSession(FSessions.Objects[i]).JWTPacked = outerToken) then begin result := true; session := TFhirSession(FSessions.Objects[i]).Link; session.useCount := session.useCount + 1; break; end; finally FLock.Unlock; end; end; function TFHIRDataStore.GetTagByKey(key: integer): TFhirTag; begin FLock.Lock('GetTagByKey'); try result := TFhirTag(FTagsByKey.GetValueByKey(key)); finally FLock.Unlock; end; end; function TFHIRDataStore.getTypeForKey(key: integer): TFhirResourceType; var a : TFHIRResourceType; begin result := frtNull; for a := Low(FResConfig) to High(FResConfig) do if FResConfig[a].key = key then begin result := a; exit; end; end; function TFHIRDataStore.KeyForTag(scheme, term: String): Integer; var i : integer; p : String; s : string; begin FLock.Lock('KeyForTag'); try p := TagCombine(scheme, term); i := FTags.IndexByName(p); if i = -1 then begin for i := 0 to FTags.count - 1 do s := s + FTags[i].Name+#13#10; writeln(s); result := -1; // nothing will match end else result := TFhirTag(FTags[i]).Key; finally FLock.Unlock; end; end; procedure TFHIRDataStore.MarkSessionChecked(sCookie, sName: String); var i : integer; session : TFhirSession; begin FLock.Lock('MarkSessionChecked'); try i := FSessions.IndexOf(sCookie); if i > -1 then begin session := TFhirSession(FSessions.Objects[i]); session.NextTokenCheck := UniversalDateTime + 5 * DATETIME_MINUTE_ONE; session.Name := sName; end; finally FLock.Unlock; end; end; function TFHIRDataStore.NextTagVersionKey: Integer; begin FLock.Lock('NextTagVersionKey'); try inc(FLastTagVersionKey); result := FLastTagVersionKey; finally FLock.UnLock; end; end; function TFHIRDataStore.NextVersionKey: Integer; begin FLock.Lock('NextVersionKey'); try inc(FLastVersionKey); result := FLastVersionKey; finally FLock.UnLock; end; end; function TFHIRDataStore.RegisterSession(provider : TFHIRAuthProvider; innerToken, outerToken, id, name, email, original, expires, ip, rights: String): TFhirSession; var session : TFhirSession; se : TFhirSecurityEvent; C : TFhirCoding; p : TFhirSecurityEventParticipant; begin session := TFhirSession.create; try session.InnerToken := innerToken; session.OuterToken := outerToken; session.Id := id; session.Name := name; session.Expires := LocalDateTime + DATETIME_SECOND_ONE * StrToInt(expires); session.Cookie := OAUTH_SESSION_PREFIX + copy(GUIDToString(CreateGuid), 2, 36); session.Provider := provider; session.originalUrl := original; session.email := email; session.NextTokenCheck := UniversalDateTime + 5 * DATETIME_MINUTE_ONE; session.User := GetFhirUserStructure(USER_SCHEME_PROVIDER[provider], id); session.rights.commaText := rights; FLock.Lock('RegisterSession'); try inc(FLastSessionKey); session.Key := FLastSessionKey; FSessions.AddObject(session.Cookie, session.Link); finally FLock.Unlock; end; se := TFhirSecurityEvent.create; try se.event := TFhirSecurityEventEvent.create; se.event.type_ := TFhirCodeableConcept.create; c := se.event.type_.codingList.Append; c.codeST := '110114'; c.systemST := 'http://nema.org/dicom/dcid'; c.displayST := 'User Authentication'; c := se.event.subtypeList.append.codingList.Append; c.codeST := '110122'; c.systemST := 'http://nema.org/dicom/dcid'; c.displayST := 'Login'; se.event.actionST := SecurityEventActionE; se.event.outcomeST := SecurityEventOutcome0; se.event.dateTimeST := NowUTC; se.source := TFhirSecurityEventSource.create; se.source.siteST := 'Cloud'; se.source.identifierST := ''+FOwnerName+''; c := se.source.type_List.Append; c.codeST := '3'; c.displayST := 'Web Server'; c.systemST := 'http://hl7.org/fhir/security-source-type'; // participant - the web browser / user proxy p := se.participantList.Append; p.userIdST := inttostr(session.Key); p.altIdST := session.Id; p.nameST := session.Name; if (ip <> '') then begin p.network := TFhirSecurityEventParticipantNetwork.create; p.network.identifierST := ip; p.network.type_ST := NetworkType2; p.requestorST := true; end; SaveSecurityEvent(se); finally se.free; end; result := session.Link as TFhirSession; finally session.free; end; RecordFhirSession(result); end; procedure TFHIRDataStore.RegisterTag(tag : TFHIRAtomCategory; conn : TKDBConnection); var i : integer; t : TFhirTag; begin FLock.Lock('RegisterTag'); try i := FTags.IndexByName(TagCombine(Tag.scheme, Tag.term)); if i > -1 then begin tag.TagKey := TFhirTag(FTags[i]).Key; if tag.label_ = '' then tag.label_ := TFhirTag(FTags[i]).Label_; end else begin t := TFhirTag.create; try t.Scheme := tag.scheme; t.Term := tag.term; t.Label_ := tag.label_; t.Name := t.combine; inc(FLastTagKey); t.key := FLastTagKey; registerTag(t); tag.TagKey := t.Key; FTags.add(t.Link); FTagsByKey.Add(t.Key, t.Link); finally t.free; end; end; finally FLock.UnLock; end; end; procedure TFHIRDataStore.registerTag(tag: TFhirTag); var conn : TKDBConnection; begin conn := FDB.GetConnection('fhir'); try conn.SQL := 'insert into Tags (TagKey, SchemeUri, TermUri, Label) values (:k, :s, :u, :l)'; conn.Prepare; conn.BindInteger('k', tag.Key); conn.BindString('s', tag.Scheme); conn.BindString('u', tag.Term); conn.BindString('l', tag.Label_); conn.Execute; conn.terminate; conn.Release; except on e:exception do begin conn.Error(e); raise; end; end; end; function TFHIRDataStore.ResourceTypeKeyForName(name: String): integer; var i : integer; begin i := StringArrayIndexOfSensitive(CODES_TFhirResourceType, name); if i < 1 then raise Exception.Create('Unknown Resource Type '''+name+''''); result := FResConfig[TFhirResourceType(i)].key; end; procedure TFHIRDataStore.Sweep; var key, i : integer; session : TFhirSession; d : TDateTime; begin key := 0; d := UniversalDateTime; FLock.Lock('sweep2'); try for i := FSessions.Count - 1 downto 0 do begin session := TFhirSession(FSessions.Objects[i]); if session.Expires < d then begin try key := session.key; FSessions.Delete(i); finally session.free; end; end; end; finally FLock.Unlock; end; if key > 0 then CloseFhirSession(key); end; procedure TFHIRDataStore.SeeResource(key, vkey : Integer; id : string; resource : TFHIRResource; conn : TKDBConnection; reload : boolean; session : TFhirSession); var profile : TFhirProfile; begin FLock.Lock('SeeResource'); try if resource.ResourceType in [frtValueSet, frtConceptMap] then TerminologyServer.SeeTerminologyResource(Codes_TFHIRResourceType[resource.ResourceType]+'/'+id, key, resource) else if resource.ResourceType = frtProfile then begin profile := resource as TFhirProfile; FProfiles.matches[id] := profile.nameST; end; { else if resource.ResourceType = frtUser then begin user := resource as TFhirUser; FUserIds.matches[id] := user.link; FUserLogins.matches[user.providerST+#1+user.loginST] := user.link; end;} {$IFNDEF FHIR-DSTU} FSubscriptionManager.SeeResource(key, vkey, id, resource, conn, reload, session); {$ENDIF} finally FLock.Unlock; end; end; procedure TFHIRDataStore.DropResource(key, vkey : Integer; id : string; aType : TFhirResourceType; indexer : TFhirIndexManager); begin FLock.Lock('DropResource'); try if aType in [frtValueSet, frtConceptMap] then TerminologyServer.DropTerminologyResource(key, Codes_TFHIRResourceType[aType]+'/'+id, aType) else if aType = frtProfile then begin FProfiles.DeleteByKey(id); end; { else if aType = frtUser then begin user := FUserIds.Matches[id] as TFHIRUser; FUserLogins.DeleteByKey(user.providerST+#1+user.loginST); FUserIds.DeleteByKey(id); end;} {$IFNDEF FHIR-DSTU} FSubscriptionManager.DropResource(key, vkey); {$ENDIF} finally FLock.Unlock; end; end; procedure TFHIRDataStore.SaveSecurityEvent(se: TFhirSecurityEvent); var request : TFHIRRequest; response : TFHIRResponse; begin request := TFHIRRequest.create; try request.ResourceType := frtSecurityEvent; request.CommandType := fcmdCreate; request.Resource := se.link; request.lastModifiedDate := se.event.dateTimeST.AsUTCDateTime; request.Session := nil; response := TFHIRResponse.create; try DoExecuteOperation(request, response, false); finally response.free; end; finally request.free; end; end; procedure TFHIRDataStore.ProcessSubscriptions; begin {$IFNDEF FHIR-DSTU} FSubscriptionManager.Process; {$ENDIF} end; function TFHIRDataStore.ProfilesAsOptionList: String; var i : integer; sn, sv : string; begin result := ''; FLock.Enter; try for i := 0 to FProfiles.Count - 1 do begin sn := FProfiles.KeyByIndex[i]; sv := FProfiles.ValueByIndex[i]; result := result + '<option value="'+sn+'">'; if sv = '' then result := result + '@'+sn+'</option>'+#13#10 else result := result + sv+'</option>'+#13#10; end; finally FLock.Leave; end; end; function TFHIRDataStore.GetFhirUser(namespace, name: String): TFHIRUser; begin FLock.Enter; try result := FUserLogins.Matches[namespace + #1 + name] as TFhirUser; finally FLock.Leave; end; end; function TFHIRDataStore.GetFhirUserStructure(namespace, name: String): TFHIRUserStructure; var user : TFHIRUser; conn : TKDBConnection; begin FLock.Enter; try user := FUserLogins.Matches[namespace + #1 + name] as TFhirUser; if user = nil then result := nil else begin result := TFhirUserStructure.create; try result.Resource := user.link; // todo: read other patient compartments conn := FDB.GetConnection('fhir'); try conn.sql := 'select Id from Ids where MostRecent in (select ResourceVersionKey from VersionTags where TagKey in (select TagKey from Tags where Scheme = '''+FHIR_TAG_SCHEME+''' and Uri = ''http://fhir.org/connectathon4/patient-compartment-user/'+SQLWrapString(user.login)+'''))'; conn.Prepare; conn.Execute; while conn.FetchNext do result.TaggedCompartments.Add(Conn.ColStringByName['Id']); conn.terminate; conn.Release; except on e:exception do begin conn.Error(e); raise; end; end; result.link; finally result.free; end; end; finally FLock.Leave; end; end; function TFHIRDataStore.NextSearchKey: Integer; begin FLock.Lock('NextSearchKey'); try inc(FLastSearchKey); result := FLastSearchKey; finally FLock.UnLock; end; end; function TFHIRDataStore.NextResourceKey: Integer; begin FLock.Lock('NextResourceKey'); try inc(FLastResourceKey); result := FLastResourceKey; finally FLock.UnLock; end; end; function TFHIRDataStore.NextEntryKey : Integer; begin FLock.Lock('NextEntryKey'); try inc(FLastEntryKey); result := FLastEntryKey; finally FLock.UnLock; end; end; function TFHIRDataStore.NextCompartmentKey : Integer; begin FLock.Lock('NextCompartmentKey'); try inc(FLastCompartmentKey); result := FLastCompartmentKey; finally FLock.UnLock; end; end; function TFHIRDataStore.GetNextKey(keytype: TKeyType): Integer; begin case keyType of ktResource : result := NextResourceKey; ktEntries : result := NextEntryKey; ktCompartment : result := NextCompartmentKey; else raise exception.create('not done'); end; end; function TFHIRDataStore.Link: TFHIRDataStore; begin result := TFHIRDataStore(Inherited Link); end; procedure TFHIRDataStore.LoadExistingResources(conn : TKDBConnection); var parser : TFHIRParser; mem : TBytes; i : integer; cback : TKDBConnection; begin conn.SQL := 'select Ids.ResourceKey, Versions.ResourceVersionKey, Ids.Id, Content from Ids, Types, Versions where '+ 'Versions.ResourceVersionKey = Ids.MostRecent and '+ 'Ids.ResourceTypeKey = Types.ResourceTypeKey and '+ '(Types.ResourceName = ''ValueSet'' or Types.ResourceName = ''ConceptMap'' or Types.ResourceName = ''Profile'' or Types.ResourceName = ''User''or Types.ResourceName = ''Subscription'') and not Versions.Deleted = 1'; conn.Prepare; try cback := FDB.GetConnection('load2'); try i := 0; conn.execute; while conn.FetchNext do begin inc(i); mem := ZDecompressBytes(conn.ColBlobByName['Content']); parser := MakeParser('en', ffXml, mem, xppDrop); try SeeResource(conn.colIntegerByName['ResourceKey'], conn.colIntegerByName['ResourceVersionKey'], conn.colStringByName['Id'], parser.resource, cback, true, nil); finally parser.free; end; end; cback.Release; except on e : Exception do begin cback.Error(e); raise; end; end; finally conn.terminate; end; FTotalResourceCount := i; end; { TFhirTag } function TFhirTag.combine: String; begin result := TagCombine(scheme, term); end; end.
unit Histogram; interface uses AbstractDataSet,SingleDataSet,IntDataSet,SysUtils; type THistogram = class protected FElements: TAbstractDataSet; FCounter: TAbstractDataSet; FTotalCount: integer; // Constructor procedure Initialize; // Gets function GetElement(_ID: integer): single; function GetElementUnsafe(_ID: integer): single; function GetCounter(_ID: integer): integer; function GetCounterUnsafe(_ID: integer): integer; function GetSize: integer; function GetLast: integer; function GetAverageCounter: single; function GetTotalCount: integer; // ReOrder procedure QuickSortElementsAscendent(_min, _max : integer); procedure QuickSortElementsDescendent(_min, _max : integer); procedure QuickSortCounterAscendent(_min, _max : integer); procedure QuickSortCounterDescendent(_min, _max : integer); public // Constructors and destructors constructor Create; destructor Destroy; override; procedure Clear; // I/O procedure SaveAsCSV(const _Filename,_ElementsLabel,_QuantityLabel,_PercentageLabel,_AverageLabel: string); overload; procedure SaveAsCSV(const _Filename: string); overload; // Adds procedure AddToHistogram(_Element: single); // ReOrder procedure ReOrderByElementsAscendently; procedure ReOrderByElementsDescendently; procedure ReOrderByCounterAscendently; procedure ReOrderByCounterDescendently; // Properties property Size:integer read GetSize; property Last:integer read GetLast; property TotalCount:integer read GetTotalCount; property Elements[_ID: integer]: single read GetElementUnsafe; property ElementsSafe[_ID: integer]: single read GetElement; property Counters[_ID: integer]: integer read GetCounterUnsafe; property CountersSafe[_ID: integer]: integer read GetCounter; end; implementation // Constructors and destructors constructor THistogram.Create; begin Initialize; end; destructor THistogram.Destroy; begin FElements.Free; FCounter.Free; inherited Destroy; end; procedure THistogram.Clear; begin FElements.Length := 0; FCounter.Length := 0; FTotalCount := 0; end; procedure THistogram.Initialize; begin FElements := TSingleDataSet.Create; FCounter := TIntDataSet.Create; Clear; end; // I/O procedure THistogram.SaveAsCSV(const _Filename,_ElementsLabel,_QuantityLabel,_PercentageLabel,_AverageLabel: string); var CSVFile: System.Text; i,config : integer; ElementsLabel : string; begin config := 0; if Length(_ElementsLabel) > 0 then begin ElementsLabel := copy(_ElementsLabel,1,Length(_ElementsLabel)); end else begin ElementsLabel := 'Elements'; end; if Length(_QuantityLabel) > 0 then begin config := config or 1; end; if Length(_PercentageLabel) > 0 then begin config := config or 2; end; DecimalSeparator := ','; AssignFile(CSVFIle,_Filename); Rewrite(CSVFile); case config of 0: begin WriteLn(CSVFile,'"' + ElementsLabel + '"'); for i := 0 to FElements.Last do begin WriteLn(CSVFile,FloatToStr(GetElement(i))); end; end; 1: begin WriteLn(CSVFile,'"' + ElementsLabel + '";"' + _QuantityLabel + '"'); for i := 0 to FElements.Last do begin WriteLn(CSVFile,FloatToStr(GetElement(i)) + ';' + IntToStr(GetCounter(i))); end; end; 2: begin WriteLn(CSVFile,'"' + ElementsLabel + '";"' + _PercentageLabel + '"'); for i := 0 to FElements.Last do begin WriteLn(CSVFile,FloatToStr(GetElement(i)) + ';' + FloatToStr(GetCounter(i) / FTotalCount)); end; end; 3: begin WriteLn(CSVFile,'"' + ElementsLabel + '";"' + _QuantityLabel + '";"' + _PercentageLabel + '"'); for i := 0 to FElements.Last do begin WriteLn(CSVFile,FloatToStr(GetElement(i)) + ';' + IntToStr(GetCounter(i)) + ';' + FloatToStr(GetCounter(i) / FTotalCount)); end; end; end; if Length(_AverageLabel) > 0 then begin WriteLn(CSVFile,''); WriteLn(CSVFile,'"' + _AverageLabel + '";' + FloatToStr(GetAverageCounter())); end; CloseFile(CSVFIle); end; procedure THistogram.SaveAsCSV(const _Filename: string); begin SaveAsCSV(_Filename,'Elements','Quantity','%:','Average:'); end; // Gets function THistogram.GetElement(_ID: integer): single; begin Result := -1; if (_ID >= 0) and (_ID <= FElements.Last) then begin Result := (FElements as TSingleDataSet).Data[_ID]; end; end; function THistogram.GetElementUnsafe(_ID: integer): single; begin Result := (FElements as TSingleDataSet).Data[_ID]; end; function THistogram.GetCounter(_ID: integer): integer; begin Result := -1; if (_ID >= 0) and (_ID <= FElements.Last) then begin Result := (FCounter as TIntDataSet).Data[_ID]; end; end; function THistogram.GetCounterUnsafe(_ID: integer): integer; begin Result := (FCounter as TIntDataSet).Data[_ID]; end; function THistogram.GetSize: integer; begin Result := FElements.Length; end; function THistogram.GetLast: integer; begin Result := FElements.Last; end; function THistogram.GetAverageCounter: single; var i : integer; begin Result := 0; for i := 0 to FElements.Last do begin Result := Result + ((FElements as TSingleDataSet).Data[i] * (FCounter as TIntDataSet).Data[i]); end; Result := Result / FTotalCount; end; function THistogram.GetTotalCount: integer; begin Result := FTotalCount; end; // Adds procedure THistogram.AddToHistogram(_Element: single); var i : integer; begin inc(FTotalCount); i := 0; while i <= FElements.Last do begin if _Element = (FElements as TSingleDataSet).Data[i] then begin (FCounter as TIntDataSet).Data[i] := (FCounter as TIntDataSet).Data[i] + 1; exit; end; inc(i); end; // element not found. Add a new element. FElements.Length := FElements.Length + 1; FCounter.Length := FCounter.Length + 1; (FElements as TSingleDataSet).Data[FElements.Last] := _Element; (FCounter as TIntDataSet).Data[FCounter.Last] := 1; end; // ReOrder procedure THistogram.ReOrderByElementsAscendently; begin QuickSortElementsAscendent(0,FElements.Last); end; procedure THistogram.ReOrderByElementsDescendently; begin QuickSortElementsDescendent(0,FElements.Last); end; procedure THistogram.ReOrderByCounterAscendently; begin QuickSortCounterAscendent(0,FElements.Last); end; procedure THistogram.ReOrderByCounterDescendently; begin QuickSortCounterDescendent(0,FElements.Last); end; procedure THistogram.QuickSortElementsAscendent(_min, _max : integer); var Lo, Hi, Mid, T: Integer; A : real; begin Lo := _min; Hi := _max; Mid := (Lo + Hi) div 2; repeat while ((FElements as TSingleDataSet).Data[Lo] - (FElements as TSingleDataSet).Data[Mid]) < 0 do Inc(Lo); while ((FElements as TSingleDataSet).Data[Hi] - (FElements as TSingleDataSet).Data[Mid]) > 0 do Dec(Hi); if Lo <= Hi then begin A := (FElements as TSingleDataSet).Data[Lo]; (FElements as TSingleDataSet).Data[Lo] := (FElements as TSingleDataSet).Data[Hi]; (FElements as TSingleDataSet).Data[Hi] := A; T := (FCounter as TIntDataSet).Data[Lo]; (FCounter as TIntDataSet).Data[Lo] := (FCounter as TIntDataSet).Data[Hi]; (FCounter as TIntDataSet).Data[Hi] := T; if (Lo = Mid) and (Hi <> Mid) then Mid := Hi else if (Hi = Mid) and (Lo <> Mid) then Mid := Lo; Inc(Lo); Dec(Hi); end; until Lo > Hi; if Hi > _min then QuickSortElementsAscendent(_min, Hi); if Lo < _max then QuickSortElementsAscendent(Lo, _max); end; procedure THistogram.QuickSortElementsDescendent(_min, _max : integer); var Lo, Hi, Mid, T: Integer; A : real; begin Lo := _min; Hi := _max; Mid := (Lo + Hi) div 2; repeat while ((FElements as TSingleDataSet).Data[Lo] - (FElements as TSingleDataSet).Data[Mid]) > 0 do Inc(Lo); while ((FElements as TSingleDataSet).Data[Hi] - (FElements as TSingleDataSet).Data[Mid]) < 0 do Dec(Hi); if Lo <= Hi then begin A := (FElements as TSingleDataSet).Data[Lo]; (FElements as TSingleDataSet).Data[Lo] := (FElements as TSingleDataSet).Data[Hi]; (FElements as TSingleDataSet).Data[Hi] := A; T := (FCounter as TIntDataSet).Data[Lo]; (FCounter as TIntDataSet).Data[Lo] := (FCounter as TIntDataSet).Data[Hi]; (FCounter as TIntDataSet).Data[Hi] := T; if (Lo = Mid) and (Hi <> Mid) then Mid := Hi else if (Hi = Mid) and (Lo <> Mid) then Mid := Lo; Inc(Lo); Dec(Hi); end; until Lo > Hi; if Hi > _min then QuickSortElementsDescendent(_min, Hi); if Lo < _max then QuickSortElementsDescendent(Lo, _max); end; procedure THistogram.QuickSortCounterAscendent(_min, _max : integer); var Lo, Hi, Mid, T: Integer; A : real; begin Lo := _min; Hi := _max; Mid := (Lo + Hi) div 2; repeat while ((FCounter as TIntDataSet).Data[Lo] - (FCounter as TIntDataSet).Data[Mid]) < 0 do Inc(Lo); while ((FCounter as TIntDataSet).Data[Hi] - (FCounter as TIntDataSet).Data[Mid]) > 0 do Dec(Hi); if Lo <= Hi then begin A := (FElements as TSingleDataSet).Data[Lo]; (FElements as TSingleDataSet).Data[Lo] := (FElements as TSingleDataSet).Data[Hi]; (FElements as TSingleDataSet).Data[Hi] := A; T := (FCounter as TIntDataSet).Data[Lo]; (FCounter as TIntDataSet).Data[Lo] := (FCounter as TIntDataSet).Data[Hi]; (FCounter as TIntDataSet).Data[Hi] := T; if (Lo = Mid) and (Hi <> Mid) then Mid := Hi else if (Hi = Mid) and (Lo <> Mid) then Mid := Lo; Inc(Lo); Dec(Hi); end; until Lo > Hi; if Hi > _min then QuickSortCounterAscendent(_min, Hi); if Lo < _max then QuickSortCounterAscendent(Lo, _max); end; procedure THistogram.QuickSortCounterDescendent(_min, _max : integer); var Lo, Hi, Mid, T: Integer; A : real; begin Lo := _min; Hi := _max; Mid := (Lo + Hi) div 2; repeat while ((FCounter as TIntDataSet).Data[Lo] - (FCounter as TIntDataSet).Data[Mid]) > 0 do Inc(Lo); while ((FCounter as TIntDataSet).Data[Hi] - (FCounter as TIntDataSet).Data[Mid]) < 0 do Dec(Hi); if Lo <= Hi then begin A := (FElements as TSingleDataSet).Data[Lo]; (FElements as TSingleDataSet).Data[Lo] := (FElements as TSingleDataSet).Data[Hi]; (FElements as TSingleDataSet).Data[Hi] := A; T := (FCounter as TIntDataSet).Data[Lo]; (FCounter as TIntDataSet).Data[Lo] := (FCounter as TIntDataSet).Data[Hi]; (FCounter as TIntDataSet).Data[Hi] := T; if (Lo = Mid) and (Hi <> Mid) then Mid := Hi else if (Hi = Mid) and (Lo <> Mid) then Mid := Lo; Inc(Lo); Dec(Hi); end; until Lo > Hi; if Hi > _min then QuickSortCounterDescendent(_min, Hi); if Lo < _max then QuickSortCounterDescendent(Lo, _max); end; end.
unit htRows; interface uses Windows, SysUtils, Types, Classes, Controls, Graphics, htInterfaces, htMarkup; type ThtCustomRows = class(TCustomControl, IhtGenerator) protected procedure AlignControls(AControl: TControl; var Rect: TRect); override; procedure Paint; override; public constructor Create(inOwner: TComponent); override; procedure Generate(inMarkup: ThtMarkup); end; // ThtRows = class(ThtCustomRows) published property Align; property Visible; end; implementation uses LrControlIterator, LrVclUtils; { ThtCustomRows } constructor ThtCustomRows.Create(inOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [ csAcceptsControls ]; end; procedure ThtCustomRows.Paint; begin inherited; with Canvas do begin SetBkColor(Handle, ColorToRgb(Brush.Color)); //SetBkMode(Handle, TRANSPARENT); Brush.Style := bsHorizontal; Brush.Color := ColorToRgb(clSilver); Pen.Style := psClear; Rectangle(ClientRect); Brush.Style := bsSolid; Pen.Style := psSolid; //SetBkMode(Handle, OPAQUE); end; end; procedure ThtCustomRows.AlignControls(AControl: TControl; var Rect: TRect); var i: Integer; begin for i := 0 to Pred(ControlCount) do Controls[i].Align := alTop; inherited; end; procedure ThtCustomRows.Generate(inMarkup: ThtMarkup); var g: IhtGenerator; begin with TLrSortedCtrlIterator.Create(Self, alTop) do try while Next do begin inMarkup.Styles.Add(Format( '#%s { width:100%%; height:%dpx; border:1px solid black; }', [ Ctrl.Name, Ctrl.Height ])); inMarkup.Add(Format(' <div id="%s">', [ Ctrl.Name ])); // if (LrIsAs(Ctrl, IhtGenerator, g)) then g.Generate(inMarkup) else inMarkup.Add(Ctrl.Name); // inMarkup.Add(' <span style=" vertical-align:middle;">' + Ctrl.Name + '</span>'); // inMarkup.Add(' </div>'); end; finally Free; end; end; end.
UNIT UFonctions; INTERFACE USES UStructures, UEquipes,UPointeurs,UAffichage; FUNCTION listeAdvPossible (c1,c2 : chapeau) : AdvPoss; FUNCTION selectionDeLEquipeDuC2(VAR c2:chapeau):equipe; FUNCTION eltAppartientALaListe(equ : equipe ; tete : ptrNoeud) : BOOLEAN; FUNCTION matchPossible (e1,e2 : equipe): BOOLEAN; PROCEDURE creerAdv(eSelec: equipe; teteBlacklist : ptrNoeud; VAR teteAdv : ptrNoeud; VAR c1 : chapeau); PROCEDURE effacerEquipe(e :equipe; VAR c : chapeau); PROCEDURE rajouterEquipe (VAR c : chapeau; eq : equipe); IMPLEMENTATION //determine la liste des adv possible des equipes du chapeau 2 dans le chapeau 1 FUNCTION listeAdvPossible (c1,c2 : chapeau) : AdvPoss; VAR i,j : INTEGER; t : AdvPoss; BEGIN FOR i := 1 TO 8 DO BEGIN t[i] := creerNoeud(copierEq(c2[i])); // tete = equipe du c2 afficherListe(t[i]); FOR j:= 1 TO 8 DO BEGIN IF matchPossible(c2[i],c1[j]) THEN ajouterDebut(c1[j],t[i]); END; writeln('liste de ',t[i]^.eq.nom); afficherListe(t[i]); writeln; END; listeAdvPossible := t; END; //Choix d'une équipe du chapeau 2 FUNCTION selectionDeLEquipeDuC2(VAR c2:chapeau):equipe; VAR i : INTEGER; BEGIN Randomize; i := Random(8)+1; WHILE c2[i].nom = 'V' DO i:= Random(8)+1; selectionDeLEquipeDuC2 := copierEq(c2[i]); END; //détermine si e1 peut affronter e2 avec les conditions basiques FUNCTION matchPossible (e1,e2 : equipe): BOOLEAN; BEGIN IF ((e1.nom = 'V') OR (e2.nom = 'V')) THEN matchPossible := FALSE // pour prévenir le choix dans l'avancement du tirage ELSE IF e1.pays <> e2.pays THEN IF e1.grp <> e2.grp THEN IF e1.rg <> e2.rg THEN IF e1.nom <> e2.nom THEN matchPossible := TRUE ELSE matchPossible := FALSE ELSE matchPossible := FALSE ELSE matchPossible := FALSE ELSE matchPossible := FALSE; END; // verifie si une equipe est dans la blacklist FUNCTION eltAppartientALaListe(equ : equipe ; tete : ptrNoeud) : BOOLEAN; VAR bool : BOOLEAN; tmp : ptrNoeud; BEGIN //si ma liste est vide alors appartient pas IF (tete = Nil) THEN eltAppartientALaListe := FALSE ELSE BEGIN bool := FALSE; // on suppose que l'équipe en question n'appartient pas à la liste tmp := tete; WHILE (tmp <> Nil) DO BEGIN //on verifie si l'element en parametre match avec l'element actuelle IF tmp^.eq.nom = equ.nom THEN BEGIN bool := TRUE; // si elle appartient on passe à true END; tmp := tmp^.suivant; END; eltAppartientALaListe := bool; END; END; //établi la liste des adversaires possibles poutr chaque tirage PROCEDURE creerAdv(eSelec: equipe; teteBlacklist : ptrNoeud; VAR teteAdv : ptrNoeud; VAR c1 : chapeau); VAR i : INTEGER; BEGIN FOR i := 1 TO 8 DO BEGIN //si on est dans une case "vide" alors on passe à la suivante IF (c1[i].nom <> 'V') THEN IF (NOT eltAppartientALaListe(c1[i],teteBlacklist)) THEN IF matchPossible(eSelec,c1[i]) THEN ajouterDebut(copierEq(c1[i]),teteAdv); END; END; //efface une équipe du chapeau de départ pour ne pas le tirer 2 fois PROCEDURE effacerEquipe(e :equipe; VAR c : chapeau); VAR i : INTEGER; evide : equipe; BEGIN initEVide(evide); FOR i := 1 TO 8 DO IF (c[i].nom = e.nom) THEN c[i] := evide; END; //rajoute une equipe au chapeau donné PROCEDURE rajouterEquipe (VAR c : chapeau; eq : equipe); VAR i : INTEGER; BEGIN i := 1; WHILE ( i <= 8 ) AND (c[i].nom <> 'V') DO Inc(i); c[i] := copierEq(eq); END; END.
unit uGlobal; interface uses Windows, Forms, SysUtils, StrUtils, Variants, Classes, Graphics, Registry, Menus, Quiz, jpeg, PngImage, GifImage, ShlObj, ShellAPI, ActiveX, FlashObjects; const APP_CAPTION = '秋风试题大师'; AW_HOMEPAGE = 'http://www.awindsoft.net'; HH_DISPLAY_TOPIC = $0000; QUIZ_TEMPLET = 'templet.swf'; MAX_QUES_COUNT = 15; type TRegType = (rtNone, rtTrial, rtUnReged); TApp = class private FCaption: string; FPath: string; FTmpPath: string; FTmpJpg: string; FExeName: string; FRegistry: TRegistry; FWindowState: TWindowState; FShowCount: Boolean; //注册信息 FRegMail: string; FRegCode: string; function GetVersion: string; function GetRegType: TRegType; procedure GetTemplet; //注册aqb文件类型 procedure RegAqbFile; //写Flash播放器信任文件 procedure WriteFlashTrustFile; //从注册表读值 procedure LoadFromReg; public constructor Create; destructor Destroy; override; //存入注册表...开启public是因为要在reg窗体即时写入注册表 procedure SaveToReg; //加载最近试题列表 procedure LoadRecentDocs(AMenuItem: TMenuItem; MenuItemClick: TNotifyEvent); //存储最近试题列表 procedure SaveRecentDocs; property Caption: string read FCaption; property Path: string read FPath; property TmpPath: string read FTmpPath; property TmpJpg: string read FTmpJpg; property ExeName: string read FExeName; property Version: string read GetVersion; property WindowState: TWindowState read FWindowState write FWindowState; property ShowCount: Boolean read FShowCount write FShowCount; //版本类型 property RegType: TRegType read GetRegType; property RegMail: string read FRegMail write FRegMail; property RegCode: string read FRegCode write FRegCode; end; resourcestring sAqbFiler = '试题工程文件 (*.aqb)|*.aqb'; sXlsFilter = 'Microsoft Excel 文件(*.xls; *.xlsx)|*.xls;*.xlsx'; //获取图片大小 function GetImageSize(const AImgFile: string): TSize; //处理图片 function DealImage(const AImgFile: string; AMaxWidth: Integer = 640; AMaxHeight: Integer = 480): Boolean; //是否是可处理的图片 function GetDealImgStr(const AImgFile: string): string; //获取图片流 function GetImageStream(AImgFile: string): TStream; //Delphi之Color转换为Flash之Color function GetColorStr(AColor: TColor): WideString; //选择文件夹 function SelectDirectory(Handle: HWND; const Caption, DefaultDir: string; out Directory: string): Boolean; function BoolToLowerStr(AValue: Boolean): string; //清空文件夹 function DeleteDirectory(const AFolder: string): Boolean; //复制文件夹 function CopyFolder(const AFrom, ATo: string): Boolean; //是否可以再添加 function GetCanAdd(AHandle: Integer): Boolean; //调用dll...以检测注册情况及初始化影片 //检测注册码是否正确 function CheckRegCode(const AKey, ACode: string): Boolean; export; stdcall; //生成FlashMovie function BuildMovie(const AWidth, AHeight: Integer; const AFps: Integer = 12): TFlashMovie; stdcall; //调用帮助文件 function HtmlHelp(hwd: THandle; pszFile: string; uCommand, dwData: Integer): Integer; stdcall; var App: TApp; implementation const DLL_NAME = 'AWQuiz.dll'; function CheckRegCode; stdcall; external DLL_NAME name 'Autumn'; function BuildMovie; stdcall; external DLL_NAME name 'Wind'; function HtmlHelp; stdcall; external 'HHCtrl.ocx' name 'HtmlHelpA'; //获取图片大小 function GetImageSize(const AImgFile: string): TSize; var pic: TPicture; begin Result.cx := 0; Result.cy := 0; if not FileExists(AImgFile) then Exit; pic := TPicture.Create; try pic.LoadFromFile(AImgFile); Result.cx := pic.Width; Result.cy := pic.Height; finally pic.Free; end; end; //处理图片 function DealImage(const AImgFile: string; AMaxWidth, AMaxHeight: Integer): Boolean; var pic: TPicture; bmp: TBitmap; jpg: TJPEGImage; fScale: Single; iWidth, iHeight: Integer; begin Result := False; if not FileExists(AImgFile) then Exit; pic := TPicture.Create; bmp := TBitmap.Create; jpg := TJPEGImage.Create; try try pic.LoadFromFile(AImgFile); if (pic.Width > AMaxWidth) or (pic.Height > AMaxHeight) then begin fScale := AMaxHeight / AMaxWidth; if (pic.Height / pic.Width) > fScale then begin iWidth := Round(pic.Width * AMaxHeight / pic.Height); iHeight := AMaxHeight; end else begin iWidth := AMaxWidth; iHeight := Round(pic.Height * AMaxWidth / pic.Width); end; end else begin iWidth := pic.Width; iHeight := pic.Height; end; bmp.PixelFormat := pf24bit; bmp.Width := iWidth; bmp.Height := iHeight; bmp.Canvas.StretchDraw(Rect(0, 0, iWidth, iHeight), pic.Graphic); jpg.Assign(bmp); jpg.SaveToFile(App.TmpJpg); Result := True; except Result := False; end; finally pic.Free; bmp.Free; jpg.Free; end; end; function GetDealImgStr(const AImgFile: string): string; var sExt: string; begin sExt := LowerCase(ExtractFileExt(AImgFile)); if (Pos(sExt, '.swf.gif.jpg') = 0) then Result := ChangeFileExt(AImgFile, '.jpg') else Result := AImgFile; end; function GetImageStream(AImgFile: string): TStream; var jpg: TJPEGImage; begin jpg := TJPEGImage.Create; try jpg.LoadFromFile(AImgFile); Result := TMemoryStream.Create; jpg.SaveToStream(Result); finally jpg.Free; end; end; function GetColorStr(AColor: TColor): WideString; begin Result := '0x' + IntToHex(GetRValue(AColor), 2) + IntToHex(GetGValue(AColor), 2) + IntToHex(GetBValue(AColor), 2); end; function SelectDirectory(Handle: HWND; const Caption, DefaultDir: string; out Directory: string): Boolean; function BrowseCallBackProc(Wnd: HWND; uMsg: UINT; lParam, lpData: LPARAM): Integer stdcall; begin if uMsg = BFFM_INITIALIZED then Result := SendMessage(Wnd, BFFM_SETSELECTION, Ord(TRUE), lpData) else Result := 1; end; var bi: _browseinfoA; pid: PItemIDList; buf: array[0..MAX_PATH - 1] of Char; begin Directory := DefaultDir; FillChar(bi, SizeOf(BROWSEINFO), 0); bi.hWndOwner := Handle; bi.iImage := 0; bi.lParam := 1; bi.lpfn := nil; bi.lpszTitle := PAnsiChar(Caption); bi.ulFlags := BIF_RETURNONLYFSDIRS; bi.lpfn := @BrowseCallBackProc; bi.lParam := Integer(PAnsiChar(DefaultDir)); pid := SHBrowseForFolder(bi); Result := pid <> nil; if Result and SHGetPathFromIDList(pid, buf) then begin Directory := StrPas(buf); if Directory[Length(Directory)] <> '\' then Directory := Directory + '\'; end; end; function BoolToLowerStr(AValue: Boolean): string; begin Result := LowerCase(BoolToStr(AValue, True)); end; function DeleteDirectory(const AFolder: string): Boolean; var fo: TSHFILEOPSTRUCT; begin FillChar(fo, SizeOf(fo), 0); with fo do begin Wnd := 0; wFunc := FO_DELETE; pFrom := PChar(AFolder + #0); pTo := #0; fFlags := FOF_NOCONFIRMATION + FOF_SILENT; end; Result := SHFileOperation(fo) = 0; end; function CopyFolder(const AFrom, ATo: string): Boolean; Var fo: TSHFileOpStruct; begin with fo do begin Wnd := 0; wFunc := FO_Copy; pFrom := PAnsiChar(AFrom + #0); pTo := PAnsiChar(ATo + #0); fFlags := FOF_NOCONFIRMATION or FOF_SILENT; end; Result := ShFileOperation(fo) = 0; end; { TApp } constructor TApp.Create; begin CoInitialize(nil); SetWindowLong(Application.Handle, GWL_EXSTYLE, GetWindowLong(Application.Handle, GWL_EXSTYLE) or not WS_EX_APPWINDOW); FCaption := APP_CAPTION; FPath := ExtractFilePath(Application.ExeName); FTmpPath := ExtractFilePath(Application.ExeName) + 'temp\'; FTmpJpg := FTmpPath + 'tmp.jpg'; if not DirectoryExists(FTmpPath) then ForceDirectories(FTmpPath); FExeName := Application.ExeName; FWindowState := wsMaximized; FRegistry := TRegistry.Create; FRegistry.RootKey := HKEY_CURRENT_USER; LoadFromReg(); //释放播放器模板 GetTemplet; //注册aqb文件 RegAqbFile; //写Flash信任文件 WriteFlashTrustFile; end; destructor TApp.Destroy; begin SaveToReg(); FRegistry.Free; WinExec(PAnsiChar('cmd.exe /c rmdir /s/q "' + FTmpPath + '"'), SW_HIDE); CoUninitialize(); inherited Destroy; end; procedure TApp.LoadFromReg; begin with FRegistry do begin if not KeyExists(QUIZ_KEY_NAME) then Exit; OpenKey(QUIZ_KEY_NAME, False); if ValueExists('WindowState') then FWindowState := TWindowState(ReadInteger('WindowState')); if FWindowState = wsMinimized then FWindowState := wsNormal; if ValueExists('ShowCount') then FShowCount := ReadBool('ShowCount'); if RegType = rtTrial then begin if ValueExists('RegMail') then DeleteValue('RegMail'); if ValueExists('RegCode') then DeleteValue('RegCode'); end else begin if ValueExists('RegMail') then FRegMail := ReadString('RegMail'); if ValueExists('RegCode') then FRegCode := ReadString('RegCode'); end; CloseKey(); end; end; procedure TApp.SaveToReg; begin with FRegistry do begin if not OpenKey(QUIZ_KEY_NAME, True) then Exit; WriteInteger('WindowState', Ord(FWindowState)); WriteBool('ShowCount', FShowCount); if RegType <> rtTrial then begin WriteString('RegMail', FRegMail); WriteString('RegCode', FRegCode); end; CloseKey(); end; end; function TApp.GetVersion: string; var InfoSize, Wnd: DWORD; VerBuf: Pointer; szName: array[0..MAX_PATH - 1] of Char; Value: Pointer; Len: UINT; TransString: string; begin InfoSize := GetFileVersionInfoSize(PChar(FExeName), Wnd); if InfoSize <> 0 then begin GetMem(VerBuf, InfoSize); try if GetFileVersionInfo(PChar(FExeName), Wnd, InfoSize, VerBuf) then begin Value :=nil; VerQueryValue(VerBuf, '\VarFileInfo\Translation', Value, Len); if Value <> nil then TransString := IntToHex(MakeLong(HiWord(Longint(Value^)), LoWord(Longint(Value^))), 8); Result := ''; StrPCopy(szName, '\StringFileInfo\'+Transstring+'\FileVersion'); //ProductVersion: 产品版本 if VerQueryValue(VerBuf, szName, Value, Len) then Result := StrPas(PChar(Value)); end; finally FreeMem(VerBuf); end; end; end; function TApp.GetRegType: TRegType; begin {$IFDEF _TRIAL} Result := rtTrial; {$ELSE} if CheckRegCode(FRegMail, FRegCode) then Result := rtNone else Result := rtUnReged; {$ENDIF} end; procedure TApp.GetTemplet; var h: HMODULE; Stream: TResourceStream; begin h := LoadLibrary('AWQuiz.dll'); try Stream := TResourceStream.Create(h, 'templet', 'SWF'); Stream.SaveToFile(FTmpPath + QUIZ_TEMPLET); Stream.Free; finally FreeLibrary(h); end; end; //注册aqb文件类型 procedure TApp.RegAqbFile; var reg: TRegistry; begin reg := TRegistry.Create; reg.RootKey := HKEY_CLASSES_ROOT; try if reg.KeyExists('.aqb') then Exit; reg.OpenKey('.aqb', True); reg.WriteString('', 'aqbFile'); reg.CloseKey(); reg.OpenKey('aqbFile\DefaultIcon', True); reg.WriteString('', Application.ExeName + ',1'); reg.CloseKey(); reg.OpenKey('aqbFile\shell\open\command', True); reg.WriteString('', '"' + Application.ExeName + '" "%1"'); reg.CloseKey(); finally reg.Free; end; end; procedure TApp.WriteFlashTrustFile; function GetSystemPath: string; var buf: array [0..MAX_PATH - 1] of Char; begin GetSystemDirectory(buf, MAX_PATH); Result := StrPas(buf) + '\'; end; var sTrustFile, sSystemPath: string; sl: TStrings; Drives: set of 0..25; Drive: Integer; DrivePath: string; begin sSystemPath := GetSystemPath; sTrustFile := sSystemPath + 'Macromed\Flash\FlashPlayerTrust\AW_TrustFile.cfg'; if FileExists(sTrustFile) then Exit; if not DirectoryExists(sSystemPath + 'Macromed\Flash\FlashPlayerTrust\') then ForceDirectories(sSystemPath + 'Macromed\Flash\FlashPlayerTrust\'); sl := TStringList.Create; sl.Append('# 秋风试题大师之Flash Player安全信任文件'); try DWORD(Drives) := GetLogicalDrives; for Drive := 0 to 25 do if Drive in Drives then begin DrivePath := Char(Ord('A') + Drive) + ':'; if GetDriveType(PAnsiChar(DrivePath)) = DRIVE_FIXED then sl.Append(DrivePath + '\'); end; try sl.SaveToFile(sTrustFile); except //do nothing end; finally sl.Free; end; end; function GetCanAdd(AHandle: Integer): Boolean; begin if (App.RegType <> rtNone) and (QuizObj.QuesList.Count >= MAX_QUES_COUNT) then begin Result := False; if App.RegType = rtTrial then MessageBox(AHandle, PAnsiChar('试用版只能添加' + IntToStr(MAX_QUES_COUNT) + '条试题,您已不能再添加'), '提示', MB_OK + MB_ICONINFORMATION) else MessageBox(AHandle, PAnsiChar('未注册版只能添加' + IntToStr(MAX_QUES_COUNT) + '条试题,您已不能再添加'), '提示', MB_OK + MB_ICONINFORMATION); end else Result := True; end; procedure TApp.LoadRecentDocs(AMenuItem: TMenuItem; MenuItemClick: TNotifyEvent); var sl: TStrings; i: Integer; mi: TMenuItem; sProj: string; begin if not FRegistry.KeyExists(QUIZ_KEY_NAME + '\RecentDocs') then Exit; //删除原有值 for i := AMenuItem.Count - 1 downto 0 do if Pos('miQuiz', AMenuItem.Items[i].Name) <> 0 then AMenuItem.Items[i].Free; sl := TStringList.Create; try //有ReadOnly后,其后所用到的赋值都会错误,故不用 //FRegistry.OpenKeyReadOnly(QUIZ_KEY_NAME + '\RecentDocs'); FRegistry.OpenKey(QUIZ_KEY_NAME + '\RecentDocs', False); FRegistry.GetValueNames(sl); if sl.Count > 0 then begin for i := 0 to sl.Count - 1 do begin sProj := FRegistry.ReadString(IntToStr(i + 1)); if not FileExists(sProj) then Continue; mi := TMenuItem.Create(AMenuItem); mi.Name := 'miQuiz' + IntToStr(i + 1); mi.Caption := sProj; mi.OnClick := MenuItemClick; AMenuItem.Insert(AMenuItem.Count - 1, mi); end; //插入分隔条 mi := TMenuItem.Create(AMenuItem); mi.Caption := '-'; AMenuItem.Insert(AMenuItem.Count - 1, mi); end; FRegistry.CloseKey(); finally sl.Free; end; end; procedure TApp.SaveRecentDocs; var sl: TStrings; i, Count: Integer; sProj: string; begin if not FileExists(QuizObj.ProjPath) or (LowerCase(ExtractFileExt(QuizObj.ProjPath)) <> '.aqb') then Exit; if not FRegistry.OpenKey(QUIZ_KEY_NAME + '\RecentDocs', True) then Exit; sl := TStringList.Create; try FRegistry.GetValueNames(sl); Count := sl.Count; sl.Clear; sl.Append(QuizObj.ProjPath); //载入原始值... for i := 0 to Count - 1 do if FRegistry.ValueExists(IntToStr(i + 1)) then begin sProj := FRegistry.ReadString(IntToStr(i + 1)); if sl.IndexOf(sProj) = -1 then sl.Append(FRegistry.ReadString(IntToStr(i + 1))); end; //存入新值 for i := 0 to sl.Count - 1 do begin if i = QUIZ_MAX_LIST then Break; FRegistry.WriteString(IntToStr(i + 1), sl[i]); end; FRegistry.CloseKey(); finally sl.Free; end; end; end.
unit BaseUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls; type TMainForm = class(TForm) CreationDate: TDateTimePicker; OpenDialog: TOpenDialog; FileNameField: TEdit; OpenFileButton: TButton; Label1: TLabel; CreationTime: TDateTimePicker; Label2: TLabel; ChangeDate: TDateTimePicker; ChangeTime: TDateTimePicker; SaveButton: TButton; Label3: TLabel; LastAccessDate: TDateTimePicker; LastAccessTime: TDateTimePicker; procedure OpenFileButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FileNameFieldDblClick(Sender: TObject); procedure SaveButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.dfm} procedure GetFileInfo(const FileName: String; out CreationTime, ModificationTime, LastAccesTime: TDateTime); var FileAttributeData: TWin32FileAttributeData; SystemTime: TSystemTime; begin ZeroMemory(@FileAttributeData, SizeOf(TWin32FileAttributeData)); GetFileAttributesEx(PAnsiChar(FileName), GetFileExInfoStandard, @FileAttributeData); FileTimeToLocalFileTime(FileAttributeData.ftCreationTime, FileAttributeData.ftCreationTime); FileTimeToSystemTime(FileAttributeData.ftCreationTime, SystemTime); CreationTime := SystemTimeToDateTime(SystemTime); FileTimeToLocalFileTime(FileAttributeData.ftLastWriteTime, FileAttributeData.ftLastWriteTime); FileTimeToSystemTime(FileAttributeData.ftLastWriteTime, SystemTime); ModificationTime := SystemTimeToDateTime(SystemTime); FileTimeToLocalFileTime(FileAttributeData.ftLastAccessTime, FileAttributeData.ftLastAccessTime); FileTimeToSystemTime(FileAttributeData.ftLastAccessTime, SystemTime); LastAccesTime := SystemTimeToDateTime(SystemTime); end; function GetFileTime(DateTime: TDateTime): TFileTime; var SystemTime: TSystemTime; LocalFileTime, FileTime: TFileTime; begin DateTimeToSystemTime(DateTime, SystemTime); SystemTimeToFileTime(SystemTime, LocalFileTime); LocalFileTimeToFileTime(LocalFileTime, FileTime); Result := FileTime; end; procedure SetFileInfo(const FileName: String; CreationTime, ModificationTime, LastAccesTime: TDateTime); var FileHandle: integer; CreationFileTime, ModificationFileTime, LastAccessFileTime: TFileTime; begin FileHandle := CreateFile(PChar(FileName), GENERIC_WRITE, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); try CreationFileTime := GetFileTime(CreationTime); ModificationFileTime := GetFileTime(ModificationTime); LastAccessFileTime := GetFileTime(LastAccesTime); SetFileTime(FileHandle, @CreationFileTime, @LastAccessFileTime, @ModificationFileTime); finally CloseHandle(FileHandle); end; end; procedure TMainForm.OpenFileButtonClick(Sender: TObject); var creationDateTime, modificationDateTime, lastAccessDateTime: TDateTime; begin if (OpenDialog.Execute) then begin FileNameField.Text := OpenDialog.FileName; ChangeDate.Enabled := true; ChangeTime.Enabled := true; CreationDate.Enabled := true; CreationTime.Enabled := true; LastAccessDate.Enabled := true; LastAccessTime.Enabled := true; SaveButton.Enabled := true; ChangeDate.Format := 'dd MMMM yyyy'; ChangeTime.Format := 'HH:mm:ss'; CreationDate.Format := 'dd MMMM yyyy'; CreationTime.Format := 'HH:mm:ss'; LastAccessDate.Format := 'dd MMMM yyyy'; LastAccessTime.Format := 'HH:mm:ss'; GetFileInfo(OpenDialog.FileName, creationDateTime, modificationDateTime, lastAccessDateTime); CreationDate.DateTime := creationDateTime; CreationTime.DateTime := creationDateTime; ChangeDate.DateTime := modificationDateTime; ChangeTime.DateTime := modificationDateTime; LastAccessDate.DateTime := lastAccessDateTime; LastAccessTime.DateTime := lastAccessDateTime; end; end; procedure TMainForm.FormCreate(Sender: TObject); begin ChangeDate.Format := ''''''; ChangeTime.Format := ''''''; CreationDate.Format := ''''''; CreationTime.Format := ''''''; LastAccessDate.Format := ''''''; LastAccessTime.Format := ''''''; end; procedure TMainForm.FileNameFieldDblClick(Sender: TObject); begin OpenFileButtonClick(Sender); end; procedure TMainForm.SaveButtonClick(Sender: TObject); begin CreationDate.Time := CreationTime.Time; ChangeDate.Time := ChangeTime.Time; LastAccessDate.Time := LastAccessTime.Time; SetFileInfo(OpenDialog.FileName, CreationDate.DateTime, ChangeDate.Time, LastAccessDate.DateTime); ShowMessage('Настройки успешно сохранены'); end; end.
unit NewFrontiers.Configuration; interface uses Generics.Collections; type /// <summary> /// Basis-Interface für alle Arten der Konfiguration. Intern werden /// Hierarchie-Ebenen mit Punkten als Trennern angegeben. Also z.B. /// database.server oder sysmon.server. Die konkreten Implementierungen des /// Interfaces müssen das dann entsrpechend Umsetzen, z.B. in Sections in /// einem INI-File oder Ordnern in der Registry. /// </summary> IConfiguration = interface(IInterface) /// <summary> /// Gibt den Wert eines Konfigurationsschlüssels als String aus /// </summary> /// <param name="aName"> /// Schlüsselname /// </param> /// <param name="aDefault"> /// Default-Wert, wenn der Schlüssel nicht gefunden werden konnte /// </param> /// <returns> /// Der Wert des Schlüssels /// </returns> function getString(aName: string; aDefault: string = ''): string; /// <summary> /// Gibt den Wert eines Konfigurationsschlüssels als Integer aus /// </summary> /// <param name="aName"> /// Schlüsselname /// </param> /// <param name="aDefault"> /// Default-Wert, wenn der Schlüssel nicht gefunden werden konnte /// </param> /// <returns> /// Der Wert des Schlüssels /// </returns> function getInteger(aName: string; aDefault: integer = 0): integer; /// <summary> /// Gibt den Wert eines Konfigurationsschlüssels als Integer aus /// </summary> /// <param name="aName"> /// Schlüsselname /// </param> /// <param name="aDefault"> /// Default-Wert, wenn der Schlüssel nicht gefunden werden konnte /// </param> /// <returns> /// Der Wert des Schlüssels /// </returns> function getBoolean(aName: string; aDefault: boolean = false): boolean; /// <summary> /// Gibt den Wert eines Konfigurationsschlüssels als Integer aus /// </summary> /// <param name="aName"> /// Schlüsselname /// </param> /// <param name="aDefault"> /// Default-Wert, wenn der Schlüssel nicht gefunden werden konnte /// </param> /// <returns> /// Der Wert des Schlüssels /// </returns> function getDateTime(aName: string; aDefault: TDateTime = 0): TDateTime; /// <summary> /// Setzt den Wert eines Schlüssels in der Konfiguration. Damit der /// Wert persistiert wird, muss saveConfiguration aufgerufen werden. /// </summary> /// <param name="aName"> /// Schlüsselname /// </param> /// <param name="aValue"> /// Neuer Wert des Schlüssels /// </param> /// <returns> /// true, falls der Schlüssel gesetzt werden konnte /// </returns> function setString(aName, aValue: string): boolean; /// <summary> /// Setzt den Wert eines Schlüssels in der Konfiguration. Damit der /// Wert persistiert wird, muss saveConfiguration aufgerufen werden. /// </summary> /// <param name="aName"> /// Schlüsselname /// </param> /// <param name="aValue"> /// Neuer Wert des Schlüssels /// </param> /// <returns> /// true, falls der Schlüssel gesetzt werden konnte /// </returns> function setInteger(aName: string; aValue: integer): boolean; /// <summary> /// Setzt den Wert eines Schlüssels in der Konfiguration. Damit der /// Wert persistiert wird, muss saveConfiguration aufgerufen werden. /// </summary> /// <param name="aName"> /// Schlüsselname /// </param> /// <param name="aValue"> /// Neuer Wert des Schlüssels /// </param> /// <returns> /// true, falls der Schlüssel gesetzt werden konnte /// </returns> function setBoolean(aName: string; aValue: boolean): boolean; /// <summary> /// Setzt den Wert eines Schlüssels in der Konfiguration. Damit der /// Wert persistiert wird, muss saveConfiguration aufgerufen werden. /// </summary> /// <param name="aName"> /// Schlüsselname /// </param> /// <param name="aValue"> /// Neuer Wert des Schlüssels /// </param> /// <returns> /// true, falls der Schlüssel gesetzt werden konnte /// </returns> function setDateTime(aName: string; aValue: TDateTime): boolean; end; /// <summary> /// Der Configuration-Manager verwaltet die unterschiedlichen /// Konfigurationsquellen und ermöglicht das Lesen und Schreiben der /// Konfiguration. Implementiert als Singleton, so dass er auch genutzt /// werden kann, wenn keine Dependency Injection möglich ist. /// </summary> TConfigurationManager = class protected _configurationSources: TDictionary<string, IConfiguration>; constructor Create; public destructor Destroy; override; /// <summary> /// Gibt die Instanz des Managers zurück. Existiert noch keine, wird /// eine neue Instanz angelegt. /// </summary> class function getInstance: TConfigurationManager; /// <summary> /// Gibt einen Konfigurationswert zurück /// </summary> /// <param name="aSchluessel"> /// Schlüssel der Form quelle://schluessel /// </param> class function getString(aSchluessel: string): string; /// <summary> /// Gibt einen Konfigurationswert zurück /// </summary> /// <param name="aSchluessel"> /// Schlüssel der Form quelle://schluessel /// </param> class function getInteger(aSchluessel: string): integer; /// <summary> /// Gibt einen Konfigurationswert zurück /// </summary> /// <param name="aSchluessel"> /// Schlüssel der Form quelle://schluessel /// </param> class function getBoolean(aSchluessel: string): boolean; /// <summary> /// Gibt einen Konfigurationswert zurück /// </summary> /// <param name="aSchluessel"> /// Schlüssel der Form quelle://schluessel /// </param> class function getDateTime(aSchluessel: string): TDateTime; /// <summary> /// Fügt eine weitere Konfigurationsquelle hinzu /// </summary> /// <param name="aName"> /// Schlüsselname der Quelle /// </param> /// <param name="aSource"> /// Die hinzuzufügende Quelle /// </param> procedure addSource(aName: string; aSource: IConfiguration); /// <summary> /// Gibt eine Quelle zurück /// </summary> /// <param name="aName"> /// Name der zurückzugebenden Quelle /// </param> function getSource(aName: string): IConfiguration; end; implementation uses SysUtils, NewFrontiers.Utility.StringUtil; var _instance: TConfigurationManager; { TNfsConfigurationManager } procedure TConfigurationManager.addSource(aName: string; aSource: IConfiguration); var tempSource: IConfiguration; begin if (aSource = nil) then raise EArgumentNilException.Create('Source darf nicht leer sein'); if (_configurationSources.TryGetValue(aName, tempSource)) then raise EArgumentException.Create('Es wurde bereits eine Quelle mit diesem Schlüsselnamen hinzugefügt.'); _configurationSources.Add(aName, aSource); end; constructor TConfigurationManager.Create; begin _configurationSources := TDictionary<string, IConfiguration>.Create(); end; destructor TConfigurationManager.Destroy; begin freeAndNil(_configurationSources); inherited; end; class function TConfigurationManager.getBoolean(aSchluessel: string): boolean; var Source, Key: string; begin TStringUtil.StringParts(aSchluessel, '://', Source, Key); result := TConfigurationManager.getInstance.getSource(Source).getBoolean(Key); end; class function TConfigurationManager.getDateTime( aSchluessel: string): TDateTime; var Source, Key: string; begin TStringUtil.StringParts(aSchluessel, '://', Source, Key); result := TConfigurationManager.getInstance.getSource(Source).getDateTime(Key); end; class function TConfigurationManager.getInstance: TConfigurationManager; begin if (_instance = nil) then _instance := TConfigurationManager.Create; result := _instance; end; class function TConfigurationManager.getInteger( aSchluessel: string): integer; var Source, Key: string; begin TStringUtil.StringParts(aSchluessel, '://', Source, Key); result := TConfigurationManager.getInstance.getSource(Source).getInteger(Key); end; function TConfigurationManager.getSource(aName: string): IConfiguration; begin result := _configurationSources.Items[aName]; if (result = nil) then raise Exception.Create('Konfigurationsquelle ' + aName + ' nicht gefunden!'); end; class function TConfigurationManager.getString(aSchluessel: string): string; var Source, Key: string; begin TStringUtil.StringParts(aSchluessel, '://', Source, Key); result := TConfigurationManager.getInstance.getSource(Source).getString(Key); end; end.
unit ScanImageUnit; // --------------------------------------------- // MesoScan: Acquire image from selected region // --------------------------------------------- interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, math, LabIOUnit, ImageFile ; type TScanImageFrm = class(TForm) Image1: TImage; ROIPanel: TPanel; lbReadout: TLabel; bZoomIn: TButton; bZoomOut: TButton; procedure FormResize(Sender: TObject); procedure FormCreate(Sender: TObject); procedure bZoomInClick(Sender: TObject); procedure bZoomOutClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure Image1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Image1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormDestroy(Sender: TObject); procedure Image1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); private { Private declarations } DisplayMaxWidth : Integer ; DisplayMaxHeight : Integer ; ZoomFactor : Integer ; XLeft : Integer ; YTop : Integer ; XDown : Integer ; YDown : Integer ; XStep : Integer ; public { Public declarations } Bitmap : TBitmap ; FrameWidth : Integer ; FrameHeight : Integer ; NumPixelsPerFrame : Integer ; FrameWidthMicrons : Double ; PDisplayBuf : PIntArray ; RawSaved : Boolean ; procedure InitialiseImage( Width : Integer ; Height : Integer ; WidthMicrons : Double ) ; procedure UpdateImage( var LUT : Array of Word // Display look-up table [IN] ) ; procedure SaveRawImage( FileName : String ) ; end; var ScanImageFrm: TScanImageFrm; implementation {$R *.dfm} uses MainUnit; procedure TScanImageFrm.bZoomInClick(Sender: TObject); // --------------- // Magnify display // --------------- begin Inc(ZoomFactor) ; Resize ; UpdateImage(MainFrm.LUT) ; end; procedure TScanImageFrm.bZoomOutClick(Sender: TObject); // ----------------- // Demagnify display // ----------------- begin ZoomFactor := Max(ZoomFactor-1,0) ; Resize ; UpdateImage(MainFrm.LUT) ; end; procedure TScanImageFrm.FormCreate(Sender: TObject); begin BitMap := TBitMap.Create ; BitMap.Width := Screen.Width ; BitMap.Width := Screen.Height ; ZoomFactor := 0 ; XLeft := 0 ; YTop := 0 ; XDown := 0 ; YDown := 0 ; XStep := 1 ; end; procedure TScanImageFrm.FormShow(Sender: TObject); // ----------------------------------- // Initialisations when form displayed // ----------------------------------- begin Left := MainFrm.Left + 100 ; Top := MainFrm.Top + 100 ; ClientWidth := (Screen.Width - Left) - (Screen.Width div 6) ; ClientHeight := (Screen.Height - Top) - (Screen.Height div 6) ; Resize ; end; procedure TScanImageFrm.FormDestroy(Sender: TObject); begin //BitMap.ReleasePalette ; BitMap.Free ; end; procedure TScanImageFrm.FormResize(Sender: TObject); // ------------------------------- // Adjust image when form resized // ------------------------------- begin DisplayMaxWidth := ClientWidth - Image1.Left - 5 ; DisplayMaxHeight := ClientHeight - Image1.Top - 5 ; if ZoomFactor <= 0 then begin XStep := Max(Ceil(FrameWidth/DisplayMaxWidth),Ceil(FrameHeight/DisplayMaxHeight)) ; BitMap.Width := Min( FrameWidth div XStep, FrameWidth ) ; BitMap.Height := Min( FrameHeight div XStep, FrameHeight ) ; end else begin XStep := Ceil(FrameWidth/DisplayMaxWidth) ; ZoomFactor := Min(XStep-1,ZoomFactor) ; XStep := XStep - ZoomFactor ; BitMap.Width := Min(FrameWidth div XStep,DisplayMaxWidth) ; BitMap.Height := Min(FrameHeight div XStep,DisplayMaxHeight) ; end; UpdateImage(MainFrm.LUT) ; end ; procedure TScanImageFrm.Image1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); // ------------------- // Mouse down on image // ------------------- begin screen.Cursor := crHandPoint ; XDown := X ; YDown := Y ; end; procedure TScanImageFrm.Image1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); // ---------------------- // Mouse moved over image // ---------------------- var i : Integer ; PixelsToMicrons : Double ; begin i := Y*XStep*FrameWidth + X*XStep ; PixelsToMicrons := FrameWidthMicrons/FrameWidth ; if (i > 0) and (i < FrameWidth*FrameHeight) then begin lbReadout.Caption := format('X=%.5g um, Y=%.5g um, I=%d', [X*XStep*PixelsToMicrons,Y*XStep*PixelsToMicrons,pDisplayBuf[i]]) ; end ; end; procedure TScanImageFrm.Image1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); // ------------------- // Mouse up on image // ------------------- var XRight,YBottom : Integer ; begin Screen.Cursor := crDefault ; XLeft := XLeft - (X - XDown)*XStep ; XRight := Min(XLeft + Bitmap.Width*XStep,FrameWidth) ; XLeft := Max( XRight - Bitmap.Width*XStep, 0 ) ; YTop := YTop - (Y - YDown)*XStep ; YBottom := Min(YTop + Bitmap.Height*XStep,FrameHeight) ; YTop := Max( YBottom - Bitmap.Height*XStep,0) ; UpdateImage( MainFrm.LUT) ; end; procedure TScanImageFrm.InitialiseImage( Width : Integer ; Height : Integer ; WidthMicrons : Double ) ; // ------------------------------------------------------ // Initialise size of memory buffers and image bitmaps // ------------------------------------------------------ var i : Integer ; MaxBuffers : Integer ; begin // No. of pixels per frame FrameWidth := Width ; FrameHeight := Height ; NumPixelsPerFrame := Width*Height ; FrameWidthMicrons := WidthMicrons ; // Dispose of existing display buffers and create new ones if PDisplayBuf <> Nil then begin FreeMem(PDisplayBuf) ; PDisplayBuf := Nil ; end ; GetMem( PDisplayBuf,NumPixelsPerFrame*SizeOf(Integer) ) ; // Set intensity range and sliders MainFrm.SetDisplayIntensityRange( MainFrm.GreyLo,MainFrm.GreyHi ) ; // Update display look up tables MainFrm.UpdateLUT( MainFrm.ADCMaxValue ); resize ; MainFrm.SetPalette( BitMap, MainFrm.PaletteType ) ; Image1.Width := BitMap.Width ; Image1.Height := BitMap.Height ; Image1.Canvas.Pen.Color := clWhite ; Image1.Canvas.Brush.Style := bsClear ; Image1.Canvas.Font.Color := clWhite ; Image1.Canvas.TextFlags := 0 ; Image1.Canvas.Pen.Mode := pmXOR ; Image1.Canvas.Font.Name := 'Arial' ; Image1.Canvas.Font.Size := 8 ; Image1.Canvas.Font.Color := clBlue ; RawSaved := False ; end ; procedure TScanImageFrm.UpdateImage( var LUT : Array of Word // Display look-up table [IN] ) ; // -------------- // Display image // -------------- var Ybm,Yim,Xbm,Xim,i,j,StartOfLine,x,y : Integer ; iStep : Integer ; iDisplayZoom,iz : Integer ; iEnd : Integer ; PScanLine1 : PByteArray ; // Bitmap line buffer pointer PScanLine : PByteArray ; // Bitmap line buffer pointer XRight,YBottom : Integer ; begin // Copy reduced image to bitmap Image1.Width := BitMap.Width ; Image1.Height := BitMap.Height ; Ybm := 0 ; Yim := YTop ; XStep := Max(Ceil(FrameWidth/DisplayMaxWidth),Ceil(FrameHeight/DisplayMaxHeight)) ; ZoomFactor := Min(XStep-1,ZoomFactor) ; XStep := XStep - ZoomFactor ; XRight := Min(XLeft + Bitmap.Width*XStep,FrameWidth) ; XLeft := Max( XRight - Bitmap.Width*XStep, 0 ) ; YBottom := Min(YTop + Bitmap.Height*XStep,FrameHeight) ; YTop := Max( YBottom - Bitmap.Height*XStep,0) ; for Ybm := 0 to BitMap.Height-1 do begin // Get scan line array pointer PScanLine := BitMap.ScanLine[Ybm] ; // Copy line to bitmap XIm := XLeft ; i := (Yim*FrameWidth) + XIm ; for xBm := 0 to BitMap.Width-1 do begin if (Xim < FrameWidth) and (Yim < FrameHeight) then begin PScanLine[Xbm] := LUT[Word(PDisplayBuf^[i])] ; end else PScanLine[Xbm] := 0 ; Xim := Xim + XStep ; i := i + XStep ; end ; Yim := Yim + XStep end ; Image1.Picture.Assign(BitMap) ; Image1.Width := BitMap.Width ; Image1.Height := BitMap.Height ; // lbReadout.Caption := format('X%d L=%d,T=%d',[ZoomFactor,XLeft,YTop]) ; end ; procedure TScanImageFrm.SaveRawImage( FileName : String ) ; // ---------------------- // Save raw image to file // ---------------------- var iBuf16 : PBig16BitArray ; FileHandle : THandle ; i,NumPixels,iMin,iMax : Integer ; begin NumPixels := FrameWidth*FrameHeight ; GetMem( iBuf16, NumPixels*Sizeof(Integer)) ; iMin := 32767 ; iMax := -32768 ; for i := 0 to NumPixels-1 do begin iMin := Min(PDisplayBuf^[i],iMin) ; iMax := Max(PDisplayBuf^[i],iMax) ; end; outputdebugstring(pchar(format('%d %d',[iMin,iMax]))); for i := 0 to NumPixels-1 do iBuf16^[i] := PDisplayBuf^[i] ; FileHandle := FileCreate( FileName ) ; FileWrite( FileHandle, FrameWidth, Sizeof(FrameWidth)) ; FileWrite( FileHandle, FrameHeight, Sizeof(FrameHeight)) ; FileWrite( FileHandle, iBuf16^, NumPixels*Sizeof(Integer)) ; FileClose(FileHandle) ; FreeMem(iBuf16) ; RawSaved := True ; end; end.
unit UnitUpdateIP; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, StdCtrls, jpeg, ExtCtrls; type TFormUpdateIP = class(TForm) Panel1: TPanel; Image1: TImage; Button1: TButton; Button2: TButton; Edit1: TEdit; Label1: TLabel; Label2: TLabel; Edit2: TEdit; Label3: TLabel; Edit3: TEdit; Label4: TLabel; Edit4: TEdit; CheckBox1: TCheckBox; SpeedButton1: TSpeedButton; procedure SpeedButton1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure CheckBox1Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure DynDNSUpdate(DNSAddress, User, password, IP: string); procedure NoIPUpdate(DNSAddress, User, password, IP: string); end; var FormUpdateIP: TFormUpdateIP; implementation {$R *.dfm} uses IdTCPClient, UnitGetWAMip, Base64, UnitMain; ////////////////////////////////////////////////////// ////////////////// DynDNS Updater //////////////////// ////////////////////////////////////////////////////// procedure TFormUpdateIP.Button1Click(Sender: TObject); begin ModalResult := mrOK; end; procedure TFormUpdateIP.Button2Click(Sender: TObject); begin ModalResult := mrCancel; end; procedure TFormUpdateIP.CheckBox1Click(Sender: TObject); begin if CheckBox1.Checked then Edit4.PasswordChar := #0 else Edit4.PasswordChar:= '*'; end; procedure TFormUpdateIP.DynDNSUpdate(DNSAddress, User, password, IP: string); var IdTCPClient1: TIdTCPClient; i: integer; begin IdTCPClient1 := TIdTCPClient.Create(nil); IdTCPClient1.Host := 'members.dyndns.org'; IdTCPClient1.Port := 80; IdTCPClient1.Connect; i := 0; while (IdTCPClient1.Connected = false) and (i < 5) do begin sleep(200); inc(i); end; try IdTCPClient1.IOHandler.WriteLn('GET /nic/update?hostname=' + DNSAddress + '&myip=' + IP + '&wildcard=NOCHG&mx=NOCHG&backmx=NOCHG HTTP/1.0' + #13#10 + 'Host: members.dyndns.org' + #13#10 + 'Authorization: Basic ' + Base64Encode(User + ':' + password) + #13#10 + 'User-Agent: XtremeRAT' + #13#10#13#10); except end; if IdTCPClient1.Connected then IdTCPClient1.Disconnect; IdTCPClient1.Free; end; procedure TFormUpdateIP.FormCreate(Sender: TObject); var i: integer; begin Self.Left := (screen.width - Self.width) div 2 ; Self.top := (screen.height - Self.height) div 2; FormMain.ImageListDiversos.GetBitmap(78, SpeedButton1.Glyph); i := Self.Width - (button1.Width + button2.Width + 20); button1.left := i div 2; button2.Left := button1.Left + button1.Width + 20; end; ///////////////////////////////////////////////////// ////////////////// No-IP Updater //////////////////// ///////////////////////////////////////////////////// procedure TFormUpdateIP.NoIPUpdate(DNSAddress, User, password, IP: string); var IdTCPClient1: TIdTCPClient; i: integer; begin IdTCPClient1 := TIdTCPClient.Create(nil); IdTCPClient1.Host := 'dynupdate.no-ip.com'; IdTCPClient1.Port := 8245; IdTCPClient1.Connect; i := 0; while (IdTCPClient1.Connected = false) and (i < 5) do begin sleep(200); inc(i); end; try IdTCPClient1.IOHandler.WriteLn('GET /ducupdate.php?username=' + User + '&pass=' + password + '&h[]=' + DNSAddress + '&ip=' + IP + ' HTTP/1.0'+#13#10 + 'Accept: */*' + #13#10 + 'User-Agent: DUC v2.2.1' + #13#10 + 'Host: ' + 'dynupdate.no-ip.com' + #13#10+ 'Pragma: no-cache'+#13#10#13#10); except end; if IdTCPClient1.Connected then IdTCPClient1.Disconnect; IdTCPClient1.Free; end; procedure TFormUpdateIP.SpeedButton1Click(Sender: TObject); begin edit1.Text := GetWanIP; end; end.
unit MenuAndActionsDemoUnit; interface {$R MenuAndActionsDemoUnit.res} uses Windows, AIMPCustomPlugin, apiCore, apiMenu, apiActions, apiObjects; type { TAIMPMenuAndActionsPlugin } TAIMPMenuAndActionsPlugin = class(TAIMPCustomPlugin) private function CreateGlyph(const ResName: string): IAIMPImage; function GetBuiltInMenu(ID: Integer): IAIMPMenuItem; procedure CreateMenuWithSubItemsAndWithoutAction; procedure CreateSimpleMenuWithAction; procedure CreateSimpleMenuWithoutAction; protected function InfoGet(Index: Integer): PWideChar; override; stdcall; function InfoGetCategories: Cardinal; override; stdcall; function Initialize(Core: IAIMPCore): HRESULT; override; stdcall; end; { TAIMPActionEventHandler } TAIMPActionEventHandler = class(TInterfacedObject, IAIMPActionEvent) public procedure OnExecute(Data: IInterface); stdcall; end; { TAIMPMenuItemEventHandler } TAIMPMenuItemEventHandler = class(TInterfacedObject, IAIMPActionEvent) public procedure OnExecute(Data: IInterface); stdcall; end; implementation uses apiPlugin, Classes, apiWrappers; { TAIMPMenuAndActionsPlugin } function TAIMPMenuAndActionsPlugin.InfoGet(Index: Integer): PWideChar; begin case Index of AIMP_PLUGIN_INFO_NAME: Result := 'Menu and actions demo plugin'; AIMP_PLUGIN_INFO_AUTHOR: Result := 'Artem Izmaylov'; AIMP_PLUGIN_INFO_SHORT_DESCRIPTION: Result := 'Single line short description'; else Result := nil; end; end; function TAIMPMenuAndActionsPlugin.InfoGetCategories: Cardinal; begin Result := AIMP_PLUGIN_CATEGORY_ADDONS; end; function TAIMPMenuAndActionsPlugin.Initialize(Core: IAIMPCore): HRESULT; var AService: IAIMPServiceMenuManager; begin // Check, if the Menu Service supported by core Result := Core.QueryInterface(IID_IAIMPServiceMenuManager, AService); if Succeeded(Result) then begin Result := inherited Initialize(Core); if Succeeded(Result) then begin CreateSimpleMenuWithAction; CreateSimpleMenuWithoutAction; CreateMenuWithSubItemsAndWithoutAction; end; end; end; function TAIMPMenuAndActionsPlugin.CreateGlyph(const ResName: string): IAIMPImage; var AContainer: IAIMPImageContainer; AResStream: TResourceStream; begin CheckResult(CoreIntf.CreateObject(IID_IAIMPImageContainer, AContainer)); AResStream := TResourceStream.Create(HInstance, ResName, RT_RCDATA); try CheckResult(AContainer.SetDataSize(AResStream.Size)); AResStream.ReadBuffer(AContainer.GetData^, AContainer.GetDataSize); CheckResult(AContainer.CreateImage(Result)); finally AResStream.Free; end; end; procedure TAIMPMenuAndActionsPlugin.CreateMenuWithSubItemsAndWithoutAction; var AMenuItem: IAIMPMenuItem; AMenuSubItem: IAIMPMenuItem; begin // Create menu item CheckResult(CoreIntf.CreateObject(IID_IAIMPMenuItem, AMenuItem)); // Setup it CheckResult(AMenuItem.SetValueAsObject(AIMP_MENUITEM_PROPID_ID, MakeString('aimp.MenuAndActionsDemo.menuitem.2'))); CheckResult(AMenuItem.SetValueAsObject(AIMP_MENUITEM_PROPID_NAME, MakeString('This menu has sub items'))); CheckResult(AMenuItem.SetValueAsObject(AIMP_MENUITEM_PROPID_PARENT, GetBuiltInMenu(AIMP_MENUID_PLAYER_MAIN_FUNCTIONS))); CheckResult(AMenuItem.SetValueAsObject(AIMP_MENUITEM_PROPID_GLYPH, CreateGlyph('AIMP3LOGO'))); // Register the menu item in manager CoreIntf.RegisterExtension(IID_IAIMPServiceMenuManager, AMenuItem); // Create first menu sub item CheckResult(CoreIntf.CreateObject(IID_IAIMPMenuItem, AMenuSubItem)); CheckResult(AMenuSubItem.SetValueAsObject(AIMP_MENUITEM_PROPID_ID, MakeString('aimp.MenuAndActionsDemo.menuitem.2.subitem.1'))); CheckResult(AMenuSubItem.SetValueAsObject(AIMP_MENUITEM_PROPID_NAME, MakeString('Sub item 1'))); CheckResult(AMenuSubItem.SetValueAsObject(AIMP_MENUITEM_PROPID_PARENT, AMenuItem)); CheckResult(AMenuSubItem.SetValueAsObject(AIMP_MENUITEM_PROPID_EVENT, TAIMPMenuItemEventHandler.Create)); // Register the menu item in manager CoreIntf.RegisterExtension(IID_IAIMPServiceMenuManager, AMenuSubItem); // Create second menu sub item CheckResult(CoreIntf.CreateObject(IID_IAIMPMenuItem, AMenuSubItem)); CheckResult(AMenuSubItem.SetValueAsObject(AIMP_MENUITEM_PROPID_ID, MakeString('aimp.MenuAndActionsDemo.menuitem.2.subitem.2'))); CheckResult(AMenuSubItem.SetValueAsObject(AIMP_MENUITEM_PROPID_NAME, MakeString('Sub item 2'))); CheckResult(AMenuSubItem.SetValueAsObject(AIMP_MENUITEM_PROPID_PARENT, AMenuItem)); CheckResult(AMenuSubItem.SetValueAsObject(AIMP_MENUITEM_PROPID_EVENT, TAIMPMenuItemEventHandler.Create)); // Register the menu item in manager CoreIntf.RegisterExtension(IID_IAIMPServiceMenuManager, AMenuSubItem); end; procedure TAIMPMenuAndActionsPlugin.CreateSimpleMenuWithAction; var AAction: IAIMPAction; AMenuItem: IAIMPMenuItem; begin // Create Action CheckResult(CoreIntf.CreateObject(IID_IAIMPAction, AAction)); // Setup it CheckResult(AAction.SetValueAsObject(AIMP_ACTION_PROPID_ID, MakeString('aimp.MenuAndActionsDemo.action.1'))); CheckResult(AAction.SetValueAsObject(AIMP_ACTION_PROPID_NAME, MakeString('Simple action title'))); CheckResult(AAction.SetValueAsObject(AIMP_ACTION_PROPID_GROUPNAME, MakeString('Menu And Actions Demo'))); CheckResult(AAction.SetValueAsObject(AIMP_ACTION_PROPID_EVENT, TAIMPActionEventHandler.Create)); // Register the action in manager CoreIntf.RegisterExtension(IID_IAIMPServiceActionManager, AAction); // Create menu item CheckResult(CoreIntf.CreateObject(IID_IAIMPMenuItem, AMenuItem)); // Setup it CheckResult(AMenuItem.SetValueAsObject(AIMP_MENUITEM_PROPID_ID, MakeString('aimp.MenuAndActionsDemo.menuitem.with.action'))); CheckResult(AMenuItem.SetValueAsObject(AIMP_MENUITEM_PROPID_NAME, MakeString('Menu item with linked action'))); CheckResult(AMenuItem.SetValueAsObject(AIMP_MENUITEM_PROPID_ACTION, AAction)); CheckResult(AMenuItem.SetValueAsObject(AIMP_MENUITEM_PROPID_PARENT, GetBuiltInMenu(AIMP_MENUID_PLAYER_MAIN_OPTIONS))); CheckResult(AMenuItem.SetValueAsObject(AIMP_MENUITEM_PROPID_GLYPH, CreateGlyph('AIMP3LOGO'))); // Register the menu item in manager CoreIntf.RegisterExtension(IID_IAIMPServiceMenuManager, AMenuItem); end; procedure TAIMPMenuAndActionsPlugin.CreateSimpleMenuWithoutAction; var AMenuItem: IAIMPMenuItem; begin // Create menu item CheckResult(CoreIntf.CreateObject(IID_IAIMPMenuItem, AMenuItem)); // Setup it CheckResult(AMenuItem.SetValueAsObject(AIMP_MENUITEM_PROPID_ID, MakeString('aimp.MenuAndActionsDemo.menuitem.1'))); CheckResult(AMenuItem.SetValueAsObject(AIMP_MENUITEM_PROPID_NAME, MakeString('Simple menu title'))); CheckResult(AMenuItem.SetValueAsObject(AIMP_MENUITEM_PROPID_EVENT, TAIMPMenuItemEventHandler.Create)); CheckResult(AMenuItem.SetValueAsObject(AIMP_MENUITEM_PROPID_PARENT, GetBuiltInMenu(AIMP_MENUID_COMMON_UTILITIES))); CheckResult(AMenuItem.SetValueAsObject(AIMP_MENUITEM_PROPID_GLYPH, CreateGlyph('AIMP3LOGO'))); // Register the menu item in manager CoreIntf.RegisterExtension(IID_IAIMPServiceMenuManager, AMenuItem); end; function TAIMPMenuAndActionsPlugin.GetBuiltInMenu(ID: Integer): IAIMPMenuItem; var AMenuService: IAIMPServiceMenuManager; begin CheckResult(CoreIntf.QueryInterface(IAIMPServiceMenuManager, AMenuService)); CheckResult(AMenuService.GetBuiltIn(ID, Result)); end; { TAIMPActionEventHandler } procedure TAIMPActionEventHandler.OnExecute(Data: IInterface); begin MessageBox(0, 'Action executed', 'Demo', 0); end; { TAIMPMenuItemEventHandler } procedure TAIMPMenuItemEventHandler.OnExecute(Data: IInterface); begin MessageBox(0, 'Menu item clicked', 'Demo', 0); end; end.
//////////////////////////////////////////////////////////////////////////// // PaxCompiler // Site: http://www.paxcompiler.com // Author: Alexander Baranovsky (paxscript@gmail.com) // ======================================================================== // Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved. // Code Version: 4.2 // ======================================================================== // Unit: PAXCOMP_PROG.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} {$O-} unit PAXCOMP_PROG; interface uses {$I uses.def} TypInfo, SysUtils, Classes, PaxInfos, PAXCOMP_CONSTANTS, PAXCOMP_TYPES, PAXCOMP_SYS, PAXCOMP_STDLIB, PAXCOMP_SYMBOL_REC, PAXCOMP_BASESYMBOL_TABLE, PAXCOMP_LOCALSYMBOL_TABLE, PAXCOMP_CLASSLST, PAXCOMP_CLASSFACT, PAXCOMP_DISASM, PAXCOMP_TRYLST, PAXCOMP_PAUSE, PAXCOMP_RTI, PAXCOMP_EVENT, PAXCOMP_MAP, PAXCOMP_TYPEINFO, PAXCOMP_PROGLIST, PAXCOMP_GC, PAXCOMP_BASERUNNER, PAXCOMP_INVOKE, PaxInvoke; type TProgram = class; TCallStackRec = class public EBP: Integer; SubId: Integer; NCall: Integer; Prg: TProgram; procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream); end; TCallStack = class(TTypedList) private function GetRecord(I: Integer): TCallStackRec; public function Push(EBP, SubId, NCall: Integer; Prg: TProgram): TCallStackRec; procedure Pop; function Top: TCallStackRec; function IndexOf(SubId: Integer): Integer; function LastIndexOf(SubId: Integer): Integer; procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream); property Records[I: Integer]: TCallStackRec read GetRecord; default; end; TTryStackRec = class public TryBlockNumber: Integer; Prog: TProgram; TR: TTryRec; constructor Create; destructor Destroy; override; end; TTryStack = class(TTypedList) private function GetRecord(I: Integer): TTryStackRec; function GetTop: TTryStackRec; public function Push(ATryBlockNumber: Integer; AProg: TProgram): TTryStackRec; procedure Pop; function IndexOf(ATryBlockNumber: Integer): Integer; procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream); property Top: TTryStackRec read GetTop; property Records[I: Integer]: TTryStackRec read GetRecord; default; end; TProgram = class(TBaseRunner) private fTryList: TTryList; fTryStack: TTryStack; fPauseRec: TPauseRec; fESP0: Integer; fCallStack: TCallStack; InitialOffset: Integer; fVirtualAllocProg: Boolean; procedure SetVirtualAllocProg(value: Boolean); function GetInteger(Shift: Integer): Integer; function GetInt64(Shift: Integer): Int64; function GetPChar(Shift: Integer): PChar; function GetShortString(Shift: Integer): ShortString; function GetRootProg: TProgram; function GetTryStack: TTryStack; function GetCallStack: TCallStack; function GetESP0: Integer; procedure SetESP0(value: Integer); function GetCurrException: Exception; procedure SetCurrException(value: Exception); protected function GetProgramSize: Integer; override; function _VirtualAlloc(Address: Pointer; Size, flAllocType, flProtect: Cardinal): Pointer; override; procedure _VirtualFree(Address: Pointer; Size: Cardinal); override; function GetVirtualAllocProg: Boolean; function GetCodePtr: PBytes; override; procedure DoOnReaderFindMethod( Reader: TReader; const MethodName: string; var Address: Pointer; var Error: Boolean); public EventHandlerList: TEventHandlerList; ZList: TIntegerList; OwnerEventHandlerMethod: TMethod; {$IFDEF MSWINDOWS} mbi: TMemoryBasicInformation; {$ENDIF} OldProtect: Cardinal; IsProtected: Boolean; IsPauseUpdated: Boolean; ExitLevelId: Integer; FinalizationOffset: Integer; SourceLineFinally: Integer; ModuleNameFinally: String; PauseSEH: Boolean; ExcFrame0: PExcFrame; constructor Create; override; destructor Destroy; override; procedure Reset; override; procedure ResetRun; override; function GetDestructorAddress: Pointer; override; procedure SaveToStream(S: TStream); override; procedure LoadFromStream(S: TStream); override; procedure Reallocate(NewCodeSize: Integer); procedure AssignEventHandlerRunner(MethodAddress: Pointer; Instance: TObject); override; function GetCallStackCount: Integer; override; function GetCallStackItem(I: Integer): Integer; override; function GetCallStackLineNumber(I: Integer): Integer; override; function GetCallStackModuleName(I: Integer): String; override; function GetCallStackModuleIndex(I: Integer): Integer; override; procedure RunInternal; override; procedure Run; override; procedure RunInitialization; override; procedure RunExceptInitialization; override; procedure RunFinalization; override; procedure PushPtrs; function GetPauseFlag: Integer; procedure InitByteCodeLine; function IsPaused: Boolean; override; procedure Pause; override; procedure DiscardPause; override; procedure Terminate; procedure RemovePause; override; function Valid: Boolean; override; procedure SetZList; function GetImageCodePtr: Integer; function GetImageAddress(const FullName: String; var MR: TMapRec): Integer; function CreateScriptObject(const ScriptClassName: String; const ParamList: array of const): TObject; override; procedure DiscardDebugMode; override; procedure RunEx; procedure SaveState(S: TStream); override; procedure LoadState(S: TStream); override; procedure RebindEvents(AnInstance: TObject); override; function CallFunc(const FullName: String; This: Pointer; const ParamList: array of OleVariant; OverCount: Integer = 0): OleVariant; override; function CallFuncEx(const FullName: String; This: Pointer; const ParamList: array of const; IsConstructor: Boolean = false; OverCount: integer = 0): Variant; procedure Protect; override; procedure UnProtect; override; procedure ResetException; procedure SetEntryPoint(EntryPoint: TPaxInvoke); override; procedure ResetEntryPoint(EntryPoint: TPaxInvoke); override; function GetParamAddress(Offset: Integer): Pointer; overload; override; function GetLocalAddress(Offset: Integer): Pointer; overload; override; function GetParamAddress(StackFrameNumber, Offset: Integer): Pointer; overload; override; function GetLocalAddress(StackFrameNumber, Offset: Integer): Pointer; overload; override; property Integers[Shift: Integer]: Integer read GetInteger; property Int64s[Shift: Integer]: Int64 read GetInt64; property PChars[Shift: Integer]: PChar read GetPChar; property ShortStrings[Shift: Integer]: ShortString read GetShortString; property TryList: TTryList read fTryList; property PauseRec: TPauseRec read fPauseRec; property RootTryStack: TTryStack read GetTryStack; property RootCallStack: TCallStack read GetCallStack; property RootESP0: Integer read GetESP0 write SetESP0; property CurrException: Exception read GetCurrException write SetCurrException; property VirtualAllocProg: Boolean read GetVirtualAllocProg write SetVirtualAllocProg; property RootProg: TProgram read GetRootProg; end; procedure ZZZ; implementation uses PAXCOMP_PROGLIB, PAXCOMP_JavaScript; // TCallStackRec --------------------------------------------------------------- procedure TCallStackRec.SaveToStream(S: TStream); begin S.Write(EBP, SizeOf(Integer)); S.Write(SubId, SizeOf(Integer)); S.Write(NCall, SizeOf(Integer)); end; procedure TCallStackRec.LoadFromStream(S: TStream); begin S.Read(EBP, SizeOf(Integer)); S.Read(SubId, SizeOf(Integer)); S.Read(NCall, SizeOf(Integer)); end; // TCallStack ------------------------------------------------------------------ function TCallStack.GetRecord(I: Integer): TCallStackRec; begin result := TCallStackRec(L[I]); end; function TCallStack.Push(EBP, SubId, NCall: Integer; Prg: TProgram): TCallStackRec; begin result := TCallStackRec.Create; result.EBP := EBP; result.SubId := SubId; result.NCall := NCall; result.Prg := Prg; L.Add(result); end; procedure TCallStack.Pop; begin RemoveAt(Count - 1); end; function TCallStack.Top: TCallStackRec; begin result := TCallStackRec(L[Count - 1]); end; function TCallStack.IndexOf(SubId: Integer): Integer; var I: Integer; begin result := -1; for I := 0 to Count - 1 do if Records[I].SubId = SubId then begin result := I; Exit; end; end; function TCallStack.LastIndexOf(SubId: Integer): Integer; var I: Integer; begin result := -1; for I := Count - 1 downto 0 do if Records[I].SubId = SubId then begin result := I; Exit; end; end; procedure TCallStack.SaveToStream(S: TStream); var I, K: Integer; begin K := Count; S.Write(K, SizeOf(Integer)); for I := 0 to K - 1 do Records[I].SaveToStream(S); end; procedure TCallStack.LoadFromStream(S: TStream); var I, K: Integer; R: TCallStackRec; begin S.Read(K, SizeOf(Integer)); for I := 0 to K - 1 do begin R := TCallStackRec.Create; R.LoadFromStream(S); L.Add(R); end; end; // TTryRec --------------------------------------------------------------------- constructor TTryStackRec.Create; begin inherited; end; destructor TTryStackRec.Destroy; begin if TR <> nil then FreeAndNil(TR); inherited; end; // TTryStack ------------------------------------------------------------------- function TTryStack.GetRecord(I: Integer): TTryStackRec; begin result := TTryStackRec(L[I]); end; function TTryStack.GetTop: TTryStackRec; begin if Count = 0 then raise PaxCompilerException.Create(errInternalError); result := Records[Count - 1]; end; function TTryStack.IndexOf(ATryBlockNumber: Integer): Integer; var I: Integer; begin result := -1; for I := 0 to Count - 1 do if Records[I].TryBlockNumber = ATryBlockNumber then begin result := I; Exit; end; end; function TTryStack.Push(ATryBlockNumber: Integer; AProg: TProgram): TTryStackRec; begin result := TTryStackRec.Create; result.TryBlockNumber := ATryBlockNumber; result.Prog := AProg; result.TR := AProg.TryList[ATryBlockNumber].Clone; L.Add(result); end; procedure TTryStack.Pop; begin Records[Count - 1].Free; L.Delete(Count - 1); end; procedure TTryStack.SaveToStream(S: TStream); var I, K: Integer; begin K := Count; S.Write(K, SizeOf(K)); for I := 0 to K - 1 do with Records[I] do begin S.Write(TryBlockNumber, SizeOf(TryBlockNumber)); S.Write(Prog, SizeOf(Prog)); TR.SaveToStream(S); end; end; procedure TTryStack.LoadFromStream(S: TStream); var I, K: Integer; R: TTryStackRec; begin Clear; S.Read(K, SizeOf(K)); for I := 0 to K - 1 do begin R := TTryStackRec.Create; with R do begin S.Read(TryBlockNumber, SizeOf(TryBlockNumber)); S.Read(Prog, SizeOf(Prog)); TR := TTryRec.Create; TR.LoadFromStream(S); end; L.Add(R); end; end; // TProgram -------------------------------------------------------------------- constructor TProgram.Create; begin inherited Create; {$IFDEF MSWINDOWS} fVirtualAllocProg := true; {$ENDIF} CurrProg := Self; fTryList := TTryList.Create; fTryStack := TTryStack.Create; fPauseRec := TPauseRec.Create; EventHandlerList := TEventHandlerList.Create; fCallStack := TCallStack.Create; EPoint := nil; PCUOwner := nil; ZList := TIntegerList.Create; IsRunning := false; UseMapping := false; end; destructor TProgram.Destroy; begin ResetException; UnloadDlls; FreeAndNil(ZList); FreeAndNil(fTryList); FreeAndNil(fTryStack); FreeAndNil(fPauseRec); FreeAndNil(fCallStack); try Deallocate; except end; FreeAndNil(EventHandlerList); ClearCurrException; inherited; end; procedure TProgram.Reset; begin inherited; fImageDataPtr := 0; ZList.Clear; fTryList.Clear; fTryStack.Clear; fPauseRec.Clear; EventHandlerList.Clear; fCallStack.Clear; RootInitCallStackCount := 0; Deallocate; EPoint := nil; IsRunning := false; RootIsEvent := false; PauseSEH := false; FinallyCount := 0; PCULang := 0; end; procedure TProgram.ResetRun; begin fTryStack.Clear; fPauseRec.Clear; fCallStack.Clear; RootInitCallStackCount := 0; EPoint := nil; IsRunning := false; RootIsEvent := false; PauseSEH := false; end; procedure TProgram.SetZList; var I, S: Integer; P: Pointer; begin {$IFDEF PAX64} for I:=0 to ZList.Count - 1 do begin S := ZList[I]; P := ShiftPointer(CodePtr, S + 2); Pointer(P^) := CodePtr; P := ShiftPointer(P, 10); Pointer(P^) := DataPtr; end; {$ELSE} for I:=0 to ZList.Count - 1 do begin S := ZList[I]; P := ShiftPointer(CodePtr, S + 1); Pointer(P^) := CodePtr; P := ShiftPointer(P, 5); Pointer(P^) := DataPtr; end; {$ENDIF} end; function TProgram.GetInteger(Shift: Integer): Integer; var P: Pointer; begin P := ShiftPointer(DataPtr, Shift); result := LongInt(P^); end; function TProgram.GetInt64(Shift: Integer): Int64; var P: Pointer; begin P := ShiftPointer(DataPtr, Shift); result := Int64(P^); end; function TProgram.GetPChar(Shift: Integer): PChar; var P: Pointer; begin P := ShiftPointer(DataPtr, Shift); result := PChar(P^); end; function TProgram.GetShortString(Shift: Integer): ShortString; var P: Pointer; begin P := ShiftPointer(DataPtr, Shift); result := ShortString(P^); end; procedure TProgram.Reallocate(NewCodeSize: Integer); var buff: Pointer; begin if NewCodeSize = CodeSize then Exit; if NewCodeSize < CodeSize then RaiseError(errInternalError, []); Unprotect; buff := _VirtualAlloc(nil, CodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); Move(Prog^, buff^, CodeSize); _VirtualFree(Prog, CodeSize); Prog := _VirtualAlloc(nil, NewCodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); Move(buff^, Prog^, CodeSize); _VirtualFree(buff, CodeSize); CodeSize := NewCodeSize; Protect; end; function TProgram.Valid: Boolean; begin result := (Data <> nil) and (Prog <> nil); end; function TProgram.GetImageAddress(const FullName: String; var MR: TMapRec): Integer; begin result := 0; MR := ScriptMapTable.Lookup(FullName); if MR <> nil then begin case MR.Kind of KindVAR, kindTYPE: result := GetImageDataPtr + MR.Offset; KindSUB, KindCONSTRUCTOR, KindDESTRUCTOR: begin if MR.IsExternal then result := 0 else result := GetImageCodePtr + MR.Offset; end; end; Exit; end; MR := HostMapTable.Lookup(FullName); if MR <> nil then if MR.Kind in KindSUBS + [KindVAR] then begin result := GetImageDataPtr + MR.Offset; // result := Pointer(result^); end; end; function TProgram.GetCodePtr: PBytes; begin result := Prog; end; function TProgram.GetPauseFlag: Integer; var P: Pointer; begin P := ShiftPointer(Data, H_Flag); result := LongInt(P^); end; procedure TProgram.InitByteCodeLine; var P: Pointer; begin P := ShiftPointer(Data, H_ByteCodePtr); LongInt(P^) := -1; end; function TProgram.GetImageCodePtr: Integer; begin result := GetImageDataPtr + DataSize; end; procedure TProgram.SaveToStream(S: TStream); var StartSize, EndSize, StartPos, EndPos, StreamSize: Integer; CustomDataSize, CustomDataSizePos, temp: Integer; SS: ShortString; begin StartSize := S.Size; StartPos := S.Position; S.Write(StreamSize, SizeOf(Integer)); S.Write(CompiledScriptVersion, SizeOf(CompiledScriptVersion)); PShortStringFromString(@ SS, TProgram.ClassName); SaveShortStringToStream(SS, S); CustomDataSize := 0; CustomDataSizePos := S.Position; S.Write(CustomDataSize, SizeOf(Integer)); if Assigned(OnSaveToStream) and IsRootProg then begin OnSaveToStream(Owner, S); CustomDataSize := S.Position - CustomDataSizePos - 4; if CustomDataSize > 0 then begin temp := S.Position; S.Position := CustomDataSizePos; S.Write(CustomDataSize, SizeOf(Integer)); S.Position := temp; end else begin CustomDataSize := 0; S.Position := CustomDataSizePos; S.Write(CustomDataSize, SizeOf(Integer)); end; end; S.Write(DataSize, SizeOf(Integer)); S.Write(fCodeSize, SizeOf(Integer)); fImageDataPtr := S.Position - StartPos; S.Write(Data^, DataSize); S.Write(Prog^, fCodeSize); S.Write(JS_Record, SizeOf(JS_Record)); S.Write(ModeSEH, SizeOf(ModeSEH)); S.Write(PAX64, SizeOf(PAX64)); if GENERICS_ALLOWED then S.Write(PCULang, SizeOf(PCULang)); ClassList.SaveToStream(S); RunTimeModuleList.SaveToStream(S); TryList.SaveToStream(S); ZList.SaveToStream(S); HostMapTable.SaveToStream(S); ScriptMapTable.SaveToStream(S); OffsetList.SaveToStream(S); ExportList.SaveToStream(S); MessageList.SaveToStream(S); ProgTypeInfoList.SaveToStream(S); ProgList.SaveToStream(S); EndSize := S.Size; EndPos := S.Position; StreamSize := EndSize - StartSize; S.Position := StartPos; S.Write(StreamSize, SizeOf(Integer)); S.Position := EndPos; end; procedure TProgram.LoadFromStream(S: TStream); var Version: Integer; K: Integer; CustomDataSize, temp: Integer; P: Pointer; SS: ShortString; ST: String; begin Deallocate; S.Read(K, SizeOf(Integer)); S.Read(Version, SizeOf(CompiledScriptVersion)); if Version <> CompiledScriptVersion then RaiseError(errIncorrectCompiledScriptVersion, []); SS := LoadShortStringFromStream(S); ST := TProgram.ClassName; if not StrEql(StringFromPShortString(@SS), ST) then RaiseError(errIncorrectCompiledScriptVersion, []); S.Read(CustomDataSize, SizeOf(Integer)); if Assigned(OnLoadFromStream) and IsRootProg then begin temp := S.Position; OnLoadFromStream(Owner, S); if S.Position - temp <> CustomDataSize then RaiseError(errIncorrectCustomDataSize, []); end else if CustomDataSize > 0 then begin P := AllocMem(CustomDataSize); try S.Read(P^, CustomDataSize); finally FreeMem(P, CustomDataSize); end; end; S.Read(fDataSize, SizeOf(Integer)); S.Read(fCodeSize, SizeOf(Integer)); Data := AllocMem(fDataSize); Prog := _VirtualAlloc(nil, fCodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); S.Read(Data^, fDataSize); S.Read(Prog^, fCodeSize); S.Read(JS_Record, SizeOf(JS_Record)); S.Read(ModeSEH, SizeOf(ModeSEH)); S.Read(PAX64, SizeOf(PAX64)); if GENERICS_ALLOWED then S.Read(PCULang, SizeOf(PCULang)); {$IFDEF MACOS} ModeSEH := false; {$ENDIF} ClassList.Clear; ClassList.LoadFromStream(S, Version); RunTimeModuleList.Clear; RunTimeModuleList.LoadFromStream(S); TryList.Clear; TryList.LoadFromStream(S); ZList.Clear; ZList.LoadFromStream(S); HostMapTable.Clear; HostMapTable.LoadFromStream(S); ScriptMapTable.Clear; ScriptMapTable.LoadFromStream(S); OffsetList.Clear; OffsetList.LoadFromStream(S); ExportList.Clear; ExportList.LoadFromStream(S); MessageList.Clear; MessageList.LoadFromStream(S); ProgTypeInfoList.Clear; ProgTypeInfoList.LoadFromStream(S); ProgList.Clear; ProgList.LoadFromStream(S, Self); ProgList.SetPCUOwner(Self); UseMapping := HostMapTable.Count > 0; SetAddress(H_SelfPtr, Self); SetAddress(H_ExceptionPtr, @ fCurrException); RegisterDefinitions(GlobalSym); if UseMapping then begin FreeAndNil(LocalSymbolTable); LocalSymbolTable := TProgSymbolTable.Create(GlobalSym); LocalSymbolTable.Reset; RegisterDefinitions(LocalSymbolTable); end; SetZList; SetupInterfaces(CodePtr); ProgClassFactory.ForceCreate := true; end; function TProgram.IsPaused: Boolean; begin result := RootProg.PauseRec.ProgOffset > 0; end; { procedure TProgram.Resume; begin if not IsPaused then RaiseError(errProgramIsNotPaused, []); Run; end; } procedure TProgram.Pause; var P: Pointer; begin P := ShiftPointer(Data, H_Flag); LongInt(P^) := 1; end; procedure TProgram.Terminate; var P: Pointer; begin P := ShiftPointer(Data, H_Flag); LongInt(P^) := 2; end; procedure TProgram.RemovePause; var P: Pointer; begin P := ShiftPointer(Data, H_Flag); LongInt(P^) := 0; end; procedure TProgram.Protect; begin {$IFDEF MSWINDOWS} if IsProtected then Exit; VirtualQuery(Prog, mbi, sizeof(mbi)); // VirtualProtect(mbi.BaseAddress, mbi.RegionSize, PAGE_EXECUTE_READWRITE, OldProtect); VirtualProtect(Prog, fCodeSize, PAGE_EXECUTE_READWRITE, OldProtect); FlushInstructionCache(GetCurrentProcess, Prog, fCodeSize); // Applications should call FlushInstructionCache if they generate or modify // code in memory. The CPU cannot detect the change, and may execute the old // code it cached. {$ENDIF} IsProtected := true; end; procedure TProgram.UnProtect; begin {$IFDEF MSWINDOWS} if not IsProtected then Exit; // VirtualProtect(mbi.BaseAddress, mbi.RegionSize, OldProtect, OldProtect); VirtualProtect(Prog, fCodeSize, OldProtect, OldProtect); {$ENDIF} IsProtected := false; end; procedure TProgram.ResetException; var aPrg : TProgram; i : integer; begin for i := 0 to ProgList.count - 1 do begin aPrg := TProgram(ProgList.Records[i].Prog); if (aPrg <> nil) then aPrg.ResetException; end; if HasError then begin if fCurrException <> nil then fCurrException.Free; fCurrException := nil; fPrevException := nil; ExceptionRec := nil; HasError := false; fGC.Collect; end; end; {$IFDEF PAX64} function GetFS0: Pointer; assembler; {$IFDEF FPC} nostackframe; asm {$ELSE} asm .NOFRAME {$ENDIF} mov rax, fs:[0] end; function GetRSP: IntPax; assembler; {$IFDEF FPC} nostackframe; asm {$ELSE} asm .NOFRAME {$ENDIF} mov rax, rsp end; procedure CopyStackFrame(I: IntPax; StackFrame: Pointer; StackFrameSize, K: IntPax); asm mov rax, I mov rbx, StackFrame add rbx, StackFrameSize //!! sub rbx, 8 //!! mov rcx, K @@loop: mov rdx, [rbx] mov [rax], rdx sub rax, 8 sub rbx, 8 sub rcx, 1 cmp rcx, 0 jnz @@loop end; procedure AssignFS0(I: IntPax); assembler; {$IFDEF FPC} nostackframe; asm {$ELSE} asm .NOFRAME {$ENDIF} mov fs:[0], rcx end; procedure AssignSegmentsAndJump(D, P0, P: Pointer; _ESP, _EBP: IntPax); assembler; asm // assign code and data registers mov rsi, D mov rdi, P0 mov rax, P mov rsp, _ESP mov rbp, _EBP jmp rax end; procedure AssignSegmentsAndCall(D, P: Pointer); assembler; {$IFDEF FPC} nostackframe; asm {$ELSE} asm .NOFRAME {$ENDIF} push rbp mov rbp, rsp mov rsi, rcx mov rdi, rdx call rdx pop rbp ret end; procedure AssignSegments(D, P: Pointer); assembler; {$IFDEF FPC} nostackframe; asm {$ELSE} asm .NOFRAME {$ENDIF} mov rsi, rcx mov rdi, rdx end; procedure Assign_R14(P: Pointer); assembler; {$IFDEF FPC} nostackframe; asm {$ELSE} asm .NOFRAME {$ENDIF} mov r14, rcx end; procedure Assign_R15(P: Pointer); assembler; {$IFDEF FPC} nostackframe; asm {$ELSE} asm .NOFRAME {$ENDIF} mov r15, rcx end; procedure Call_R15; assembler; {$IFDEF FPC} nostackframe; asm {$ELSE} asm .NOFRAME {$ENDIF} push rbp sub rsp, $1000 mov rbp, rsp // if EPoint.IsInternal then // EPoint.PushArgumentsBackward // else // EPoint.PushArguments; mov rcx, r14 call TInvoke.IsInternal cmp al, 0 jz @@l1 mov rcx, r14 call TInvoke.PushArgumentsBackward jmp @@l2 @@l1: mov rcx, r14 call TInvoke.PushArguments @@l2: call r15 add rsp, $1000 pop rbp ret end; {$ENDIF} procedure TProgram.Run; var PaxFrame: PPaxExcFrame; Delta: IntPax; I: Integer; D, P, P0, temp: Pointer; ProgOffset: Integer; Handled: Boolean; _EBP, _ESP: IntPax; TryRec: TTryRec; ClsIndex: Integer; ClassRec: TClassRec; StackFrame: Pointer; K: Integer; SourceLine: Integer; ModuleName: String; CE: TExceptionClass; PEpoint: Pointer; StackFrameSize: Integer; IsHaltException: Boolean; IsPauseException: Boolean; IsExitException: Boolean; TryBlockNumber: Integer; SelfPtr: TProgram; HandledByExcept: Boolean; label Again; begin // PChars[0]; // ShortStrings[0]; Integers[0]; Int64s[0]; SourceLineFinally := -1; ModuleNameFinally := ''; IsRootProg; if ProgClassFactory.ForceCreate then begin CreateClassFactory; ProgClassFactory.ForceCreate := false; end; IsRunning := true; IsHalted := false; IsPauseUpdated := false; PEpoint := nil; ProgOffset := 0; Handled := false; SelfPtr := Self; with SelfPtr do begin D := Data; P0 := Prog; end; SourceLine := -1; ExitCode := 0; IsHaltException := false; IsPauseException := false; RootInitCallStackCount := fCallStack.Count; if IsPaused then begin Handled := true; StackFrameSize := PauseRec.StackFrameSize; K := StackFrameSize div 4; StackFrame := PauseRec.StackFrame; ProgOffset := PauseRec.ProgOffset; _ESP := PauseRec._ESP; _EBP := PauseRec._EBP; PauseRec.ProgOffset := 0; end; RemovePause; Again: if HasError then GetRootProg.ResetException; HasError := false; HandledByExcept := false; try if ModeSEH then begin {$IFDEF PAX64} // temp := GetFS0; {$ELSE} asm mov eax, fs:[0] mov temp, eax end; {$ENDIF} ExcFrame0 := temp; end; if Handled then begin Handled := false; {$IFDEF PAX64} I := GetRSP; {$ELSE} asm mov I, esp end; {$ENDIF} PaxFrame := PauseRec.PaxExcFrame1; Delta := fESP0 - I; fESP0 := I; _ESP := _ESP - Delta; _EBP := _EBP - Delta; for I := 0 to fCallStack.Count - 1 do fCallStack[I].EBP := fCallStack[I].EBP - Delta; {$IFDEF PAX64} // restore stack frame I := fESP0 - 8; CopyStackFrame(I, StackFrame, StackFrameSize, K); P := Pointer(LongInt(P0) + ProgOffset); if ModeSEH and PauseSEH then begin IntPax(PaxFrame) := Integer(PaxFrame) - Delta; I := IntPax(PaxFrame); AssignFS0(I); while PaxFrame.Magic = PAX_SEH do begin PaxFrame^.hEBP := PaxFrame^.hEBP - Delta; PaxFrame^.hESP := PaxFrame^.hESP - Delta; PaxFrame^.Next := Pointer(Integer(PaxFrame^.Next) - Delta); PaxFrame := PaxFrame^.Next; end; PaxFrame^.Next := Pointer(ExcFrame0); PauseSEH := false; end; AssignSegmentsAndJump(D, P0, P, _ESP, _EBP); // end of win64 {$ELSE} //win32 // restore stack frame I := fESP0 - 4; asm mov eax, I mov ebx, StackFrame add ebx, StackFrameSize //!! sub ebx, 4 //!! mov ecx, K @@loop: mov edx, [ebx] mov [eax], edx sub eax, 4 // add ebx, 4 sub ebx, 4 sub ecx, 1 cmp ecx, 0 jnz @@loop end; P := Pointer(LongInt(P0) + ProgOffset); if ModeSEH and PauseSEH then begin Integer(PaxFrame) := Integer(PaxFrame) - Delta; I := Integer(PaxFrame); asm mov eax, I mov fs:[0], eax end; while PaxFrame.Magic = PAX_SEH do begin PaxFrame^.hEBP := PaxFrame^.hEBP - Delta; PaxFrame^.hESP := PaxFrame^.hESP - Delta; PaxFrame^.Next := Pointer(Integer(PaxFrame^.Next) - Delta); PaxFrame := PaxFrame^.Next; end; PaxFrame^.Next := Pointer(ExcFrame0); PauseSEH := false; end; asm // assign code and data registers mov esi, D mov edi, P0 mov eax, P mov esp, _ESP mov ebp, _EBP jmp eax end; {$ENDIF} // win32 end else begin InitByteCodeLine; {$IFDEF PAX64} _ESP := GetRSP(); {$ELSE} asm mov _ESP, esp end; {$ENDIF} fESP0 := _ESP; {$IFDEF PCU_EX} RootProg.fESP0 := fESP0; {$ENDIF} if EPoint = nil then begin P := P0; {$IFDEF PAX64} AssignSegmentsAndCall(D, P); {$ELSE} asm mov esi, D mov edi, P {$IFDEF MACOS} add esp, - $0c {$ENDIF} call P {$IFDEF MACOS} add esp, $0c {$ENDIF} end; {$ENDIF} end else begin if not EPoint.IsInternal then EPoint.Setup; PEpoint := EPoint; // P := ShiftPointer(EPoint.Address, 14); P := EPoint.Address; {$IFDEF PAX64} AssignSegments(D, P0); Assign_R14(EPoint); Assign_R15(P); Call_R15; EPoint.SaveResult; {$ELSE} asm mov esi, D mov edi, P0 end; if EPoint.IsInternal then EPoint.PushArgumentsBackward else EPoint.PushArguments; asm call P end; asm mov ebx, PEpoint cmp ebx, 0 jz @@Return // if call convention is cdecl then pop arguments mov ecx, [ebx + 28] // fCallConv cmp ecx, ccCDECL jnz @@Ret mov ecx, [ebx + 8] // fStackSize add esp, ecx @@Ret: mov ecx, [ebx + 32] // fResultType cmp ecx, typeINTEGER jnz @@RetDOUBLE mov ecx, [ebx + 28] // fCallConv cmp ecx, ccSAFECALL jz @@Return mov [ebx + INVOKE_RESULT_OFFSET], eax jmp @@Return // @@RetDOUBLE: cmp ecx, typeDOUBLE jnz @@RetSINGLE fstp qword ptr [ebx + INVOKE_RESULT_OFFSET] jmp @@Return // @@RetSINGLE: cmp ecx, typeSINGLE jnz @@RetEXTENDED fstp dword ptr [ebx + INVOKE_RESULT_OFFSET] jmp @@Return // @@RetEXTENDED: cmp ecx, typeEXTENDED jnz @@RetCURRENCY fstp tbyte ptr [ebx + INVOKE_RESULT_OFFSET] jmp @@Return // @@RetCURRENCY: cmp ecx, typeCURRENCY jnz @@RetINT64 fistp qword ptr [ebx + INVOKE_RESULT_OFFSET] jmp @@Return // @@RetINT64: cmp ecx, typeINT64 jnz @@Return mov [ebx + INVOKE_RESULT_OFFSET], eax mov [ebx + INVOKE_RESULT_OFFSET + 4], edx @@Return: end; {$ENDIF} end; end; except on E: Exception do begin if fTryStack.Count > 0 then begin TryBlockNumber := fTryStack.Top.TryBlockNumber; SelfPtr := fTryStack.Top.Prog; end else begin SelfPtr := Self; TryBlockNumber := 0; end; with SelfPtr do begin D := Data; P0 := Prog; SourceLine := GetSourceLine; ModuleName := GetModuleName; end; IsExitException := E is PaxExitException; IsPauseException := E is TPauseException; IsHaltException := (E is THaltException) or ((E is EAbort) and (not IsPauseException) and (not IsExitException)); IsHalted := IsHaltException; HasError := true; if E is THaltException then ExitCode := (E as THaltException).ExitCode; with SelfPtr do if RootTryStack.Count > 0 then if (not IsPauseException) and (not IsHaltException) and (TryBlockNumber >= 0) and (TryBlockNumber < TryList.Count) then begin // TryRec := TryList[TryBlockNumber]; TryRec := fTryStack.Top.TR; _EBP := TryRec._EBP; _ESP := TryRec._ESP; K := TryRec.StackFrameSize div 4; StackFrame := TryRec.StackFrame; StackFrameSize := TryRec.StackFrameSize; if TryRec.TryKind = tryFinally then begin ProcessingExceptBlock := false; if SourceLineFinally = -1 then begin SourceLineFinally := GetSourceLine; ModuleNameFinally := GetModuleName; end; end else begin ProcessingExceptBlock := true; HandledByExcept := true; end; if TryRec.ExceptOnInfo.Count = 0 then ProgOffset := TryRec.ProgOffset else begin for I:=0 to TryRec.ExceptOnInfo.Count - 1 do begin ClsIndex := TryRec.ExceptOnInfo.Keys[I]; ProgOffset := TryRec.ExceptOnInfo.Values[I]; if ClsIndex >= 0 then begin ClassRec := ClassList[ClsIndex]; if ClassRec.PClass <> nil then begin if E is ClassRec.PClass then break; if StrEql(ClassRec.PClass.ClassName, 'TJS_Object') then break; end; end; end; end; Handled := true; end; if Assigned(fCurrException) then FreeAndNil(fCurrException); fPrevException := nil; if (not IsPauseException) and (not IsHaltException) then begin IntPax(CE) := IntPax(E.ClassType); fCurrException := CE.Create(E.Message); if Assigned(OnCustomExceptionHelper) then OnCustomExceptionHelper(Owner, E, fCurrException); end; end; // on: E Exception else begin // custom exception end; end; // try RuntimeModuleList.TempBreakpoint.Clear; if Handled then begin if Assigned(OnException) and RootExceptionIsAvailableForHostApplication then if HandledByExcept then OnException(Owner, fCurrException, ModuleName, SourceLine); RootExceptionIsAvailableForHostApplication := true; goto Again; end else begin IsRunning := false; if (not SuspendFinalization) and (ProgTag <> 1) then fGC.ClearObjects; if HasError then begin if Assigned(OnHalt) and IsHaltException then begin OnHalt(Owner, ExitCode, ModuleName, SourceLine); RootExceptionIsAvailableForHostApplication := true; fPauseRec.Clear; ClearCurrException; Exit; end else if Assigned(OnPause) and IsPauseException then begin OnPause(Owner, ModuleName, SourceLine); RootExceptionIsAvailableForHostApplication := true; ClearCurrException; Exit; end; if Assigned(OnUnhandledException) then if fCurrException <> nil then if RootExceptionIsAvailableForHostApplication then begin if SourceLineFinally = -1 then OnUnhandledException(Owner, fCurrException, ModuleName, SourceLine) else OnUnhandledException(Owner, fCurrException, ModuleNameFinally, SourceLineFinally); end; RootExceptionIsAvailableForHostApplication := true; end; end; ClearCurrException; end; {$O-} procedure TProgram.RunInternal; begin Run; end; procedure TProgram.RunInitialization; var P: Pointer; begin if InitializationIsProcessed then Exit; Protect; if fGC = RootGC then fGC.Clear; ProgList.RunInitialization; P := ShiftPointer(Data, H_InitOnly); LongInt(P^) := 2; try ProgTag := 1; Run; InitMessageList; finally ProgTag := 0; LongInt(P^) := 0; InitializationIsProcessed := true; InitialOffset := GetInitializationOffset(CodePtr, CodeSize, PAX64); end; end; procedure TProgram.RunExceptInitialization; var P: Pointer; begin if InitialOffset <= 0 then InitialOffset := GetInitializationOffset(CodePtr, CodeSize, PAX64); if InitialOffset = -1 then Exit; P := ShiftPointer(Data, H_BodyOnly); if SuspendFinalization then LongInt(P^) := 3 else LongInt(P^) := 0; EPoint := nil; P := ShiftPointer(CodePtr, 1); Move(InitialOffset, P^, 4); try Run; finally LongInt(P^) := 0; end; end; procedure TProgram.RunFinalization; var P: Pointer; Offset: Integer; begin if CodePtr = nil then Exit; ProgList.RunFinalization; Offset := GetFinalizationOffset(CodePtr, CodeSize, PAX64); if Offset = -1 then Exit; EPoint := nil; P := ShiftPointer(CodePtr, 1); Move(Offset, P^, 4); try Run; finally InitializationIsProcessed := false; LongInt(P^) := 0; Unprotect; end; end; procedure TProgram.SaveState(S: TStream); var K: Integer; begin S.Write(DataPtr^, DataSize); fCallStack.SaveToStream(S); K := fTryStack.Count; S.Write(K, SizeOf(Integer)); // fTryStack.SaveToStream(S); end; procedure TProgram.LoadState(S: TStream); var K: Integer; begin S.Read(DataPtr^, DataSize); fCallStack.Clear; fCallStack.LoadFromStream(S); S.Read(K, SizeOf(Integer)); while fTryStack.Count > K do fTryStack.Pop; // fTryStack.LoadFromStream(S); end; {$IFDEF PAX64} procedure TProgram.PushPtrs; {$IFDEF FPC} nostackframe; asm {$ELSE} asm .NOFRAME {$ENDIF} mov rcx, [rsp] push rcx push rcx mov rdx, [rax + 8] mov [rsp + 8], rdx mov rdx, [rax + 8 + 8] mov [rsp + 8 + 8], rdx end; {$ELSE} procedure TProgram.PushPtrs; assembler; {$IFDEF FPC} nostackframe; asm {$ELSE} asm {$ENDIF} mov ecx, [esp] push ecx push ecx mov edx, [eax + 4] mov [esp + 4], edx mov edx, [eax + 8] mov [esp + 8], edx end; {$ENDIF} function TProgram.GetProgramSize: Integer; begin result := DataSize + CodeSize + 2; end; procedure TProgram.DiscardDebugMode; begin PAXCOMP_DISASM.DiscardDebugMode(CodePtr, CodeSize, PAX64); end; {$IFDEF PAX64} procedure Call_M_2(Code, Data: Pointer); assembler; asm CALL RCX end; procedure Call_M(M: TMethod); begin Call_M_2(M.Code, M.Data); end; {$ENDIF} {$IFDEF PAX64} procedure TProgram.RunEx; var M: TMethod; begin M := OwnerEventHandlerMethod; if Assigned(M.Code) then begin Call_M(M); end else Run; end; {$ELSE} procedure TProgram.RunEx; var M: TMethod; begin M := OwnerEventHandlerMethod; if Assigned(M.Code) then begin asm MOV EAX,DWORD PTR M.Data; CALL M.Code; end; end else Run; end; {$ENDIF} procedure TProgram.DoOnReaderFindMethod( Reader: TReader; const MethodName: string; var Address: Pointer; var Error: Boolean); Var aFullName: String; ER: TEventHandlerRec; MR: TMapRec; M: TMethod; begin aFullName := ProgTypeInfoList.FindMethodFullName(Address); Address := GetAddress(aFullName, MR); M.Code := Address; M.Data := gInstance; Error := Address = Nil; ER := EventHandlerList.Add(Self, M.Code, M.Data, GetCallConv(aFullName), GetRetSize(aFullName)); M.Code := @ TEventHandlerRec.Invoke; M.Data := ER; // Address := nil; end; procedure TProgram.RebindEvents(AnInstance: TObject); procedure _RebindEvents(Instance: TObject); var pti, PropType: PTypeInfo; ptd: PTypeData; Loop, nProps: Integer; pProps: PPropList; ppi: PPropInfo; M: TMethod; C: TComponent; I: Integer; aFullName: String; ER: TEventHandlerRec; begin pti := Instance.ClassInfo; if pti = nil then Exit; ptd := GetTypeData(pti); nProps := ptd^.PropCount; if nProps > 0 then begin GetMem(pProps, SizeOf(PPropInfo) * nProps); GetPropInfos(pti, pProps); for Loop:=0 to nProps - 1 do begin {$ifdef fpc} ppi := pProps^[Loop]; PropType := PPropInfo(ppi)^.PropType; {$else} ppi := pProps[Loop]; PropType := PPropInfo(ppi)^.PropType^; {$endif} if PropType^.Kind = tkMethod then begin M := GetMethodProp(Instance, ppi); if Assigned(M.Code) and Assigned(M.Data) then begin aFullName := ProgTypeInfoList.FindMethodFullName(M.Code); if AFullName = '' then continue; ER := EventHandlerList.Add(Self, M.Code, M.Data, GetCallConv(aFullName), GetRetSize(aFullName)); M.Code := @ TEventHandlerRec.Invoke; M.Data := ER; SetMethodProp(Instance, ppi, M); end; end; end; FreeMem(pProps, SizeOf(PPropInfo) * nProps); end; if Instance is TComponent then begin C := TComponent(Instance); for I := 0 to C.ComponentCount - 1 do _RebindEvents(C.Components[I]); end; end; begin _RebindEvents(AnInstance); end; {$IFDEF PAX64} procedure ZZZ; assembler; {$IFDEF FPC} nostackframe; asm {$ELSE} asm .NOFRAME {$ENDIF} pop rsi; jmp rsi; end; {$ELSE} procedure ZZZ; {$IFDEF FPC} nostackframe; asm {$ELSE} asm {$ENDIF} pop esi; jmp esi; end; {$ENDIF} function TProgram.CallFunc(const FullName: String; This: Pointer; const ParamList: array of OleVariant; OverCount: Integer = 0): OleVariant; const MaxParam = 30; var Invoke, OldEPoint: TInvoke; Address: Pointer; MR: TMapRec; OldESP0, I, NP, T: Integer; Value: OleVariant; {$IFNDEF PAXARM} AnsiStrings: array [0..MaxParam] of AnsiString; WideStrings: array [0..MaxParam] of WideString; ShortStrings: array [0..MaxParam] of ShortString; AnsiS: AnsiString; {$ENDIF} UnicStrings: array [0..MaxParam] of UnicString; valueDouble: Double; valueSingle: Single; valueExtended: Extended; valueCurrency: Currency; UnicS: UnicString; begin Address := GetAddressEx(FullName, OverCount, MR); if Address = nil then RaiseError(errRoutineNotFound, [FullName]); NP := MR.SubDesc.ParamList.Count; if NP > System.Length(ParamList) then RaiseError(errNotEnoughActualParameters, []) else if NP < System.Length(ParamList) then RaiseError(errTooManyActualParameters, []); Invoke := TInvoke.Create; Invoke.CallConv := MR.SubDesc.CallConv; if MR.SubDesc.ResTypeId in (OrdinalTypes + [typeCLASS, typeCLASSREF, typePOINTER, typePROC, typeINTERFACE]) then Invoke.SetResType(typeINTEGER) else Invoke.SetResType(MR.SubDesc.ResTypeId); Invoke.SetResSize(MR.SubDesc.RetSize); Invoke.Address := Address; Invoke.SetThis(This); for I := 0 to NP - 1 do begin T := MR.SubDesc.ParamList[I].FinTypeId; value := ParamList[I]; case T of typeVOID: Invoke.AddArg(value, typeINTEGER); typeBOOLEAN: Invoke.AddArg(value, typeINTEGER); typeBYTE: Invoke.AddArg(value, typeINTEGER); {$IFNDEF PAXARM} typeANSICHAR: Invoke.AddArg(value, typeINTEGER); typeANSISTRING: begin AnsiStrings[I] := AnsiString(value); Invoke.AddArg(IntPax(AnsiStrings[I]), typeINTEGER); end; typeSHORTSTRING: begin ShortStrings[I] := ShortString(value); Invoke.AddArg(LongInt(@ShortStrings[I]), typeINTEGER); end; typeWIDESTRING: begin WideStrings[I] := value; Invoke.AddArg(IntPax(WideStrings[I]), typeINTEGER); end; {$ENDIF} typeWORD: Invoke.AddArg(value, typeINTEGER); typeINTEGER: Invoke.AddArg(value, typeINTEGER); typeDOUBLE: begin valueDouble := value; Invoke.AddArgByVal(valueDouble, SizeOf(Double)); end; typePOINTER: Invoke.AddArg(LongInt(value), typeINTEGER); typeRECORD: Invoke.AddArg(LongInt(value), typeINTEGER); typeARRAY: Invoke.AddArg(LongInt(value), typeINTEGER); typeALIAS: Invoke.AddArg(LongInt(value), typeINTEGER); typeENUM: Invoke.AddArg(LongInt(value), typeINTEGER); typePROC: Invoke.AddArg(LongInt(value), typeINTEGER); typeSET: Invoke.AddArg(LongInt(value), typeINTEGER); typeSINGLE: begin valueSingle := value; Invoke.AddArgByVal(valueSingle, SizeOf(Single)); end; typeEXTENDED: begin valueExtended := value; Invoke.AddArgByVal(valueExtended, SizeOf(Extended)); end; typeCLASS: Invoke.AddArg(LongInt(value), typeINTEGER); typeCLASSREF: Invoke.AddArg(LongInt(value), typeINTEGER); typeWIDECHAR: Invoke.AddArg(LongInt(value), typeINTEGER); typeVARIANT: begin if MR.SubDesc.ParamList[I].ParamMod = PM_BYVAL then Invoke.AddArg(value, typeVARIANT) else Invoke.AddArg(LongInt(@ParamList[I]), typeINTEGER); end; typeDYNARRAY: Invoke.AddArg(LongInt(value), typeINTEGER); typeINT64: Invoke.AddArgByVal(value, SizeOf(Int64)); typeINTERFACE: Invoke.AddArg(LongInt(value), typeINTEGER); typeCARDINAL: Invoke.AddArg(LongInt(value), typeINTEGER); typeEVENT: Invoke.AddArg(LongInt(value), typeINTEGER); typeCURRENCY: begin valueCurrency := value; Invoke.AddArgByVal(valueCurrency, SizeOf(Single)); end; typeSMALLINT: Invoke.AddArg(LongInt(value), typeINTEGER); typeSHORTINT: Invoke.AddArg(LongInt(value), typeINTEGER); typeWORDBOOL: Invoke.AddArg(LongInt(value), typeINTEGER); typeLONGBOOL: Invoke.AddArg(LongInt(value), typeINTEGER); typeBYTEBOOL: Invoke.AddArg(LongInt(value), typeINTEGER); typeOLEVARIANT: Invoke.AddArg(value, typeVARIANT); typeUNICSTRING: begin UnicStrings[I] := value; Invoke.AddArg(IntPax(UnicStrings[I]), typeINTEGER); end; end; end; OldEPoint := EPoint; OldESP0 := fESP0; try Invoke.SetUp; EPoint := Invoke; Run; finally Address := EPoint.GetResultPtr; fESP0 := OldESP0; EPoint := OldEPoint; FreeAndNil(Invoke); end; case MR.SubDesc.ResTypeId of typeVOID: result := Unassigned; typeBOOLEAN: result := Boolean(Address^); typeBYTE: result := Byte(Address^); {$IFNDEF PAXARM} typeANSICHAR: result := AnsiChar(Address^); typeANSISTRING: begin AnsiS := AnsiString(Address^); if Length(AnsiS) > 0 then begin Address := StrRefCountPtr(Pointer(AnsiS)); Integer(Address^) := Integer(Address^) - 1; end; result := AnsiS; end; typeSHORTSTRING: result := ShortString(Address^); typeWIDESTRING: result := WideString(Address^); {$ENDIF} typeWORD: result := Word(Address^); typeINTEGER: result := LongInt(Address^); typeDOUBLE: result := Double(Address^); typePOINTER: result := LongInt(Address^); typeRECORD: result := LongInt(Address); typeARRAY: result := LongInt(Address); typeALIAS: result := Unassigned; typeENUM: result := Byte(Address^); typePROC: result := LongInt(Address^); typeSET: result := LongInt(Address^); typeSINGLE: result := Single(Address^); typeEXTENDED: result := Extended(Address^); typeCLASS: result := LongInt(Address^); typeCLASSREF: result := LongInt(Address^); typeWIDECHAR: result := WideChar(Address^); typeVARIANT: result := Variant(Address^); typeDYNARRAY: result := LongInt(Address^); typeINT64: result := Integer(Address^); typeINTERFACE: result := LongInt(Address^); {$IFDEF VARIANTS} typeCARDINAL: result := Cardinal(Address^); {$ELSE} typeCARDINAL: result := LongInt(Address^); {$ENDIF} typeEVENT: result := Unassigned; typeCURRENCY: result := Currency(Address^); typeSMALLINT: result := SmallInt(Address^); typeSHORTINT: result := ShortInt(Address^); typeWORDBOOL: result := WordBool(Address^); typeLONGBOOL: result := LongBool(Address^); typeBYTEBOOL: result := ByteBool(Address^); typeOLEVARIANT: result := OleVariant(Address^); typeUNICSTRING: begin UnicS := UnicString(Address^); if Length(UnicS) > 0 then begin Address := StrRefCountPtr(Pointer(UnicS)); Integer(Address^) := Integer(Address^) - 1; end; result := UnicS; end; else result := Integer(Address^); end; if IsHalted then raise THaltException.Create(ExitCode); end; function TProgram.CallFuncEx(const FullName: String; This: Pointer; const ParamList: array of const; IsConstructor: Boolean = false; OverCount: integer = 0): Variant; const MaxParam = 30; var Invoke, OldEPoint: TInvoke; Address: Pointer; MR: TMapRec; OldESP0, I, NP, T: Integer; {$IFNDEF PAXARM} AnsiStrings: array [0..MaxParam] of AnsiString; ShortStrings: array [0..MaxParam] of ShortString; WideStrings: array [0..MaxParam] of WideString; {$ENDIF} UnicStrings: array [0..MaxParam] of UnicString; valueDouble: Double; valueSingle: Single; valueExtended: Extended; valueCurrency: Currency; valueInt64: Int64; begin Address := GetAddressEx(FullName, OverCount, MR); if Address = nil then RaiseError(errRoutineNotFound, [FullName]); NP := MR.SubDesc.ParamList.Count; if NP > System.Length(ParamList) then RaiseError(errNotEnoughActualParameters, []) else if NP < System.Length(ParamList) then RaiseError(errTooManyActualParameters, []); Invoke := TInvoke.Create; Invoke.CallConv := MR.SubDesc.CallConv; if MR.SubDesc.ResTypeId in (OrdinalTypes + [typeCLASS, typeCLASSREF, typePOINTER, typePROC, typeINTERFACE]) then Invoke.SetResType(typeINTEGER) else Invoke.SetResType(MR.SubDesc.ResTypeId); Invoke.SetResSize(MR.SubDesc.RetSize); Invoke.Address := Address; Invoke.SetThis(This); if IsConstructor then Invoke.AddArg(1, typeINTEGER); // EDX for I := 0 to NP - 1 do begin T := MR.SubDesc.ParamList[I].FinTypeId; case T of typeVOID: Invoke.AddArg(ParamList[I].VInteger, typeINTEGER); typeBOOLEAN: Invoke.AddArg(ParamList[I].VBoolean, typeINTEGER); typeBYTE: Invoke.AddArg(ParamList[I].VInteger, typeINTEGER); {$IFNDEF PAXARM} typeANSICHAR: Invoke.AddArg(ParamList[I].VChar, typeINTEGER); typeANSISTRING: begin case ParamList[I].VType of vtString: AnsiStrings[I] := PShortString(ParamList[I].VString)^; vtAnsiString: AnsiStrings[I] := PAnsiString(ParamList[I].VAnsiString)^; vtWideString: AnsiStrings[I] := AnsiString(PWideString(ParamList[I].VWideString)^); {$IFDEF UNIC} vtUnicodeString: AnsiStrings[I] := AnsiString(PUnicodeString(ParamList[I].VUnicodeString)^); {$ENDIF} vtVariant: AnsiStrings[I] := AnsiString(PVariant(ParamList[I].VVariant)^); vtChar: AnsiStrings[I] := ParamList[I].VChar; vtWideChar: AnsiStrings[I] := AnsiChar(ParamList[I].VWideChar); end; Invoke.AddArg(IntPax(AnsiStrings[I]), typeINTEGER); end; typeSHORTSTRING: begin case ParamList[I].VType of vtString: ShortStrings[I] := PShortString(ParamList[I].VString)^; vtAnsiString: ShortStrings[I] := PAnsiString(ParamList[I].VAnsiString)^; vtWideString: ShortStrings[I] := ShortString(PWideString(ParamList[I].VWideString)^); {$IFDEF UNIC} vtUnicodeString: ShortStrings[I] := AnsiString(PUnicodeString(ParamList[I].VUnicodeString)^); {$ENDIF} vtVariant: ShortStrings[I] := ShortString(PVariant(ParamList[I].VVariant)^); vtChar: ShortStrings[I] := ParamList[I].VChar; vtWideChar: ShortStrings[I] := AnsiChar(ParamList[I].VWideChar); end; Invoke.AddArg(LongInt(@ShortStrings[I]), typeINTEGER); end; typeWIDESTRING: begin case ParamList[I].VType of vtString: WideStrings[I] := WideString(PShortString(ParamList[I].VString)^); vtAnsiString: WideStrings[I] := WideString(PAnsiString(ParamList[I].VAnsiString)^); vtWideString: WideStrings[I] := PWideString(ParamList[I].VWideString)^; {$IFDEF UNIC} vtUnicodeString: WideStrings[I] := PUnicodeString(ParamList[I].VUnicodeString)^; {$ENDIF} vtVariant: WideStrings[I] := PVariant(ParamList[I].VVariant)^; vtChar: WideStrings[I] := WideChar(ParamList[I].VChar); vtWideChar: WideStrings[I] := ParamList[I].VWideChar; vtPWideChar: WideStrings[I] := ParamList[I].VPWideChar; end; Invoke.AddArg(IntPax(WideStrings[I]), typeINTEGER); end; {$ENDIF} typeWORD: Invoke.AddArg(ParamList[I].VInteger, typeINTEGER); typeINTEGER: Invoke.AddArg(ParamList[I].VInteger, typeINTEGER); typeDOUBLE: begin valueDouble := ParamList[I].VExtended^; Invoke.AddArgByVal(valueDouble, SizeOf(Double)); end; typePOINTER: Invoke.AddArg(LongInt(ParamList[I].VPointer), typeINTEGER); typeRECORD: Invoke.AddArg(LongInt(ParamList[I].VPointer), typeINTEGER); typeARRAY: Invoke.AddArg(LongInt(ParamList[I].VPointer), typeINTEGER); typeALIAS: Invoke.AddArg(ParamList[I].VInteger, typeINTEGER); typeENUM: Invoke.AddArg(ParamList[I].VInteger, typeINTEGER); typePROC: Invoke.AddArg(LongInt(ParamList[I].VPointer), typeINTEGER); typeSET: Invoke.AddArg(ParamList[I].VInteger, typeINTEGER); typeSINGLE: begin valueSingle := ParamList[I].VExtended^; Invoke.AddArgByVal(valueSingle, SizeOf(Single)); end; typeEXTENDED: begin valueExtended := ParamList[I].VExtended^; Invoke.AddArgByVal(valueExtended, SizeOf(Extended)); end; typeCLASS: Invoke.AddArg(LongInt(ParamList[I].VObject), typeINTEGER); typeCLASSREF: Invoke.AddArg(LongInt(ParamList[I].VPointer), typeINTEGER); typeWIDECHAR: Invoke.AddArg(LongInt(ParamList[I].VWideChar), typeINTEGER); typeVARIANT: begin if MR.SubDesc.ParamList[I].ParamMod = PM_BYVAL then Invoke.AddArg(ParamList[I].VVariant^, typeVARIANT) else Invoke.AddArg(LongInt(ParamList[I].VVariant), typeINTEGER); end; typeDYNARRAY: Invoke.AddArg(LongInt(ParamList[I].VPointer), typeINTEGER); typeINT64: case ParamList[i].VType of vtInteger: begin valueInt64 := Int64(ParamList[I].VInteger); Invoke.AddArgByVal(valueInt64, SizeOf(Int64)); end; else Invoke.AddArgByVal(ParamList[I].VInt64^, SizeOf(Int64)); end; typeINTERFACE: Invoke.AddArg(LongInt(ParamList[I].VInterface), typeINTEGER); typeCARDINAL: Invoke.AddArg(ParamList[I].VInteger, typeINTEGER); typeEVENT: Invoke.AddArg(ParamList[I].VInteger, typeINTEGER); typeCURRENCY: begin valueCurrency := ParamList[I].VExtended^; Invoke.AddArgByVal(valueCurrency, SizeOf(Single)); end; typeSMALLINT: Invoke.AddArg(ParamList[I].VInteger, typeINTEGER); typeSHORTINT: Invoke.AddArg(ParamList[I].VInteger, typeINTEGER); typeWORDBOOL: Invoke.AddArg(ParamList[I].VInteger, typeINTEGER); typeLONGBOOL: Invoke.AddArg(ParamList[I].VInteger, typeINTEGER); typeBYTEBOOL: Invoke.AddArg(ParamList[I].VInteger, typeINTEGER); typeOLEVARIANT: begin if MR.SubDesc.ParamList[I].ParamMod = PM_BYVAL then Invoke.AddArg(ParamList[I].VVariant^, typeVARIANT) else Invoke.AddArg(LongInt(ParamList[I].VVariant), typeINTEGER); end; typeUNICSTRING: begin case ParamList[I].VType of {$IFNDEF PAXARM} vtString: UnicStrings[I] := UnicString(PShortString(ParamList[I].VString)^); vtAnsiString: UnicStrings[I] := UnicString(PAnsiString(ParamList[I].VAnsiString)^); vtWideString: UnicStrings[I] := PWideString(ParamList[I].VWideString)^; vtChar: UnicStrings[I] := WideChar(ParamList[I].VChar); {$ENDIF} {$IFDEF UNIC} vtUnicodeString: UnicStrings[I] := PUnicodeString(ParamList[I].VUnicodeString)^; {$ENDIF} vtVariant: UnicStrings[I] := PVariant(ParamList[I].VVariant)^; vtWideChar: UnicStrings[I] := ParamList[I].VWideChar; vtPWideChar: UnicStrings[I] := ParamList[I].VPWideChar; end; Invoke.AddArg(IntPax(UnicStrings[I]), typeINTEGER); end; end; end; OldEPoint := EPoint; OldESP0 := fESP0; try Invoke.SetUp; EPoint := Invoke; Run; finally Address := EPoint.GetResultPtr; fESP0 := OldESP0; EPoint := OldEPoint; FreeAndNil(Invoke); end; case MR.SubDesc.ResTypeId of typeVOID: result := Unassigned; typeBOOLEAN: result := Boolean(Address^); typeBYTE: result := Byte(Address^); {$IFNDEF PAXARM} typeANSICHAR: result := AnsiChar(Address^); typeANSISTRING: result := AnsiString(Address^); typeSHORTSTRING: result := ShortString(Address^); typeWIDESTRING: result := WideString(Address^); {$ENDIF} typeWORD: result := Word(Address^); typeINTEGER: result := LongInt(Address^); typeDOUBLE: result := Double(Address^); typePOINTER: result := LongInt(Address^); typeRECORD: result := LongInt(Address); typeARRAY: result := LongInt(Address); typeALIAS: result := Unassigned; typeENUM: result := Byte(Address^); typePROC: result := LongInt(Address^); typeSET: result := LongInt(Address^); typeSINGLE: result := Single(Address^); typeEXTENDED: result := Extended(Address^); typeCLASS: result := LongInt(Address^); typeCLASSREF: result := LongInt(Address^); typeWIDECHAR: result := WideChar(Address^); typeVARIANT: result := Variant(Address^); typeDYNARRAY: result := LongInt(Address^); typeINT64: result := LongInt(Address^); typeINTERFACE: result := LongInt(Address^); {$IFDEF VARIANTS} typeCARDINAL: result := Cardinal(Address^); {$ELSE} typeCARDINAL: result := LongInt(Address^); {$ENDIF} typeEVENT: result := Unassigned; typeCURRENCY: result := Currency(Address^); typeSMALLINT: result := SmallInt(Address^); typeSHORTINT: result := ShortInt(Address^); typeWORDBOOL: result := WordBool(Address^); typeLONGBOOL: result := LongBool(Address^); typeBYTEBOOL: result := ByteBool(Address^); typeOLEVARIANT: result := OleVariant(Address^); typeUNICSTRING: result := UnicString(Address^); else result := LongInt(Address^); end; if IsHalted then raise THaltException.Create(ExitCode); end; function TProgram.CreateScriptObject(const ScriptClassName: String; const ParamList: array of const): TObject; var ClassIndex: Integer; PClass: TClass; MR: TMapRec; NP: Integer; V: Variant; begin result := nil; ClassIndex := ClassList.IndexOf(ScriptClassName); if ClassIndex = -1 then RaiseError(errClassNotFound, [ScriptClassName]); PClass := ClassList[ClassIndex].PClass; NP := System.Length(ParamList); MR := ScriptMapTable.LookupConstructor(ScriptClassName, NP); if MR = nil then Exit; V := CallFuncEx(MR.FullName, PClass, ParamList, true, MR.SubDesc.OverCount); result := TObject(TVarData(V).VInteger); end; function TProgram.GetTryStack: TTryStack; begin result := RootProg.fTryStack; end; function TProgram.GetCallStack: TCallStack; begin result := RootProg.fCallStack; end; function TProgram.GetESP0: Integer; begin result := RootProg.fESP0; end; procedure TProgram.SetESP0(value: Integer); begin RootProg.fESP0 := value; end; function TProgram.GetCurrException: Exception; begin result := fCurrException; end; procedure TProgram.SetCurrException(value: Exception); begin fCurrException := value; end; function TProgram.GetVirtualAllocProg: Boolean; begin result := RootProg.fVirtualAllocProg; end; procedure TProgram.SetVirtualAllocProg(value: Boolean); begin RootProg.fVirtualAllocProg := value; end; function TProgram._VirtualAlloc(Address: Pointer; Size, flAllocType, flProtect: Cardinal): Pointer; begin {$IFDEF MSWINDOWS} if VirtualAllocProg then result := VirtualAlloc(Address, Size, flAllocType, flProtect) else result := AllocMem(Size); {$ELSE} result := AllocMem(Size); {$ENDIF} end; procedure TProgram._VirtualFree(Address: Pointer; Size: Cardinal); begin {$IFDEF MSWINDOWS} if VirtualAllocProg then VirtualFree(Address, 0, MEM_RELEASE) else FreeMem(Address, Size); {$ELSE} FreeMem(Address, Size); {$ENDIF} end; function TProgram.GetRootProg: TProgram; begin result := Self; while result.PCUOwner <> nil do result := result.PCUOwner as TProgram; end; function TProgram.GetCallStackCount: Integer; begin result := RootCallStack.Count; end; function TProgram.GetCallStackItem(I: Integer): Integer; begin if (I >= 0) and (I < GetCallStackCount) then result := RootCallStack[I].SubId else result := 0; end; function TProgram.GetCallStackLineNumber(I: Integer): Integer; var N: Integer; begin if (I >= 0) and (I < GetCallStackCount) then begin N := RootCallStack[I].NCall; if N = -1 then begin N := GetByteCodeLine; RootCallStack[I].NCall := N; end; result := RunTimeModuleList.GetSourceLine(N); end else result := 0; end; function TProgram.GetCallStackModuleName(I: Integer): String; var N: Integer; begin result := ''; if (I >= 0) and (I < GetCallStackCount) then begin N := RootCallStack[I].NCall; if N = - 1 then Exit; result := RunTimeModuleList.GetModuleName(N); end; end; function TProgram.GetCallStackModuleIndex(I: Integer): Integer; var N: Integer; begin result := -1; if (I >= 0) and (I < GetCallStackCount) then begin N := RootCallStack[I].NCall; if N = - 1 then Exit; result := RunTimeModuleList.GetModuleIndex(N); end; end; procedure TProgram.DiscardPause; begin PauseRec.ProgOffset := 0; end; procedure TProgram.SetEntryPoint(EntryPoint: TPaxInvoke); begin if EntryPoint = nil then EPoint := nil else begin EPoint := TInvoke(EntryPoint.GetImplementation); TInvoke(EntryPoint.GetImplementation).OldESP0 := RootESP0; end; end; procedure TProgram.ResetEntryPoint(EntryPoint: TPaxInvoke); begin if EntryPoint = nil then Exit else RootESP0 := TInvoke(EntryPoint.GetImplementation).OldESP0; end; procedure TProgram.AssignEventHandlerRunner(MethodAddress: Pointer; Instance: TObject); begin OwnerEventHandlerMethod.Code := MethodAddress; OwnerEventHandlerMethod.Data := Instance; end; function TProgram.GetDestructorAddress: Pointer; begin result := Address_DestroyObject; end; function TProgram.GetParamAddress(Offset: Integer): Pointer; var EBP_Value: IntPax; begin EBP_Value := RootCallStack.Top.EBP; result := PauseRec.GetPtr(EBP_Value, Offset); end; function TProgram.GetLocalAddress(Offset: Integer): Pointer; var EBP_Value: IntPax; begin EBP_Value := RootCallStack.Top.EBP; result := PauseRec.GetPtr(EBP_Value, Offset); end; function TProgram.GetParamAddress(StackFrameNumber, Offset: Integer): Pointer; var EBP_Value: IntPax; begin result := nil; if StackFrameNumber >= 0 then EBP_Value := RootCallStack[StackFrameNumber].EBP else Exit; result := PauseRec.GetPtr(EBP_Value, Offset); end; function TProgram.GetLocalAddress(StackFrameNumber, Offset: Integer): Pointer; var EBP_Value: IntPax; begin result := nil; if StackFrameNumber >= 0 then EBP_Value := RootCallStack[StackFrameNumber].EBP else Exit; result := PauseRec.GetPtr(EBP_Value, Offset); end; end.
unit Forms.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AdvMemo, Vcl.StdCtrls; const DEMO_TITLE = 'FNC Core Utils - JSON'; DEMO_BUTTON = 'Execute'; type TFrmMain = class(TForm) btnExecute: TButton; txtLog: TAdvMemo; procedure btnExecuteClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } FJSON: String; procedure DoExecute; public { Public declarations } end; var FrmMain: TFrmMain; implementation {$R *.dfm} uses System.JSON, TMSFNCUtils; procedure TFrmMain.btnExecuteClick(Sender: TObject); begin DoExecute; end; procedure TFrmMain.DoExecute; var LArray: TJSONArray; LItem: TJSONObject; LName: TJSONObject; LFriends: TJSONArray; LFriendItem: TJSONObject; i : Integer; begin LArray := TTMSFNCUtils.ParseJSON(FJSON) as TJSONArray; txtLog.Lines.Add( Format( 'Records: %d', [ TTMSFNCUtils.GetJSONArraySize(LArray) ] ) ); LItem := TTMSFNCUtils.GetJSONArrayItem( LArray, 0 ) as TJSONObject; LName := TTMSFNCUtils.GetJSONValue(LItem, 'name') as TJSONObject; txtLog.Lines.Add( 'First: ' + TTMSFNCUtils.GetJSONProp(LName, 'first')); txtLog.Lines.Add( 'Last: ' + TTMSFNCUtils.GetJSONProp(LName, 'last')); LFriends := TTMSFNCUtils.GetJSONValue(LItem, 'friends') as TJSONArray; for i := 0 to TTMSFNCUtils.GetJSONArraySize(LFriends)-1 do begin LFriendItem := TTMSFNCUtils.GetJSONArrayItem(LFriends, i) as TJSONObject; txtLog.Lines.Add( Format( 'Friend %d: %s', [ i+1, TTMSFNCUtils.GetJSONProp(LFriendItem, 'name')] ) ); end; end; procedure TFrmMain.FormCreate(Sender: TObject); begin btnExecute.Caption := DEMO_BUTTON; self.Caption := DEMO_TITLE; txtLog.Lines.Clear; FJSON := '[' + '{' + ' "index": 1,' + ' "guid": "cfbb764a-cde9-4f0e-ab18-9bf35fbc69ee",' + ' "name": {' + ' "first": "Marta",' + ' "last": "Byrd",' + ' "full": "Byrd, Marta"' + ' },' + ' "email": "marta.byrd@undefined.name",' + ' "phone": "+1 (933) 553-3181",' + ' "friends": [' + ' {' + ' "id": 0,' + ' "name": "Lilly Hammond"' + ' },' + ' {' + ' "id": 1,' + ' "name": "England Sellers"' + ' },' + ' {' + ' "id": 2,' + ' "name": "Autumn Jones"' + ' }' + ' ]' + '}' + ']'; end; end.
namespace SharedUI.Shared; type AppDelegate = public partial class public property mainWindowController: MainWindowController read private write; method start; begin // // this is the cross-platform entry point for the app // mainWindowController := new MainWindowController(); mainWindowController.showWindow(nil); end; // // Add Shared code here // end; end.
EXTERN {=================================================================} FUNCTION sin (x : real) : real; CONST pi = 3.1415926535897; two_pi = 6.2831853071796; VAR i : integer; {=================================================================} PROCEDURE compute_sin; VAR result, result2, f, exclam, x2, power : real; odd1, i : integer; BEGIN (* compute_sin *) x2 := sqr(x); power := x * x2; odd1 := - 1; i := 0; result := x; exclam := 6.0; f := 3.0; REPEAT result2 := result; IF odd1 = 1 THEN result := result + (power / exclam) ELSE result := result - (power / exclam); power := power * x2; odd1 := - odd1; f := f + 2.0; exclam := f * (f - 1.0) * exclam; i := i + 1; IF i > 5 THEN BEGIN i := 0; IF abs(result - result2) < (1e-12 * result) THEN result2 := result; END; UNTIL result = result2; sin := result; END; (* compute_sin *) BEGIN (* sin *) IF (x = 0.0) OR (x = pi) OR (x = two_pi) THEN sin := 0.0 ELSE BEGIN WHILE x < 0.0 DO x := x + two_pi; WHILE x > two_pi DO x := x - two_pi; IF x > 1.0e-08 THEN compute_sin ELSE sin := x; END; (* else *) END; (* sin *) . 
unit uFrmServerConnection; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uParent, siComp, ExtCtrls, StdCtrls, IniFiles, ComCtrls; const CON_DCOM = 0; CON_SOCKET = 1; CON_WEB = 2; type TFrmServerConnection = class(TFrmParent) Panel1: TPanel; BNext: TButton; BClose: TButton; bvBottom: TBevel; pgOption: TPageControl; tsConnection: TTabSheet; Label1: TLabel; lbHost: TLabel; lbPort: TLabel; Label2: TLabel; cbxConnectionType: TComboBox; edtHost: TEdit; edtPort: TEdit; edtClientID: TEdit; tsLicense: TTabSheet; Label3: TLabel; Label4: TLabel; btnLicense: TButton; lbKey: TLabel; lbExpiration: TLabel; procedure cbxConnectionTypeChange(Sender: TObject); procedure BNextClick(Sender: TObject); procedure BCloseClick(Sender: TObject); procedure btnLicenseClick(Sender: TObject); private procedure GetConfigFile; procedure SetConfigFile; procedure RefreshConType; procedure DisplayKeyInfo; public function Start(iOption : Integer):Boolean; end; implementation uses uDMImportExport, uDMGlobalNTier, uMainRetailKeyConst, uMsgBox; {$R *.dfm} { TFrmServerConnection } function TFrmServerConnection.Start(iOption : Integer): Boolean; begin tsConnection.TabVisible := False; tsLicense.TabVisible := False; case iOption of 1 : begin GetConfigFile; tsConnection.TabVisible := True; end; 2 : begin DisplayKeyInfo; tsLicense.TabVisible := True; end; end; ShowModal; end; procedure TFrmServerConnection.DisplayKeyInfo; begin lbKey.Caption := Copy(DMImportExport.FMRKey, 1, 10) + ' ... ' + Copy(DMImportExport.FMRKey, Length(DMImportExport.FMRKey)-10, Length(DMImportExport.FMRKey)); lbExpiration.Caption := FormatDateTime('ddddd', DMImportExport.FSoftwareExpirationDate); end; procedure TFrmServerConnection.cbxConnectionTypeChange(Sender: TObject); begin inherited; RefreshConType; end; procedure TFrmServerConnection.GetConfigFile; var sConType : String; begin sConType := DMImportExport.GetAppProperty('Connection', 'Type'); if sConType = CON_TYPE_SOCKET then cbxConnectionType.ItemIndex := CON_SOCKET else if sConType = CON_TYPE_DCOM then cbxConnectionType.ItemIndex := CON_DCOM else if sConType = CON_TYPE_WEB then cbxConnectionType.ItemIndex := CON_WEB; RefreshConType; edtClientID.Text := DMImportExport.GetAppProperty('Connection', 'ClientID'); edtHost.Text := DMImportExport.GetAppProperty('Connection', 'Host'); edtPort.Text := DMImportExport.GetAppProperty('Connection', 'Port'); end; procedure TFrmServerConnection.SetConfigFile; begin if tsConnection.TabVisible then begin case cbxConnectionType.ItemIndex of CON_SOCKET : DMImportExport.SetAppProperty('Connection', 'Type', CON_TYPE_SOCKET); CON_DCOM : DMImportExport.SetAppProperty('Connection', 'Type', CON_TYPE_DCOM); CON_WEB : DMImportExport.SetAppProperty('Connection', 'Type', CON_TYPE_WEB); end; DMImportExport.SetAppProperty('Connection', 'ClientID', edtClientID.Text); DMImportExport.SetAppProperty('Connection', 'Host', edtHost.Text); DMImportExport.SetAppProperty('Connection', 'Port', edtPort.Text); end; end; procedure TFrmServerConnection.BNextClick(Sender: TObject); begin inherited; SetConfigFile; Close; end; procedure TFrmServerConnection.BCloseClick(Sender: TObject); begin inherited; Close; end; procedure TFrmServerConnection.RefreshConType; var fPort : Boolean; begin inherited; case cbxConnectionType.ItemIndex of CON_DCOM : fPort := False; CON_SOCKET : fPort := True; CON_WEB : fPort := False; end; lbPort.Visible := fPort; edtPort.Visible := fPort; end; procedure TFrmServerConnection.btnLicenseClick(Sender: TObject); begin inherited; DMImportExport.ActiveConnection.AppServer.SoftwareDelete(SOFTWARE_IE); MsgBox('License Updated. Close Import/Export and reopen it to use your new license.', vbInformation + vbOKOnly); end; end.
unit Personas.View.Desktop; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Rtti, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.ScrollBox, FMX.StdCtrls, FMX.Objects, FMX.Edit, FMX.Layouts, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView, FMX.ListBox, FMX.Grid, FMX.Grid.Style, System.Actions, FMX.ActnList, DataSet.Interfaces, MVVM.Attributes, MVVM.Interfaces, MVVM.Bindings, MVVM.Controls.Platform.FMX, MVVM.Views.Platform.FMX; type [View_For_ViewModel('PersonasMain', IDataSet_ViewModel, 'WINDOWS_DESKTOP')] TfrmPersonasDesktop = class(TFormView<IDataSet_ViewModel>) Layout1: TLayout; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Grid1: TGrid; ActionList1: TActionList; [Command(GET_ROWS)] actGet: TAction; [Command(APPEND_ROW, DATASET_IS_OPEN)] actNew: TAction; [Command(DELETE_ROW, DATASET_IS_OPEN)] actDelete: TAction; [Command(UPDATE_ROW, DATASET_IS_OPEN)] actUpdate: TAction; Button5: TButton; Button6: TButton; [Command(CLOSE_DATASET, DATASET_IS_OPEN)] actCloseDataSet: TAction; [Command(OPEN_DATASET, DATASET_IS_CLOSED)] actOpenDataSet: TAction; protected { Private declarations } procedure SetupView; override; public { Public declarations } end; implementation uses DataSet.ViewModel, MVVM.Core, MVVM.Types; {$R *.fmx} procedure TfrmPersonasDesktop.SetupView; begin inherited; // dataset configuration ViewModel.TableName := 'Personas'; // views configuration ViewModel.NewRowView := 'New.Persona'; ViewModel.UpdateRowView := 'Update.Persona'; // actions binding //actGet.Bind(ViewModel.DoMakeGetRows); //actNew.Bind(ViewModel.DoMakeAppend, ViewModel.IsOpen); //actUpdate.Bind(ViewModel.DoMakeUpdate, ViewModel.IsOpen); //actDelete.Bind(ViewModel.DoDeleteActiveRow, ViewModel.IsOpen); // Dataset binding ViewModel.DoMakeGetRows; //open the dataset and get rows Binder.BindDataSetToGrid(ViewModel.DataSet, Grid1); end; initialization TfrmPersonasDesktop.ClassName; end.
{------------------------------------------------------------------------------- Unit Name: frmColourTool Author: HochwimmerA Purpose: Colour Tool - used to enter colour by RGBA or Hex and output to file Thanks to Dave Kerr for the suggestion. History: -------------------------------------------------------------------------------} unit frmColourTool; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGrids, DB, ComCtrls, geExportFile, geImportFile, ToolWin, ActnMan, ActnCtrls, XPStyleActnCtrls, ActnList, StdCtrls, ExtCtrls, {kbmMemTable,} cUtilities, ImgList, GLTexture, GLColor ; type TformColourEdit = class(TForm) ActionManager: TActionManager; ActionToolBarColourEdit: TActionToolBar; dsRGBA: TDataSource; geExportFile: TGEExportFile; geImportFile: TGEImportFile; PageControl1: TPageControl; tsHex: TTabSheet; tsRGB: TTabSheet; dsHex: TDataSource; dbgRGBA: TDBGrid; dbgHex: TDBGrid; acImport: TAction; ImageList: TImageList; acExport: TAction; acImportCSV: TAction; acImportTSV: TAction; acImportSSV: TAction; acImportFixed: TAction; acImportClipboard: TAction; acExportCSV: TAction; acExportSSV: TAction; acExportTSV: TAction; acExportLatex: TAction; acExportXML: TAction; acExportClipboard: TAction; acDone: TAction; ColorDialog: TColorDialog; ///kbmRGBA: TkbmMemTable; ///kbmHex: TkbmMemTable; procedure dbgHexDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure acImportExecute(Sender: TObject); procedure PageControl1Change(Sender: TObject); procedure FormShow(Sender: TObject); procedure dbgRGBADrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure kbmRGBABeforePost(DataSet: TDataSet); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure acExportExecute(Sender: TObject); procedure acExportUpdate(Sender: TObject); procedure acImportClipboardExecute(Sender: TObject); procedure acImportClipboardUpdate(Sender: TObject); procedure acImportCSVExecute(Sender: TObject); procedure acImportCSVUpdate(Sender: TObject); procedure acImportFixedExecute(Sender: TObject); procedure acImportFixedUpdate(Sender: TObject); procedure acImportSSVExecute(Sender: TObject); procedure acImportSSVUpdate(Sender: TObject); procedure acImportTSVExecute(Sender: TObject); procedure acImportTSVUpdate(Sender: TObject); procedure acExportCSVExecute(Sender: TObject); procedure acExportCSVUpdate(Sender: TObject); procedure acExportSSVExecute(Sender: TObject); procedure acExportSSVUpdate(Sender: TObject); procedure acExportTSVExecute(Sender: TObject); procedure acExportTSVUpdate(Sender: TObject); procedure acExportLatexExecute(Sender: TObject); procedure acExportLatexUpdate(Sender: TObject); procedure acExportXMLExecute(Sender: TObject); procedure acExportXMLUpdate(Sender: TObject); procedure acExportClipboardExecute(Sender: TObject); procedure acExportClipboardUpdate(Sender: TObject); procedure acDoneExecute(Sender: TObject); procedure dbgHexDblClick(Sender: TObject); procedure dbgRGBADblClick(Sender: TObject); private aGLColour : TGLColor; public end; implementation {$R *.dfm} // ----- TfrmColourEdit.dbgHexDrawColumnCell ----------------------------------- procedure TformColourEdit.dbgHexDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if (Column.Field.FieldName <> 'Hex') then dbgHex.DefaultDrawColumnCell(Rect,DataCol,Column,State) else begin {** Colour} if (Column.Field.DisplayText = '') then dbgHex.Canvas.Brush.Color := clWhite else try dbgHex.Canvas.Brush.Color := HexToColor(Column.Field.DisplayText); except dbgHex.Canvas.Brush.Color := clWhite; end; dbgHex.DefaultDrawColumnCell(Rect,DataCol,Column,State); end; end; // ----- TfrmColourEdit.acImportExecute ---------------------------------------- procedure TformColourEdit.acImportExecute(Sender: TObject); begin ///geImportFile.Destination.Edit; geImportFile.Execute; end; // ----- TfrmColourEdit.PageControl1Change ------------------------------------- procedure TformColourEdit.PageControl1Change(Sender: TObject); begin if PageControl1.ActivePage = tsHex then begin geImportFile.Identifier := 'Hex'; ///geImportFile.Destination := kbmHex; geExportFile.Identifier := 'Hex'; ///geExportFile.Source := kbmHex; end else if (PageControl1.ActivePage = tsRGB) then begin geImportFile.Identifier := 'RGBA'; ///geImportFile.Destination := kbmRGBA; geExportFile.Identifier := 'RGBA'; ///geExportFile.Source := kbmRGBA; end; end; // ----- TfrmColourEdit.FormShow ----------------------------------------------- procedure TformColourEdit.FormShow(Sender: TObject); begin PageControl1Change(nil); // set up the hex end; // ----- TformColourEdit.dbgRGBADrawColumnCell --------------------------------- procedure TformColourEdit.dbgRGBADrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if (Column.Field.FieldName <> 'Hex') then dbgRGBA.DefaultDrawColumnCell(Rect,DataCol,Column,State) else begin {** Colour} if (Column.Field.DisplayText = '') then dbgRGBA.Canvas.Brush.Color := clWhite else try dbgRGBA.Canvas.Brush.Color := HexToColor(Column.Field.DisplayText); except dbgRGBA.Canvas.Brush.Color := clWhite; end; dbgRGBA.DefaultDrawColumnCell(Rect,DataCol,Column,State); end; end; // ----- TformColourEdit.kbmRGBABeforePost ------------------------------------- // before posting ensure that the R,G,B,A fields are bounded : [0,1] procedure TformColourEdit.kbmRGBABeforePost(DataSet: TDataSet); procedure BoundField(aField:TField); begin if (aField.AsFloat < 0.0) then aField.AsFloat := 0.0 else if (aField.AsFloat > 1.0) then aField.AsFloat := 1.0; end; begin (* BoundField(kbmRGBA.FieldByName('Red')); BoundField(kbmRGBA.FieldByName('Green')); BoundField(kbmRGBA.FieldByName('Blue')); BoundField(kbmRGBA.FieldByName('Alpha')); // calculate Hex string aGLColour.Red := kbmRGBA.FieldByName('Red').AsFloat; aGLColour.Blue := kbmRGBA.FieldByName('Blue').AsFloat; aGLColour.Green := kbmRGBA.FieldByName('Green').AsFloat; aGLColour.Alpha := kbmRGBA.FieldByName('Alpha').AsFloat; kbmRGBA.FieldByName('Hex').AsString := ColorToHex(aGLColour.AsWinColor); *) end; // ----- TformColourEdit.FormCreate -------------------------------------------- procedure TformColourEdit.FormCreate(Sender: TObject); begin aGLColour := TGLColor.Create(nil); end; // ----- TformColourEdit.FormDestroy ------------------------------------------- procedure TformColourEdit.FormDestroy(Sender: TObject); begin aGLColour.Free; end; // ----- TformColourEdit.acExportExecute --------------------------------------- procedure TformColourEdit.acExportExecute(Sender: TObject); begin GEExportFile.Execute; end; // ----- TformColourEdit.acExportUpdate ---------------------------------------- procedure TformColourEdit.acExportUpdate(Sender: TObject); begin acExport.Enabled := (geExportFile.Source.RecordCount > 0); end; // ----- TformColourEdit.acImportCSVExecute ------------------------------------ procedure TformColourEdit.acImportCSVExecute(Sender: TObject); begin geImportFile.ImportFileType := ifCSV; acImport.Execute; end; // ----- TformColourEdit.acImportCSVUpdate ------------------------------------- procedure TformColourEdit.acImportCSVUpdate(Sender: TObject); begin acImportCSV.Checked := (geImportFile.ImportFileType = ifCSV); end; // ----- TformColourEdit.acImportTSVExecute ------------------------------------ procedure TformColourEdit.acImportTSVExecute(Sender: TObject); begin geImportFile.ImportFileType := ifTSV; acImport.Execute; end; // ----- TformColourEdit.acImportTSVUpdate ------------------------------------- procedure TformColourEdit.acImportTSVUpdate(Sender: TObject); begin acImportTSV.Checked := (geImportFile.ImportFileType = ifTSV); end; // ----- TformColourEdit.acImportSSVExecute ------------------------------------ procedure TformColourEdit.acImportSSVExecute(Sender: TObject); begin geImportFile.ImportFileType := ifSSV; acImport.Execute; end; // ----- TformColourEdit.acImportSSVUpdate ------------------------------------- procedure TformColourEdit.acImportSSVUpdate(Sender: TObject); begin acImportSSV.Checked := (geImportFile.ImportFileType = ifSSV); end; // ----- TformColourEdit.acImportFixedExecute ---------------------------------- procedure TformColourEdit.acImportFixedExecute(Sender: TObject); begin geImportFile.ImportFileType := ifFixedFormatSpace; acImport.Execute; end; // ----- TformColourEdit.acImportFixedUpdate ----------------------------------- procedure TformColourEdit.acImportFixedUpdate(Sender: TObject); begin acImportFixed.Checked := (geImportFile.ImportFileType = ifFixedFormatSpace); end; // ----- TformColourEdit.acImportClipboardExecute ------------------------------ procedure TformColourEdit.acImportClipboardExecute(Sender: TObject); begin geImportFile.ImportFileType := ifClipboard; acImport.Execute; end; // ----- TformColourEdit.acImportClipboardUpdate ------------------------------- procedure TformColourEdit.acImportClipboardUpdate(Sender: TObject); begin acImportClipboard.Checked := (geImportFile.ImportFileType = ifClipboard); end; // ----- TformColourEdit.acExportCSVExecute ------------------------------------ procedure TformColourEdit.acExportCSVExecute(Sender: TObject); begin GEExportFile.ExportFileType := efCSV; GEExportFile.Execute; end; // ----- TformColourEdit.acExportCSVUpdate ------------------------------------- procedure TformColourEdit.acExportCSVUpdate(Sender: TObject); begin acExportCSV.Checked := (geExportFile.ExportFileType = efCSV); end; // ----- TformColourEdit.acExportSSVExecute ------------------------------------ procedure TformColourEdit.acExportSSVExecute(Sender: TObject); begin GEExportFile.ExportFileType := efSSV; GEExportFile.Execute; end; // ----- TformColourEdit.acExportSSVUpdate ------------------------------------- procedure TformColourEdit.acExportSSVUpdate(Sender: TObject); begin acExportSSV.Checked := (geExportFile.ExportFileType = efSSV); end; // ----- TformColourEdit.acExportTSVExecute ------------------------------------ procedure TformColourEdit.acExportTSVExecute(Sender: TObject); begin GEExportFile.ExportFileType := efTSV; GEExportFile.Execute; end; // ----- TformColourEdit.acExportTSVUpdate ------------------------------------- procedure TformColourEdit.acExportTSVUpdate(Sender: TObject); begin acExportTSV.Checked := (geExportFile.ExportFileType = efTSV); end; // ----- TformColourEdit.acExportLatexExecute ---------------------------------- procedure TformColourEdit.acExportLatexExecute(Sender: TObject); begin GEExportFile.ExportFileType := efLaTex; GEExportFile.Execute; end; // ----- TformColourEdit.acExportLatexUpdate ----------------------------------- procedure TformColourEdit.acExportLatexUpdate(Sender: TObject); begin acExportLatex.Checked := (geExportFile.ExportFileType = efLatex); end; // ----- TformColourEdit.acExportXMLExecute ------------------------------------ procedure TformColourEdit.acExportXMLExecute(Sender: TObject); begin GEExportFile.ExportFileType := efXML; GEExportFile.Execute; end; // ----- TformColourEdit.acExportXMLUpdate ------------------------------------- procedure TformColourEdit.acExportXMLUpdate(Sender: TObject); begin acExportXML.Checked := (geExportFile.ExportFileType = efXML); end; // ----- TformColourEdit.acExportClipboardExecute ------------------------------ procedure TformColourEdit.acExportClipboardExecute(Sender: TObject); begin GEExportFile.ExportFileType := efClipboard; GEExportFile.Execute; end; // ----- TformColourEdit.acExportClipboardUpdate ------------------------------- procedure TformColourEdit.acExportClipboardUpdate(Sender: TObject); begin acExportClipboard.Checked := (geExportFile.ExportFileType = efClipboard); end; // ----- TformColourEdit.acDoneExecute ----------------------------------------- procedure TformColourEdit.acDoneExecute(Sender: TObject); begin Close; end; // ============================================================================= procedure TformColourEdit.dbgHexDblClick(Sender: TObject); begin (* if (dbgHex.Columns.Items[dbgHex.SelectedIndex].FieldName = 'Hex') then begin if (kbmHex.FieldByName('Hex').AsString <> '') then begin try ColorDialog.Color := HexToColor(kbmHex.FieldByName('Hex').AsString) except ColorDialog.Color := clWhite; end; end else ColorDialog.Color := clWhite; if ColorDialog.Execute then begin kbmHex.Edit; kbmHex.FieldByName('Hex').AsString := ColorToHex(ColorDialog.Color); kbmHex.Post; end; end; *) end; // ----- TformColourEdit.dbgRGBADblClick --------------------------------------- procedure TformColourEdit.dbgRGBADblClick(Sender: TObject); begin (* if (dbgRGBA.Columns.Items[dbgRGBA.SelectedIndex].FieldName = 'Hex') then begin if (kbmRGBA.FieldByName('Hex').AsString <> '') then begin try ColorDialog.Color := HexToColor(kbmRGBA.FieldByName('Hex').AsString) except ColorDialog.Color := clWhite; end; end else ColorDialog.Color := clWhite; if ColorDialog.Execute then begin aGLColour.AsWinColor := ColorDialog.Color; kbmRGBA.Edit; kbmRGBA.FieldByName('Red').AsFloat := aGLColour.Red; kbmRGBA.FieldByName('Green').AsFloat := aGLColour.Green; kbmRGBA.FieldByName('Blue').AsFloat := aGLColour.Blue; kbmRGBA.Post; end; end; *) end; // ============================================================================= end.
unit Demo.ColumnChart.LabelingColumns; interface uses System.Classes, Demo.BaseFrame, cfs.GCharts; type TDemo_ColumnChart_LabelingColumns = class(TDemoBaseFrame) public procedure GenerateChart; override; end; implementation procedure TDemo_ColumnChart_LabelingColumns.GenerateChart; var Chart1, Chart2: IcfsGChartProducer; // Defined as TInterfacedObject No need try..finally begin // Chart 1 Chart1 := TcfsGChartProducer.Create; Chart1.ClassChartType := TcfsGChartProducer.CLASS_COLUMN_CHART; Chart1.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Element'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Density'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, '', TcfsGChartDataCol.ROLE_STYLE), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, '', TcfsGChartDataCol.ROLE_ANOTATION) ]); Chart1.Data.AddRow(['Copper', 8.94, '#b87333', 'Cu']); // RGB value Chart1.Data.AddRow(['Silver', 10.49, 'silver', 'Ag']); // English color name Chart1.Data.AddRow(['Gold', 19.30, 'gold', 'Au']); Chart1.Data.AddRow(['Platinum', 21.45, 'color: #e5e4e2', 'Pt' ]); // CSS-style declaration Chart1.Options.Title('Density of Precious Metals, in g/cm^3'); Chart1.Options.Legend('position', 'none'); Chart1.Options.Bar('groupWidth', '95%'); // Chart 2 Chart2 := TcfsGChartProducer.Create; Chart2.ClassChartType := TcfsGChartProducer.CLASS_COLUMN_CHART; Chart2.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Element'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Density'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, '', TcfsGChartDataCol.ROLE_STYLE) ]); Chart2.Data.AddRow(['Copper', 8.94, '#b87333']); // RGB value Chart2.Data.AddRow(['Silver', 10.49, 'silver']); // English color name Chart2.Data.AddRow(['Gold', 19.30, 'gold']); Chart2.Data.AddRow(['Platinum', 21.45, 'color: #e5e4e2']); // CSS-style declaration Chart2.Options.Title('Density of Precious Metals, in g/cm^3'); Chart2.Options.Legend('position', 'none'); Chart2.Options.Bar('groupWidth', '95%'); Chart2.ScripCodeBeforeCallDraw := 'var view = new google.visualization.DataView(data);' + 'view.setColumns([0, 1, { calc: "stringify", sourceColumn: 1, type: "string", role: "annotation" }, 2]);' ; // Generate GChartsFrame.DocumentInit; GChartsFrame.DocumentSetBody( '<div id="Chart1" style="width: 100%;height: 50%;"></div>' + '<div id="Chart2" style="width: 100%;height: 50%;">' ); GChartsFrame.DocumentGenerate('Chart1', Chart1); GChartsFrame.DocumentGenerate('Chart2', Chart2); GChartsFrame.DocumentPost; end; initialization RegisterClass(TDemo_ColumnChart_LabelingColumns); end.
unit LHEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Level, Misc_utils; type TLHEditor = class(TForm) Label1: TLabel; EBMusic: TEdit; BNMusic: TButton; Label2: TLabel; EBParallax_X: TEdit; Label3: TLabel; EBParallax_Y: TEdit; BNOK: TButton; Button3: TButton; procedure BNOKClick(Sender: TObject); procedure BNMusicClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } Lev:TLevel; public MapWindow:TForm; { Public declarations } Function EditHeader(L:TLevel):Boolean; end; var LHEditor: TLHEditor; implementation uses ResourcePicker, Mapper; {$R *.DFM} Function TLHEditor.EditHeader(L:TLevel):Boolean; begin EBMusic.Text:=L.Music; EBParallax_X.Text:=FloatToStr(L.Parallax_X); EBParallax_Y.Text:=FloatToStr(L.Parallax_Y); Lev:=l; Result:=ShowModal=mrOK; end; procedure TLHEditor.BNOKClick(Sender: TObject); var P_X,P_Y:double; begin if ValDouble(EBParallax_X.Text,P_X) then if ValDouble(EBParallax_Y.Text,P_Y) then begin if Trim(EBMusic.Text)='' then Lev.Music:='NULL' else Lev.Music:=EBMusic.Text; Lev.Parallax_X:=P_X; Lev.Parallax_Y:=P_Y; ModalResult:=mrOK; Hide; end else MsgBox('Invalid value for Parallax Y','Error',mb_ok) else MsgBox('Invalid value for Parallax Y','Error',mb_ok); end; procedure TLHEditor.BNMusicClick(Sender: TObject); begin { if MapWindow<>nil then ResPicker.ProjectDirectory:= TMapWindow(MapWindow).ProjectDirectory;} EBMusic.Text:=ResPicker.PickMusic(EBMusic.Text); end; procedure TLHEditor.FormCreate(Sender: TObject); begin ClientWidth:=Label1.Left+BNOK.Left+BNOK.Width; ClientHeight:=Label1.Top+EBParallax_X.Top+EBParallax_X.Height; end; end.
unit PromoFactory; interface uses PromoClass, PromoSaleClass, PromoLoyaltyClass, PromoFreqBuyerClass, PromoCouponClass, uSystemConst, SysUtils; type TPromoFactory = class public function createPromo(arg_type: Integer; arg_invoice, arg_idmov: Integer): TPromo; end; implementation { TPromoFactory } function TPromoFactory.createPromo(arg_type: Integer; arg_invoice, arg_idmov: Integer): TPromo; begin case arg_type of PROMO_COUPON_TYPE : result := TPromoCoupon.create(arg_invoice, arg_idmov); PROMO_FREQBUYER_TYPE: result := TPromoFreqBuyer.Create(arg_invoice, arg_idmov); PROMO_LOYALTY_TYPE: result := TPromoLoyalty.Create(arg_invoice, arg_idmov); PROMO_SALE_TYPE: result := TPromoSale.create(arg_invoice, arg_idmov); else begin raise Exception.Create('Unknown type of Promo'); end; end; end; end.
{* ***** BEGIN LICENSE BLOCK ***** Copyright 2009, 2010 Sean B. Durkin This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free software being offered under a dual licensing scheme: LGPL3 or MPL1.1. The contents of this file are subject to the Mozilla Public License (MPL) Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Alternatively, you may redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. You should have received a copy of the Lesser GNU General Public License along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>. TurboPower LockBox 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. In relation to LGPL, see the GNU Lesser General Public License for more details. In relation to MPL, see the MPL License for the specific language governing rights and limitations under the License. The Initial Developer of the Original Code for TurboPower LockBox version 2 and earlier was TurboPower Software. * ***** END LICENSE BLOCK ***** *} unit uTPLb_Hash; interface uses SysUtils, Classes, uTPLb_StreamCipher, uTPLb_BaseNonVisualComponent, uTPLb_CryptographicLibrary, uTPLb_HashDsc; type TOnHashProgress = function( Sender: TObject; CountBytesProcessed: int64): boolean of object; IHash = interface ['{97CF303A-B823-42F3-98F6-7022015FDCB5}'] function GetIsHashing: boolean; function GetHash: IHashDsc; procedure SetHash( const Value: IHashDsc); function GetHashOutput: TStream; function GetonProgress: TOnHashProgress; procedure SetOnProgress( Value: TOnHashProgress); procedure Begin_Hash; procedure UpdateMemory(const Plaintext; Count: Integer); procedure End_Hash; procedure Burn; procedure HashStream( Plaintext: TStream); procedure HashFile ( const PlaintextFileName: string); procedure HashString(const Plaintext: string; AEncoding: TEncoding); procedure HashAnsiString( const Plaintext: string); function isUserAborted: boolean; procedure WriteHashOutputToStream( Dest: TStream); procedure WriteHashOutputToMemory( var Dest); property isHashing: boolean read GetIsHashing; property Hash: IHashDsc read GetHash write SetHash; property HashOutputValue: TStream read GetHashOutput; property OnProgress : TOnHashProgress read GetonProgress write SetOnProgress; end; IHash_TestAccess = interface // This method is ONLY to be used by unit test programs. ['{E6604CED-09A1-4EA6-BE22-B3371379218B}'] function GetHasher: IHasher; end; TSimpleHash = class( TInterfacedPersistent, IHash, IEventOrigin, IHash_TestAccess) private FSender: TObject; function GetIsHashing: boolean; function GetHash: IHashDsc; procedure SetHash( const Value: IHashDsc); function GetHashOutput: TStream; function GetonProgress: TOnHashProgress; procedure SetOnProgress( Value: TOnHashProgress); procedure Begin_Hash; procedure UpdateMemory(const Plaintext; Count: Integer); procedure End_Hash; procedure Burn; procedure HashStream( Plaintext: TStream); procedure HashFile ( const PlaintextFileName: string); procedure HashString(const Plaintext: string; AEncoding: TEncoding); procedure HashAnsiString( const Plaintext: string); function isUserAborted: boolean; procedure SetEventSender( Sender: TObject); procedure WriteHashOutputToStream( Dest: TStream); procedure WriteHashOutputToMemory( var Dest); // IHash_TestAccess. Just for testing function GetHasher: IHasher; protected FHashDsc: IHashDsc; FHasher: IHasher; FInputBufferLen: integer; // Physical length of FInputBuffer. FInputBuffer: TMemoryStream; // FInputBuffer will have the physical length of the hash block size. // Its logical length will be indication by the stream position. FOutputValue: TMemoryStream; FOnProgress: TOnHashProgress; FCount: int64; FisUserAborted: boolean; public constructor Create; destructor Destroy; override; end; THash = class( TTPLb_BaseNonVisualComponent, ICryptographicLibraryWatcher, IHash_TestAccess) private FHashObj: TSimpleHash; FHash : IHash; FLib: TCryptographicLibrary; FHashId: string; FIntfCached: boolean; function GetIsHashing: boolean; function GetHashOutput: TStream; function GetonProgress: TOnHashProgress; procedure SetOnProgress( Value: TOnHashProgress); procedure ProgIdsChanged; procedure SetLib( Value: TCryptographicLibrary); procedure Dummy( const Value: string); procedure SetHashId( const Value: string); procedure SetIntfCached( Value: boolean); function GetFeatures: TAlgorithmicFeatureSet; procedure ReadData( Reader: TReader); procedure WriteData( Writer: TWriter); // IHash_TestAccess. Just for testing function GetHasher: IHasher; protected procedure Notification( AComponent: TComponent; Operation: TOperation); override; procedure DefineProperties( Filer: TFiler); override; function GetHashDisplayName: string; virtual; procedure Loaded; override; property InterfacesAreCached: boolean read FIntfCached write SetIntfCached; public constructor Create( AOwner: TComponent); override; destructor Destroy; override; procedure Begin_Hash; procedure UpdateMemory(const Plaintext; PlaintextLen: Integer); procedure End_Hash; procedure Burn; procedure HashStream( Plaintext: TStream); procedure HashFile ( const PlaintextFileName: string); procedure HashString(const Plaintext: string; AEncoding: TEncoding); procedure HashAnsiString(const Plaintext: string); function isUserAborted: boolean; property isHashing: boolean read GetIsHashing; property HashId: string read FHashId write SetHashId; property HashOutputValue: TStream read GetHashOutput; published property Hash: string read GetHashDisplayName write Dummy stored False; property Features: TAlgorithmicFeatureSet read GetFeatures stored False; property CryptoLibrary: TCryptographicLibrary read FLib write SetLib; property OnProgress : TOnHashProgress read GetonProgress write SetOnProgress; end; implementation uses uTPLb_StreamUtils, uTPLb_BinaryUtils, Math, uTPLB_StrUtils; { TSimpleHash } constructor TSimpleHash.Create; begin FInputBufferLen := 0; FInputBuffer := TMemoryStream.Create; FOutputValue := TMemoryStream.Create; FSender := self end; destructor TSimpleHash.Destroy; begin Burn; FInputBuffer.Free; FOutputValue.Free; FisUserAborted := False; inherited end; procedure TSimpleHash.Begin_Hash; begin if not assigned( FHashDsc) then raise Exception.Create( 'TSimpleHash.Begin_Hash - without undefined hash algorithm.'); FHasher := nil; if assigned( FHashDsc) then begin FHasher := FHashDsc.MakeHasher( self); FInputBufferLen := FHashDsc.UpdateSize div 8; FOutputValue.Size := FHashDsc.DigestSize div 8 end; FInputBuffer.Size := FInputBufferLen; FInputBuffer.Position := 0; FCount := 0; FisUserAborted := False end; procedure TSimpleHash.Burn; begin if assigned( FHasher) then begin FHasher.Burn; FHasher := nil end; BurnMemoryStream( FInputBuffer); BurnMemoryStream( FOutputValue); FCount := 0; FisUserAborted := False end; procedure TSimpleHash.End_Hash; begin if FisUserAborted then FOutputValue.Clear else begin FOutputValue.Size := FHashDsc.DigestSize div 8; FOutputValue.Position := 0; FHasher.End_Hash( FInputBuffer, FOutputValue); FOutputValue.Position := 0 end; FHasher := nil; FCount := 0 end; function TSimpleHash.GetHash: IHashDsc; begin result := FHashDsc end; function TSimpleHash.GetHasher: IHasher; begin result := FHasher end; function TSimpleHash.GetHashOutput: TStream; begin result := FOutputValue end; function TSimpleHash.GetIsHashing: boolean; begin result := assigned( FHasher) end; function TSimpleHash.GetonProgress: TOnHashProgress; begin result := FOnProgress end; procedure TSimpleHash.HashAnsiString( const Plaintext: string); var pBytes: TBytes; begin Begin_Hash; try if Plaintext <> '' then begin pBytes := AnsiBytesOf(Plaintext); UpdateMemory(pBytes[0], Length(pBytes)); end; finally End_Hash; end; end; procedure TSimpleHash.HashFile( const PlaintextFileName: string); var Plaintext: TStream; begin Plaintext := TFileStream.Create( PlaintextFileName, fmOpenRead); try HashStream( Plaintext) finally Plaintext.Free end end; procedure TSimpleHash.HashStream( Plaintext: TStream); var //Buffer: packed array[ 0..128 ] of byte; Buffer: TBytes; TargetBufSize: integer; BufSize: integer; begin Begin_Hash; try Plaintext.Seek( 0, soBeginning); SetLength(Buffer, 129); TargetBufSize := Length( Buffer); repeat BufSize := Plaintext.Read( Buffer, TargetBufSize); if BufSize > 0 then UpdateMemory(Buffer[0], BufSize) until (BufSize <> TargetBufSize) or FisUserAborted finally End_Hash end end; procedure TSimpleHash.HashString(const Plaintext: string; AEncoding: TEncoding); var pBytes: TBytes; begin Begin_Hash; try if Plaintext <> '' then begin pBytes := AEncoding.GetBytes(Plaintext); UpdateMemory(pBytes[0], Length(pBytes)); end; finally End_Hash; end end; function TSimpleHash.isUserAborted: boolean; begin result := FisUserAborted end; procedure TSimpleHash.SetEventSender( Sender: TObject); begin FSender := Sender end; procedure TSimpleHash.SetHash( const Value: IHashDsc); begin if FHashDsc = Value then exit; //if assigned( FHasher) then // raise Exception.Create( 'TSimpleHash.SetHash - Cannot change hash ' + // 'algorithm while a hash operation is underway.'); FHasher := nil; FHashDsc := Value; if assigned( FHashDsc) then begin FHasher := FHashDsc.MakeHasher( self); FInputBufferLen := FHashDsc.UpdateSize div 8; FOutputValue.Size := FHashDsc.DigestSize div 8 end else FOutputValue.Clear; FInputBuffer.Size := FInputBufferLen end; procedure TSimpleHash.SetOnProgress( Value: TOnHashProgress); begin FOnProgress := Value end; procedure TSimpleHash.UpdateMemory(const Plaintext; Count: Integer); var PlaintextP: PByte; Xfer: integer; InSize: integer; begin if not assigned( FHasher) then raise Exception.Create( 'TSimpleHash.UpdateMemory - hashing not started.'); PlaintextP := @Plaintext; InSize := FInputBuffer.Position; // FCount == Total count of input bytes hashed since BeginHash. // Count == For this call, the remaining count of input bytes to be processed. // InSize == Logical size of the input buffer. A shadow to FInputBuffer.Position // FInputBufferLen == Physical length of the input buffer, or equivalently, the hash update block size. // Xfer == Amount of input bytes to be processed in one hit. // FInputBuffer.Position == Logical size of the input buffer. // PlaintextP == Cursor into the plaintext (input bytes to be processed). while (Count > 0) and (not FisUserAborted) do begin Xfer := Min( FInputBufferLen - InSize, Count); if Xfer > 0 then begin FInputBuffer.Write( PlaintextP^, Xfer); Inc( PlaintextP, Xfer); Inc( InSize, Xfer); Dec( Count, Xfer); Inc( FCount, Xfer) end; if InSize < FInputBufferLen then break; FHasher.Update( FInputBuffer); FInputBuffer.Position := 0; InSize := 0; if assigned( FOnProgress) and (not FOnProgress( FSender, FCount)) then begin FisUserAborted := True; End_Hash; break end; end end; procedure TSimpleHash.WriteHashOutputToMemory( var Dest); begin FOutputValue.Position := 0; FOutputValue.Read( Dest, FOutputValue.Size); FOutputValue.Position := 0 end; procedure TSimpleHash.WriteHashOutputToStream( Dest: TStream); begin Dest.CopyFrom( FOutputValue, 0); FOutputValue.Position := 0 end; { THash } constructor THash.Create( AOwner: TComponent); var Origin: IEventOrigin; begin inherited Create( AOwner); FHashObj := TSimpleHash.Create; FHash := FHashObj as IHash; if Supports( FHashObj, IEventOrigin, Origin) then Origin.SetEventSender( self); FLib := nil; FHashId := ''; FIntfCached := False end; destructor THash.Destroy; begin FHash.Burn; SetLib( nil); FHash := nil; FHashObj.Free; inherited end; procedure THash.Begin_Hash; begin InterfacesAreCached := True; FHash.Begin_Hash end; procedure THash.Burn; begin FHash.Burn end; procedure THash.DefineProperties( Filer: TFiler); begin inherited; Filer.DefineProperty('HashId', ReadData, WriteData, True) end; procedure THash.Dummy( const Value: string); begin end; procedure THash.End_Hash; begin FHash.Burn end; function THash.GetFeatures: TAlgorithmicFeatureSet; begin InterfacesAreCached := True; if FHash.Hash <> nil then result := FHash.Hash.Features else result := [afNotImplementedYet] end; function THash.GetHashDisplayName: string; begin InterfacesAreCached := True; if FHash.Hash <> nil then result := TCryptographicLibrary.ComputeHashDisplayName( FHash.Hash) else result := '' end; function THash.GetHasher: IHasher; var TestAccess: IHash_TestAccess; begin InterfacesAreCached := True; if Supports( FHash, IHash_TestAccess, TestAccess) then result := TestAccess.GetHasher else result := nil end; function THash.GetHashOutput: TStream; begin result := FHash.HashOutputValue end; function THash.GetIsHashing: boolean; begin result := FHash.isHashing end; function THash.GetonProgress: TOnHashProgress; begin result := FHash.OnProgress end; procedure THash.HashAnsiString(const Plaintext: string); begin InterfacesAreCached := True; FHash.HashAnsiString(Plaintext); end; procedure THash.HashFile( const PlaintextFileName: string); begin InterfacesAreCached := True; FHash.HashFile( PlaintextFileName) end; procedure THash.HashStream( Plaintext: TStream); begin InterfacesAreCached := True; FHash.HashStream( Plaintext) end; procedure THash.HashString(const Plaintext: string; AEncoding: TEncoding); begin InterfacesAreCached := True; FHash.HashString(Plaintext, AEncoding); end; function THash.isUserAborted: boolean; begin result := FHash.isUserAborted end; procedure THash.Loaded; begin inherited; InterfacesAreCached := True end; procedure THash.Notification( AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FLib) then SetLib( nil) end; procedure THash.ProgIdsChanged; begin InterfacesAreCached := False end; procedure THash.SetHashId( const Value: string); begin if FHashId = Value then exit; InterfacesAreCached := False; FHashId := Value end; procedure THash.SetIntfCached( Value: boolean); begin if FIntfCached = Value then exit; FIntfCached := Value; FHash.Hash := nil; if FIntfCached and assigned( FLib) then FHash.Hash := FLib.HashIntfc( FHashId) end; procedure THash.SetLib( Value: TCryptographicLibrary); var OldLib: TCryptographicLibrary; begin if FLib = Value then exit; if assigned( FLib) then begin OldLib := FLib; FLib := nil; OldLib.DegisterWatcher( self); OldLib.RemoveFreeNotification( self) end; InterfacesAreCached := False; FLib := Value; if assigned( FLib) then begin FLib.FreeNotification( self); FLib.RegisterWatcher ( self) end end; procedure THash.SetOnProgress( Value: TOnHashProgress); begin FHash.OnProgress := Value end; procedure THash.UpdateMemory(const Plaintext; PlaintextLen: Integer); begin FHash.UpdateMemory(Plaintext, PlaintextLen) end; procedure THash.WriteData( Writer: TWriter); begin Writer.WriteString( FHashId) end; procedure THash.ReadData( Reader: TReader); begin HashId := Reader.ReadString end; end.
unit uFormCals; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.WinXCalendars, Vcl.WinXCtrls, Vcl.StdCtrls, System.Math; type TForm3 = class(TForm) CalendarView1: TCalendarView; CalendarPicker1: TCalendarPicker; ToggleSwitch1: TToggleSwitch; memLog: TMemo; procedure CalendarView1DrawDayItem(Sender: TObject; DrawParams: TDrawViewInfoParams; CalendarViewViewInfo: TCellItemViewInfo); procedure CalendarView1DrawMonthItem(Sender: TObject; DrawParams: TDrawViewInfoParams; CalendarViewViewInfo: TCellItemViewInfo); procedure CalendarView1DrawYearItem(Sender: TObject; DrawParams: TDrawViewInfoParams; CalendarViewViewInfo: TCellItemViewInfo); procedure ToggleSwitch1Click(Sender: TObject); procedure CalendarView1Click(Sender: TObject); private function CurrentMonth: word; function CurrentYear: integer; public { Public declarations } end; var Form3: TForm3; implementation uses System.DateUtils; {$R *.dfm} procedure TForm3.CalendarView1Click(Sender: TObject); var i: integer; begin memLog.Clear; for i := 0 to CalendarView1.SelectionCount-1 do memLog.Lines.Add(DateToStr(CalendarView1.SelectedDates[i])); end; procedure TForm3.CalendarView1DrawDayItem(Sender: TObject; DrawParams: TDrawViewInfoParams; CalendarViewViewInfo: TCellItemViewInfo); var d: integer; begin d := DayOfTheWeek(CalendarViewViewInfo.Date); if (d = 6) or (d = 7) then DrawParams.ForegroundColor := clRed; end; procedure TForm3.CalendarView1DrawMonthItem(Sender: TObject; DrawParams: TDrawViewInfoParams; CalendarViewViewInfo: TCellItemViewInfo); begin if MonthOf(CalendarViewViewInfo.Date) = CurrentMonth then DrawParams.ForegroundColor := clRed; end; procedure TForm3.CalendarView1DrawYearItem(Sender: TObject; DrawParams: TDrawViewInfoParams; CalendarViewViewInfo: TCellItemViewInfo); begin if YearOf(CalendarViewViewInfo.Date) = CurrentYear then DrawParams.ForegroundColor := clRed; end; function TForm3.CurrentMonth: word; var y, m, d: word; begin DecodeDate(Now, y, m, d); Result := m; end; function TForm3.CurrentYear: integer; var y, m, d: word; begin DecodeDate(Now, y, m, d); Result := y; end; procedure TForm3.ToggleSwitch1Click(Sender: TObject); begin if ToggleSwitch1.State = TToggleSwitchState.tssOn then CalendarView1.SelectionMode := TSelectionMode.smMultiple else CalendarView1.SelectionMode := TSelectionMode.smSingle; end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Classe VO padrão de onde herdam todas as classes de VO The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (T2Ti.COM) @version 2.0 ******************************************************************************* } unit VO; {$mode objfpc}{$H+} interface uses TypInfo, SysUtils, Classes, FPJSON, FGL, fpjsonrtti, DOM, XMLRead; type { TVO } TVO = class(TPersistent) published constructor Create; overload; virtual; function ToJSON: TJSONObject; virtual; function ToJSONString: string; end; TClassVO = class of TVO; TListaVO = specialize TFPGObjectList<TVO>; implementation {$Region 'TVO'} constructor TVO.Create; begin inherited Create; end; function TVO.ToJSON: TJSONObject; var TypeData: PTypeData; TypeInfo: PTypeInfo; PropList: PPropList; PropInfo: PPropInfo; I, J, K: Integer; Caminho, NomeTipo, NomeCampo, NomePropriedade: String; Documento: TXMLDocument; Node: TDOMNode; begin try DecimalSeparator := '.'; Result := TJSONObject.Create; Result.Clear; TypeInfo := Self.ClassInfo; TypeData := GetTypeData(TypeInfo); // Lê no arquivo xml no disco Caminho := 'C:\Projetos\T2Ti ERP 2.0\Lazarus\Retaguarda\Comum\VO\' + TypeData^.UnitName + '.xml'; ReadXMLFile(Documento, Caminho); Node := Documento.DocumentElement.FirstChild; // Monta o Json com os dados do VO GetMem(PropList, TypeData^.PropCount * SizeOf(Pointer)); GetPropInfos(TypeInfo, PropList); for I := 0 to TypeData^.PropCount - 1 do begin for J := 0 to (Node.ChildNodes.Count - 1) do begin if Node.ChildNodes.Item[J].NodeName = 'property' then begin for K := 0 to 4 do begin if Node.ChildNodes.Item[J].Attributes.Item[K].NodeName = 'name' then NomePropriedade := Node.ChildNodes.Item[J].Attributes.Item[K].NodeValue; if Node.ChildNodes.Item[J].Attributes.Item[K].NodeName = 'column' then NomeCampo := Node.ChildNodes.Item[J].Attributes.Item[K].NodeValue; end; if NomePropriedade = PropList^[I]^.Name then begin PropInfo := GetPropInfo(Self, PropList^[I]^.Name); NomeTipo := PropInfo^.PropType^.Name; if PropInfo^.PropType^.Kind in [tkInteger, tkInt64] then begin if GetInt64Prop(Self, PropList^[I]^.Name) <> 0 then Result.Add(NomeCampo, GetInt64Prop(Self, PropList^[I]^.Name)); end else if PropInfo^.PropType^.Kind in [tkString, tkUString, tkAString] then begin if GetStrProp(Self, PropList^[I]^.Name) <> '' then begin Result.Add(NomeCampo, GetStrProp(Self, PropList^[I]^.Name)); end; end else if PropInfo^.PropType^.Kind in [tkFloat] then begin Result.Add(NomeCampo, GetFloatProp(Self, PropList^[I]^.Name)); end; end; end; end; (* if PropList^[I]^.Name = 'Id' then begin Result.Add('ID', GetInt64Prop(Self, PropList^[I]^.Name)); end; *) end; finally DecimalSeparator := ','; FreeMem(PropList); end; end; function TVO.ToJSONString: String; var Serializa: TJSONStreamer; begin Serializa := TJSONStreamer.Create(nil); try Serializa.Options := Serializa.Options + [jsoTStringsAsArray]; Serializa.Options := Serializa.Options + [jsoComponentsInline]; Serializa.Options := Serializa.Options + [jsoDateTimeAsString]; Serializa.Options := Serializa.Options + [jsoStreamChildren]; // JSON convert and output Result := Serializa.ObjectToJSONString(Self); finally Serializa.Free; end; end; {$EndRegion 'TVO'} end.
unit UV_RefreshSKR_FieldNames; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxControls, cxContainer, cxEdit, cxLabel, cxLookAndFeelPainters, ExtCtrls, StdCtrls, cxButtons, cxTextEdit, cxMaskEdit, ActnList, Unit_ZGlobal_Consts, ZProc, IniFiles, ZMessages; type TFUV_RefreshSkr_FieldNames = class(TForm) LabelNameFieldTin: TcxLabel; LabelNameFieldAcctCard: TcxLabel; MaskEditNameFieldTin: TcxMaskEdit; MaskEditNameFieldCard: TcxMaskEdit; YesBtn: TcxButton; CancelBtn: TcxButton; Bevel: TBevel; ActionList: TActionList; ActionYes: TAction; ActionCancel: TAction; procedure ActionCancelExecute(Sender: TObject); procedure ActionYesExecute(Sender: TObject); private PLanguageIndex:byte; public constructor Create(AOwner:TComponent);reintroduce; end; function TinFieldName:String; function CardFieldName:String; implementation {$R *.dfm} const Path_IniFile_Reports = 'Reports\Zarplata\Reports.ini'; const Section_IniFile_RefreshCards = 'Reports\Zarplata\Reports.ini'; function TinFieldName:String; var IniFile:TIniFile; begin IniFile:=TIniFile.Create(ExtractFilePath(Application.ExeName)+Path_IniFile_Reports); Result := IniFile.ReadString(Section_IniFile_RefreshCards,'TIN','KOD_NAL'); IniFile.Free; end; function CardFieldName:String; var IniFile:TIniFile; begin IniFile:=TIniFile.Create(ExtractFilePath(Application.ExeName)+Path_IniFile_Reports); Result := IniFile.ReadString(Section_IniFile_RefreshCards,'CARD','CARD_NO'); IniFile.Free; end; constructor TFUV_RefreshSkr_FieldNames.Create(Aowner:TComponent); begin inherited Create(AOwner); PLanguageIndex:=LanguageIndex; //****************************************************************************** CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex]; CancelBtn.Hint := CancelBtn.Caption; YesBtn.Caption := YesBtn_Caption[PLanguageIndex]; YesBtn.Hint := YesBtn.Caption; Caption := FUV_RefreshSkr_FieldNames_Caption[PLanguageIndex]; LabelNameFieldTin.Caption := FUV_RefreshSkr_FieldNamesTin_Caption[PLanguageIndex]; LabelNameFieldAcctCard.Caption := FUV_RefreshSkr_FieldNamesAcctCard_Caption[PLanguageIndex]; //****************************************************************************** MaskEditNameFieldTin.Text := TinFieldName; MaskEditNameFieldCard.Text := CardFieldName; end; procedure TFUV_RefreshSkr_FieldNames.ActionCancelExecute(Sender: TObject); begin ModalResult := mrCancel; end; procedure TFUV_RefreshSkr_FieldNames.ActionYesExecute(Sender: TObject); var IniFile:TIniFile; begin if Trim(MaskEditNameFieldTin.Text)='' then begin ZShowMessage(Error_Caption[PLanguageIndex],FUV_RefreshSkr_FieldNamesTin_NotInput_Text[PLanguageIndex],mtInformation,[mbOK]); MaskEditNameFieldTin.SetFocus; Exit; end; if Trim(MaskEditNameFieldTin.Text)='' then begin ZShowMessage(Error_Caption[PLanguageIndex],FUV_RefreshSkr_FieldNamesAcctCard_NotInput_Text[PLanguageIndex],mtInformation,[mbOK]); MaskEditNameFieldTin.SetFocus; Exit; end; try if not FileExists(ExtractFilePath(Application.ExeName)+Path_IniFile_Reports) then FileCreate(ExtractFilePath(Application.ExeName)+Path_IniFile_Reports); IniFile:=TIniFile.Create(ExtractFilePath(Application.ExeName)+Path_IniFile_Reports); IniFile.WriteString(Section_IniFile_RefreshCards,'TIN',MaskEditNameFieldTin.Text); IniFile.WriteString(Section_IniFile_RefreshCards,'CARD',MaskEditNameFieldCard.Text); IniFile.Free; except on e:exception do begin ZShowMessage(Error_Caption[PLanguageIndex],e.Message,mtError,[mbOK]); Exit; end; end; ModalResult:=mrYes; end; end.
unit Demo.DiffChart.Column; interface uses System.Classes, Demo.BaseFrame, cfs.GCharts; type TDemo_DiffChart_Column = class(TDemoBaseFrame) public procedure GenerateChart; override; end; implementation procedure TDemo_DiffChart_Column.GenerateChart; var OldData: IcfsGChartData; NewData: IcfsGChartData; ChartBefore: IcfsGChartProducer; ChartAfter: IcfsGChartProducer; ChartDiff: IcfsGChartProducer; begin // Old Data OldData := TcfsGChartData.Create; OldData.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Name'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Popularity') ]); OldData.AddRow(['Cesar', 250]); OldData.AddRow(['Rachel', 4200]); OldData.AddRow(['Patrick', 2900]); OldData.AddRow(['Eric', 8200]); // New Data NewData := TcfsGChartData.Create; NewData.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Name'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Popularity') ]); NewData.AddRow(['Cesar', 370]); NewData.AddRow(['Rachel', 600]); NewData.AddRow(['Patrick', 700]); NewData.AddRow(['Eric', 1500]); // Chart Before ChartBefore := TcfsGChartProducer.Create; ChartBefore.ClassChartType := TcfsGChartProducer.CLASS_COLUMN_CHART; ChartBefore.Data.Assign(OldData); ChartBefore.Options.Title('Popularity of some names in 1980s'); //ChartBefore.Options.Legend('position', 'top'); // Chart After ChartAfter := TcfsGChartProducer.Create; ChartAfter.ClassChartType := TcfsGChartProducer.CLASS_COLUMN_CHART; ChartAfter.Data.Assign(NewData); ChartAfter.Options.Title('Present popularity of some names'); //ChartAfter.Options.Legend('position', 'top'); // Chart Diff ChartDiff := TcfsGChartProducer.Create; ChartDiff.ClassChartType := TcfsGChartProducer.CLASS_COLUMN_CHART; ChartDiff.OldData.Assign(OldData); ChartDiff.Data.Assign(NewData); ChartDiff.Options.Legend('position', 'top'); //ChartDiff.Options.Diff('innerCircle', '{ radiusFactor: 0.3 }'); // Generate GChartsFrame.DocumentInit; GChartsFrame.DocumentSetBody( '<div style="display: flex; width: 100%; height: 50%;">' + '<div id="ChartBefore" style="width: 50%"></div>' + '<div id="ChartAfter" style="flex-grow: 1;"></div>' + '</div>' + '<div style="display: flex; width: 100%; height: 50%;">' + '<div id="ChartDiff" style="width: 100%"></div>' + '</div>' ); GChartsFrame.DocumentGenerate('ChartBefore', ChartBefore); GChartsFrame.DocumentGenerate('ChartAfter', ChartAfter); GChartsFrame.DocumentGenerate('ChartDiff', ChartDiff); GChartsFrame.DocumentPost; end; initialization RegisterClass(TDemo_DiffChart_Column); end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Utils.Process; interface uses System.Classes, VSoft.CancellationToken; type IEnvironmentBlock = interface ['{5A5AA8E1-1F8F-424D-827C-75B0C43FF972}'] procedure Clear; procedure LoadCurrentEnvironmentBlock; procedure AddOrSet(const name : string; const value : string); function GetValue(const name : string) : string; procedure ApplyValues(const list : TStrings); procedure RemoveVariable(const name : string); function GetEnvironmentBlock : Pointer; end; // Simple wrapper around ShellExecute for now //TODO : Rework to use CreateProcess and capture stdout using pipes. TProcess = class //throws if cannot create process. class function Execute(const cancellationToken : ICancellationToken; const executable : string; const commandLine : string) : Cardinal; //new version using createprocess - not capturing output. class function Execute2(const cancellationToken : ICancellationToken; const executable : string; const commandLine : string; const startingDir : string; const enviroment : IEnvironmentBlock = nil; const timeout : integer = -1) : Cardinal; end; TEnvironmentBlockFactory = class class function Create(const AList : TStrings; const AReadCurrent : boolean = true) : IEnvironmentBlock; end; implementation uses WinApi.Windows, WinApi.ShellAPI, Winapi.TlHelp32, System.SysUtils; function StripQuotes(const value : string) : string; var len: integer; begin result := value; len := Length(Value); if len > 2 then begin if (Value[1] = Value[len]) then begin if (Value[1] = '"') or (Value[1] = '''') then Result := Copy(value, 2, len - 2); end; end; end; function DoubleQuoteString(const value: string; const checkString: boolean = True): string; begin result := StripQuotes(value); if checkString then begin if (pos(' ', result) > 0) then result := '"' + result + '"'; end else result := '"' + result + '"'; end; function TerminateProcessTree(const ParentProcessID : Cardinal) : Cardinal; var hSnapshot : THandle; function _TerminateProcess(const ProcessID : Cardinal) : Cardinal; // A simple wrapper around TerminateProcess var hProcess : THandle; begin Result := 1001; hProcess := OpenProcess(PROCESS_TERMINATE,False, ProcessID); if (hProcess <> 0) and (hProcess <> INVALID_HANDLE_VALUE) then begin TerminateProcess(hProcess,Result); CloseHandle(hProcess); end; end; function _TerminateProcessAndChildren(const snapshot : THandle; const processID : DWORD) : Cardinal; // Nested recursive function var processInfo : PROCESSENTRY32; res : Boolean; begin processInfo.dwSize := sizeof(PROCESSENTRY32); res := Process32First(snapshot, processInfo); while res do begin if processInfo.th32ParentProcessID = ProcessID then // Child process of ProcessID _TerminateProcess(processInfo.th32ProcessID); res := Process32Next(hSnapshot, processInfo); end; result := _TerminateProcess(processID); end; begin // First set up a global system snapshot to provide data to the recursive function hSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); if hSnapshot = INVALID_HANDLE_VALUE then begin // If we can't get a snapshot (for some reason) just kill the parent process Result := _TerminateProcess(ParentProcessID); exit; end; try Result := _TerminateProcessAndChildren(hSnapshot, ParentProcessID); finally CloseHandle(hSnapshot); end; end; { TProcess } class function TProcess.Execute2(const cancellationToken : ICancellationToken; const executable : string; const commandLine : string; const startingDir : string; const enviroment : IEnvironmentBlock = nil; const timeout : integer = -1) : Cardinal; var sParams: string; pDir: PChar; pEnvironment : Pointer; startupInfo : TStartupInfo; processInfo: TProcessInformation; timeOutDuration: Cardinal; waitRes: Cardinal; objHandles: array[0..1] of THandle; function DoGetExitCodeProcess: Cardinal; begin if not GetExitCodeProcess(processInfo.hProcess, result) then result := GetLastError; end; begin FillChar(startupInfo, SizeOf(TStartupInfo), 0); FillChar(processInfo, SizeOf(TProcessInformation), 0); startupInfo.cb := SizeOf(startupInfo); startupInfo.dwFlags := STARTF_USESHOWWINDOW; startupInfo.wShowWindow := SW_HIDE; if enviroment <> nil then pEnvironment := enviroment.GetEnvironmentBlock else pEnvironment := nil; if startingDir <> '' then pDir := PChar(startingDir) else pDir := nil; sParams := DoubleQuoteString(executable) + ' ' + commandLine; if not CreateProcess(nil, PChar(sParams), nil, nil, false, CREATE_UNICODE_ENVIRONMENT + CREATE_NEW_CONSOLE, pEnvironment, pDir, startupInfo, processInfo) then begin result := GetLastError; exit; end; //we don't need this handle. CloseHandle(processInfo.hThread); { Set timeout length } if timeout < 0 then timeoutDuration := INFINITE else timeoutDuration := Cardinal(timeout); objHandles[0] := processInfo.hProcess; objHandles[1] := cancellationToken.Handle; { Wait for Something interesting to happen } waitRes := WaitForMultipleObjects(2, @objHandles, False, timeoutDuration); case waitRes of WAIT_OBJECT_0: // Process.hProcess has exited begin Result := DoGetExitCodeProcess; end; WAIT_OBJECT_0 + 1: // Event signalled to terminate process begin result := TerminateProcessTree(processInfo.dwProcessId); end; WAIT_TIMEOUT: // Timed out begin Result := DoGetExitCodeProcess; // Check is still running (just in case) if (result = STILL_ACTIVE) then begin result := TerminateProcessTree(processInfo.dwProcessId); end; end; else // Something else happened (like WAIT_FAILED) begin CloseHandle(processInfo.hProcess); raise Exception.Create('IProcess : Unexpected event wait result ' + IntToStr(waitRes)); end; end; CloseHandle(processInfo.hProcess); end; class function TProcess.Execute(const cancellationToken : ICancellationToken; const executable, commandLine : string) : Cardinal; var shellInfo : TShellExecuteInfo; waitHandles : array[0..1] of THandle; waitRes : DWORD; begin result := MaxInt; shellInfo.cbSize := sizeOf(TShellExecuteInfo); shellInfo.fMask := SEE_MASK_NOCLOSEPROCESS; shellInfo.Wnd := 0; shellInfo.lpVerb := nil; shellInfo.lpFile := PChar(executable); shellInfo.lpParameters := PChar(commandLine); shellInfo.lpDirectory := PChar(ExtractFilePath(executable)); shellInfo.nShow := SW_HIDE; shellInfo.hInstApp := 0; if ShellExecuteEx(@shellInfo) then begin waitHandles[0] := shellInfo.hProcess; waitHandles[1] := cancellationToken.Handle; waitRes := WaitForMultipleObjects(2, @waithandles[0], false, 60000); try case waitRes of WAIT_OBJECT_0 : // Process has exited begin //all good end; WAIT_OBJECT_0 + 1 : // Event signalled to terminate process begin TerminateProcess(shellInfo.hProcess, 999); result := 999; end; WAIT_TIMEOUT : // Timed out begin TerminateProcess(shellInfo.hProcess, 888); end; else // Something else happened (like WAIT_FAILED) raise Exception.Create('Unexpected event wait result ' + IntToStr(waitRes)); end; finally GetExitCodeProcess(shellInfo.hProcess, result); CloseHandle(shellInfo.hProcess); end; end else raise Exception.Create('Unable to execute process : ' + SysErrorMessage(GetLastError)); end; type TEnvBlock = class(TInterfacedObject,IEnvironmentBlock) private FChanged : boolean; FData : TBytes; FVariables : TStringList; public constructor Create(const list : TStrings; const AReadCurrent : boolean = true); destructor Destroy;override; procedure Clear; procedure LoadCurrentEnvironmentBlock; procedure AddOrSet(const name : string; const value : string); function GetValue(const name : string) : string; procedure ApplyValues(const list : TStrings); procedure RemoveVariable(const name : string); function GetEnvironmentBlock : Pointer; function GetEnvironmentBlockText : string; end; { TEnvBlock } constructor TEnvBlock.Create(const list : TStrings; const AReadCurrent: boolean); begin inherited Create; SetLength(FData,0); FVariables := TStringList.Create; if AReadCurrent then LoadCurrentEnvironmentBlock; if list <> nil then ApplyValues(list); end; destructor TEnvBlock.Destroy; begin SetLength(FData,0); FVariables.Free; inherited; end; procedure TEnvBlock.AddOrSet(const name, value: string); var idx : integer; begin idx := FVariables.IndexOfName(name); if idx <> -1 then FVariables.ValueFromIndex[idx] := value else FVariables.Add(name +'=' + value); FChanged := True; end; procedure TEnvBlock.ApplyValues(const list: TStrings); var I: Integer; begin if list = nil then exit; for I := 0 to list.Count -1 do begin if Pos('=',list.Strings[i]) <> 0 then AddOrSet(list.Names[i],list.ValueFromIndex[i]); end; end; procedure TEnvBlock.Clear; begin FVariables.Clear; FChanged := True; SetLength(FData,0); //Should we zero the data here? end; function TEnvBlock.GetEnvironmentBlock: Pointer; var len : integer; bytes : TBytes; byteCount : integer; count : integer; i: Integer; begin if not FChanged then begin if Length(FData) > 0 then result := @FData[0] else result := nil; exit; end; SetLength(FData,0); len := 2048; SetLength(FData,2048); count := 0; for i := 0 to FVariables.Count - 1 do begin bytes := TEncoding.Unicode.GetBytes(FVariables.Strings[i]); byteCount := Length(bytes); while (count + byteCount + 2) > len do begin Inc(len,2048); SetLength(FData,len); end; Move(bytes[0],FData[count],byteCount); Inc(count,byteCount); FData[count] := 0; Inc(count); FData[count] := 0; Inc(count); end; if count + 2 > len then begin Inc(len,2); SetLength(FData,len); end; FData[count] := 0; FData[count+1] := 0; result := @FData[0]; end; function TEnvBlock.GetEnvironmentBlockText: string; begin result := FVariables.Text; end; function TEnvBlock.GetValue(const name: string): string; var idx : integer; begin result := ''; idx := FVariables.IndexOfName(name); if idx <> -1 then result := FVariables.Strings[idx]; end; procedure TEnvBlock.LoadCurrentEnvironmentBlock; var PEnvBlock : PChar; pTmp : PChar; sTmp : string; begin Self.Clear; PEnvBlock := GetEnvironmentStrings; try pTmp := PEnvBlock; while pTmp^ <> #0 do begin stmp := string(pTmp); pTmp := pTmp + Length(sTmp) + 1; if (Trim(sTmp) <> '') and (Trim(stmp) <> '=::=::\') then FVariables.Add(stmp); end; // while finally FreeEnvironmentStrings(PEnvBlock); end; FChanged := True; end; procedure TEnvBlock.RemoveVariable(const name: string); var idx : integer; begin idx := FVariables.IndexOfName(name); if idx <> -1 then begin FVariables.Delete(idx); FChanged := true; end; end; { TEnvironmentBlockFactory } class function TEnvironmentBlockFactory.Create(const AList: TStrings; const AReadCurrent: boolean): IEnvironmentBlock; begin result := TEnvBlock.Create(AList, AReadCurrent); end; end.
unit uDadosCobradores; interface uses System.SysUtils, System.Classes, Data.FMTBcd, Data.DB, Datasnap.DBClient, Datasnap.Provider, Data.SqlExpr, Vcl.Dialogs, System.UITypes; const NENHUM_COBRADOR_SELECIONADO = 'Nenhum cobrador está selecionado.'; type TdmDadosCobradores = class(TDataModule) sqlTblcob: TSQLDataSet; dspTblcob: TDataSetProvider; cdsTblcob: TClientDataSet; cdsTblcobcobcod: TIntegerField; cdsTblcobcobnome: TStringField; procedure dspTblcobUpdateError(Sender: TObject; DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind; var Response: TResolverResponse); procedure cdsTblcobNewRecord(DataSet: TDataSet); procedure cdsTblcobcobnomeValidate(Sender: TField); private { Private declarations } public { Public declarations } procedure FiltrarCobradores(ACodigo: Integer = 0; ANome: String = ''); procedure PosicionarCobrador(ACodigo: integer); procedure AdicionarCobrador; procedure EditarCobrador; procedure ExcluirCobrador; procedure SalvarCobrador; procedure CalcelarManutencaoCobrador; function GetNomeCobrador(Acobcod: Integer): String; end; var dmDadosCobradores: TdmDadosCobradores; implementation {%CLASSGROUP 'System.Classes.TPersistent'} uses uConexao; {$R *.dfm} procedure TdmDadosCobradores.AdicionarCobrador; begin if not cdsTblcob.Active then FiltrarCobradores; CalcelarManutencaoCobrador; cdsTblcob.Append; end; procedure TdmDadosCobradores.CalcelarManutencaoCobrador; begin if not cdsTblcob.Active then exit; if cdsTblcob.State in [dsEdit, dsInsert] then cdsTblcob.Cancel; if cdsTblcob.ChangeCount > 0 then cdsTblcob.CancelUpdates; end; procedure TdmDadosCobradores.cdsTblcobcobnomeValidate(Sender: TField); begin if trim(cdsTblcobcobnome.AsString) = EmptyStr then raise Exception.Create('Nome do cobrador não pode ser nulo.'); end; procedure TdmDadosCobradores.cdsTblcobNewRecord(DataSet: TDataSet); begin cdsTblcob.Tag := 1; try cdsTblcobcobcod.Value := 0; // campo auto-incremento finally cdsTblcob.Tag := 0; end; end; procedure TdmDadosCobradores.dspTblcobUpdateError(Sender: TObject; DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind; var Response: TResolverResponse); begin raise Exception.Create(e.Message); end; procedure TdmDadosCobradores.EditarCobrador; begin if not cdsTblcob.Active then raise Exception.Create(NENHUM_COBRADOR_SELECIONADO); if cdsTblcob.RecordCount = 0 then raise Exception.Create(NENHUM_COBRADOR_SELECIONADO); cdsTblcob.Edit; end; procedure TdmDadosCobradores.ExcluirCobrador; begin if not cdsTblcob.Active then raise Exception.Create(NENHUM_COBRADOR_SELECIONADO); if cdsTblcob.RecordCount = 0 then raise Exception.Create(NENHUM_COBRADOR_SELECIONADO); if MessageDlg('Deseja realmente excluir o cobrador selecionado?', mtConfirmation,[mbYes, mbNo],0) <> mrYes then exit; cdsTblcob.Delete; try cdsTblcob.Tag := 1; SalvarCobrador; finally cdsTblcob.Tag := 0; end; end; procedure TdmDadosCobradores.FiltrarCobradores(ACodigo: Integer; ANome: String); var SQL: String; CodigoCobrador: integer; begin // Será utilizado para posicionar na lista if cdsTblcob.Active then CodigoCobrador := cdsTblcobcobcod.AsInteger else CodigoCobrador := -1; ANome:= trim(ANome); SQL := 'select * from tblcob'; if (ACodigo = 0) and (ANome = EmptyStr) then begin SQL := SQL + ' where 1 = 2'; end else begin SQL := SQL + ' where 1 = 1'; if ACodigo > 0 then SQL := SQL + ' and cobcod = ' + IntToStr(ACodigo); if ANome <> EmptyStr then SQL := SQL + ' and cobnome like "%' + ANome + '%"'; end; SQL := SQL + ' order by cobnome'; sqlTblcob.Close; sqlTblcob.CommandText := SQL; cdsTblcob.DisableControls; try cdsTblcob.Close; cdsTblcob.Open; PosicionarCobrador(CodigoCobrador); finally cdsTblcob.EnableControls; end; end; function TdmDadosCobradores.GetNomeCobrador(Acobcod: Integer): String; begin FiltrarCobradores(Acobcod, ''); if cdsTblcob.RecordCount > 0 then Result := trim(cdsTblcobcobnome.Value) else Result := ''; end; procedure TdmDadosCobradores.PosicionarCobrador(ACodigo: integer); begin if not cdsTblcob.Active then exit; if cdsTblcob.RecordCount = 0 then exit; if ACodigo = -1 then exit; cdsTblcob.Locate('cobcod', ACodigo, []); end; procedure TdmDadosCobradores.SalvarCobrador; begin if not cdsTblcob.Active then raise Exception.Create(NENHUM_COBRADOR_SELECIONADO); // --------------------------------------------------------------------------- // Aplica mais uma vez os métodos de validação // --------------------------------------------------------------------------- cdsTblcobcobnomeValidate(cdsTblcobcobnome); try if cdsTblcob.State in [dsEdit, dsInsert] then cdsTblcob.Post; cdsTblcob.ApplyUpdates(0); except on E: Exception do begin if cdsTblcob.ChangeCount > 0 then cdsTblcob.Cancel; if pos('key violation', LowerCase(e.Message)) > 0 then raise Exception.Create('Cobrador informado já está cadastrado.') else if pos('duplicate entry', LowerCase(e.Message)) > 0 then raise Exception.Create('Cobrador informado já está cadastrado.') else if pos('foreign key constraint fails', LowerCase(e.Message)) > 0 then raise Exception.Create('Não é possível excluir este cobrador, pois existem assinantes que estão ligados a este cobrador.') else raise Exception.Create(e.Message); end; end; end; end.
{ *********************************************************************** } { } { The Bantung Software Runtime Library } { Bantung - Common Utility Library } { } { Copyright (c) 2012 Bantung Software Co., Ltd. } { } { *********************************************************************** } unit CommonUtils; interface uses Windows, Messages,Classes, Forms,jvUIb,CommonLIB,SysUtils,IdIPWatch,MyAccess; type TShowWindowType = (swNone, swModal, swNomal); TFuncShowReportGenerator = function ( _MainApp: TApplication; _DBConn: TMyConnection; _Type: TShowWindowType; _Parameter: TDLLParameter;DefaultValue:TList;AutoReport:boolean): TForm; stdcall; function ShowInsigniaRegister( _MainApp: TApplication; _DBConn: TJvUIBDataBase; _Type: TShowWindowType; _Parameter: string): TForm; stdcall; function ShowFavorRegister( _MainApp: TApplication; _DBConn: TJvUIBDataBase; _Type: TShowWindowType; _Parameter: string): TForm; stdcall; function SelectFund(_MainApp: TApplication; _DBConn: TJvUIBDataBase; _Type: TShowWindowType; _Parameter: TDLLParameter; out _Output : TDLLParameter): TForm;stdcall; function ShowReportGenerator( _MainApp: TApplication; _DBConn: TMyConnection; _Type: TShowWindowType; _Parameter: TDLLParameter;DefaultValue:TList;AutoReport:boolean;RptGroup:string): TForm; stdcall; function SelSearch(_MainApp: TApplication; _Type: TShowWindowType; _Parameter: TDLLParameter; out _Output : TDLLParameter; _SearchType,_Cols,_ColsWidth:TList;_SelectField,_SQL:string): TForm; stdcall; function DecryptEx(const S: String; const Level: Byte = 2): String; function EncryptEx(const S: String; const Level: Byte = 2): String; procedure executilsdxInitialize;stdcall; implementation const InsignigReg = 'InsigniaReg.dll'; FavorReg = 'FavorReg.dll'; FndUtils = 'FndUtils.dll'; RGLib = 'RGLib.dll'; ExecUtilsLib ='seachutils.dll'; var RGLib_DLLHandle : THandle; _FuncShowReportGenerator : TFuncShowReportGenerator; function ShowInsigniaRegister( _MainApp: TApplication; _DBConn: TJvUIBDataBase; _Type: TShowWindowType; _Parameter: string):TForm; external InsignigReg name 'Execute'; function ShowFavorRegister( _MainApp: TApplication; _DBConn: TJvUIBDataBase; _Type: TShowWindowType; _Parameter: string):TForm; external FavorReg name 'Execute'; function SelectFund(_MainApp: TApplication; _DBConn: TJvUIBDataBase; _Type: TShowWindowType; _Parameter: TDLLParameter; out _Output : TDLLParameter): TForm; external FndUtils name 'SelectFund'; function SelSearch(_MainApp: TApplication; _Type: TShowWindowType; _Parameter: TDLLParameter; out _Output : TDLLParameter; _SearchType,_Cols,_ColsWidth:TList;_SelectField,_SQL:string): TForm; external ExecUtilsLib name 'SelSearch'; function ShowReportGenerator(_MainApp: TApplication; _DBConn: TMyConnection; _Type: TShowWindowType; _Parameter: TDLLParameter;DefaultValue:TList;AutoReport:boolean;RptGroup:string): TForm; external RGLib name 'Execute'; procedure executilsdxInitialize; external ExecUtilsLib name 'dxInitialize'; { function ShowReportGenerator( _MainApp: TApplication; _DBConn: TMyConnection; _Type: TShowWindowType; _Parameter: TDLLParameter;DefaultValue:TList;AutoReport:boolean):TForm;stdcall; begin try RGLib_DLLHandle := LoadLibrary(RGLib); if RGLib_DLLHandle<>0 then begin _FuncShowReportGenerator := GetProcAddress(RGLib_DLLHandle,'Execute'); if Assigned(_FuncShowReportGenerator) then begin Result := _FuncShowReportGenerator(_MainApp,_DBConn,_Type,_Parameter,DefaultValue,AutoReport); end; end; finally FreeLibrary(RGLib_DLLHandle); end; end; } //========= function DecryptStr(const S: String; const Key: Byte = 11; const Level: Byte = 1): String; var i, l: Integer; _S1, _S2: String; begin Result := ''; _S1 := S; while (_S1 <> '') do begin _S2 := Copy(_S1, 1, 2); Delete(_S1, 1, 2); Result := Result + Chr(StrToInt('$' + _S2)); end; for l := Level downto 1 do for i := 1 to Length(Result) do Result[i] := Chr(Ord(Result[i]) xor (not Key xor l)); for i := 1 to Length(Result) do Result[i] := Chr(Ord(Result[i]) xor Key); end; function EncryptStr(const S: String; const Key: Byte = 11; const Level: Byte = 1): String; var i, l: Integer; _St: String; begin _St := ''; for i := 1 to Length(S) do _St := _St + Chr(Ord(S[i]) xor Key); for l := 1 to Level do for i := 1 to Length(_St) do _St[i] := Chr(Ord(_St[i]) xor (not Key xor l)); Result := ''; for i := 1 to Length(_St) do Result := Result + IntToHex(Ord(_St[i]), 2); end; function DecryptEx(const S: String; const Level: Byte = 2): String; var i: Integer; begin Result := S; for i := 1 to Level do Result := DecryptStr(Result); end; function EncryptEx(const S: String; const Level: Byte = 2): String; var i: Integer; begin Result := S; for i := 1 to Level do Result := EncryptStr(Result); end; end.
unit Demo.PieChart.Exploding_a_Slice; interface uses System.Classes, Demo.BaseFrame, cfs.GCharts; type TDemo_PieChart_Exploding_a_Slice = class(TDemoBaseFrame) public procedure GenerateChart; override; end; implementation procedure TDemo_PieChart_Exploding_a_Slice.GenerateChart; var Chart: IcfsGChartProducer; // Defined as TInterfacedObject No need try..finally Slices: TArray<string>; begin Chart := TcfsGChartProducer.Create; Chart.ClassChartType := TcfsGChartProducer.CLASS_PIE_CHART; // Data Chart.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Language'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Speakers (in millions)') ]); Chart.Data.AddRow(['Assamese', 13]); Chart.Data.AddRow(['Bengali', 83]); Chart.Data.AddRow(['Bodo', 1.4]); Chart.Data.AddRow(['Dogri', 2.3]); Chart.Data.AddRow(['Gujarati', 46]); Chart.Data.AddRow(['Hindi', 300]); Chart.Data.AddRow(['Kannada', 38]); Chart.Data.AddRow(['Kashmiri', 5.5]); Chart.Data.AddRow(['Konkani', 5]); Chart.Data.AddRow(['Maithili', 20]); Chart.Data.AddRow(['Malayalam', 33]); Chart.Data.AddRow(['Manipuri', 1.5]); Chart.Data.AddRow(['Marathi', 72]); Chart.Data.AddRow(['Nepali', 2.9]); Chart.Data.AddRow(['Oriya', 33]); Chart.Data.AddRow(['Punjabi', 29]); Chart.Data.AddRow(['Sanskrit', 0.01]); Chart.Data.AddRow(['Santhali', 6.5]); Chart.Data.AddRow(['Sindhi', 2.5]); Chart.Data.AddRow(['Tamil', 61]); Chart.Data.AddRow(['Telugu', 74]); Chart.Data.AddRow(['Urdu', 52]); // Options Chart.Options.Title('Indian Language Use'); Chart.Options.Legend('position', 'none'); Chart.Options.PieSliceText('label'); SetLength(Slices, 16); Slices[ 4] := 'offset: 0.2'; Slices[12] := 'offset: 0.3'; Slices[14] := 'offset: 0.4'; Slices[15] := 'offset: 0.5'; Chart.Options.Slices(Slices); // Generate GChartsFrame.DocumentInit; GChartsFrame.DocumentSetBody('<div id="Chart1" style="width:100%;height:100%;"></div>'); GChartsFrame.DocumentGenerate('Chart1', Chart); GChartsFrame.DocumentPost; end; initialization RegisterClass(TDemo_PieChart_Exploding_a_Slice); end.
unit IndexActsCtrl_MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxDropDownEdit, cxCalendar, cxSpinEdit, cxTextEdit, cxMaskEdit, cxContainer, cxEdit, cxLabel, ExtCtrls, cxControls, cxGroupBox, cxButtonEdit, Kernel, Unit_ZGlobal_Consts, IBase, PackageLoad, FIBQuery, pFIBQuery,ZTypes, pFIBStoredProc, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, ZMessages, ActnList, IndexActsCtrl_DM, zProc, ComCtrls, cxCheckBox; type TFIndexActsControl = class(TForm) PeriodBox: TcxGroupBox; DateBegLabel: TcxLabel; ActionList1: TActionList; Action1: TAction; Action2: TAction; DateBeg: TDateTimePicker; DateEnd: TDateTimePicker; WorkDatabase: TpFIBDatabase; ReadTransaction: TpFIBTransaction; EditSumma: TcxMaskEdit; cxMaskEdit1: TcxMaskEdit; cxCheckBox0: TcxCheckBox; cxCheckBox1: TcxCheckBox; cxCheckBox2: TcxCheckBox; CancelBtn: TcxButton; YesBtn: TcxButton; procedure CancelBtnClick(Sender: TObject); procedure Action1Execute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Action2Execute(Sender: TObject); procedure CheckBoxMonthFinishPropertiesChange(Sender: TObject); procedure cxCheckBox1PropertiesChange(Sender: TObject); procedure cxCheckBox2PropertiesChange(Sender: TObject); private PParameter:TZIndexParameters; DM:TDM_Ctrl; PLanguageIndex:byte; public constructor Create(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AParameter:TZIndexParameters);reintroduce; property Parameter:TZIndexParameters read PParameter; end; implementation uses dateUtils; {$R *.dfm} constructor TFIndexActsControl.Create(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AParameter:TZIndexParameters); var RecInfo:RECORD_INFO_STRUCTURE; DecimalSeparator:string; curzp_date:TDateTime; CurPeriodInfo:TpFibDataSet; KodSetup:Integer; begin inherited Create(AOwner); PParameter:=AParameter; PLanguageIndex:=LanguageIndex; //****************************************************************************** //DateBegLabel.Caption:='Розрахунковий період'; //DateEndLabel.Caption:='Базовий період індексаці'; YesBtn.Caption:=YesBtn_Caption[PLanguageIndex]; //****************************************************************************** //100,00 | \d\d? ([,]\d\d?)? DecimalSeparator := ZSystemDecimalSeparator; //****************************************************************************** DM:=TDM_Ctrl.Create(self,ADB_HANDLE,PParameter); case PParameter.ControlFormStyle of zcfsInsert: begin cxCheckBox0.Checked:=False; cxCheckBox1.Checked:=False; cxCheckBox2.Checked:=False; cxMaskEdit1.Enabled:=False; EditSumma.Enabled:=False; DateEnd.Enabled:=False; CancelBtn.Caption:= CancelBtn_Caption[PLanguageIndex]; DateBeg.Date := EncodeDate(YearOf(Date),MonthOf(Date),1); DateEnd.Date := EncodeDate(YearOf(Date),MonthOf(Date),1); CancelBtn.Caption:= CancelBtn_Caption[PLanguageIndex]; end; zcfsUpdate: begin DateBeg.Date := PParameter.ActualDate; DateBeg.Enabled := false; if PParameter.IS_HAND_EDIT=False then begin cxCheckBox0.Checked:=False; DateEnd.Enabled:=False; end else begin cxCheckBox0.Checked:=true; DateEnd.Enabled:=true; end; if PParameter.SUMMA_IND_FACT_BOOL=False then begin //EditSumma.Enabled:=False; cxCheckBox1.Checked:=False; end; if PParameter.SUMMA_IND_FIX_BOOL=False then begin //cxMaskEdit1.Enabled:=False; cxCheckBox2.Checked:=False; end; DateEnd.Date := PParameter.IndexBaseDate; EditSumma.text := PParameter.SUMMA_IND_FACT; cxMaskEdit1.text:= PParameter.SUMMA_IND_FIX; CancelBtn.Caption:= CancelBtn_Caption[PLanguageIndex]; end; zcfsShowDetails: begin YesBtn.Visible:=False; CancelBtn.Caption:= ExitBtn_Caption[PLanguageIndex]; end; end; YesBtn.Hint := YesBtn.Caption; CancelBtn.Hint := CancelBtn.Caption+' (Esc)'; WorkDatabase.Handle:=ADB_HANDLE; ReadTransaction.StartTransaction; CurPeriodInfo:=TpFibDataSet.Create(self); CurPeriodInfo.Database:=WorkDatabase; CurPeriodInfo.Transaction:=ReadTransaction; CurPeriodInfo.SelectSQL.Text:='SELECT * FROM Z_KOD_SETUP_RETURN'; CurPeriodInfo.Open; if (CurPeriodInfo.RecordCount>0) then begin KodSetup:=CurPeriodInfo.FieldByName('KOD_SETUP').Value; CurPeriodInfo.Close; CurPeriodInfo.SelectSQL.Text:='SELECT OUT_DATE FROM Z_CONVERT_KOD_TO_DATE('+IntToStr(KodSetup)+')'; CurPeriodInfo.Open; if (CurPeriodInfo.RecordCount>0) then begin curzp_date:=CurPeriodInfo.FieldByName('OUT_DATE').Value; end else curzp_date:=Date; CurPeriodInfo.Close; end; if CurPeriodInfo.Active then CurPeriodInfo.Close; CurPeriodInfo.Free; DateBeg.MinDate:=IncMonth(curzp_date,-50); DateEnd.MinDate:=IncMonth(curzp_date,-50); end; procedure TFIndexActsControl.CancelBtnClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TFIndexActsControl.Action1Execute(Sender: TObject); var TId:Integer; begin case PParameter.ControlFormStyle of zcfsInsert: with DM do try StoredProc.Transaction.StartTransaction; StoredProc.StoredProcName := 'Z_INDEX_ACTS_INS'; StoredProc.Prepare; StoredProc.ParamByName('ID_MAN').AsInteger := PParameter.ID_man; StoredProc.ParamByName('kod_setup').AsDate := DateBeg.Date; if cxCheckBox0.checked then StoredProc.ParamByName('BASE_KOD_SETUP').AsDate := DateEnd.Date; if cxCheckBox1.checked then if EditSumma.text<>'' then StoredProc.ParamByName('SUMMA_IND_FACT').AsCurrency:= StrToFloat(EditSumma.text) else begin ShowMessage('"Сума фактична" не заповнена'); EditSumma.SetFocus; Exit; end; if cxCheckBox2.checked then if cxMaskEdit1.text<>'' then StoredProc.ParamByName('SUMMA_IND_FIX').AsCurrency := StrToFloat(cxMaskEdit1.text) else begin ShowMessage('"Сума фіксована" не заповнена'); cxMaskEdit1.SetFocus; Exit; end; StoredProc.ExecProc; TID:=StoredProc.ParamByName('ID_record').AsInt64; StoredProc.Transaction.Commit; PParameter.ID := TId; ModalResult:=mrYes; except on E: Exception do begin ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOk]); WriteTransaction.Rollback; end end; zcfsUpdate: with DM do try StoredProc.Transaction.StartTransaction; StoredProc.StoredProcName := 'Z_INDEX_ACTS_UPD'; StoredProc.Prepare; StoredProc.ParamByName('ID_man').AsInt64 := PParameter.id_man; StoredProc.ParamByName('ID_record').AsInt64 := PParameter.id; StoredProc.ParamByName('KOD_SETUP_DATE').AsDate := DateBeg.Date; if cxCheckBox0.checked then StoredProc.ParamByName('BASE_KOD_SETUP_DATE').AsDate := DateEnd.Date else StoredProc.ParamByName('BASE_KOD_SETUP_DATE').AsVariant :=null; if cxCheckBox2.checked then begin if cxMaskEdit1.text<>'' then StoredProc.ParamByName('SUMMA_IND_FIX').AsCurrency := StrToFloat(cxMaskEdit1.text) else begin ShowMessage('"Сума фіксована" не заповнена'); cxMaskEdit1.SetFocus; Exit; end; end else StoredProc.ParamByName('SUMMA_IND_FIX').AsVariant := NULL; if cxCheckBox1.checked then if EditSumma.text<>'' then StoredProc.ParamByName('SUMMA_IND_FACT').AsCurrency:= StrToFloat(EditSumma.text) else begin ShowMessage('"Сума фактична" не заповнена'); EditSumma.SetFocus; Exit; end else StoredProc.ParamByName('SUMMA_IND_FACT').AsVariant:= NULL; StoredProc.ExecProc; TID:=StoredProc.ParamByName('ID_record_out').AsInt64; StoredProc.Transaction.Commit; PParameter.ID := TId; ModalResult:=mrYes; except on E: Exception do begin ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOk]); WriteTransaction.Rollback; end end; end; end; procedure TFIndexActsControl.FormCreate(Sender: TObject); var RecInfo:RECORD_INFO_STRUCTURE; begin if PParameter.ControlFormStyle=zcfsDelete then begin with DM do try StoredProc.Transaction.StartTransaction; StoredProc.StoredProcName := 'Z_INDEX_ACTS_DEL'; StoredProc.Prepare; StoredProc.ParamByName('ID_RECORD').AsInteger := PParameter.ID; StoredProc.ExecProc; StoredProc.Transaction.Commit; ModalResult:=mrYes; PParameter.ID:=-1; except on E:exception do begin ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOk]); WriteTransaction.Rollback; PParameter.ID := -1; ModalResult:=mrCancel; end; end; end; end; procedure TFIndexActsControl.FormDestroy(Sender: TObject); begin if DM<>nil then DM.Destroy; end; procedure TFIndexActsControl.Action2Execute(Sender: TObject); begin if YesBtn.Focused Then Action1Execute(Sender); if CancelBtn.Focused Then CancelBtnClick(Sender); SendKeyDown(Self.ActiveControl,VK_TAB,[]); end; procedure TFIndexActsControl.CheckBoxMonthFinishPropertiesChange( Sender: TObject); begin DateEnd.Enabled:=not DateEnd.Enabled; end; procedure TFIndexActsControl.cxCheckBox1PropertiesChange(Sender: TObject); begin EditSumma.enabled:= not EditSumma.enabled; end; procedure TFIndexActsControl.cxCheckBox2PropertiesChange(Sender: TObject); begin cxMaskEdit1.enabled:= not cxMaskEdit1.enabled; end; end.
unit uCs_types; interface uses Classes, Ibase, Windows, Forms; type TCSMode = (CSShow, CSSelect, CSEdit, CSAdd, CSUpdate, CSDelete, CSInsert); //расширится со временем type TZFormStyle = (zfsModal, zfsNormal, zfsChild); // Для Совместимости с процедурой вызова видопл!! Скопировал из ЗАрплатаДПК чтоб его полностью не подколючать Type TcsSimpleParam = class(TObject) DB_Handle:TISC_DB_HANDLE; Owner:TComponent; end; Type TcsPaymentTypeParam = class(TcsSimpleParam) //тип выплаты контингента Mode: set of TCSMode; //тип множества ID_PAYMENT_TYPE:Int64; NAME_PAYMENT_TYPE:string; ID_VIDOPL:Int64; ID_TYPE_CALC: integer; end; Type TcsVidOplParam = class(TcsSimpleParam) // для подгрузки видов оплат. спионерил из ЗарплатаДПК, дабы его не привязывать PZFormStyle:TZFormStyle; end; Type TcsTypeOrderParam = class(TcsSimpleParam) Id_order_type:integer; Id_order:integer; Num_item:integer; Num_sub_item:integer; outer_hwnd: HWND; mode:TCSMode; //0 -add; 1 -update; iz up end; type TCSKernelMode =class(TcsSimpleParam) TR_HANDLE: TISC_DB_HANDLE; ID_ORDER:Int64; ID_ORDER_ITEM_IN:Int64; ID_SESSION:Int64; FILL_INST :Integer; FILL_MAIN_DATA:Integer; CHECK_DATA:Integer; end; type TcsParamPacks= class(TcsSimpleParam) Formstyle: TFormStyle; mode:integer; ID_SESSION: Int64; ID_User : Int64; ID_Locate : int64; ID_Locate_1 : int64; ID_Locate_2 : int64; end; implementation end.
unit Unit6; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, ComPort, LightControl, ALCommonMeter, ALVUMeter, LPComponent, ALAudioIn, Math; type TForm6 = class(TForm) Button1: TButton; Panel1: TPanel; TrackBarWinkelDifferenz: TTrackBar; Label1: TLabel; EditWinkelDifferenz: TEdit; ButtonWinkelDifferenz: TButton; Label2: TLabel; TrackBarWinkelgeschwindigkeit: TTrackBar; EditWinkelgeschwindigkeit: TEdit; ButtonWinkelgeschwindigkeit: TButton; GroupBox1: TGroupBox; Label3: TLabel; TrackBarHelligkeit: TTrackBar; EditHelligkeit: TEdit; ButtonHelligkeit: TButton; Label4: TLabel; TrackBarSaettigung: TTrackBar; EditSaettigung: TEdit; ButtonSaettigung: TButton; GroupBox2: TGroupBox; CheckBoxVUMeter: TCheckBox; Edit1: TEdit; Label5: TLabel; ALAudioIn1: TALAudioIn; ALVUMeter1: TALVUMeter; Label6: TLabel; Label7: TLabel; LabelVUMeterAktuell: TLabel; LabelVUMeterMax: TLabel; Timer1: TTimer; Label8: TLabel; LabelNachrichtenProSekunde: TLabel; Memo1: TMemo; TrackBarVUWinkel: TTrackBar; Label9: TLabel; LabelVUWinkel: TLabel; EditVUMin: TEdit; Label10: TLabel; LabelVUBeats: TLabel; Timer2: TTimer; procedure Button1Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ButtonWinkelDifferenzClick(Sender: TObject); procedure TrackBarWinkelDifferenzChange(Sender: TObject); procedure ButtonWinkelgeschwindigkeitClick(Sender: TObject); procedure TrackBarWinkelgeschwindigkeitChange(Sender: TObject); procedure ButtonHelligkeitClick(Sender: TObject); procedure TrackBarHelligkeitChange(Sender: TObject); procedure TrackBarSaettigungChange(Sender: TObject); procedure ButtonSaettigungClick(Sender: TObject); procedure CheckBoxVUMeterClick(Sender: TObject); procedure ALVUMeter1ValueChange(Sender: TObject; AChannel: Integer; AValue, AMin, AMax: Real); procedure Timer1Timer(Sender: TObject); procedure TrackBarVUWinkelChange(Sender: TObject); procedure EditVUMinChange(Sender: TObject); procedure Timer2Timer(Sender: TObject); private procedure OnComPortWriteLn(const aLine: AnsiString); procedure DetectBeats(aValue: Real); procedure OnBeatDetected; public { Public-Deklarationen } end; var Form6: TForm6; ComPort: TComPort; LightControl: TLightControl; VUmax, VUaktuell, VUMin: Extended; VUWinkel: Real; VUBeats: Integer; implementation {$R *.dfm} procedure TForm6.ALVUMeter1ValueChange(Sender: TObject; AChannel: Integer; AValue, AMin, AMax: Real); begin if CheckBoxVUMeter.Checked then DetectBeats(aValue); end; procedure TForm6.Button1Click(Sender: TObject); begin if not assigned(ComPort) then begin ComPort := TComPort.Create; ComPort.OnWriteLn := OnComPortWriteLn; end; if assigned(LightControl) then begin LightControl.Free; LightControl := nil; end; LightControl := TLightControl.Create(StrToInt(Edit1.Text)); if ComPort.Open('COM5:') and ComPort.Setup(9600) then begin Button1.Enabled := false; Panel1.Enabled := true; Edit1.Enabled := false; end else ShowMessage('COM-Port konnte nicht eingerichtet werden.'); end; procedure TForm6.ButtonHelligkeitClick(Sender: TObject); var brightness: Extended; begin if TryStrToFloat(EditHelligkeit.Text, brightness) then ComPort.WriteLn( LightControl.SetzeHelligkeitProzent(brightness)); end; procedure TForm6.Timer1Timer(Sender: TObject); begin if assigned(LightControl) then begin LabelNachrichtenProSekunde.Caption := IntToStr(LightControl.fMessageCounter); LightControl.fMessageCounter := 0; end; end; procedure TForm6.Timer2Timer(Sender: TObject); begin LabelVUBeats.Caption := IntToStr(VUBeats * 6) + ' BPM'; VUBeats := 0; end; procedure TForm6.TrackBarHelligkeitChange(Sender: TObject); var brightness: Extended; begin brightness := TrackBarHelligkeit.Position / 2; ComPort.WriteLn(LightControl.SetzeHelligkeitProzent(brightness)); EditHelligkeit.Text := FloatToStr(TrackBarHelligkeit.Position / 2); end; procedure TForm6.ButtonSaettigungClick(Sender: TObject); var saturation: Extended; begin if TryStrToFloat(EditSaettigung.Text, saturation) then ComPort.WriteLn( LightControl.SetzeSaettigungProzent(saturation)); end; procedure TForm6.TrackBarSaettigungChange(Sender: TObject); var saturation: Extended; begin saturation := TrackBarSaettigung.Position / 2; ComPort.WriteLn(LightControl.SetzeSaettigungProzent(saturation)); EditSaettigung.Text := FloatToStr(TrackBarSaettigung.Position / 2); end; procedure TForm6.TrackBarVUWinkelChange(Sender: TObject); begin VUWinkel := TrackBarVUWinkel.Position / 10; LabelVUWinkel.Caption := FloatToStr(RoundTo(TrackBarVUWinkel.Position / 10, -2)); end; procedure TForm6.ButtonWinkelDifferenzClick(Sender: TObject); var diff: Extended; begin if TryStrToFloat(EditWinkelDifferenz.Text, diff) then ComPort.WriteLn(LightControl.StarteMoodLightGrad(0, diff)); end; procedure TForm6.TrackBarWinkelDifferenzChange(Sender: TObject); var diff: Integer; begin diff := TrackBarWinkelDifferenz.Position; ComPort.WriteLn(LightControl.StarteMoodLightGrad(0, diff)); EditWinkelDifferenz.Text := IntToStr(diff); end; procedure TForm6.ButtonWinkelgeschwindigkeitClick(Sender: TObject); var diff: Extended; begin DecimalSeparator := ','; if TryStrToFloat(EditWinkelgeschwindigkeit.Text, diff) then ComPort.WriteLn(LightControl.SetzeGeschwindigkeitGrad(diff)); end; procedure TForm6.CheckBoxVUMeterClick(Sender: TObject); var anzahlLampen: Integer; deltaPhi: Real; begin if TryStrToInt(Edit1.Text, anzahlLampen) and CheckBoxVUMeter.Checked then begin LightControl.fStartWinkel := 0; VUWinkel := TrackBarVUWinkel.Position / 10; ComPort.WriteLn(LightControl.SetzeGeschwindigkeitGrad(0)); ComPort.WriteLn(LightControl.StarteMoodlightGrad(LightControl.fStartWinkel, LightControl.WinkelDifferenz)); VUBeats := 0; end else if not CheckBoxVUMeter.Checked then begin deltaPhi := TrackBarWinkelgeschwindigkeit.Position / 100; ComPort.WriteLn(LightControl.SetzeGeschwindigkeitGrad(deltaPhi)); ComPort.WriteLn(LightControl.StarteMoodlightGrad(LightControl.fStartWinkel, LightControl.WinkelDifferenz)); end; if not TryStrToFloat(EditVUMin.Text, VUMin) then VUMin := 100; ALAudioIn1.Enabled := CheckBoxVUMeter.Checked; Timer2.Enabled := CheckBoxVUMeter.Checked; end; procedure TForm6.DetectBeats(aValue: Real); begin if aValue > VUmax then begin VUmax := aValue; if aValue > VUMin then OnBeatDetected; end else VUmax := VUmax - 10; if VUmax < 0 then VUmax := 0; if VUmax > 2 * aValue then VUmax := VUmax / 2; VUaktuell := aValue; LabelVUMeterAktuell.Caption := IntToStr(Round(VUaktuell)); LabelVUMeterMax.Caption := IntToStr(Round(VUmax)); end; procedure TForm6.EditVUMinChange(Sender: TObject); var neu: Integer; begin if not TryStrToInt(EditVUMin.Text, neu) then neu := 100; VUMin := neu; end; procedure TForm6.OnBeatDetected; begin LightControl.fStartWinkel := LightControl.fStartWinkel + VUWinkel; if LightControl.fStartWinkel > 360 then LightControl.fStartWinkel := LightControl.fStartWinkel - 360; ComPort.WriteLn(LightControl.StarteMoodlightGrad(LightControl.fStartWinkel, LightControl.WinkelDifferenz)); Inc(VUBeats); end; procedure TForm6.OnComPortWriteLn(const aLine: AnsiString); begin Memo1.Lines.Add(aLine); end; procedure TForm6.TrackBarWinkelgeschwindigkeitChange(Sender: TObject); var deltaPhi: Extended; begin deltaPhi := TrackBarWinkelgeschwindigkeit.Position / 100; ComPort.WriteLn(LightControl.SetzeGeschwindigkeitGrad(deltaPhi)); DecimalSeparator := ','; EditWinkelgeschwindigkeit.Text := FloatToStr(deltaPhi); end; procedure TForm6.FormClose(Sender: TObject; var Action: TCloseAction); begin if assigned(ComPort) then ComPort.Close; end; end.
unit CCustomDBMiddleEngine; (******************************************************************************* * CLASE: TCustomDBMiddleEngine. * * FECHA DE CREACIÓN: 30-07-2001 * * PROGRAMADOR: Saulo Alvarado Mateos (CINCA) * * DESCRIPCIÓN: * * La finalidad es la de crear un esqueleto reusable de un objeto que * * permita mantener separados la representación interna de los objetos de el * * soporte de almacenamiento de los mismos. Es una clase abstracta que deberá * * ser redefinida por sus descendientes. * * Esta clase hace uso de la clase, también en este módulo, * * TCustomRecordProxy. * * * * FECHA MODIFICACIÓN: * * CAMBIOS (DESCRIPCIÓN): * * * ******************************************************************************* * CLASE: TCustomRecordProxy * * FECHA DE CREACIÓN: 30-07-2001 * * PROGRAMADOR: Saulo Alvarado Mateos (CINCA) * * DESCRIPCIÓN: * * Establece un intermediario para manejar los registros de forma común * * para operaciones como la de selección, que luego será convertido al tipo * * oportuno como si de una factoría se tratara. * *******************************************************************************) interface uses classes, contnrs; (* TObjectList *) type (******* DEFINICIÓN ANTICIPADA DE LAS CLASES PARA REFERENCIAS CRUZADAS *******) TCustomRecordProxy = class; TCustomSystemRecord = class; TCustomDBMiddleEngine = class; (******* DEFINICIÓN DETALLADA DE LAS CLASES E INTERFACES ******) TCustomSystemRecord = class( TObject ) protected FOID: String; // identificador único del registro public // propiedades: property OID: String read FOID; constructor Create; overload; virtual; constructor Create( aProxy: TCustomRecordProxy ); overload; virtual; abstract; procedure getData( aStringList: TStrings ); virtual; abstract; procedure setData( aStringList: TStrings ); virtual; abstract; end; // -- TCustomSystemRecord // :: TCustomRecordProxy = class( TObject ) protected FData: TStringList; public // constructores y destructores constructor Create; virtual; constructor CreateWithData( aStrings: TStrings ); virtual; destructor Destroy; override; // otros métodos públicos procedure getData( aStringList: TStrings ); virtual; end; // -- TCustomRecordProxy // :: TCustomDBMiddleEngine = class( TObject ) public constructor Create; virtual; abstract; function getListOfRecords: TObjectList ; virtual; abstract; function readRecord( aRecProxy: TCustomRecordProxy ): TCustomSystemRecord; virtual; abstract; procedure writeRecord( aSystemRecord: TCustomSystemRecord ); virtual; abstract; procedure deleteRecord( aRecProxy: TCustomRecordProxy ); virtual; abstract; // function getRecFromProxy( aRecordProxy: TCustomRecordProxy ): TCustomSystemRecord; virtual; abstract; end; // -- TCustomDBMiddleEngine //************ implementation //************ (***************************************************) (*************** TCustomRecordProxy ****************) (***************************************************) (**** CONSTRUCTORES Y DESTRUCTORES ****) constructor TCustomRecordProxy.Create; begin inherited; FData := TStringList.Create; end; // -- TCustomRecordProxy.Create; constructor TCustomRecordProxy.CreateWithData( aStrings: TStrings ); begin self.Create(); FData.Assign( aStrings ); end; destructor TCustomRecordProxy.Destroy; begin FData.Free; inherited; end; // -- TCustomRecordProxy.Destroy (**** MÉTODOS PÚBLICOS ****) procedure TCustomRecordProxy.getData( aStringList: TStrings ); begin aStringList.Assign( FData ); end; // -- TCustomRecordProxy.getDate(...) (***************************************************) (*************** TCustomSystemRecord ***************) (***************************************************) (**** CONSTRUCTORES Y DESTRUCTORES ****) constructor TCustomSystemRecord.Create; begin inherited; end; end.
unit fMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, IPPeerClient, IPPeerServer, System.Actions, FMX.ActnList, FMX.StdCtrls, FMX.Layouts, FMX.Memo, System.Tether.Manager, FMX.Menus, System.Tether.AppProfile, FMX.Edit, FMX.Controls.Presentation; type TForm1 = class(TForm) TetheringManager1: TTetheringManager; ToolBar1: TToolBar; Button1: TButton; ActionList1: TActionList; actConnect: TAction; actLogLine: TAction; actClearLog: TAction; TetheringAppProfile1: TTetheringAppProfile; Panel1: TPanel; Edit1: TEdit; Label1: TLabel; EditButton1: TEditButton; Label2: TLabel; lblSomeReply: TLabel; GroupBox1: TGroupBox; GroupBox2: TGroupBox; ImageControl1: TImageControl; Label3: TLabel; OpenDialog1: TOpenDialog; Label4: TLabel; ImageControl2: TImageControl; Button2: TButton; actToggleChecked: TAction; GroupBox3: TGroupBox; Switch1: TSwitch; Label5: TLabel; lblStatus: TLabel; Label6: TLabel; procedure actConnectUpdate(Sender: TObject); procedure actConnectExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure TetheringManager1RequestManagerPassword(const Sender: TObject; const ARemoteIdentifier: string; var Password: string); procedure TetheringManager1PairedToRemote(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); procedure TetheringAppProfile1ResourceReceived(const Sender: TObject; const AResource: TRemoteResource); procedure EditButton1Click(Sender: TObject); procedure ImageControl1Click(Sender: TObject); procedure actToggleCheckedExecute(Sender: TObject); procedure TetheringManager1UnPairManager(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation uses rtti; {$R *.fmx} procedure TForm1.actConnectExecute(Sender: TObject); begin if TetheringManager1.PairedManagers.Count > 0 then begin TetheringManager1.UnPairManager(TetheringManager1.PairedManagers.First); end else begin TetheringManager1.AutoConnect; end; end; procedure TForm1.actConnectUpdate(Sender: TObject); begin if TetheringManager1.PairedManagers.Count > 0 then begin actConnect.Text := 'Disconnect'; end else begin actConnect.Text := 'Connect'; lblStatus.Text := 'Disconnected'; end; end; procedure TForm1.actToggleCheckedExecute(Sender: TObject); begin Switch1.IsChecked := not Switch1.IsChecked; end; procedure TForm1.EditButton1Click(Sender: TObject); begin TetheringAppProfile1.Resources.FindByName('SomeText').Value := Edit1.Text; end; procedure TForm1.FormCreate(Sender: TObject); begin Caption := TetheringManager1.Identifier; end; procedure TForm1.ImageControl1Click(Sender: TObject); var LStream : TMemoryStream; begin if OpenDialog1.Execute then begin ImageControl1.LoadFromFile(OpenDialog1.FileName); Lstream := TMemoryStream.Create; ImageControl1.Bitmap.SaveToStream(LStream); LStream.Position := 0; TetheringAppProfile1.Resources.FindByName('SomeImage').Value := LStream; end; end; procedure TForm1.TetheringAppProfile1ResourceReceived(const Sender: TObject; const AResource: TRemoteResource); begin if AResource.Hint = 'ReplyText' then begin lblSomeReply.Text := AResource.Value.AsString; end else if AResource.Hint = 'ReplyImage' then begin Aresource.Value.AsStream.Position := 0; ImageControl2.Bitmap.LoadFromStream(Aresource.Value.AsStream); end; end; procedure TForm1.TetheringManager1PairedToRemote(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); begin lblStatus.Text := Format('Connected : %s %s', [AManagerInfo.ManagerIdentifier, AManagerInfo.ManagerName]); end; procedure TForm1.TetheringManager1RequestManagerPassword(const Sender: TObject; const ARemoteIdentifier: string; var Password: string); begin Password := 'foobar'; end; procedure TForm1.TetheringManager1UnPairManager(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); begin lblStatus.Text := 'Disconnected'; end; end.
unit Win32.DEVIOCTL; (*++ BUILD Version: 0004 // Increment this if a change has global effects Copyright (c) 1992-1999 Microsoft Corporation Module Name: devioctl.h Abstract: This module contains Revision History: --*) {$mode delphi} interface uses Windows, Classes, SysUtils; const // Define the various device type values. Note that values used by Microsoft // Corporation are in the range 0-32767, and 32768-65535 are reserved for use // by customers. FILE_DEVICE_BEEP = $00000001; FILE_DEVICE_CD_ROM = $00000002; FILE_DEVICE_CD_ROM_FILE_SYSTEM = $00000003; FILE_DEVICE_CONTROLLER = $00000004; FILE_DEVICE_DATALINK = $00000005; FILE_DEVICE_DFS = $00000006; FILE_DEVICE_DISK = $00000007; FILE_DEVICE_DISK_FILE_SYSTEM = $00000008; FILE_DEVICE_FILE_SYSTEM = $00000009; FILE_DEVICE_INPORT_PORT = $0000000a; FILE_DEVICE_KEYBOARD = $0000000b; FILE_DEVICE_MAILSLOT = $0000000c; FILE_DEVICE_MIDI_IN = $0000000d; FILE_DEVICE_MIDI_OUT = $0000000e; FILE_DEVICE_MOUSE = $0000000f; FILE_DEVICE_MULTI_UNC_PROVIDER = $00000010; FILE_DEVICE_NAMED_PIPE = $00000011; FILE_DEVICE_NETWORK = $00000012; FILE_DEVICE_NETWORK_BROWSER = $00000013; FILE_DEVICE_NETWORK_FILE_SYSTEM = $00000014; FILE_DEVICE_NULL = $00000015; FILE_DEVICE_PARALLEL_PORT = $00000016; FILE_DEVICE_PHYSICAL_NETCARD = $00000017; FILE_DEVICE_PRINTER = $00000018; FILE_DEVICE_SCANNER = $00000019; FILE_DEVICE_SERIAL_MOUSE_PORT = $0000001a; FILE_DEVICE_SERIAL_PORT = $0000001b; FILE_DEVICE_SCREEN = $0000001c; FILE_DEVICE_SOUND = $0000001d; FILE_DEVICE_STREAMS = $0000001e; FILE_DEVICE_TAPE = $0000001f; FILE_DEVICE_TAPE_FILE_SYSTEM = $00000020; FILE_DEVICE_TRANSPORT = $00000021; FILE_DEVICE_UNKNOWN = $00000022; FILE_DEVICE_VIDEO = $00000023; FILE_DEVICE_VIRTUAL_DISK = $00000024; FILE_DEVICE_WAVE_IN = $00000025; FILE_DEVICE_WAVE_OUT = $00000026; FILE_DEVICE_8042_PORT = $00000027; FILE_DEVICE_NETWORK_REDIRECTOR = $00000028; FILE_DEVICE_BATTERY = $00000029; FILE_DEVICE_BUS_EXTENDER = $0000002a; FILE_DEVICE_MODEM = $0000002b; FILE_DEVICE_VDM = $0000002c; FILE_DEVICE_MASS_STORAGE = $0000002d; FILE_DEVICE_SMB = $0000002e; FILE_DEVICE_KS = $0000002f; FILE_DEVICE_CHANGER = $00000030; FILE_DEVICE_SMARTCARD = $00000031; FILE_DEVICE_ACPI = $00000032; FILE_DEVICE_DVD = $00000033; FILE_DEVICE_FULLSCREEN_VIDEO = $00000034; FILE_DEVICE_DFS_FILE_SYSTEM = $00000035; FILE_DEVICE_DFS_VOLUME = $00000036; FILE_DEVICE_SERENUM = $00000037; FILE_DEVICE_TERMSRV = $00000038; FILE_DEVICE_KSEC = $00000039; FILE_DEVICE_FIPS = $0000003A; FILE_DEVICE_INFINIBAND = $0000003B; FILE_DEVICE_VMBUS = $0000003E; FILE_DEVICE_CRYPT_PROVIDER = $0000003F; FILE_DEVICE_WPD = $00000040; FILE_DEVICE_BLUETOOTH = $00000041; FILE_DEVICE_MT_COMPOSITE = $00000042; FILE_DEVICE_MT_TRANSPORT = $00000043; FILE_DEVICE_BIOMETRIC = $00000044; FILE_DEVICE_PMI = $00000045; FILE_DEVICE_EHSTOR = $00000046; FILE_DEVICE_DEVAPI = $00000047; FILE_DEVICE_GPIO = $00000048; FILE_DEVICE_USBEX = $00000049; FILE_DEVICE_CONSOLE = $00000050; FILE_DEVICE_NFP = $00000051; FILE_DEVICE_SYSENV = $00000052; FILE_DEVICE_VIRTUAL_BLOCK = $00000053; FILE_DEVICE_POINT_OF_SERVICE = $00000054; FILE_DEVICE_STORAGE_REPLICATION = $00000055; FILE_DEVICE_TRUST_ENV = $00000056; FILE_DEVICE_UCM = $00000057; FILE_DEVICE_UCMTCPCI = $00000058; FILE_DEVICE_PERSISTENT_MEMORY = $00000059; FILE_DEVICE_NVDIMM = $0000005a; FILE_DEVICE_HOLOGRAPHIC = $0000005b; FILE_DEVICE_SDFXHCI = $0000005c; FILE_DEVICE_UCMUCSI = $0000005d; // Define the method codes for how buffers are passed for I/O and FS controls METHOD_BUFFERED = 0; METHOD_IN_DIRECT = 1; METHOD_OUT_DIRECT = 2; METHOD_NEITHER = 3; // Define some easier to comprehend aliases: // METHOD_DIRECT_TO_HARDWARE (writes, aka METHOD_IN_DIRECT) // METHOD_DIRECT_FROM_HARDWARE (reads, aka METHOD_OUT_DIRECT) METHOD_DIRECT_TO_HARDWARE = METHOD_IN_DIRECT; METHOD_DIRECT_FROM_HARDWARE = METHOD_OUT_DIRECT; // Define the access check value for any access // The FILE_READ_ACCESS and FILE_WRITE_ACCESS constants are also defined in // ntioapi.h as FILE_READ_DATA and FILE_WRITE_DATA. The values for these // constants *MUST* always be in sync. // FILE_SPECIAL_ACCESS is checked by the NT I/O system the same as FILE_ANY_ACCESS. // The file systems, however, may add additional access checks for I/O and FS controls // that use this value. FILE_ANY_ACCESS = 0; FILE_SPECIAL_ACCESS = (FILE_ANY_ACCESS); FILE_READ_ACCESS = ($0001); // file & pipe FILE_WRITE_ACCESS = ($0002); // file & pipe type TDEVICE_TYPE = ULONG; implementation end.
unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, GLScene, GLMesh, GLWin32Viewer, ExtCtrls, GLCadencer, GLVectorGeometry, GLVectorLists, OpenGL1x, StdCtrls, GLTexture, GLContext, GLObjects, GLCoordinates, GLCrossPlatform, GLBaseClasses, GLRenderContextInfo, OpenGLTokens; type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLCamera1: TGLCamera; GLLightSource1: TGLLightSource; GLDummyCube1: TGLDummyCube; DOImmediate: TGLDirectOpenGL; GLMesh1: TGLMesh; Timer1: TTimer; GLCadencer1: TGLCadencer; RBBuildList: TRadioButton; RBImmediate: TRadioButton; DOVertexArray: TGLDirectOpenGL; RBVertexArray: TRadioButton; DOVBO: TGLDirectOpenGL; RBVBO: TRadioButton; RBStreamVBO: TRadioButton; procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure FormDestroy(Sender: TObject); procedure DOImmediateRender(Sender: TObject; var rci: TGLRenderContextInfo); procedure RBImmediateClick(Sender: TObject); procedure DOVertexArrayRender(Sender: TObject; var rci: TGLRenderContextInfo); procedure DOVBORender(Sender: TObject; var rci: TGLRenderContextInfo); private public vertices, normals : TAffineVectorList; indices : TIntegerList; // indices : array of SmallInt; vboVerticesBuffer, vboNormalsBuffer : TGLVBOArrayBufferHandle; vboIndicesBuffer : TGLVBOElementArrayHandle; end; var Form1: TForm1; implementation {$R *.dfm} uses GLUtils, GLState; type TSmallIntArray = packed array [0..MaxInt shr 2] of SmallInt; PSmallIntArray = ^TSmallIntArray; procedure TForm1.FormCreate(Sender: TObject); var i : Integer; f : Single; begin with GLMesh1 do begin Mode:=mmTriangleStrip; VertexMode:=vmVN; Vertices.Clear; for i:=-40000 to 15000 do begin f:=i*0.001; Vertices.AddVertex(AffineVectorMake(f*0.1, Sin(f), -0.1), YVector); Vertices.AddVertex(AffineVectorMake(f*0.1, Sin(f), 0.1), YVector); end; CalcNormals(fwClockWise); end; vertices:=TAffineVectorList.Create; normals:=TAffineVectorList.Create; for i:=0 to GLMesh1.Vertices.Count-1 do with GLMesh1.Vertices.Vertices[i] do begin vertices.Add(coord); normals.Add(normal); end; indices:=TIntegerList.Create; indices.AddSerie(0, 1, vertices.Count); end; procedure TForm1.FormDestroy(Sender: TObject); begin vboVerticesBuffer.Free; vboNormalsBuffer.Free; vboIndicesBuffer.Free; indices.Free; vertices.Free; normals.Free; end; procedure TForm1.Timer1Timer(Sender: TObject); begin Caption:=Format('%.1f FPS - %.1f MTri/s', [GLSceneViewer1.FramesPerSecond, GLSceneViewer1.FramesPerSecond*indices.Count/(1024*1024)]); GLSceneViewer1.ResetPerformanceMonitor; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); begin GLSceneViewer1.Invalidate; end; procedure TForm1.RBImmediateClick(Sender: TObject); begin GLMesh1.Visible:=RBBuildList.Checked; DOImmediate.Visible:=RBImmediate.Checked; DOVertexArray.Visible:=RBVertexArray.Checked; DOVBO.Visible:=RBVBO.Checked or RBStreamVBO.Checked; end; procedure TForm1.DOImmediateRender(Sender: TObject; var rci: TGLRenderContextInfo); var i, k : Integer; normalsList, verticesList : PAffineVectorArray; begin normalsList:=normals.List; verticesList:=vertices.List; glBegin(GL_TRIANGLE_STRIP); for i:=0 to indices.Count-1 do begin k:=indices.List[i]; glNormal3fv(@normalsList[k]); glVertex3fv(@verticesList[k]); end; glEnd; end; procedure TForm1.DOVertexArrayRender(Sender: TObject; var rci: TGLRenderContextInfo); begin glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glVertexPointer(3, GL_FLOAT, 0, vertices.List); glNormalPointer(GL_FLOAT, 0, normals.List); GL.LockArrays(0, vertices.Count); glDrawElements(GL_TRIANGLE_STRIP, indices.Count, GL_UNSIGNED_INT, indices.List); GL.UnlockArrays; glPopClientAttrib; end; procedure TForm1.DOVBORender(Sender: TObject; var rci: TGLRenderContextInfo); var arrayMode : TGLEnum; begin if Tag=0 then begin vboVerticesBuffer:=TGLVBOArrayBufferHandle.Create; vboVerticesBuffer.AllocateHandle; vboNormalsBuffer:=TGLVBOArrayBufferHandle.Create; vboNormalsBuffer.AllocateHandle; vboIndicesBuffer:=TGLVBOElementArrayHandle.Create; vboIndicesBuffer.AllocateHandle; end; if RBStreamVBO.Checked or (Tag=0) then begin if RBStreamVBO.Checked then arrayMode:=GL_STREAM_DRAW_ARB else arrayMode:=GL_STATIC_DRAW_ARB; // arrayMode:=GL_DYNAMIC_DRAW_ARB; vboVerticesBuffer.Bind; vboVerticesBuffer.BufferData(vertices.List, vertices.DataSize, arrayMode); vboVerticesBuffer.UnBind; vboNormalsBuffer.Bind; vboNormalsBuffer.BufferData(normals.List, normals.DataSize, arrayMode); vboNormalsBuffer.UnBind; vboIndicesBuffer.Bind; vboIndicesBuffer.BufferData(indices.List, indices.DataSize, arrayMode); vboIndicesBuffer.UnBind; Tag:=1; end; glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT); vboVerticesBuffer.Bind; glVertexPointer(3, GL_FLOAT, 0, nil); vboVerticesBuffer.UnBind; vboNormalsBuffer.Bind; glNormalPointer(GL_FLOAT, 0, nil); vboNormalsBuffer.UnBind; vboIndicesBuffer.Bind; glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glDrawElements(GL_TRIANGLE_STRIP, indices.Count, GL_UNSIGNED_INT, nil); vboIndicesBuffer.UnBind; glPopClientAttrib; end; end.
unit UCnMainAccounts; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ToolWin, ImgList, cxStyles, Ibase, FIBDatabase, pFIBDatabase, StdCtrls, ExtCtrls,pFibDataSet, Menus, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxTextEdit, cxDBEdit, cxMemo, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxContainer, cxCheckBox, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGrid, FIBDataSet,pFibStoredProc, UCnShowProgressThread, UCnDoCalculationsThread, UCnDoProvsThread, UCnCloseSysThread, cxLookAndFeelPainters, cxButtons, cn_Common_Types, cn_Common_Loader, cxTL, dxBarExtItems, dxBar, cn_Common_Funcs, cnConsts, frxClass, frxDBSet; type TfrmAccountMain = class(TForm) WorkDatabase: TpFIBDatabase; ReadTransaction: TpFIBTransaction; WriteTransaction: TpFIBTransaction; Panel1: TPanel; ViewAcc: TcxGridDBTableView; LevelAcc: TcxGridLevel; GridAcc: TcxGrid; CheckFilterPanel: TcxCheckBox; ACC_NUM: TcxGridDBColumn; STATUS: TcxGridDBColumn; DATE_REG: TcxGridDBColumn; DATE_BEG: TcxGridDBColumn; DATE_END: TcxGridDBColumn; CheckExtInfo: TcxCheckBox; ExtPanel: TPanel; Splitter1: TSplitter; cxDBMemo1: TcxDBMemo; Label3: TLabel; AccDataSet: TpFIBDataSet; AccDataSource: TDataSource; MainPopupMenu: TPopupMenu; N5: TMenuItem; N6: TMenuItem; N7: TMenuItem; N8: TMenuItem; N9: TMenuItem; N10: TMenuItem; N11: TMenuItem; N12: TMenuItem; N13: TMenuItem; N14: TMenuItem; N15: TMenuItem; N16: TMenuItem; ViewAccDBColumn1: TcxGridDBColumn; CalcProgressBar: TProgressBar; RedLabel: TLabel; N19: TMenuItem; N20: TMenuItem; Label1: TLabel; cbMonth: TComboBox; cbYear: TComboBox; lbGlobalCalcProcess: TLabel; pbGlobalCalcProcess: TProgressBar; TerminateButton: TcxButton; N4: TMenuItem; NEntryRest: TMenuItem; PopupImageList: TImageList; BarManager: TdxBarManager; InsertButton: TdxBarLargeButton; EditButton: TdxBarLargeButton; DeleteButton: TdxBarLargeButton; RefreshButton: TdxBarLargeButton; CloseButton: TdxBarLargeButton; PrintButton: TdxBarLargeButton; ConfigureButton: TdxBarLargeButton; LgotaButton: TdxBarLargeButton; EntryRestButton: TdxBarLargeButton; HistoryButton: TdxBarLargeButton; FIO_BarContainer: TdxBarControlContainerItem; FilterExecute_Button: TdxBarButton; Dog_Filter_Edit: TdxBarEdit; FilterButton: TdxBarLargeButton; DsetRecordCount: TdxBarButton; CreditButton: TdxBarLargeButton; Faculty_Footer_Label: TdxBarStatic; Spec_Footer_Label: TdxBarStatic; Gragdanstvo_Footer_Label: TdxBarStatic; FormStudy_Footer_Label: TdxBarStatic; CategoryStudy_Footer_Label: TdxBarStatic; Kurs_Footer_Label: TdxBarStatic; Group_Footer_Label: TdxBarStatic; ProvsButton: TdxBarLargeButton; CalcButton: TdxBarLargeButton; PayerData_Button: TdxBarButton; RastorgPri4ina_Button: TdxBarButton; dxBarStatic1: TdxBarStatic; Dodatki_Button: TdxBarSubItem; Log: TdxBarButton; RecoveryBtn: TdxBarButton; OrdersBtn: TdxBarLargeButton; SelectBtn: TdxBarLargeButton; Erased_Btn: TdxBarButton; NoteStatic: TdxBarStatic; ExportDataBtn: TdxBarButton; dxBarStatic2: TdxBarStatic; dxBarButton1: TdxBarButton; dxBarButton2: TdxBarButton; dxBarButton3: TdxBarButton; Dog_status_label: TdxBarStatic; dxBarToolbarsListItem1: TdxBarToolbarsListItem; dxBarLargeButton5: TdxBarLargeButton; Scan_button: TdxBarButton; dxBarButton4: TdxBarButton; LargeImages: TImageList; DisabledLargeImages: TImageList; WorkPopupMenu: TdxBarPopupMenu; N17: TdxBarButton; N26: TdxBarButton; N18: TdxBarButton; N23: TdxBarButton; N24: TdxBarButton; PrintPopupMenu: TdxBarPopupMenu; N1: TdxBarButton; N25: TdxBarButton; N3: TdxBarButton; N2: TdxBarButton; Styles: TcxStyleRepository; BackGround: TcxStyle; FocusedRecord: TcxStyle; Header: TcxStyle; DesabledRecord: TcxStyle; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; cxStyle4: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; cxStyle15: TcxStyle; cxStyle16: TcxStyle; cxStyle17: TcxStyle; cxStyle18: TcxStyle; cxStyle19: TcxStyle; cxStyle20: TcxStyle; cxStyle21: TcxStyle; cxStyle22: TcxStyle; cxStyle23: TcxStyle; cxStyle24: TcxStyle; 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; cxStyle47: TcxStyle; cxStyle48: TcxStyle; cxStyle49: TcxStyle; cxStyle50: TcxStyle; cxStyle51: TcxStyle; cxStyle52: TcxStyle; cxStyle53: TcxStyle; cxStyle54: TcxStyle; cxStyle55: TcxStyle; cxStyle56: TcxStyle; cxStyle57: TcxStyle; testColorStyle: TcxStyle; TreeListStyleSheetDevExpress: TcxTreeListStyleSheet; dxBarButton5: TdxBarButton; dxBarButton6: TdxBarButton; dxBarLargeButton1: TdxBarLargeButton; AnalDataSet: TpFIBDataSet; frxDBDataset1: TfrxDBDataset; frxReport1: TfrxReport; Panel2: TPanel; CheckBox_display_account: TcxCheckBox; procedure CloseButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ConfigureButtonClick(Sender: TObject); procedure InsertButtonClick(Sender: TObject); procedure CheckExtInfoPropertiesChange(Sender: TObject); procedure CheckFilterPanelPropertiesChange(Sender: TObject); procedure RefreshButtonClick(Sender: TObject); procedure EditButtonClick(Sender: TObject); procedure FilterButtonClick(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure N17Click(Sender: TObject); procedure ProvsButtonClick(Sender: TObject); procedure N18Click(Sender: TObject); procedure N23Click(Sender: TObject); procedure N26Click(Sender: TObject); procedure N1Click(Sender: TObject); procedure N2Click(Sender: TObject); procedure N3Click(Sender: TObject); procedure N24Click(Sender: TObject); procedure TerminateButtonClick(Sender: TObject); procedure cbYearChange(Sender: TObject); procedure NEntryRestClick(Sender: TObject); procedure N25Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure dxBarLargeButton1Click(Sender: TObject); private PLanguageIndex : Integer; procedure OnTerminateCalcThread(Sender:TObject); procedure OnTerminateCalcThread_DB(Sender:TObject); procedure prOnTerminateCalcThread(Sender:TObject); procedure prOnTerminateCalcThread_DB(Sender:TObject); procedure makeOnTerminateCalcThread(Sender:TObject); procedure makeOnTerminateCalcThread_DB(Sender:TObject); procedure makeOut_saldo(New_Date:TDateTime); procedure SetControls(Enabled,ExtPB:Boolean); public { Public declarations } Id_User:Integer; Login:String; User:String; DoResult:Integer; ErrorID_KOD:String; Progress_Thread:TShowProgressThread; Calculat_Thread:UDoCalclationsThread; DoProvs_Thread:TDoProvsThread; DoSaldo_Thread:TCloseSysThread; CALC_KEY_SESSION:Int64; MBookDate:TDateTime; ActualDate:TDateTime; CalcMode: Integer; Constructor Create(AOwner:TComponent;DBHandle:TISC_DB_HANDLE;Id_user:Integer;Login,Pswrd:STRING);reintroduce; function getSqlText:String; end; implementation uses BaseTypes, Resources_unitb, DateUtils, UCnAccountConf, UCnEditAccounts, cxDropDownEdit, cxCalendar, UCnAccountDetail, UCnErrors, Kernel, UCnDocPrinting, UCnCalcConfigure,uCnPrintOborot; {$R *.dfm} constructor TfrmAccountMain.Create(AOwner: TComponent;DBHandle: TISC_DB_HANDLE; Id_user: Integer;Login,Pswrd:sTRING); var I:Integer; SysInfo:TpFibDataSet; AccInfo:TpFibDataSet; begin inherited Create(AOwner); WorkDatabase.Handle:=DBHandle; ReadTransaction.StartTransaction; self.Id_User:=Id_user; SysInfo:=TpFibDataSet.Create(Self); SysInfo.Database:=WorkDatabase; SysInfo.Transaction:=ReadTransaction; SysInfo.SelectSQL.Text:='SELECT * FROM PUB_SYS_DATA'; SysInfo.Open; if (SysInfo.RecordCount>0) then MBookDate:=SysInfo.FieldByName('MAIN_BOOK_DATE').Value else MBookDate:=Date; AccInfo:=TpFibDataSet.Create(Self); AccInfo.Database:=WorkDatabase; AccInfo.Transaction:=ReadTransaction; AccInfo.SelectSQL.Text:='SELECT * FROM CN_DT_ACCOUNTS_INI'; AccInfo.Open; CalcMode:=AccInfo.FieldByName('CALC_MODE').AsInteger; cbMonth.Items.Add(TRIM(BU_Month_01)); cbMonth.Items.Add(TRIM(BU_Month_02)); cbMonth.Items.Add(TRIM(BU_Month_03)); cbMonth.Items.Add(TRIM(BU_Month_04)); cbMonth.Items.Add(TRIM(BU_Month_05)); cbMonth.Items.Add(TRIM(BU_Month_06)); cbMonth.Items.Add(TRIM(BU_Month_07)); cbMonth.Items.Add(TRIM(BU_Month_08)); cbMonth.Items.Add(TRIM(BU_Month_09)); cbMonth.Items.Add(TRIM(BU_Month_10)); cbMonth.Items.Add(TRIM(BU_Month_11)); cbMonth.Items.Add(TRIM(BU_Month_12)); for i:=0 to 25 do begin cbYear.Items.Add(TRIM(IntToStr(2000+i))); end; cbMonth.ItemIndex:=0; for i:=0 to cbYear.Items.Count-1 do begin if pos(cbYear.Items[i],IntToStr(YearOf(MBookDate)))>0 then begin cbYear.ItemIndex:=i; break; end; end; DateSeparator:='.'; ActualDate:=StrToDate('01.'+IntToStr(cbMonth.ItemIndex+1)+'.'+cbYear.Items[cbYear.ItemIndex]); AccDataSet.SelectSQL.Text:=getSqlText; AccDataSet.Open; ViewAcc.Controller.FocusedRowIndex:=0; CALC_KEY_SESSION:=WorkDatabase.Gen_Id('KERNEL_GEN_ID_SESSION',1); end; procedure TfrmAccountMain.CloseButtonClick(Sender: TObject); begin Close; end; procedure TfrmAccountMain.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree; end; procedure TfrmAccountMain.ConfigureButtonClick(Sender: TObject); var T: TfrmAccConf; USP:TpFibStoredProc; begin T:=TfrmAccConf.Create(self); if T.ShowModal=mrYes then begin USP:=TpFibStoredProc.Create(self); USP.Database:=WorkDatabase; USP.Transaction:=WriteTransaction; WriteTransaction.StartTransaction; USP.StoredProcName:='CN_DT_ACCOUNTS_INI_UPDATE'; USP.Prepare; USP.ParamByName('GLOBAL_ID_DOG').AsInt64:=T.WorkIdDog; USP.ParamByName('WORK_SCH').AsInt64:=T.WorkSch; USP.ParamByName('DATE_START').Value:=T.cxDateEdit1.Date; USP.ParamByName('ONLY_MAIN_DOCS').Value:=Integer(T.cxCheckBox1.Checked); USP.ParamByName('CALC_MODE').Value:=T.cxComboBox1.ItemIndex; USP.ExecProc; WriteTransaction.Commit; USP.Close; USP.Free; end; T.Free; end; procedure TfrmAccountMain.InsertButtonClick(Sender: TObject); var InsertSP:TpFibStoredProc; ID_ACC:Integer; begin with TfrmEditAcc.Create(self) do begin isEditMode:=false; ShowModal; if ModalResult = mrok then begin EdNote.Text := 'Рахунок за період '+DateToStr(DateBeg)+'-'+DateToStr(DateEnd) + '; ' + EdNote.Text; InsertSP:=TpFibStoredProc.Create(self); InsertSP.Database:=TfrmAccountMain(Owner).WorkDatabase; InsertSP.Transaction:=TfrmAccountMain(Owner).WriteTransaction; TfrmAccountMain(Owner).WriteTransaction.StartTransaction; InsertSP.StoredProcName:='CN_DT_ACCOUNTS_INSERT'; InsertSP.Prepare; InsertSP.ParamByName('DATE_BEG').Value := DateBeg; InsertSP.ParamByName('DATE_END').Value := DateEnd; InsertSP.ParamByName('NOTE').Value := EdNote.Text; InsertSP.ParamByName('is_account').Value := 1; InsertSP.ExecProc; ID_ACC:=InsertSP.ParamByName('ID_ACCOUNT').Value; TfrmAccountMain(Owner).WriteTransaction.Commit; TfrmAccountMain(Owner).AccDataSet.CloseOpen(true); TfrmAccountMain(Owner).AccDataSet.Locate('ID_ACCOUNT',ID_ACC,[]); end; Free; end; end; procedure TfrmAccountMain.CheckExtInfoPropertiesChange(Sender: TObject); begin if CheckExtInfo.Checked then begin ExtPanel.Visible:=true; Splitter1.Top:=ExtPanel.Top+1; end else begin ExtPanel.Visible:=false; end; end; procedure TfrmAccountMain.CheckFilterPanelPropertiesChange( Sender: TObject); begin ViewAcc.OptionsView.GroupByBox:=CheckFilterPanel.Checked; end; function TfrmAccountMain.getSqlText: String; var sql : string; begin sql := 'SELECT * FROM CN_DT_ACCOUNTS_SELECT('+''''+DateToStr(ActualDate)+''''+')'; if CheckBox_display_account.Checked then sql := sql + ' where is_account = 1' else sql := sql + ' where is_account in (0, 1)'; result := sql; end; procedure TfrmAccountMain.RefreshButtonClick(Sender: TObject); var ID_ACC:Int64; begin ID_ACC:=0; if AccDataSet.Active then begin if (AccDataSet.RecordCount>0) then ID_ACC:=StrToInt64(AccDataSet.FieldByName('ID_ACCOUNT').AsString); AccDataSet.Close; end; AccDataSet.SelectSQL.Text:=getSqlText; AccDataSet.Open; AccDataSet.Locate('ID_ACCOUNT',ID_ACC,[]); end; procedure TfrmAccountMain.EditButtonClick(Sender: TObject); var InsertSP:TpFibStoredProc; ID_ACC:Integer; begin if (AccDataSet.RecordCount = 0) then exit; if (AccDataSet.FieldByName('STATUS').AsInteger <> 0) then begin Showmessage('Не можна редагувати цей рахунок.'); exit; End; with TfrmEditAcc.Create(self) do begin isEditMode:=true; Calc_Mode:=CalcMode; dateBeg:=AccDataSet.FieldByName('DATE_BEG').Value; dateEnd:=AccDataSet.FieldByName('DATE_END').Value; EdNote.Text:=AccDataSet.FieldByName('NOTE').AsString; EdAccNum.Text:=AccDataSet.FieldByName('NUM_SCH').AsString; ShowModal; if ModalResult = mrOk then Begin InsertSP:=TpFibStoredProc.Create(self); InsertSP.Database:=TfrmAccountMain(Owner).WorkDatabase; InsertSP.Transaction:=TfrmAccountMain(Owner).WriteTransaction; TfrmAccountMain(Owner).WriteTransaction.StartTransaction; InsertSP.StoredProcName:='CN_DT_ACCOUNTS_UPDATE'; InsertSP.Prepare; ID_ACC:=TfrmAccountMain(Owner).AccDataSet.FieldByName('ID_ACCOUNT').Value; InsertSP.ParamByName('ID_ACCOUNT').Value := TfrmAccountMain(Owner).AccDataSet.FieldByName('ID_ACCOUNT').Value; InsertSP.ParamByName('DATE_BEG').Value := DateBeg; InsertSP.ParamByName('DATE_END').Value := DateEnd; InsertSP.ParamByName('NOTE').Value := EdNote.Text; InsertSP.ExecProc; TfrmAccountMain(Owner).WriteTransaction.Commit; TfrmAccountMain(Owner).AccDataSet.CloseOpen(true); TfrmAccountMain(Owner).AccDataSet.Locate('ID_ACCOUNT',ID_ACC,[]); end; Free; end; end; procedure TfrmAccountMain.FilterButtonClick(Sender: TObject); var I:Integer; begin for i:=0 to ViewAcc.ColumnCount-1 do ViewAcc.Columns[i].Options.Filtering:=FilterButton.Down; end; procedure TfrmAccountMain.DeleteButtonClick(Sender: TObject); var InsertSP:TpFibStoredProc; begin if (AccDataSet.RecordCount>0) then begin if (AccDataSet.FieldByName('STATUS').AsInteger<2) then begin if BaseTypes.agMessageDlg(BU_WarningCaption,BU_DeleteConfirmation,mtWarning,[mbYes,mbNo])=mrYes then begin InsertSP:=TpFibStoredProc.Create(self); InsertSP.Database:=WorkDatabase; InsertSP.Transaction:=WriteTransaction; WriteTransaction.StartTransaction; InsertSP.StoredProcName:='CN_DT_ACCOUNTS_DELETE'; InsertSP.Prepare; InsertSP.ParamByName('ID_ACCOUNT').Value:=AccDataSet.FieldByName('ID_ACCOUNT').AsInteger; InsertSP.ExecProc; WriteTransaction.Commit; AccDataSet.CacheDelete; end; end else BaseTypes.agMessageDlg(BU_WarningCaption,'Не можна видалити проведений документ.',mtConfirmation,[mbOK]); end; end; procedure TfrmAccountMain.OnTerminateCalcThread(Sender: TObject); begin SetControls(true,false); MessageBox(self.Handle,'Процес розрахунку завершено.','Увага!',MB_OK); RefreshButtonClick(Self); end; procedure TfrmAccountMain.OnTerminateCalcThread_DB(Sender: TObject); begin if Assigned(Progress_Thread) then Progress_Thread.Terminate; end; procedure TfrmAccountMain.SetControls(Enabled,ExtPB: Boolean); begin InsertButton.Enabled :=Enabled; DeleteButton.Enabled :=Enabled; RefreshButton.Enabled :=Enabled; CloseButton.Enabled :=Enabled; CalcButton.Enabled :=Enabled; ProvsButton.Enabled :=Enabled; FilterButton.Enabled :=Enabled; PrintButton.Enabled :=Enabled; N1.Enabled :=Enabled; N2.Enabled :=Enabled; N3.Enabled :=Enabled; ConfigureButton.Enabled :=Enabled; N5.Enabled :=Enabled; N6.Enabled :=Enabled; N7.Enabled :=Enabled; N8.Enabled :=Enabled; N9.Enabled :=Enabled; N10.Enabled :=Enabled; N11.Enabled :=Enabled; N12.Enabled :=Enabled; N13.Enabled :=Enabled; N14.Enabled :=Enabled; N15.Enabled :=Enabled; EditButton.Enabled :=Enabled; N16.Enabled :=Enabled; RedLabel.Enabled :=not Enabled; CalcProgressBar.Enabled := not Enabled; dxBarLargeButton1.Enabled := Enabled; GridAcc.Enabled := Enabled; lbGlobalCalcProcess.Visible:=ExtPB; pbGlobalCalcProcess.Visible:=ExtPB; TerminateButton.Visible:=ExtPB; end; procedure TfrmAccountMain.N17Click(Sender: TObject); var CheckSP:TpFibStoredProc; T:TfrmCalcConfigure; F:Integer; GetDataMode:Integer; begin CALC_KEY_SESSION:=WorkDatabase.Gen_Id('KERNEL_GEN_ID_SESSION',1); DoResult:=0; if (AccDataSet.RecordCount>0) then begin //Проверяем статус счета if (AccDataSet.FieldByName('STATUS').AsInteger=2) then begin ShowMessage('Рахунок вже проведений по бухгалтерії.'); Exit; end else begin if CalcMode<>1 then begin //Проверяем есть ли между эти счетом и ближайшим расчитанным "нерасчитанные" счета CheckSP:=TpFibStoredProc.Create(self); CheckSP.Database:=WorkDatabase; CheckSP.Transaction:=ReadTransaction; CheckSP.StoredProcName:='CN_ACCOUTS_IS_MAY_BEE_CALC'; CheckSP.Prepare; CheckSP.ParamByName('ID_ACCOUNT').AsInt64:=StrToInt64(AccDataSet.FieldByName('ID_ACCOUNT').AsString); CheckSP.ExecProc; F:=CheckSP.ParamByName('RESULT').AsInteger; if (f=0) then begin BaseTypes.agMessageDlg(BU_WarningCaption,CheckSP.ParamByName('WARNING_MSG').AsString,mtError,[mbOk]); CheckSP.Close; CheckSP.Free; Exit; end else begin CheckSP.Close; CheckSP.Free; end; end; //Предупреждаем пользователя о том что расчет по этому документу уже совершался if (AccDataSet.FieldByName('STATUS').AsInteger=1)then begin if BaseTypes.agMessageDlg(BU_WarningCaption,'По документу вже зроблено розрахунок. Виконати розрахунок?',mtConfirmation,[mbYes,mbNo])=mrNo then Exit; end; T:=TfrmCalcConfigure.Create(self, WorkDatabase.Handle); if (T.ShowModal=mrYes) then begin SetControls(false,true); Progress_Thread :=TShowProgressThread.Create(true,self); Progress_Thread.FreeOnTerminate:=true; Progress_Thread.Priority :=tpNormal; Progress_Thread.OnTerminate :=OnTerminateCalcThread; Progress_Thread.Resume; GetDataMode:=1; if T.rbFilter.Checked then GetDataMode:=1; if T.rbFixedKod.Checked then GetDataMode:=2; Calculat_Thread := UDoCalclationsThread.Create(true, //CreateSuspended self, //Form T.DoCalc.Checked, //DoCalc T.DoReversCalc.Checked, //DoReversCalc T.Recalc.Checked, //DoRecalc T.DoRecalcByFilter.Checked, //DoRecalcByFilter T.DoRecalcWithoutFilter.Checked, //DoRecalcWithoutFilter T.DoRecalcWithCheckEdit.Checked, //DoRecalcWithCheckEdit StrToInt64(T.edFixedKode.Text), //UsedFixedIdKod T.ID_SESSION_FILTER, //Used_SESSION_FILTER GetDataMode, //GetDataMode StrToInt64(AccDataSet.FieldByName('ID_ACCOUNT').AsString)); Calculat_Thread.FreeOnTerminate := true; Calculat_Thread.Priority := tpNormal; Calculat_Thread.OnTerminate := OnTerminateCalcThread_DB; Calculat_Thread.Resume; end; T.Free; end; end; end; procedure TfrmAccountMain.ProvsButtonClick(Sender: TObject); var T: TfrmAccDetail; begin if (AccDataSet.RecordCount>0) then begin T:=TfrmAccDetail.Create(self, WorkDatabase.Handle, AccDataSet.FieldBYName('STATUS').Value); T.ShowModal; T.Free; end; end; procedure TfrmAccountMain.N18Click(Sender: TObject); var CheckSP:TpFibStoredProc; F:Integer; begin CALC_KEY_SESSION:=WorkDatabase.Gen_Id('KERNEL_GEN_ID_SESSION',1); DoResult:=0; if (AccDataSet.RecordCount>0) then begin //Проверяем статус счета if (AccDataSet.FieldByName('STATUS').AsInteger=0) then begin ShowMessage('Рахунок ще не розрахований.'); Exit; end else begin //Проверяем есть ли между эти счетом и ближайшим проведенным "нерасчитанные" счета CheckSP:=TpFibStoredProc.Create(self); CheckSP.Database:=WorkDatabase; CheckSP.Transaction:=ReadTransaction; CheckSP.StoredProcName:='CN_ACCOUTS_IS_MAY_BEE_PROV'; CheckSP.Prepare; CheckSP.ParamByName('ID_ACCOUNT').AsInt64:=StrToInt64(AccDataSet.FieldByName('ID_ACCOUNT').AsString); CheckSP.ExecProc; F:=CheckSP.ParamByName('RESULT').AsInteger; CheckSP.Close; CheckSP.Free; if (f=0) then begin BaseTypes.agMessageDlg(BU_WarningCaption,'Не можна проводити рахунок, є не проведені рахунки, які додані раніше! ',mtError,[mbOk]); Exit; end; SetControls(false,false); Progress_Thread :=TShowProgressThread.Create(true,self); Progress_Thread.FreeOnTerminate:=true; Progress_Thread.Priority :=tpNormal; Progress_Thread.OnTerminate :=prOnTerminateCalcThread; Progress_Thread.Resume; DoProvs_Thread :=TDoProvsThread.Create(true,self); DoProvs_Thread.FreeOnTerminate :=true; DoProvs_Thread.Priority :=tpNormal; DoProvs_Thread.OnTerminate :=prOnTerminateCalcThread_DB; DoProvs_Thread.Resume; end; end; end; procedure TfrmAccountMain.prOnTerminateCalcThread(Sender: TObject); var T:TfrmGetErrors; begin SetControls(true,false); if (DoResult=1) then MessageBox(self.Handle,'Процес проведення документу завершено.','Увага!',MB_OK) else begin T:=TfrmGetErrors.Create(self); T.cxMemo1.Lines.Add('Під час проведення документу виникли помилки'); T.cxMemo1.Lines.Add(ErrorID_KOD); T.ShowModal; T.Free; ErrorID_KOD:=''; end; RefreshButtonClick(Self); end; procedure TfrmAccountMain.prOnTerminateCalcThread_DB(Sender: TObject); begin if Assigned(Progress_Thread) then Progress_Thread.Terminate; end; procedure TfrmAccountMain.N23Click(Sender: TObject); var GetOSTDate:TpFibStoredProc; begin CALC_KEY_SESSION:=WorkDatabase.Gen_Id('KERNEL_GEN_ID_SESSION',1); GetOSTDate:=TpFibStoredProc.Create(self); GetOSTDate.Database:=WorkDatabase; GetOSTDate.Transaction:=ReadTransaction; GetOSTDate.StoredProcName:='CN_ACCOUNTS_GET_OST_DATE'; GetOSTDate.Prepare; GetOSTDate.ExecProc; if agMessageDlg(BU_WarningCaption,'Сформувати залишки на '+GetOSTDate.ParamByName('LAST_OST_DATE').AsString,mtConfirmation,[mbYes,mbNo])=mrYes then begin makeOut_saldo(GetOSTDate.ParamByName('LAST_OST_DATE').AsDateTime); end; GetOSTDate.Close; GetOSTDate.Free; end; procedure TfrmAccountMain.N26Click(Sender: TObject); var BackOSTDate:TpFibStoredProc; begin BackOSTDate:=TpFibStoredProc.Create(self); BackOSTDate.Database:=WorkDatabase; BackOSTDate.Transaction:=WriteTransaction; WriteTransaction.StartTransaction; BackOSTDate.StoredProcName:='CN_ACCOUNTS_BACK_SALDO'; BackOSTDate.Prepare; BackOSTDate.ExecProc; WriteTransaction.Commit; BackOSTDate.Close; BackOSTDate.Free; RefreshButtonClick(self); end; procedure TfrmAccountMain.makeOut_saldo(New_Date: TDateTime); begin DoResult:=0; SetControls(false,false); Progress_Thread :=TShowProgressThread.Create(true,self); Progress_Thread.FreeOnTerminate:=true; Progress_Thread.Priority :=tpNormal; Progress_Thread.OnTerminate :=makeOnTerminateCalcThread; Progress_Thread.Resume; DoSaldo_Thread :=TCloseSysThread.Create(true,self,New_Date); DoSaldo_Thread.FreeOnTerminate :=true; DoSaldo_Thread.Priority :=tpNormal; DoSaldo_Thread.OnTerminate :=makeOnTerminateCalcThread_DB; DoSaldo_Thread.Resume; end; procedure TfrmAccountMain.makeOnTerminateCalcThread(Sender: TObject); begin SetControls(true,false); if (DoResult=1) then MessageBox(self.Handle,'Процес розрахунку залишків завершено успішно.','Увага!',MB_OK) else MessageBox(self.Handle,PAnsiChar('Під час розрахунку залишків виникли помилки.'+#13+ '(Error ID_KOD='+ErrorID_KOD+')'+#13+ ' Зверніться до адміністратора системи.'),'Увага!',MB_OK); RefreshButtonClick(Self); end; procedure TfrmAccountMain.makeOnTerminateCalcThread_DB(Sender: TObject); begin if Assigned(Progress_Thread) then Progress_Thread.Terminate; end; procedure TfrmAccountMain.N1Click(Sender: TObject); var T:TfrmDocPrinting; begin if (AccDataSet.RecordCount>0) then begin T:=TfrmDocPrinting.Create(self,1); T.ShowModal; T.Free; end; end; procedure TfrmAccountMain.N2Click(Sender: TObject); var T:TfrmPrintOborot; begin if (AccDataSet.RecordCount > 0) then begin T := TfrmPrintOborot.Create(self,WorkDatabase.Handle,AccDataSet['ID_ACCOUNT'], AccDataSet.FieldByName('DATE_BEG').AsDateTime, AccDataSet.FieldByName('DATE_END').AsDateTime); end; end; procedure TfrmAccountMain.N3Click(Sender: TObject); var T:TfrmDocPrinting; begin if (AccDataSet.RecordCount>0) then begin T:=TfrmDocPrinting.Create(self,3); T.ShowModal; T.Free; end; end; procedure TfrmAccountMain.N24Click(Sender: TObject); var STRU:KERNEL_MODE_STRUCTURE; ChangeSTSP:TpFibStoredProc; ErrorList:TStringList; DoResult:Boolean; MSG_STRING:String; i:Integer; begin if (AccDataSet.RecordCount>0) then begin if (AccDataSet.FieldByName('STATUS').AsInteger=2) then begin //start_sql_monitor; WriteTransaction.StartTransaction; STRU.KEY_SESSION:=WorkDatabase.Gen_Id('KERNEL_GEN_ID_SESSION',1); STRU.TRHANDLE:=WriteTransaction.Handle; STRU.DBHANDLE:=WorkDatabase.Handle; STRU.KERNEL_ACTION:=2; STRU.PK_ID:=TFibBCDField(AccDataSet.FieldByName('BUHG_PK_ID')).AsInt64; STRU.WORKDATE:=AccDataSet.FieldByName('WORK_SCH_DATE').Value; STRU.ID_USER:=self.id_user; try DoResult:=Kernel.KernelDo(@STRU); if not DoResult then begin ErrorList:=Kernel.GetDocErrorsListEx(@STRU); MSG_STRING:='При видаленні документа були виявленні помилки. '+Chr(10)+chr(13); if ErrorList<>nil then begin for i:=0 to ErrorList.Count-1 do begin MSG_STRING:=MSG_STRING+' ПОМИЛКА- '+ErrorList.Strings[i]; end; end; ShowMessage(MSG_STRING); end else begin //Изменяем статус счета ChangeSTSP:=TpFibStoredProc.Create(self); ChangeSTSP.Database:=WorkDatabase; ChangeSTSP.Transaction:=WriteTransaction; WriteTransaction.StartTransaction; ChangeSTSP.StoredProcName:='CN_ACC_DROP_FROM_BUHG'; ChangeSTSP.Prepare; ChangeSTSP.ParamByName('ID_ACCOUNT').AsInt64:=StrToInt64(AccDataSet.FieldByName('ID_ACCOUNT').AsString); ChangeSTSP.ExecProc; ChangeSTSP.Free; end; WriteTransaction.Commit; RefreshButtonClick(self); except on E:Exception do Begin showMessage(E.Message); //Send_mail(e.Message); end; end; //stop_sql_monitor; end; end; end; procedure TfrmAccountMain.TerminateButtonClick(Sender: TObject); begin Calculat_Thread.Terminate; end; procedure TfrmAccountMain.cbYearChange(Sender: TObject); begin DateSeparator:='.'; ActualDate:=StrToDate('01.'+IntToStr(cbMonth.ItemIndex+1)+'.'+cbYear.Items[cbYear.ItemIndex]); RefreshButtonClick(self); end; procedure TfrmAccountMain.NEntryRestClick(Sender: TObject); var AParameter: TcnSimpleParamsEx; begin AParameter:= TcnSimpleParamsEx.Create; AParameter.Owner:=self; AParameter.Db_Handle:= WorkDatabase.Handle; AParameter.Formstyle:=fsNormal; AParameter.ID_User:=-1; RunFunctionFromPackage(AParameter, 'Contracts\cn_Account_Ost.bpl','ShowAccountOst'); AParameter.Free; Screen.Cursor := crDefault; end; procedure TfrmAccountMain.N25Click(Sender: TObject); var T:TfrmDocPrinting; begin if (AccDataSet.RecordCount>0) then begin T:=TfrmDocPrinting.Create(self,2); T.ShowModal; T.Free; end; end; procedure TfrmAccountMain.FormCreate(Sender: TObject); begin PLanguageIndex := cn_Common_Funcs.cnLanguageIndex(); InsertButton.Caption := cnConsts.cn_InsertBtn_Caption[PLanguageIndex]; EditButton.Caption := cnConsts.cn_EditBtn_Caption[PLanguageIndex]; DeleteButton.Caption := cnConsts.cn_DeleteBtn_Caption[PLanguageIndex]; RefreshButton.Caption := cnConsts.cn_RefreshBtn_Caption[PLanguageIndex]; CalcButton.Caption := cnConsts.cn_Main_WorkBtn_Caption[PLanguageIndex]; ProvsButton.Caption := cnConsts.cn_ViewShort_Caption[PLanguageIndex]; FilterButton.Caption := cnConsts.cn_FilterBtn_Caption[PLanguageIndex]; PrintButton.Caption := cnConsts.cn_Print_Caption[PLanguageIndex]; ConfigureButton.Caption := cnConsts.cn_Config[PLanguageIndex]; CloseButton.Caption := cnConsts.cn_ExitBtn_Caption[PLanguageIndex]; end; procedure TfrmAccountMain.dxBarLargeButton1Click(Sender: TObject); var T:TfrmCalcConfigure; m:Integer; ad:TdateTime; begin T:=TfrmCalcConfigure.Create(self, WorkDatabase.Handle); T.Panel4.Visible:=false; T.Panel5.Align:=alClient; T.cxCheckBox1.Visible:=true; T.Label1.Visible:=true; T.cbMonthBeg.Visible:=true; T.cbYearBeg.Visible:=true; T.Caption:='Вибір множини договорів для аналізу синтетичного та аналітичного обліку'; if T.ShowModal=mrYes then begin SetControls(false,false); Panel2.Visible:=true; Application.ProcessMessages; if t.rbFilter.Checked then m:=1 else m:=2; ad := StrToDate('01.'+IntToStr(T.cbMonthBeg.ItemIndex+1)+'.'+T.cbYearBeg.Properties.Items[T.cbYearBeg.ItemIndex]); ad := IncMonth(ad,1) - 1; if AnalDataSet.Active then AnalDataSet.Close; AnalDataSet.SelectSQL.Text:='select * from PC_GET_KODS_FOR_COMP('+ IntToStr(m)+','+ IntToStr(T.ID_SESSION_FILTER)+','+ T.edFixedKode.Text+','+ IntToStr(Integer(T.cxCheckBox1.Checked))+','+ ''''+DateToStr(ad)+''''+')'; AnalDataSet.Open; frxReport1.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Contracts\reestrsyntplusanal.fr3',true); frxReport1.Variables['ad']:=''''+DateToStr(ad)+''''; frxReport1.PrepareReport; frxReport1.ShowReport(true); Panel2.Visible:=false; Application.ProcessMessages; SetControls(true,true); end; T.Free; end; end.
unit Dmitry.PathProviders.FileSystem; interface uses System.SysUtils, System.StrUtils, Winapi.Windows, Winapi.ShellApi, Dmitry.Memory, Dmitry.Utils.Files, Dmitry.Utils.System, Dmitry.Utils.ShellIcons, Dmitry.PathProviders, Dmitry.PathProviders.MyComputer; type TFSItem = class(TPathItem) private FFileSize: Int64; FTimeStamp: TDateTime; protected FItemLoaded: Boolean; function InternalGetParent: TPathItem; override; function GetFileSize: Int64; override; public function LoadImage(Options, ImageSize: Integer): Boolean; override; constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override; property TimeStamp: TDateTime read FTimeStamp; end; TFileItem = class(TFSItem) protected function GetFileSize: Int64; override; procedure ReadFromSearchRec(SearchRec: TSearchRec); function InternalCreateNewInstance: TPathItem; override; end; TDirectoryItem = class(TFSItem) protected function GetIsDirectory: Boolean; override; function InternalCreateNewInstance: TPathItem; override; public constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override; end; type TFileSystemProvider = class(TPathProvider) protected function InternalFillChildList(Sender: TObject; Item: TPathItem; List: TPathItemCollection; Options, ImageSize: Integer; PacketSize: Integer; CallBack: TLoadListCallBack): Boolean; override; function Delete(Sender: TObject; Items: TPathItemCollection; Options: TPathFeatureOptions): Boolean; public function ExecuteFeature(Sender: TObject; Items: TPathItemCollection; Feature: string; Options: TPathFeatureOptions): Boolean; override; function Supports(Item: TPathItem): Boolean; override; function Supports(Path: string): Boolean; override; function SupportsFeature(Feature: string): Boolean; override; function CreateFromPath(Path: string): TPathItem; override; end; implementation uses Dmitry.PathProviders.Network; function IsNetworkDirectory(S: string): Boolean; begin Result := False; S := ExcludeTrailingPathDelimiter(S); if (Length(S) > 2) and (Copy(S, 1, 2) = '\\') and (Copy(S, 3, 1) <> '\') and (PosEx('\', S, PosEx('\', S, 3) + 1) > 0) then Result := True; end; function FastIsDirectory(S: string): Boolean; begin Result := False; if IsNetworkDirectory(S) then begin Result := True; Exit; end; if Length(S) > 1 then begin if (S[2] = ':') then begin if Length(S) > 2 then begin if (PosEx(':', S, 3) = 0) then begin Result := True; end; end else Result := True; end; end; end; function FastIsFile(S: string): Boolean; begin Result := False; end; { TFileSystemProvider } function TFileSystemProvider.Delete(Sender: TObject; Items: TPathItemCollection; Options: TPathFeatureOptions): Boolean; var I: Integer; Item: TPathItem; begin Result := False; for I := 0 to Items.Count - 1 do begin Item := Items[I]; if not System.SysUtils.DeleteFile(Item.Path) then Result := False; end; end; function TFileSystemProvider.ExecuteFeature(Sender: TObject; Items: TPathItemCollection; Feature: string; Options: TPathFeatureOptions): Boolean; begin Result := inherited ExecuteFeature(Sender, Items, Feature, Options); if Feature = PATH_FEATURE_DELETE then Result := Delete(Sender, Items, Options); end; function TFileSystemProvider.InternalFillChildList(Sender: TObject; Item: TPathItem; List: TPathItemCollection; Options, ImageSize, PacketSize: Integer; CallBack: TLoadListCallBack): Boolean; var SearchPath, FileName: string; Found: Integer; SearchRec: TSearchRec; LoadOnlyDirectories, IsDirectory: Boolean; FI: TFileItem; DI: TDirectoryItem; Cancel: Boolean; OldMode: Cardinal; begin inherited; Cancel := False; Result := True; LoadOnlyDirectories := Options and PATH_LOAD_DIRECTORIES_ONLY <> 0; SearchPath := IncludeTrailingPathDelimiter(Item.Path); if IsShortDrive(SearchPath) then SearchPath := SearchPath + '\'; OldMode := SetErrorMode(SEM_FAILCRITICALERRORS); try Found := FindFirst(SearchPath + '*', faDirectory, SearchRec); try while Found = 0 do begin IsDirectory := SearchRec.Attr and faDirectory <> 0; if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') and not (not IsDirectory and LoadOnlyDirectories) then begin FileName := SearchPath + SearchRec.Name; if not IsDirectory then begin FI := TFileItem.CreateFromPath(FileName, Options, ImageSize); FI.ReadFromSearchRec(SearchRec); List.Add(FI); end else begin DI := TDirectoryItem.CreateFromPath(FileName, Options, ImageSize); List.Add(DI); end; if List.Count mod PacketSize = 0 then begin if Assigned(CallBack) then CallBack(Sender, Item, List, Cancel); if Cancel then Break; end; end; Found := System.SysUtils.FindNext(SearchRec); end; if Assigned(CallBack) then CallBack(Sender, Item, List, Cancel); finally System.SysUtils.FindClose(SearchRec); end; finally SetErrorMode(OldMode); end; end; function TFileSystemProvider.Supports(Item: TPathItem): Boolean; begin Result := Item is TFileItem; Result := Item is TDirectoryItem or Result; Result := Result or Supports(Item.Path); end; function TFileSystemProvider.Supports(Path: string): Boolean; begin if IsNetworkServer(Path) or IsNetworkShare(Path) then begin Result := False; Exit; end; Result := FastIsFile(Path) or FastIsDirectory(Path); end; function TFileSystemProvider.CreateFromPath(Path: string): TPathItem; begin Result := nil; if IsDrive(Path) then Result := TDriveItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE or PATH_LOAD_FAST, 0) else if FastIsFile(Path) then Result := TFileItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0) else if FastIsDirectory(Path) then Result := TDirectoryItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0); end; function TFileSystemProvider.SupportsFeature(Feature: string): Boolean; begin Result := Feature = PATH_FEATURE_DELETE; Result := Result or (Feature = PATH_FEATURE_CHILD_LIST); end; { TFSItem } constructor TFSItem.CreateFromPath(APath: string; Options, ImageSize: Integer); begin inherited; FItemLoaded := False; APath := ExcludeTrailingPathDelimiter(APath); FDisplayName := ExtractFileName(APath); FFileSize := 0; FTimeStamp := Now; if (Options and PATH_LOAD_NO_IMAGE = 0) and (ImageSize > 0) then LoadImage(Options, ImageSize); end; function TFSItem.GetFileSize: Int64; begin Result := FFileSize; end; function TFSItem.InternalGetParent: TPathItem; var S: String; begin S := Path; while IsPathDelimiter(S, Length(S)) do S := ExcludeTrailingPathDelimiter(S); S := ExtractFileDir(S); if IsDrive(S) then Result := TDriveItem.CreateFromPath(S, PATH_LOAD_NO_IMAGE or PATH_LOAD_FAST, 0) else if IsNetworkShare(S) then Result := TShareItem.CreateFromPath(S, PATH_LOAD_NO_IMAGE, 0) else if S <> '' then Result := TDirectoryItem.CreateFromPath(S, PATH_LOAD_NO_IMAGE, 0) else Result := THomeItem.Create; end; function TFSItem.LoadImage(Options, ImageSize: Integer): Boolean; var Icon: HIcon; begin F(FImage); Icon := ExtractShellIcon(FPath, ImageSize); FImage := TPathImage.Create(Icon); Result := True; end; { TFileItem } function TFileItem.GetFileSize: Int64; var SearchRec: TSearchRec; HFind: THandle; begin if not FItemLoaded then begin FItemLoaded := True; HFind := FindFirst(PChar(Path), faAnyFile, SearchRec); if HFind <> INVALID_HANDLE_VALUE then begin if SearchRec.FindHandle <> INVALID_HANDLE_VALUE then begin if (SearchRec.Attr and FILE_ATTRIBUTE_DIRECTORY) = 0 then FFileSize := SearchRec.Size; FTimeStamp := SearchRec.TimeStamp; end; System.SysUtils.FindClose(SearchRec); end; end; Result := FFileSize; end; function TFileItem.InternalCreateNewInstance: TPathItem; begin Result := TFileItem.Create; end; procedure TFileItem.ReadFromSearchRec(SearchRec: TSearchRec); begin FFileSize := SearchRec.Size; FTimeStamp := SearchRec.TimeStamp; FItemLoaded := True; end; { TDirectoryItem } constructor TDirectoryItem.CreateFromPath(APath: string; Options, ImageSize: Integer); begin inherited; if Options and PATH_LOAD_CHECK_CHILDREN > 0 then FCanHaveChildren := IsDirectoryHasDirectories(Path); end; function TDirectoryItem.GetIsDirectory: Boolean; begin Result := True; end; function TDirectoryItem.InternalCreateNewInstance: TPathItem; begin Result := TDirectoryItem.Create; end; initialization PathProviderManager.RegisterProvider(TFileSystemProvider.Create); end.
unit uActions; interface uses System.Classes, uMemory; type TInstallAction = class; TActionCallback = procedure(Sender: TInstallAction; CurrentPoints, Total: Int64; var Terminate: Boolean) of object; TInstallAction = class(TObject) private FIsTerminated: Boolean; public constructor Create; virtual; function CalculateTotalPoints : Int64; virtual; abstract; procedure Execute(Callback: TActionCallback); virtual; abstract; procedure Terminate; property IsTerminated: Boolean read FIsTerminated; end; TInstallActionClass = class of TInstallAction; TInstallManager = class(TObject) private FInstallScopeList: TList; FTotal: Int64; FCurrentlyDone : Int64; FCalBack: TActionCallback; procedure InternalCallback(Sender : TInstallAction; CurrentPoints, Total : int64; var Terminate : Boolean); public constructor Create; destructor Destroy; override; class function Instance : TInstallManager; procedure RegisterScope(Scope : TInstallActionClass); function ExecuteInstallActions(Callback : TActionCallback): Boolean; end; implementation var InstallManagerInstance: TInstallManager = nil; { TInstallAction } constructor TInstallAction.Create; begin FIsTerminated := False; end; procedure TInstallAction.Terminate; begin FIsTerminated := True; end; { TInstallManager } constructor TInstallManager.Create; begin FInstallScopeList := TList.Create; end; destructor TInstallManager.Destroy; begin FreeList(FInstallScopeList); inherited; end; function TInstallManager.ExecuteInstallActions(Callback: TActionCallback): Boolean; var I: Integer; Action: TInstallAction; begin Result := True; FCalBack := Callback; FTotal := 0; FCurrentlyDone := 0; //calculating... for I := 0 to FInstallScopeList.Count - 1 do begin Action := TInstallAction(FInstallScopeList[I]); Inc(FTotal, Action.CalculateTotalPoints); end; //executing... for I := 0 to FInstallScopeList.Count - 1 do begin Action := TInstallAction(FInstallScopeList[I]); Action.Execute(InternalCallback); if Action.IsTerminated then Exit(False); Inc(FCurrentlyDone, Action.CalculateTotalPoints); end; end; procedure TInstallManager.InternalCallback(Sender: TInstallAction; CurrentPoints, Total: Int64; var Terminate: Boolean); begin FCalBack(Sender, FCurrentlyDone + CurrentPoints, FTotal, Terminate); end; class function TInstallManager.Instance: TInstallManager; begin if InstallManagerInstance = nil then InstallManagerInstance := TInstallManager.Create; Result := InstallManagerInstance; end; procedure TInstallManager.RegisterScope(Scope: TInstallActionClass); begin FInstallScopeList.Add(Scope.Create); end; initialization finalization; F(InstallManagerInstance); end.
{ GLEParticleMasksManager.pas This unit is part of GLE - GLScene Game Utilities Engine set by Kenneth Poulter difacane@telkomsa.net Module Number: 37 Description: This is merely an addon to GLScene, since i don't want to edit GLScene's source code directly and make changes (since GLScene's source code constantly changes). What the manager does is to provide a basic tool for newly created particles to be modified (their position currently). Their position is set from 3 different masks, which create a "virtual" 3d object... meaning, an actual 3d object is not created, but an outline for particles or any other objects are positioned. ActualUsage: Create the component, create a new ParticleMask, set the material library, set the materials, and use the procedures provided in the managers root. positioning and scaling applicable aswell. The images should be Licenses: Removed. Donated to GLScene's Code Base as long as the author (Kenneth Poulter) is not altered in this file. Theft of code also is not allowed, although alterations are allowed. History: 28/12/2005 - Added - LX,LY,LZ for correct positioning; Rotating; GenerateParticleMaskFromProjection; Targeting Objects (scales, positions and rotation of object applies) 27/12/2005 - Added - Scale and Positioning 27/12/2005 - Improved code speed significantly (could do better) 26/12/2005 - Creation of base code from experimentation } unit GLEParticleMasksManager; interface uses SysUtils, Classes, Types, GLTexture, GLScene, GLVectorGeometry, GLVectorTypes, GLMisc, Graphics, GLParticleFX, Dialogs; type TGLEProjectedParticleMask = (pptXMask, pptYMask, pptZMask); TGLEParticleMask = class; TGLEParticleMasks = class; TGLEParticleMask = class (TCollectionItem) private { Private Declarations } FName: String; FScale: TGLCoordinates; FPosition: TGLCoordinates; FYMask: TGLLibMaterialName; FZMask: TGLLibMaterialName; FXMask: TGLLibMaterialName; FMaterialLibrary: TGLMaterialLibrary; FBackgroundColor: TColor; FMaskColor: TColor; FMaxX, FMaxY, FMaxZ, FMinX, FMinY, FMinZ : integer; IXW, IXH, IYW, IYH, IZW, IZH : integer; LX, LY, LZ : integer; MX, MY : integer; BogusMask, BogusMaskX, BogusMaskY, BogusMaskZ : boolean; // we might have a pitch mask FRollAngle: single; FPitchAngle: single; FTurnAngle: single; procedure SetName(const Value: String); procedure SetXMask(const Value: TGLLibMaterialName); procedure SetYMask(const Value: TGLLibMaterialName); procedure SetZMask(const Value: TGLLibMaterialName); procedure SetMaterialLibrary(const Value: TGLMaterialLibrary); function XCan : TBitMap; function YCan : TBitMap; function ZCan : TBitMap; protected { Protected Declarations } function GetDisplayName : String; override; public { Public Declarations } constructor Create(Collection : TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure UpdateExtents; procedure Roll(Angle : Single); procedure Turn(Angle : Single); procedure Pitch(Angle : Single); // this generates a xmask from another mask just to fill gaps, depth is dependant on frommask width and height procedure GenerateMaskFromProjection(FromMask, ToMask : TGLEProjectedParticleMask; Depth : integer); published { Published Declarations } // scales and positions property Scale : TGLCoordinates read FScale write FScale; property Position : TGLCoordinates read FPosition write FPosition; // the reference name of the particle mask property Name : String read FName write SetName; property MaterialLibrary : TGLMaterialLibrary read FMaterialLibrary write SetMaterialLibrary; // mask images, make sure materiallibrary is assigned property XMask : TGLLibMaterialName read FXMask write SetXMask; property YMask : TGLLibMaterialName read FYMask write SetYMask; property ZMask : TGLLibMaterialName read FZMask write SetZMask; // background color is the color that prevents particles from being positioned there property BackgroundColor : TColor read FBackgroundColor write FBackgroundColor; // maskcolor is where particles are allowed to be positioned property MaskColor : TColor read FMaskColor write FMaskColor; // just the average angles for orientation property RollAngle : single read FRollAngle write FRollAngle; property PitchAngle : single read FPitchAngle write FPitchAngle; property TurnAngle : single read FTurnAngle write FTurnAngle; end; TGLEParticleMasks = class (TCollection) protected { Protected Declarations } Owner : TComponent; function GetOwner: TPersistent; override; procedure SetItems(index : Integer; const val : TGLEParticleMask); function GetItems(index : Integer) : TGLEParticleMask; public { Public Declarations } function Add : TGLEParticleMask; constructor Create(AOwner : TComponent); property Items[index : Integer] : TGLEParticleMask read GetItems write SetItems; default; end; TGLEParticleMasksManager = class(TComponent) private FParticleMasks: TGLEParticleMasks; { Private declarations } protected { Protected declarations } procedure ApplyOrthoGraphic(var Vec : TVector3f; Mask : TGLEParticleMask); procedure ApplyRotation(var Vec : TVector3f; Mask : TGLEParticleMask); procedure ApplyRotationTarget(var Vec : TVector3f; Mask : TGLEParticleMask; TargetObject : TGLBaseSceneObject); procedure ApplyScaleAndPosition(var Vec : TVector3f; Mask : TGLEParticleMask); procedure ApplyScaleAndPositionTarget(var Vec : TVector3f; Mask : TGLEParticleMask; TargetObject : TGLBaseSceneObject); procedure FindParticlePosition(var Vec : TVector3f; Mask : TGLEParticleMask); public { Public declarations } constructor Create(AOwner : TComponent); override; destructor Destroy; override; function CreateParticlePositionFromMask(MaskName : string) : TVector3f; function TargetParticlePositionFromMask(TargetObject : TGLBaseSceneObject; MaskName : String) : TVector3f; procedure SetParticlePositionFromMask(Particle : TGLParticle; MaskName : string); procedure SetParticlePositionFromMaskTarget(Particle : TGLParticle; MaskName : String; TargetObject : TGLBaseSceneObject); function ParticleMaskByName(MaskName : string) : TGLEParticleMask; published { Published declarations } property ParticleMasks : TGLEParticleMasks read FParticleMasks write FParticleMasks; end; procedure Register; implementation procedure Register; begin RegisterComponents('GLScene GameUtils', [TGLEParticleMasksManager]); end; { TGLEParticleMasks } function TGLEParticleMasks.Add: TGLEParticleMask; begin Result:=(inherited Add) as TGLEParticleMask; end; constructor TGLEParticleMasks.Create(AOwner: TComponent); begin inherited Create(TGLEParticleMask); Owner := AOwner; end; function TGLEParticleMasks.GetItems(index: Integer): TGLEParticleMask; begin Result:=TGLEParticleMask(inherited Items[index]); end; function TGLEParticleMasks.GetOwner: TPersistent; begin Result:=Owner; end; procedure TGLEParticleMasks.SetItems(index: Integer; const val: TGLEParticleMask); begin inherited Items[index]:=val; end; { TGLEParticleMask } procedure TGLEParticleMask.Assign(Source: TPersistent); begin if Source is TGLEParticleMask then begin FScale.Assign(TGLEParticleMask(Source).FScale); FPosition.Assign(TGLEParticleMask(Source).FPosition); FMaterialLibrary := TGLEParticleMask(Source).FMaterialLibrary; FXMask := TGLEParticleMask(Source).FXMask; FYMask := TGLEParticleMask(Source).FYMask; FZMask := TGLEParticleMask(Source).FZMask; end else inherited Assign(Source); end; constructor TGLEParticleMask.Create(Collection: TCollection); begin inherited Create(Collection); FName := 'ParticleMask' + IntToStr(ID); FScale := TGLCoordinates.CreateInitialized(Self, XYZHMGVector, csPoint); FPosition := TGLCoordinates.CreateInitialized(Self, NullHmgPoint, csPoint); FMaterialLibrary := nil; FMaskColor := clWhite; FBackGroundColor := clBlack; FTurnAngle := 0; FRollAngle := 0; FPitchAngle := 0; FXMask := ''; FYMask := ''; FZMask := ''; UpdateExtents; end; destructor TGLEParticleMask.Destroy; begin FScale.Free; FPosition.Free; FMaterialLibrary := nil; FBackgroundColor := clBlack; FMaskColor := clWhite; FXMask := ''; FYMask := ''; FZMask := ''; inherited Destroy; end; procedure TGLEParticleMask.GenerateMaskFromProjection(FromMask, ToMask: TGLEProjectedParticleMask; Depth: integer); var FromBitMap : TBitmap; ToBitMap : TBitMap; X, Y : Integer; Rect : TRect; begin FromBitMap := nil; ToBitMap := nil; if not assigned(FMaterialLibrary) then exit; if FromMask = ToMask then exit; // we can't project to the same mask if Depth < 0 then exit; case FromMask of pptXMask : FromBitMap := XCan; pptYMask : FromBitMap := YCan; pptZMask : FromBitMap := ZCan; end; if (FromBitMap.Width = 0) and (FromBitMap.Height = 0) then exit; // we can't use something that has no image case ToMask of pptXMask : ToBitMap := XCan; pptYMask : ToBitMap := YCan; pptZMask : ToBitMap := ZCan; end; ToBitMap.Width := FromBitMap.Width; ToBitMap.Height := FromBitMap.Height; ToBitMap.Canvas.Pen.Color := FBackgroundColor; ToBitMap.Canvas.Pen.Style := psSolid; ToBitMap.Canvas.Brush.Color := FBackgroundColor; ToBitMap.Canvas.Brush.Style := bsSolid; Rect.Left := 0; Rect.Top := 0; Rect.Right := ToBitMap.Width; Rect.Bottom := ToBitMap.Height; ToBitMap.Canvas.FillRect(Rect); ToBitMap.Canvas.Pen.Color := FMaskColor; ToBitMap.Canvas.Brush.Color := FMaskColor; for X := 0 to ToBitMap.Width do for Y := 0 to ToBitMap.Height do begin // from x mask if (FromMask = pptXMask) and (ToMask = pptYMask) then if FromBitMap.Canvas.Pixels[X,Y] = FMaskColor then begin ToBitMap.Canvas.MoveTo(((FromBitmap.Width - Depth) div 2), x); ToBitMap.Canvas.LineTo(((FromBitmap.Width + Depth) div 2), x); end; if (FromMask = pptXMask) and (ToMask = pptZMask) then if FromBitMap.Canvas.Pixels[X,Y] = FMaskColor then begin ToBitMap.Canvas.MoveTo(((FromBitmap.Width - Depth) div 2), y); ToBitMap.Canvas.LineTo(((FromBitmap.Width + Depth) div 2), y); end; // from y mask if (FromMask = pptYMask) and (ToMask = pptXMask) then if FromBitMap.Canvas.Pixels[X,Y] = FMaskColor then begin ToBitMap.Canvas.MoveTo(y, ((FromBitmap.Height - Depth) div 2)); ToBitMap.Canvas.LineTo(y, ((FromBitmap.Height + Depth) div 2)); end; if (FromMask = pptYMask) and (ToMask = pptZMask) then if FromBitMap.Canvas.Pixels[X,Y] = FMaskColor then begin ToBitMap.Canvas.MoveTo(x, ((FromBitmap.Height - Depth) div 2)); ToBitMap.Canvas.LineTo(x, ((FromBitmap.Height + Depth) div 2)); end; // from z mask if (FromMask = pptZMask) and (ToMask = pptXMask) then if FromBitMap.Canvas.Pixels[X,Y] = FMaskColor then begin ToBitMap.Canvas.MoveTo(((FromBitmap.Width - Depth) div 2), y); ToBitMap.Canvas.LineTo(((FromBitmap.Width + Depth) div 2), y); end; if (FromMask = pptZMask) and (ToMask = pptYMask) then if FromBitMap.Canvas.Pixels[X,Y] = FMaskColor then begin ToBitMap.Canvas.MoveTo(x, ((FromBitmap.Height - Depth) div 2)); ToBitMap.Canvas.LineTo(x, ((FromBitmap.Height + Depth) div 2)); end; end; UpdateExtents; end; function TGLEParticleMask.GetDisplayName: String; begin Result := ''; if FName <> '' then Result := FName else Result := 'TGLEParticleMask'; end; procedure TGLEParticleMask.Pitch(Angle: Single); begin FPitchAngle := FPitchAngle + Angle; end; procedure TGLEParticleMask.Roll(Angle: Single); begin FRollAngle := FRollAngle + Angle; end; procedure TGLEParticleMask.SetMaterialLibrary( const Value: TGLMaterialLibrary); begin FMaterialLibrary := Value; UpdateExtents; end; procedure TGLEParticleMask.SetName(const Value: String); var i : integer; begin for i := 1 to Length(Value) do if Value[i] = ' ' then begin raise Exception.Create('Cannot contain spaces or special characters.'); Exit; end; FName := Value; end; procedure TGLEParticleMask.SetXMask(const Value: TGLLibMaterialName); begin FXMask := Value; if assigned(FMaterialLibrary) then if not assigned(FMaterialLibrary.LibMaterialByName(FXMask)) then begin XCan.Width := 0; XCan.Height := 0; end; UpdateExtents; end; procedure TGLEParticleMask.SetYMask(const Value: TGLLibMaterialName); begin FYMask := Value; if assigned(FMaterialLibrary) then if not assigned(FMaterialLibrary.LibMaterialByName(FYMask)) then begin YCan.Width := 0; YCan.Height := 0; end; UpdateExtents; end; procedure TGLEParticleMask.SetZMask(const Value: TGLLibMaterialName); begin FZMask := Value; if assigned(FMaterialLibrary) then if not assigned(FMaterialLibrary.LibMaterialByName(FZMask)) then begin ZCan.Width := 0; ZCan.Height := 0; end; UpdateExtents; end; procedure TGLEParticleMask.Turn(Angle: Single); begin FTurnAngle := FTurnAngle + Angle; end; procedure TGLEParticleMask.UpdateExtents; var MinXX, MinXY, MinYX, MinYY, MinZX, MinZY : integer; MaxXX, MaxXY, MaxYX, MaxYY, MaxZX, MaxZY : integer; X,Y : integer; begin FMinX := 0; // min extents FMinY := 0; FMinZ := 0; FMaxX := 0; // max extents FMaxY := 0; FMaxZ := 0; IXW := 0; // widths IYW := 0; IZW := 0; IXH := 0; // heights IYH := 0; IZH := 0; MinXX := 0; // min plane mask extents MinXY := 0; MinYX := 0; MinYY := 0; MinZX := 0; MinZY := 0; MaxXX := 0; // max plane mask extents MaxXY := 0; MaxYX := 0; MaxYY := 0; MaxZX := 0; MaxZY := 0; BogusMask := true; // prevents system locks BogusMaskX := true; BogusMaskY := true; BogusMaskZ := true; // we don't find it? no point in continuing if not assigned(FMaterialLibrary) then exit; // it is recommended to have 3 different masks // if there is only 2, the 3rd image will just take the largest extents and use them... creating not a very good effect if XCan <> nil then begin IXW := XCan.Width; IXH := XCan.Height; end; if YCan <> nil then begin IYW := YCan.Width; IYH := YCan.Height; end; if ZCan <> nil then begin IZW := ZCan.Width; IZH := ZCan.Height; end; // we find the largest dimensions of each image and give them to min mask extents so we work backwards MX := MaxInteger(MaxInteger(IXW, IYW),IZW); MY := MaxInteger(MaxInteger(IXH, IYH),IZH); if XCan <> nil then begin MinXX := MX; MinXY := MY; end; if YCan <> nil then begin MinYX := MX; MinYY := MY; end; if ZCan <> nil then begin MinZX := MX; MinZY := MY; end; // this is where we work backwards from to find the max size of the dimensions... // in a sense, this provides information for the randomizing, and speeds up the code for x := 0 to MX do for y := 0 to MY do begin if XCan <> nil then if (X <= XCan.Width) and (Y <= XCan.Height) then if (XCan.Canvas.Pixels[x,y] = FMaskColor) then begin if x > MaxXX then MaxXX := x; if y > MaxXY then MaxXY := y; if x < MinXX then MinXX := x; if x < MinXY then MinXY := y; BogusMaskX := false; end; if YCan <> nil then if (X <= YCan.Width) and (Y <= YCan.Height) then if (YCan.Canvas.Pixels[x,y] = FMaskColor) then begin if x > MaxYX then MaxYX := x; if y > MaxYY then MaxYY := y; if x < MinYX then MinYX := x; if x < MinYY then MinYY := y; BogusMaskY := false; end; if ZCan <> nil then if (X <= ZCan.Width) and (Y <= ZCan.Height) then if (ZCan.Canvas.Pixels[x,y] = FMaskColor) then begin if x > MaxZX then MaxZX := x; if y > MaxZY then MaxZY := y; if x < MinZX then MinZX := x; if x < MinZY then MinZY := y; BogusMaskZ := false; end; end; BogusMask := (BogusMaskX or BogusMaskY or BogusMaskZ); // here we find our 3d extents from a 1st angle orthographic shape FMinX := MinInteger(MinZX,MinYX); FMinY := MinInteger(MinXY,MinZY); FMinZ := MinInteger(MinXX,MinYY); FMaxX := MaxInteger(MaxZX,MaxYX); FMaxY := MaxInteger(MaxXY,MaxZY); FMaxZ := MaxInteger(MaxXX,MaxYY); // this is the largest mask image sizes converted to orthographic and extents... used later on LX := MaxInteger(IZW, IYW); LY := MaxInteger(IXH, IZH); LZ := MaxInteger(IXW, IYH); end; function TGLEParticleMask.XCan: TBitMap; begin Result := nil; if not assigned(FMaterialLibrary) then exit; if not assigned(FMaterialLibrary.LibMaterialByName(FXMask)) then exit; if FMaterialLibrary.LibMaterialByName(FXMask).Material.Texture.ImageClassName <> TGLPersistentImage.ClassName then exit; Result := TBitMap((FMaterialLibrary.LibMaterialByName(FXMask).Material.Texture.Image as TGLPersistentImage).Picture.Bitmap); end; function TGLEParticleMask.YCan: TBitMap; begin Result := nil; if not assigned(FMaterialLibrary) then exit; if not assigned(FMaterialLibrary.LibMaterialByName(FYMask)) then exit; if FMaterialLibrary.LibMaterialByName(FYMask).Material.Texture.ImageClassName <> TGLPersistentImage.ClassName then exit; Result := TBitMap((FMaterialLibrary.LibMaterialByName(FYMask).Material.Texture.Image as TGLPersistentImage).Picture.Bitmap); end; function TGLEParticleMask.ZCan: TBitMap; begin Result := nil; if not assigned(FMaterialLibrary) then exit; if not assigned(FMaterialLibrary.LibMaterialByName(FZMask)) then exit; if FMaterialLibrary.LibMaterialByName(FZMask).Material.Texture.ImageClassName <> TGLPersistentImage.ClassName then exit; Result := TBitMap((FMaterialLibrary.LibMaterialByName(FZMask).Material.Texture.Image as TGLPersistentImage).Picture.Bitmap); end; { TGLEParticleMasksManager } procedure TGLEParticleMasksManager.ApplyOrthoGraphic(var Vec: TVector3f; Mask: TGLEParticleMask); begin Vec[0] := (Mask.LX/2-Vec[0])/Mask.LX; Vec[1] := (Mask.LY/2-Vec[1])/Mask.LY; Vec[2] := (Mask.LZ/2-Vec[2])/Mask.LZ; end; procedure TGLEParticleMasksManager.ApplyRotation(var Vec: TVector3f; Mask: TGLEParticleMask); begin Vec := VectorRotateAroundX(Vec, DegToRad(Mask.FPitchAngle)); Vec := VectorRotateAroundY(Vec, DegToRad(Mask.FTurnAngle)); Vec := VectorRotateAroundZ(Vec, DegToRad(Mask.FRollAngle)); end; procedure TGLEParticleMasksManager.ApplyRotationTarget(var Vec: TVector3f; Mask: TGLEParticleMask; TargetObject: TGLBaseSceneObject); begin Vec := VectorRotateAroundX(Vec, DegToRad(Mask.FPitchAngle + TargetObject.Rotation.X)); Vec := VectorRotateAroundY(Vec, DegToRad(Mask.FTurnAngle + TargetObject.Rotation.Y)); Vec := VectorRotateAroundZ(Vec, DegToRad(Mask.FRollAngle + TargetObject.Rotation.Z)); end; procedure TGLEParticleMasksManager.ApplyScaleAndPosition( var Vec: TVector3f; Mask: TGLEParticleMask); begin Vec[0] := Vec[0]*Mask.FScale.DirectX + Mask.FPosition.DirectX; Vec[1] := Vec[1]*Mask.FScale.DirectY + Mask.FPosition.DirectY; Vec[2] := Vec[2]*Mask.FScale.DirectZ + Mask.FPosition.DirectZ; end; procedure TGLEParticleMasksManager.ApplyScaleAndPositionTarget( var Vec: TVector3f; Mask: TGLEParticleMask; TargetObject: TGLBaseSceneObject); begin Vec[0] := Vec[0]*Mask.FScale.DirectX*TargetObject.Scale.DirectX + Mask.FPosition.DirectX + TargetObject.AbsolutePosition[0]; Vec[1] := Vec[1]*Mask.FScale.DirectY*TargetObject.Scale.DirectY + Mask.FPosition.DirectY + TargetObject.AbsolutePosition[1]; Vec[2] := Vec[2]*Mask.FScale.DirectZ*TargetObject.Scale.DirectZ + Mask.FPosition.DirectZ + TargetObject.AbsolutePosition[2]; end; constructor TGLEParticleMasksManager.Create(AOwner: TComponent); begin inherited Create(AOwner); FParticleMasks := TGLEParticleMasks.Create(Self); end; function TGLEParticleMasksManager.CreateParticlePositionFromMask( MaskName: string): TVector3f; var Mask : TGLEParticleMask; begin Result := NullVector; Mask := ParticleMaskByName(MaskName); if not assigned(Mask) then exit; if Mask.BogusMask then exit; // finds the particle position on the masks FindParticlePosition(Result, Mask); // this converts 1st angle orthographic to 3rd angle orthograhic ApplyOrthoGraphic(Result, Mask); // this just turns it accordingly ApplyRotation(Result, Mask); // this applies the scales and positioning ApplyScaleAndPosition(Result, Mask); end; destructor TGLEParticleMasksManager.Destroy; begin FParticleMasks.Destroy; inherited Destroy; end; procedure TGLEParticleMasksManager.FindParticlePosition(var Vec: TVector3f; Mask: TGLEParticleMask); var X,Y,Z : integer; begin repeat X := Random(Mask.FMaxX - Mask.FMinX) + Mask.FMinX; Y := Random(Mask.FMaxY - Mask.FMinY) + Mask.FMinY; Z := Random(Mask.FMaxZ - Mask.FMinZ) + Mask.FMinZ; until (Mask.XCan.Canvas.Pixels[Z,Y] = Mask.FMaskColor) and (Mask.YCan.Canvas.Pixels[X,Z] = Mask.FMaskColor) and (Mask.ZCan.Canvas.Pixels[X,Y] = Mask.FMaskColor); MakeVector(Vec, X, Y, Z); end; function TGLEParticleMasksManager.ParticleMaskByName( MaskName: string): TGLEParticleMask; var i : integer; begin Result := nil; if FParticleMasks.Count > 0 then for i := 0 to FParticleMasks.Count - 1 do if FParticleMasks.Items[i].FName = MaskName then Result := FParticleMasks.Items[i]; end; procedure TGLEParticleMasksManager.SetParticlePositionFromMask( Particle: TGLParticle; MaskName: string); begin if not assigned(Particle) then exit; Particle.Position := CreateParticlePositionFromMask(MaskName); end; procedure TGLEParticleMasksManager.SetParticlePositionFromMaskTarget( Particle : TGLParticle; MaskName: String; TargetObject: TGLBaseSceneObject); begin if not assigned(Particle) then exit; Particle.Position := TargetParticlePositionFromMask(TargetObject, MaskName); end; function TGLEParticleMasksManager.TargetParticlePositionFromMask( TargetObject: TGLBaseSceneObject; MaskName: String): TVector3f; var Mask : TGLEParticleMask; begin Result := NullVector; if not assigned(TargetObject) then exit; Mask := ParticleMaskByName(MaskName); if not assigned(Mask) then exit; if Mask.BogusMask then exit; // finds the particle position on the masks FindParticlePosition(Result, Mask); // this converts 1st angle orthographic to 3rd angle orthograhic ApplyOrthoGraphic(Result, Mask); // this just turns it accordingly ApplyRotationTarget(Result, Mask, TargetObject); // this applies the scales and positioning ApplyScaleAndPositionTarget(Result, Mask, TargetObject); end; end.
unit uBaseN; { Copyright (c) 2015 Ugochukwu Mmaduekwe ugo4brain@gmail.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. } interface uses System.SysUtils, System.Math, uBase; var gReverseOrder: Boolean = False; _powN: array of UInt64; OutDefaultAlphabet: array of String; tempResult: array of Char; tempResultDecode: TBytes; tempStr: String = ''; function Decode(data: String; blockMaxBitsCount: LongWord; ReverseOrder: Boolean): TBytes; function Encode(data: TBytes; blockMaxBitsCount: LongWord; ReverseOrder: Boolean): String; procedure BaseN(alphabet: array of String; blockMaxBitsCount: LongWord = 32; ReverseOrder: Boolean = False); procedure MakeCustomDefaultAlphabet(InString: String; out OutArray: array of String); function GetBits64(data: TBytes; bitPos, bitsCount: Integer): UInt64; procedure AddBits64(data: TBytes; value: UInt64; bitPos, bitsCount: Integer); procedure DecodeBlock(src: String; dst: TBytes; beginInd, endInd: Integer); procedure EncodeBlock(src: TBytes; dst: array of Char; beginInd, endInd: Integer; CharsCount: LongWord); procedure BitsToChars(out chars: array of Char; ind, count: Integer; block: UInt64; CharsCount: LongWord); function CharsToBits(data: String; ind, count: Integer): UInt64; implementation function Decode(data: String; blockMaxBitsCount: LongWord; ReverseOrder: Boolean): TBytes; var mainBitsLength, tailBitsLength, mainCharsCount, tailCharsCount, iterationCount, globalBitsLength: Integer; bits, tailBits: UInt64; begin if isNullOrEmpty(data) then begin SetLength(result, 1); result := Nil; Exit; end; MakeCustomDefaultAlphabet(tempStr, OutDefaultAlphabet); BaseN(OutDefaultAlphabet, blockMaxBitsCount, ReverseOrder); globalBitsLength := ((Length(data) - 1) * BlockBitsCount div BlockCharsCount + 8) div 8 * 8; mainBitsLength := globalBitsLength div BlockBitsCount * BlockBitsCount; tailBitsLength := globalBitsLength - mainBitsLength; mainCharsCount := mainBitsLength * BlockCharsCount div BlockBitsCount; tailCharsCount := (tailBitsLength * BlockCharsCount + BlockBitsCount - 1) div BlockBitsCount; tailBits := CharsToBits(data, mainCharsCount, tailCharsCount); if ((tailBits shr tailBitsLength) <> 0) then begin globalBitsLength := globalBitsLength + 8; mainBitsLength := globalBitsLength div BlockBitsCount * BlockBitsCount; tailBitsLength := globalBitsLength - mainBitsLength; mainCharsCount := mainBitsLength * BlockCharsCount div BlockBitsCount; tailCharsCount := (tailBitsLength * BlockCharsCount + BlockBitsCount - 1) div BlockBitsCount; end; iterationCount := mainCharsCount div BlockCharsCount; SetLength(tempResultDecode, globalBitsLength div 8); DecodeBlock(data, tempResultDecode, 0, iterationCount); if (tailCharsCount <> 0) then begin bits := CharsToBits(data, mainCharsCount, tailCharsCount); AddBits64(tempResultDecode, bits, mainBitsLength, tailBitsLength); end; result := tempResultDecode; tempResultDecode := Nil; InvAlphabet := Nil; _powN := Nil; end; function Encode(data: TBytes; blockMaxBitsCount: LongWord; ReverseOrder: Boolean): String; var mainBitsLength, tailBitsLength, mainCharsCount, tailCharsCount, globalCharsCount, iterationCount: Integer; bits: UInt64; begin if ((data = nil) or (Length(data) = 0)) then begin Exit(''); end; MakeCustomDefaultAlphabet(tempStr, OutDefaultAlphabet); BaseN(OutDefaultAlphabet, blockMaxBitsCount, ReverseOrder); mainBitsLength := (Length(data) * 8 div BlockBitsCount) * BlockBitsCount; tailBitsLength := Length(data) * 8 - mainBitsLength; mainCharsCount := mainBitsLength * BlockCharsCount div BlockBitsCount; tailCharsCount := (tailBitsLength * BlockCharsCount + BlockBitsCount - 1) div BlockBitsCount; globalCharsCount := mainCharsCount + tailCharsCount; iterationCount := mainCharsCount div BlockCharsCount; SetLength(tempResult, globalCharsCount); EncodeBlock(data, tempResult, 0, iterationCount, Length(OutDefaultAlphabet)); if (tailBitsLength <> 0) then begin bits := GetBits64(data, mainBitsLength, tailBitsLength); BitsToChars(tempResult, mainCharsCount, tailCharsCount, bits, Length(OutDefaultAlphabet)); end; SetString(result, PChar(tempResult), Length(tempResult)); tempResult := Nil; OutDefaultAlphabet := Nil; end; procedure BaseN(alphabet: array of String; blockMaxBitsCount: LongWord = 32; ReverseOrder: Boolean = False); var charsCountInBits, CharsCount, lblockMaxBitsCount: LongWord; pow: UInt64; i: Integer; begin gReverseOrder := ReverseOrder; lblockMaxBitsCount := blockMaxBitsCount; CharsCount := Length(OutDefaultAlphabet); Base(CharsCount, OutDefaultAlphabet, Char(0)); BlockBitsCount := GetOptimalBitsCount(CharsCount, charsCountInBits, lblockMaxBitsCount, 2); BlockCharsCount := Int32(charsCountInBits); SetLength(_powN, BlockCharsCount); pow := UInt64(1); i := 0; while (i < (BlockCharsCount - 1)) do begin _powN[BlockCharsCount - 1 - i] := pow; pow := pow * CharsCount; Inc(i); end; _powN[0] := pow; end; procedure MakeCustomDefaultAlphabet(InString: String; out OutArray: array of String); var i: Integer; begin SetLength(OutDefaultAlphabet, Length(InString)); for i := 1 to Length(InString) do begin OutDefaultAlphabet[i - 1] := InString[i]; end; end; function GetBits64(data: TBytes; bitPos, bitsCount: Integer): UInt64; var currentBytePos, currentBitInBytePos, xLength, x2Length: Integer; a: UInt64; begin result := UInt64(0); currentBytePos := bitPos div 8; currentBitInBytePos := bitPos mod 8; xLength := Min(bitsCount, 8 - currentBitInBytePos); if (xLength <> 0) then begin a := UInt64(UInt64(data[currentBytePos]) shl (56 + currentBitInBytePos)); result := (UInt64(a) shr (64 - xLength)) shl (bitsCount - xLength); currentBytePos := currentBytePos + (currentBitInBytePos + xLength) div 8; currentBitInBytePos := (currentBitInBytePos + xLength) mod 8; x2Length := bitsCount - xLength; if (x2Length > 8) then begin x2Length := 8; end; while (x2Length > 0) do begin xLength := xLength + x2Length; result := result or (((UInt64(data[currentBytePos])) shr (8 - x2Length)) shl (bitsCount - xLength)); currentBytePos := currentBytePos + (currentBitInBytePos + x2Length) div 8; currentBitInBytePos := (currentBitInBytePos + x2Length) mod 8; x2Length := bitsCount - xLength; if (x2Length > 8) then begin x2Length := 8; end; end; end; end; procedure AddBits64(data: TBytes; value: UInt64; bitPos, bitsCount: Integer); var currentBytePos, currentBitInBytePos, xLength, x2Length: Integer; x1, x2: Byte; begin currentBytePos := bitPos div 8; currentBitInBytePos := bitPos mod 8; xLength := Min(bitsCount, 8 - currentBitInBytePos); if (xLength <> 0) then begin x1 := Byte(((value shl (64 - bitsCount)) shr (56 + currentBitInBytePos))); data[currentBytePos] := data[currentBytePos] or x1; currentBytePos := currentBytePos + (currentBitInBytePos + xLength) div 8; currentBitInBytePos := (currentBitInBytePos + xLength) mod 8; x2Length := bitsCount - xLength; if (x2Length > 8) then begin x2Length := 8; end; while (x2Length > 0) do begin xLength := xLength + x2Length; x2 := Byte((value shr (bitsCount - xLength)) shl (8 - x2Length)); data[currentBytePos] := data[currentBytePos] or x2; currentBytePos := currentBytePos + (currentBitInBytePos + x2Length) div 8; currentBitInBytePos := (currentBitInBytePos + x2Length) mod 8; x2Length := bitsCount - xLength; if (x2Length > 8) then begin x2Length := 8; end; end end; end; procedure DecodeBlock(src: String; dst: TBytes; beginInd, endInd: Integer); var ind, charInd, bitInd: Integer; bits: UInt64; begin for ind := beginInd to Pred(endInd) do begin charInd := ind * Int32(BlockCharsCount); bitInd := ind * BlockBitsCount; bits := CharsToBits(src, charInd, Int32(BlockCharsCount)); AddBits64(dst, bits, bitInd, BlockBitsCount); end; end; procedure EncodeBlock(src: TBytes; dst: array of Char; beginInd, endInd: Integer; CharsCount: LongWord); var ind, charInd, bitInd: Integer; bits: UInt64; begin CharsCount := Length(OutDefaultAlphabet); for ind := beginInd to Pred(endInd) do begin charInd := ind * Int32(BlockCharsCount); bitInd := ind * BlockBitsCount; bits := GetBits64(src, bitInd, BlockBitsCount); BitsToChars(dst, charInd, Int32(BlockCharsCount), bits, CharsCount); end; end; procedure BitsToChars(out chars: array of Char; ind, count: Integer; block: UInt64; CharsCount: LongWord); var i: Integer; begin for i := 0 to Pred(count) do begin if not gReverseOrder then begin tempResult[ind + i] := (OutDefaultAlphabet[Int32(block mod CharsCount)])[1]; end else begin tempResult[ind + (count - 1 - i)] := (OutDefaultAlphabet[Int32(block mod CharsCount)])[1]; end; block := block div CharsCount; end; end; function CharsToBits(data: String; ind, count: Integer): UInt64; var i: Integer; begin result := UInt64(0); for i := 0 to Pred(count) do begin if not gReverseOrder then begin result := result + UInt64(InvAlphabet[Ord(data[ind + i + 1])] * _powN[BlockCharsCount - 1 - i]); end else begin result := result + UInt64(InvAlphabet[Ord(data[ind + (count - 1 - i + 1)]) ] * _powN[BlockCharsCount - 1 - i]); end; end; end; end.
unit ThTextItem; interface uses System.Types, System.Classes, System.UITypes, System.SysUtils, System.UIConsts, FMX.Types, FMX.Objects, FMX.Graphics, FMX.Text, FMX.Platform, ThTypes, ThItem; type TThTextItem = class(TThItem, IFMXTextService, IItemHighlightObject, IItemSelectionObject) private FTextService: TTextService; FFont: TFont; FFontColor: TAlphaColor; FTextAlign: TTextAlign; FWordWrap: Boolean; FSelStart: Integer; FSelLength: Integer; function GetCharX(a: Integer): Single; function GetCaretPosition: Integer; procedure SetCaretPosition(const Value: Integer); function GetText: string; procedure SetText(const Value: string); function GetSelLength: Integer; function GetSelStart: Integer; function GetSelText: string; procedure SetSelLength(const Value: Integer); procedure SetSelStart(const Value: Integer); protected function CreateHighlighter: IItemHighlighter; override; function CreateSelection: IItemSelection; override; // ThItem function PtInItem(Pt: TPointF): Boolean; override; procedure Paint; override; function CreateCaret: TCustomCaret; override; procedure KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); override; procedure InsertText(const AText: string); procedure RepaintEdit; function TextWidth(const Str: string): Single; // IItemHighlightObject procedure PaintItem(ARect: TRectF; AFillColor: TAlphaColor); // IItemSelectionObject function GetMinimumSize: TSizeF; virtual; // ITextServiceControl function GetTextService: TTextService; procedure UpdateCaretPoint; function GetTargetClausePointF: TPointF; procedure StartIMEInput; procedure EndIMEInput; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Text: string read GetText write SetText; property CaretPosition: Integer read GetCaretPosition write SetCaretPosition; function ContentRect: TRectF; property SelStart: Integer read GetSelStart write SetSelStart; property SelLength: Integer read GetSelLength write SetSelLength; property SelText: string read GetSelText; end; implementation uses ThConsts, ThItemFactory, ThItemSelection, ThItemHighlighter, FMX.Platform; { TThTextItem } function TThTextItem.ContentRect: TRectF; begin Result := LocalRect; end; constructor TThTextItem.Create(AOwner: TComponent); var PlatformTextService: IFMXTextService; begin inherited; if TPlatformServices.Current.SupportsPlatformService(IFMXTextService, IInterface(PlatformTextService)) then FTextService := PlatformTextService.GetTextServiceClass.Create(Self, False); FFont := TFont.Create; FFont.Size := 200; FFontColor := TAlphaColorRec.Black; FWordWrap := False; FTextAlign := TTextAlign.taLeading; CanFocus := True; Cursor := crIBeam; AutoCapture := True; Width := 100; Height := 22; FSelStart := 0; FSelLength := 0; end; destructor TThTextItem.Destroy; begin FreeAndNil(FFont); FreeAndNil(FTextService); inherited; end; function TThTextItem.CreateCaret: TCustomCaret; begin Result := TCustomCaret.Create(Self); Result.Color := FFontColor; Result.Visible := True; Result.ReadOnly := False; end; function TThTextItem.CreateHighlighter: IItemHighlighter; var Highlighter: TThItemRectBorderHighlighter; begin Highlighter := TThItemRectBorderHighlighter.Create(Self); Highlighter.HighlightColor := ItemHighlightColor; Highlighter.HighlightSize := ItemHighlightSize; Result := Highlighter; end; function TThTextItem.CreateSelection: IItemSelection; var Selection: TThItemSelection; begin Selection := TThItemSelection.Create(Self); Selection.SetResizeSpots([scTopLeft, scTopRight, scBottomLeft, scBottomRight]); Selection.OnTracking := SpotTracking; Result := Selection; end; function TThTextItem.GetMinimumSize: TSizeF; var MinSize: Single; begin MinSize := 100 / AbsoluteScale.X; Result := PointF(MinSize, MinSize); end; function TThTextItem.GetSelLength: Integer; begin Result := Abs(FSelLength); end; function TThTextItem.GetSelStart: Integer; begin if FSelLength > 0 then Result := FSelStart else if FSelLength < 0 then Result := FSelStart + FSelLength else Result := CaretPosition; end; function TThTextItem.GetSelText: string; begin Result := Text.Substring(SelStart, SelLength); end; function TThTextItem.GetTargetClausePointF: TPointF; var Str: String; begin Str := FTextService.CombinedText.Substring(0, Round(FTextService.TargetClausePosition.X) ); Result.X := TextWidth(Str); Result.Y := (ContentRect.Height / 2) + FFont.Size / 2 + 2; // 2 is small space between conrol and IME window Result.X := Result.X + ContentRect.Top + Self.Position.Point.X; Result.Y := Result.Y + ContentRect.Left + Self.Position.Point.Y; end; function TThTextItem.GetText: string; begin Result := FTextService.Text; end; function TThTextItem.GetTextService: TTextService; begin Result := FTextService; end; procedure TThTextItem.InsertText(const AText: string); var OldText: string; begin OldText := Text; // FActionStack.FragmentDeleted(SelStart + 1, Copy(TmpS, SelStart+1, SelLength)); OldText := OldText.Remove(SelStart, SelLength); // FActionStack.FragmentInserted(SelStart + 1, Length(AText), SelLength <> 0); OldText := OldText.Insert(SelStart, AText); Text := OldText; CaretPosition := SelStart + AText.Length; SelLength := 0; end; procedure TThTextItem.KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); var S: string; TmpS: string; LCaret: Integer; begin inherited; case Key of vkLeft: if ([ssCtrl, ssCommand] * Shift) <> [] then CaretPosition := FTextService.GetPrevWordBeginPosition(CaretPosition) else CaretPosition := FTextService.GetPrevCharacterPosition(CaretPosition); vkRight: if ([ssCtrl, ssCommand] * Shift) <> [] then CaretPosition := FTextService.GetNextWordBeginPosition(CaretPosition) else CaretPosition := FTextService.GetNextCharacterPosition(CaretPosition); vkDelete: begin begin TmpS := Text; if not TmpS.IsEmpty then begin if ([ssCtrl, ssCommand] * Shift) <> [] then begin //Delete whole word LCaret := FTextService.GetPrevWordBeginPosition(CaretPosition); if LCaret < 0 then Exit; TmpS := Text; TmpS := TmpS.Remove(LCaret, CaretPosition - LCaret); end else //Delete single character TmpS := TmpS.Remove(CaretPosition, 1); Text := TmpS; // DoTyping; end; end; end; vkBack: // if not ReadOnly and InputSupport then begin // if SelLength <> 0 then // begin // DeleteSelection; // DoTyping; // end // else begin TmpS := Text; if not TmpS.IsEmpty then begin TmpS := TmpS.Remove(CaretPosition - 1, 1); CaretPosition := CaretPosition - 1; Text := TmpS; // DoTyping; end; end; end; end; if (Ord(KeyChar) >= 32) and (KeyChar <> #0) then begin S := KeyChar; InsertText(S); KeyChar := #0; end; end; procedure TThTextItem.Paint; begin inherited; PaintItem(GetItemRect, TAlphaColorRec.Null); end; procedure TThTextItem.PaintItem(ARect: TRectF; AFillColor: TAlphaColor); var State: TCanvasSaveState; begin { draw text } if (FTextService.Text = '') and (not FTextService.HasMarkedText) then Exit; State := Canvas.SaveState; try Canvas.IntersectClipRect(ARect); Canvas.Font.Assign(FFont); Canvas.Fill.Color := FFontColor; FTextService.DrawSingleLine(Canvas, ARect, 1, FFont, AbsoluteOpacity, FillTextFlags, FTextAlign, TTextAlign.taCenter); { carret } if IsFocused then begin { selection } { if SelLength > 0 then begin R := GetSelRect; R1 := ContentRect; OffsetRect(R, -R1.Left, -R1.Top); Canvas.FillRect(R, 0, 0, AllCorners, AbsoluteOpacity, FSelectionFill); end; } end; finally Canvas.RestoreState(State); end; end; function TThTextItem.PtInItem(Pt: TPointF): Boolean; begin Result := False; if (AbsoluteRect.Width < ItemFocusMinimumSize) and (AbsoluteRect.Height < ItemFocusMinimumSize) then Exit; Result := PtInRect(GetItemRect, Pt); end; procedure TThTextItem.RepaintEdit; begin Repaint; end; procedure TThTextItem.UpdateCaretPoint; begin SetCaretPosition(CaretPosition); end; function TThTextItem.GetCaretPosition: Integer; begin Result := FTextService.CaretPosition.X; end; function TThTextItem.GetCharX(a: Integer): Single; var WholeTextWidth: Single; EditRectWidth: Single; R: TRectF; T: string; begin R := ContentRect; TCanvasManager.MeasureCanvas.Font.Assign(FFont); T := FTextService.CombinedText; if T = '' then T := 'a'; TCanvasManager.MeasureCanvas.MeasureText(R, T, False, FillTextFlags, TTextAlign.taLeading, TTextAlign.taCenter); WholeTextWidth := R.Right - ContentRect.Left; Result := ContentRect.Left; if a > 0 then begin if a <= FTextService.CombinedText.Length then begin R := ContentRect; TCanvasManager.MeasureCanvas.MeasureText(R, T.Substring(0, a), False, FillTextFlags, TTextAlign.taLeading, TTextAlign.taCenter); Result := R.Right; end else begin R := ContentRect; end; end; EditRectWidth := ContentRect.Right - ContentRect.Left; if WholeTextWidth < EditRectWidth then case FTextAlign of TTextAlign.taTrailing: Result := Result + (EditRectWidth - WholeTextWidth); TTextAlign.taCenter: Result := Result + ((EditRectWidth - WholeTextWidth) / 2); end; end; procedure TThTextItem.SetCaretPosition(const Value: Integer); var P: TPoint; Pos: TPointF; begin P.X := 0; P.Y := 0; if Value < 0 then P.X := 0 else if Value > Text.Length then P.X := Text.Length else P.X := Value; FTextService.CaretPosition := P; // UpdateFirstVisibleChar; if SelLength <= 0 then FSelStart := Value; RepaintEdit; if IsFocused then begin Pos.Y := (ContentRect.Top + ContentRect.Bottom - (FFont.Size * 1.25)) / 2; if FTextService.HasMarkedText then Pos.X := GetCharX(FTextService.TargetClausePosition.X) else Pos.X := GetCharX(FTextService.CaretPosition.X); SetCaretParams(Pos, PointF(1, (FFont.Size * 1.25)), FFontColor); end; end; procedure TThTextItem.SetSelLength(const Value: Integer); begin if FSelLength <> Value then begin FSelLength := Value; RepaintEdit; end; end; procedure TThTextItem.SetSelStart(const Value: Integer); begin if FSelStart <> Value then begin SelLength := 0; FSelStart := Value; CaretPosition := FSelStart; RepaintEdit; end; end; procedure TThTextItem.SetText(const Value: string); begin if FTextService.Text <> Value then begin FTextService.Text := Value; if FTextService.CaretPosition.X > Text.Length then SetCaretPosition(Text.Length); RepaintEdit; end; end; procedure TThTextItem.StartIMEInput; begin FTextService.CaretPosition := Point(CaretPosition, 0); end; function TThTextItem.TextWidth(const Str: string): Single; var R: TRectF; begin R := ContentRect; R.Right := 10000; TCanvasManager.MeasureCanvas.Font.Assign(FFont); TCanvasManager.MeasureCanvas.MeasureText(R, Str, False, FillTextFlags, TTextAlign.taLeading, TTextAlign.taCenter); Result := R.Width; end; procedure TThTextItem.EndIMEInput; begin FTextService.Text := FTextService.CombinedText; FTextService.CaretPosition := Point(CaretPosition + FTextService.CombinedText.Length - FTextService.Text.Length, 0); RepaintEdit; end; initialization RegisterItem(ItemFactoryIDText, TThTextItem); end.
unit CFButton; interface uses Windows, Classes, Controls, Graphics, Messages, CFControl; type TCFButton = class(TCFTextControl) private { Private declarations } FModalResult: TModalResult; protected { Protected declarations } /// <summary> /// 绘制 /// </summary> /// <param name="ACanvas">呈现画布</param> procedure DrawControl(ACanvas: TCanvas); override; /// <summary> 单击事件 </summary> procedure Click; override; /// <summary> 处理默认大小和范围 </summary> procedure AdjustBounds; override; /// <summary> /// 设置模式结果 /// </summary> /// <param name="Value">模式</param> procedure SetModalResult(Value: TModalResult); procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; /// <summary> 鼠标移入 </summary> procedure CMMouseEnter(var Msg: TMessage ); message CM_MOUSEENTER; /// <summary> 鼠标移出 </summary> procedure CMMouseLeave(var Msg: TMessage ); message CM_MOUSELEAVE; public { Public declarations } constructor Create(AOwner: TComponent); override; published { Published declarations } /// <summary> 按钮的模式结果(确定、关闭等) </summary> property ModalResult: TModalResult read FModalResult write SetModalResult default 0; property Caption; property Alpha; property OnClick; end; implementation uses CFColorUtils; { TCFButton } procedure TCFButton.AdjustBounds; var DC: HDC; vNewHeight, vNewWidth: Integer; begin if not (csReading in ComponentState) then // 不处理控件初始加载状态 begin DC := GetDC(0); // 临时DC try Canvas.Handle := DC; Canvas.Font := Font; vNewHeight := Canvas.TextHeight('荆') + GetSystemMetrics(SM_CYBORDER) * 4; vNewWidth := Canvas.TextWidth(Caption) + GetSystemMetrics(SM_CYBORDER) * 8; Canvas.Handle := 0; finally ReleaseDC(0, DC); end; if vNewHeight < 25 then vNewHeight := 25; if vNewWidth < Width then begin vNewWidth := Width; if vNewWidth < 75 then vNewWidth := 75; end; SetBounds(Left, Top, vNewWidth, vNewHeight); end; end; procedure TCFButton.Click; begin if Assigned(OnClick) then // 有赋值单击事件 inherited else begin {case FModalResult of mrClose: PostMessage(GetUIHandle, WM_CLOSE, 0, 0); // 关闭当前窗体 end;} end; end; procedure TCFButton.CMMouseEnter(var Msg: TMessage); begin inherited; UpdateDirectUI; end; procedure TCFButton.CMMouseLeave(var Msg: TMessage); begin inherited; UpdateDirectUI; end; constructor TCFButton.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 75; Height := 25; end; procedure TCFButton.DrawControl(ACanvas: TCanvas); var vRect: TRect; vText: string; vBackColor: TColor; // 绘制半透明需要的变量 // vMemDC: HDC; // vMemBitmap, vOldBitmap: HBITMAP; // vCanvas: TCanvas; // vBlendFunction: TBlendFunction; //vRgn: HRGN; //vPng: TPngImage; //AGraphics: TdxGPGraphics; //vPen: TdxGPPen; //vRgn: HRGN; //vBmp: TBitmap; begin inherited DrawControl(ACanvas); case FModalResult of // 处理颜色 mrClose: vBackColor := GAlertColor; else vBackColor := GAreaBackColor; end; ACanvas.Pen.Width := 1; ACanvas.Pen.Color := GetBorderColor(vBackColor); if cmsMouseIn in MouseState then // 鼠标在控件内 begin if cmsMouseDown in MouseState then // 鼠标按下 ACanvas.Brush.Color := GetDownColor(vBackColor) else ACanvas.Brush.Color := GetHotColor(vBackColor); end else // 普通状态 ACanvas.Brush.Color := vBackColor; vRect := Rect(0, 0, Width, Height); if RoundCorner > 0 then ACanvas.RoundRect(vRect, GRoundSize, GRoundSize) else ACanvas.FillRect(vRect); vText := Caption; ACanvas.TextRect(vRect, vText, [tfSingleLine, tfCenter,tfVerticalCenter]); {$REGION '调试透明度绘制代码'} // if AAlpha <> 255 then // begin // // 不使用GDI因为在dll中初始化gdi时界面不显示 // vMemBitmap := CreateCompatibleBitmap(ACanvas.Handle, Width, Height); // try // vMemDC := CreateCompatibleDC(ACanvas.Handle); // vOldBitmap := SelectObject(vMemDC, vMemBitmap); // BitBlt(vMemDC, 0, 0, Width, Height, ACanvas.Handle, X, Y, SRCCOPY); // 拷贝原图此位置的图像 // try // vCanvas := TCanvas.Create; // vCanvas.Handle := vMemDC; // DrawTo(vCanvas, 0, 0, 255); // // vBlendFunction.BlendOp := AC_SRC_OVER; // vBlendFunction.BlendFlags := 0; // vBlendFunction.AlphaFormat := AC_SRC_OVER; // 源位图必须是32位深 // vBlendFunction.SourceConstantAlpha := AAlpha; // 透明度 // Windows.AlphaBlend(ACanvas.Handle, // X, // Y, // Width, // Height, // vMemDC, // 0, // 0, // Width, // Height, // vBlendFunction // ); // finally // SelectObject(vMemDC, vOldBitmap) // end; // finally // vCanvas.Free; // DeleteDC(vMemDC); // DeleteObject(vMemBitmap); // end; // //{使用bmp完成 // vBmp := TBitmap.Create; // vBmp.SetSize(Width, Height); // BitBlt(vBmp.Canvas.Handle, 0, 0, Width, Height, ACanvas.Handle, X, Y, SRCCOPY); // DrawTo(vBmp.Canvas, 0, 0, 255); // //vBmp.SaveToFile('C:\a.BMP'); // // // vBlendFunction.BlendOp := AC_SRC_OVER; // vBlendFunction.BlendFlags := 0; // vBlendFunction.AlphaFormat := AC_SRC_OVER; // 源位图必须是32位深 // vBlendFunction.SourceConstantAlpha := AAlpha; // 透明度 // // Windows.AlphaBlend(ACanvas.Handle, // X, // Y, // Width, // Height, // vBmp.Canvas.Handle, // 0, // 0, // Width, // Height, // vBlendFunction // ); // // vBmp.Free;} // // //// vRgn := CreateRoundRectRgn(X, Y, Width, Height, 5, 5); //// SelectClipRgn(ACanvas.Handle, vRgn); //// AlphaBlend(ACanvas.Handle, X, Y, Width, Height, Canvas.Handle, 0, 0, Width, Height, vBlendFunction); //// SelectClipRgn(ACanvas.Handle, 0); //// DeleteObject(vRgn); //// vPng := TPngImage.CreateBlank(6, // COLOR_RGBALPHA //// 8, 500, 500); //// BitBlt(vPng.Canvas.Handle, X, Y, Width, Height, ACanvas.Handle, 0, 0, SRCCOPY); //// vPng.SaveToFile('c:\a.png'); //// //// //// vBmp := TBitmap.Create; //// vBmp.SetSize(500, 500); //// BitBlt(vBmp.Canvas.Handle, X, Y, Width, Height, ACanvas.Handle, 0, 0, SRCCOPY); //// vBmp.SaveToFile('c:\a.bmp'); //// vBmp.Free; //// //// vPng := TPngImage.Create; //// vPng.LoadFromFile('E:\参考程序\MedPlatform_V2\Source\Resource\1.png'); //// DrawTo(vPng.Canvas, 0, 0, 255); //// vPng.SaveToFile('c:\1.png'); //// ACanvas.Draw(X, Y, vPng); //// vPng.Free; // //// Rgn := CreateRoundRectRgn(X, Y, X + Width, Y + Height, 5, 5); //// SelectClipRgn(ACanvas.Handle, Rgn); //// DeleteObject(Rgn); //// //// vBlendFunction.BlendOp := AC_SRC_OVER; //// vBlendFunction.BlendFlags := 0; //// vBlendFunction.AlphaFormat := AC_SRC_ALPHA; // 源位图必须是32位深 //// vBlendFunction.SourceConstantAlpha := AAlpha; // 透明度 //// //BitBlt(ACanvas.Handle, X, Y, Width, Height, Canvas.Handle, 0, 0, SRCCOPY); //// Windows.AlphaBlend(ACanvas.Handle, //// X, //// Y, //// Width, //// Height, //// Canvas.Handle, //// 0, //// 0, //// Width, //// Height, //// vBlendFunction //// ); //// SelectClipRgn(ACanvas.Handle, 0); // 清除剪切区域 //{ vMemBitmap := CreateCompatibleBitmap(ACanvas.Handle, Width, Height); // try // vMemDC := CreateCompatibleDC(ACanvas.Handle); // vOldBitmap := SelectObject(vMemDC, vMemBitmap); // try // vCanvas := TCanvas.Create; // vCanvas.Handle := vMemDC; // vCanvas.Brush.Color := 1; // vCanvas.FillRect(Rect(0, 0, Width, Height)); // DrawTo(vCanvas, 0, 0, 255); // TransparentBlt(ACanvas.Handle, X, Y, Width, Height, vMemDC, 0, 0, Width, Height, 1); //// vRect := Rect(X, Y, X + Width, Y + Height); //// vText := Caption; //// ACanvas.TextRect(vRect, vText, [tfSingleLine, tfCenter,tfVerticalCenter]); //// vBlendFunction.BlendOp := AC_SRC_OVER; //// vBlendFunction.BlendFlags := 0; //// vBlendFunction.AlphaFormat := AC_SRC_OVER; // 源位图必须是32位深 //// vBlendFunction.SourceConstantAlpha := AAlpha; // 透明度 //// Windows.AlphaBlend(ACanvas.Handle, //// X, //// Y, //// Width, //// Height, //// vMemDC, //// 0, //// 0, //// Width, //// Height, //// vBlendFunction //// ); // //vPng.Free; // finally // SelectObject(vMemDC, vOldBitmap) // end; // finally // vCanvas.Free; // DeleteDC(vMemDC); // DeleteObject(vMemBitmap); // end; } // end // else // begin // ACanvas.Pen.Width := 1; // ACanvas.Pen.Color := FBorderColor; // if FMouseEnter then // begin // if cbsMouseDown in MouseState then // ACanvas.Brush.Color := FDownColor // else // ACanvas.Brush.Color := FHotColor; // end // else // ACanvas.Brush.Color := Color; // vRect := Rect(X, Y, X + Width, Y + Height); // //vRgn := CreateRectRgnIndirect(BoundsRect); // //SelectClipRgn(ACanvas.Handle, vRgn); // //try // ACanvas.RoundRect(vRect, GRoundSize, GRoundSize); // vText := Caption; // ACanvas.TextRect(vRect, vText, [tfSingleLine, tfCenter,tfVerticalCenter]); // //finally // // SelectClipRgn(ACanvas.Handle, 0); // // DeleteObject(vRgn); // //end; // end; {$ENDREGION} end; procedure TCFButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; UpdateDirectUI; end; procedure TCFButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; UpdateDirectUI; end; procedure TCFButton.SetModalResult(Value: TModalResult); begin if FModalResult <> Value then begin FModalResult := Value; case Value of // 处理显示文本 //mrNone; mrOk: Caption := '确 定'; mrCancel: Caption := '取 消'; mrAbort: Caption := '中 止'; mrRetry: Caption := '重 试'; mrIgnore: Caption := '忽 略'; mrYes: Caption := '是'; mrNo: Caption := '否'; mrAll: Caption := '全 部'; mrNoToAll: Caption := '全部否'; mrYesToAll: Caption := '全部是'; mrClose: Caption := '关 闭'; end; UpdateDirectUI; end; end; end.
unit NpPriceEdit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, EditBase, VirtualTable, DB, MemDS, DBAccess, Ora, uOilQuery, StdCtrls, Buttons, ExtCtrls, Mask, ToolEdit, Grids, DBGridEh, Menus, PrihSop, NPTypeRef, GridsEh; type TNpPriceEditForm = class(TEditBaseForm) vt: TVirtualTable; deDateOn: TDateEdit; Panel1: TPanel; Grid: TDBGridEh; lblDateOn: TLabel; ds: TOraDataSource; sbDel: TSpeedButton; procedure GridEditButtonClick(Sender: TObject); procedure sbDelClick(Sender: TObject); procedure GridKeyPress(Sender: TObject; var Key: Char); procedure vtBeforePost(DataSet: TDataSet); protected DATE_ON: TDateTime; private function GetVisibleCod: TNpTypeCod; procedure SetVisibleCod(const Value: TNpTypeCod); { Private declarations } public procedure Init; override; procedure Test; override; procedure Save; override; class function Edit(ADateOn:TDateTime; AInst: integer): Boolean; overload; property VisibleCod: TNpTypeCod read GetVisibleCod write SetVisibleCod; end; var NpPriceEditForm: TNpPriceEditForm; implementation uses Main, UDbFunc; {$R *.dfm} { TNpPriceEditForm } function TNpPriceEditForm.GetVisibleCod: TNpTypeCod; begin Result := CommonGetVisibleCod(Grid); end; procedure TNpPriceEditForm.Init; begin inherited; if DATE_ON <> 0 then begin deDateOn.Date := DATE_ON; q.Close; _OpenQueryPar(q, ['inst', INST, 'date_on', DATE_ON]); vt.Assign(q); vt.Open; bbOk.Enabled := MAIN_ORG.Inst = INST; end else begin deDateOn.Date := Date(); q.Close; _OpenQueryPar(q, ['inst', 0, 'date_on', DATE_ON]); vt.Assign(q); vt.Open; end; CommonVisibleCodInit(Grid); end; procedure TNpPriceEditForm.Save; begin inherited; _ExecSql('update OIL_NP_PRICE set state = ''N'' where date_on = :date_on and inst = :inst', ['date_on', deDateOn.Date, 'inst', INST]); vt.First; while not vt.Eof do begin DBSaver.SaveRecord('OIL_NP_PRICE', ['ID', GetNextId('OIL_NP_PRICE', ['DATE_ON', deDateOn.Date, 'INST',INST, 'ORG_ID', INST, 'ORG_INST', INST]), 'INST', INST, 'STATE','Y', 'ORG_ID', INST, 'ORG_INST', INST, 'NP_ID', vt.FieldByName('NP_TYPE_ID').AsInteger, 'DATE_ON', deDateOn.Date, 'PRICE', vt.FieldByName('PRICE').AsCurrency]); vt.Next; end; end; procedure TNpPriceEditForm.SetVisibleCod(const Value: TNpTypeCod); begin CommonSetVisibleCod(Grid, Value); end; procedure TNpPriceEditForm.Test; var sl: TStringList; begin inherited; vt.DisableControls; sl := TStringList.Create; try vt.First; while not vt.Eof do begin if sl.Values[vt.FieldByName('np_type_id').AsString] = '1' then raise Exception.Create('Нельзя ввести в одном приказе один товар дважды!') else sl.Values[vt.FieldByName('np_type_id').AsString] := '1'; vt.Next; end; finally sl.Free; vt.EnableControls; end; end; procedure TNpPriceEditForm.GridEditButtonClick(Sender: TObject); var Table: TOraQuery; begin inherited; if Grid.SelectedField.FieldName = 'NP_NAME' then begin Table := TOraQuery.Create(nil); try if TNPTypeRefForm.Choose(Table) then begin if not (vt.State in [dsEdit,dsInsert]) then vt.Edit; vt.FieldByName('np_type_id').AsInteger := Table.FieldByName('id').AsInteger; vt.FieldByName('np_name').AsString := Table.FieldByName('name').AsString; vt.FieldByName('codavias').AsInteger := Table.FieldByName('codavias').AsInteger; vt.FieldByName('codoptima').AsInteger := Table.FieldByName('codoptima').AsInteger; vt.FieldByName('codint').AsInteger := Table.FieldByName('codint').AsInteger; end; finally Table.Free; end; end; end; class function TNpPriceEditForm.Edit(ADateOn: TDateTime; AInst: integer): Boolean; var F: TNpPriceEditForm; begin F := Self.Create(Application); try F.DATE_ON := ADateOn; F.INST := AInst; F.Init; Result := F.ShowModal=mrOk; finally F.Free; end; end; procedure TNpPriceEditForm.sbDelClick(Sender: TObject); begin inherited; if not vt.IsEmpty then vt.Delete; end; procedure TNpPriceEditForm.GridKeyPress(Sender: TObject; var Key: Char); var Table: TOraQuery; begin inherited; if (Grid.SelectedField.FieldName = 'PRICE') then begin case key of '.', ',': key := DecimalSeparator; #13: begin vt.Append; Grid.SelectedField := vt.FieldByName(VISIBLE_COD_FIELDS[VisibleCod]); end; end; end else if (Key = #13) and (Grid.SelectedField.FieldName = VISIBLE_COD_FIELDS[VisibleCod]) then begin Table := TOraQuery.Create(nil); try if TNPTypeRefForm.Choose(vt.FieldByName(VISIBLE_COD_FIELDS[VisibleCod]).AsInteger, VisibleCod, Table) then begin if not (vt.State in [dsEdit,dsInsert]) then vt.Edit; vt.FieldByName('np_type_id').AsInteger := Table.FieldByName('id').AsInteger; vt.FieldByName('np_name').AsString := Table.FieldByName('name').AsString; vt.FieldByName('codavias').AsInteger := Table.FieldByName('codavias').AsInteger; vt.FieldByName('codoptima').AsInteger := Table.FieldByName('codoptima').AsInteger; vt.FieldByName('codint').AsInteger := Table.FieldByName('codint').AsInteger; Grid.SelectedField := vt.FieldByName('price'); end; finally Table.Free; end; end; end; procedure TNpPriceEditForm.vtBeforePost(DataSet: TDataSet); begin inherited; vt.FieldByName('ID').AsInteger := 0; vt.FieldByName('INST').AsInteger := 0; vt.FieldByName('ORG_ID').AsInteger := INST; vt.FieldByName('ORG_INST').AsInteger := INST; end; end.
unit ideSHSysUtils; interface uses Windows, SysUtils, Classes, Forms, Dialogs, Graphics, TypInfo, Mapi, IniFiles, Controls, ComCtrls, ExtCtrls, StdCtrls, Consts, ideSHConsts, ideSHMessages; procedure UnderConstruction; procedure NotSupported; function ShowMsg(const AMsg: string; DialogType: TMsgDlgType; ACaptionBox: string = ''; AFlags: Integer = 0): Boolean; overload; function ShowMsg(const AMsg: string): Integer; overload; procedure AbortWithMsg(const AMsg: string = ''); function InputQueryExt(const ACaption, APrompt: string; var Value: string; CancelBtn: Boolean = True; PswChar: Char = #0): Boolean; function InputBoxExt(const ACaption, APrompt, ADefault: string; CancelBtn: Boolean = True; PswChar: Char = #0): string; function StrToMailBody(const S: string): string; function GetNextItem(AIndex, ACount: Integer): Integer; function GetProductName: string; function GetCopyright: string; function GetOSVersion: string; function GetAvailMemory: string; function GetDxColor: TColor; function GetAppPath: string; function GetDirPath(const DirName: string): string; function GetFilePath(const FileName: string): string; function EncodeAppPath(const FileName: string): string; function DecodeAppPath(const FileName: string): string; procedure FileCopy(const SourceFileName, TargetFileName: string); procedure BackupConfigFile(const CurrentFileName, BackupFileName: string); procedure ForceConfigFile(const FileName: string); procedure EraseSectionInFile(const FileName, Section: string); procedure DeleteKeyInFile(const FileName, Section, Ident: String); procedure SaveStringsToFile(const FileName, Section: string; Source: TStrings; aEraseSection:boolean=False ); function LoadStringsFromFile(const FileName, Section: string; Dest: TStrings): Boolean; procedure GetPropValues(Source: TPersistent; AParentName: string; AStrings: TStrings; PropNameList: TStrings = nil; Include: Boolean = True); procedure SetPropValues(Dest: TPersistent; AParentName: string; AStrings: TStrings; PropNameList: TStrings = nil; Include: Boolean = True); procedure WritePropValuesToFile(const FileName, Section: string; Source: TPersistent; PropNameList: TStrings = nil; Include: Boolean = True); procedure ReadPropValuesFromFile(const FileName, Section: string; Dest: TPersistent; PropNameList: TStrings = nil; Include: Boolean = True); function Execute(const CommandLine, WorkingDirectory: string): Integer; function SendMail(ARecepients, ASubject, AMessage, AFiles: string): Integer; function GetHintLeftPart(const Hint: string; Separator: string = '|'): string; function GetHintRightPart(const Hint: string; Separator: string = '|'): string; procedure AntiLargeFont(AComponent: TComponent); procedure TextToStrings(const AText: string; AList: TStrings; DoClear: Boolean = False; DoInsert: Boolean = False); implementation uses StrUtils; procedure UnderConstruction; begin ShowMsg(Format('%s', [SUnderConstruction]), mtWarning); end; procedure NotSupported; begin ShowMsg(Format('%s', [SNotSupported]), mtWarning); end; function ShowMsg(const AMsg: string; DialogType: TMsgDlgType; ACaptionBox: string = ''; AFlags: Integer = 0): Boolean; var CaptionBox: string; MessageText, MessageCaption: PChar; Flags: Integer; begin Flags := 0; case DialogType of mtWarning: begin CaptionBox := sWarning; Flags := MB_OK + MB_ICONWARNING; end; mtError: begin CaptionBox := sError; Flags := MB_OK + MB_ICONERROR; end; mtInformation: begin CaptionBox := sInformation; Flags := MB_OK + MB_ICONINFORMATION; end; mtConfirmation: begin CaptionBox := sConfirmation; Flags := MB_OKCANCEL + MB_ICONQUESTION; end; mtCustom: ; end; MessageText := PChar(AMsg); if Length(ACaptionBox) > 0 then CaptionBox := ACaptionBox; if AFlags > 0 then Flags := AFlags; MessageCaption := PChar(CaptionBox); with Application do begin NormalizeTopMosts; Result := MessageBox(MessageText, MessageCaption, Flags) = IDOK; RestoreTopMosts; end; end; function ShowMsg(const AMsg: string): Integer; var CaptionBox: string; MessageText, MessageCaption: PChar; Flags: Integer; begin CaptionBox := sQuestion; Flags := MB_YESNOCANCEL + MB_ICONQUESTION; MessageText := PChar(AMsg); MessageCaption := PChar(CaptionBox); with Application do begin NormalizeTopMosts; Result := MessageBox(MessageText, MessageCaption, Flags); RestoreTopMosts; end end; procedure AbortWithMsg(const AMsg: string = ''); begin if Length(AMsg) > 0 then ShowMsg(AMsg, mtWarning); SysUtils.Abort; end; function GetAveCharSize(Canvas: TCanvas): TPoint; var I: Integer; Buffer: array[0..51] of Char; begin for I := 0 to 25 do Buffer[I] := Chr(I + Ord('A')); for I := 0 to 25 do Buffer[I + 26] := Chr(I + Ord('a')); GetTextExtentPoint(Canvas.Handle, Buffer, 52, TSize(Result)); Result.X := Result.X div 52; end; function InputQueryExt(const ACaption, APrompt: string; var Value: string; CancelBtn: Boolean = True; PswChar: Char = #0): Boolean; var Form: TForm; Prompt: TLabel; Edit: TEdit; DialogUnits: TPoint; ButtonTop, ButtonWidth, ButtonHeight: Integer; SysMenu: HMENU; begin Result := False; Form := TForm.Create(Application); with Form do try Canvas.Font := Font; DialogUnits := GetAveCharSize(Canvas); BorderStyle := bsDialog; Caption := ACaption; ClientWidth := MulDiv(180, DialogUnits.X, 4); Position := poScreenCenter; Prompt := TLabel.Create(Form); with Prompt do begin Parent := Form; Caption := APrompt; Left := MulDiv(8, DialogUnits.X, 4); Top := MulDiv(8, DialogUnits.Y, 8); Constraints.MaxWidth := MulDiv(164, DialogUnits.X, 4); WordWrap := True; end; Edit := TEdit.Create(Form); with Edit do begin Parent := Form; Left := Prompt.Left; Top := Prompt.Top + Prompt.Height + 5; Width := MulDiv(164, DialogUnits.X, 4); MaxLength := 255; PasswordChar := PswChar; Text := Value; SelectAll; end; ButtonTop := Edit.Top + Edit.Height + 15; ButtonWidth := MulDiv(50, DialogUnits.X, 4); ButtonHeight := MulDiv(14, DialogUnits.Y, 8); with TButton.Create(Form) do begin Parent := Form; Caption := SMsgDlgOK; ModalResult := mrOk; Default := True; if not CancelBtn then begin SysMenu := GetSystemMenu(Form.Handle, False); Windows.EnableMenuItem(SysMenu, SC_CLOSE, MF_DISABLED or MF_GRAYED); SetBounds(Edit.Width div 2 - (ButtonWidth div 2) + 8, ButtonTop, ButtonWidth, ButtonHeight); Form.ClientHeight := Top + Height + 13; end else SetBounds(MulDiv(38, DialogUnits.X, 4), ButtonTop, ButtonWidth, ButtonHeight); end; if CancelBtn then with TButton.Create(Form) do begin Parent := Form; Caption := SMsgDlgCancel; ModalResult := mrCancel; Cancel := True; SetBounds(MulDiv(92, DialogUnits.X, 4), Edit.Top + Edit.Height + 15, ButtonWidth, ButtonHeight); Form.ClientHeight := Top + Height + 13; end; if ShowModal = mrOk then begin Value := Edit.Text; Result := True; end; finally Form.Free; end; end; function InputBoxExt(const ACaption, APrompt, ADefault: string; CancelBtn: Boolean = True; PswChar: Char = #0): string; begin Result := ADefault; InputQueryExt(ACaption, APrompt, Result, CancelBtn, PswChar); end; function StrToMailBody(const S: string): string; begin Result := AnsiReplaceStr(S, ' ', '%20'); Result := AnsiReplaceStr(Result, SLineBreak, '%0D'); end; function GetNextItem(AIndex, ACount: Integer): Integer; begin Result := -1; if AIndex > 0 then Result := AIndex - 1 else if ACount > 0 then Result := AIndex; end; function GetProductName: string; begin Result := Format('%s', ['BlazeTop']); end; function GetCopyright: string; begin Result := Format('%s', ['Copyright (c) 2006-2007 Devrace']); end; function GetOSVersion: string; begin case Win32Platform of VER_PLATFORM_WIN32_WINDOWS: Result := Format('Windows 95/98/ME %s', [Win32CSDVersion]); VER_PLATFORM_WIN32_NT: begin case Win32MajorVersion of 4: Result := Format('Windows %s %d.%d', ['NT', Win32MajorVersion, Win32MinorVersion]); 5: Result := Format('Windows %s', ['2000']); 6: Result := Format('Windows %s', ['XP']); end; Result := Format(Result + ' (Build %d %s)', [Win32BuildNumber, Win32CSDVersion]); end; end; end; function GetAvailMemory: string; var FMemory: _MEMORYSTATUS; begin GlobalMemoryStatus(FMemory); Result := Format(SMemoryAvailable, [FormatFloat('###,###,###,###', FMemory.dwTotalPhys div 1024)]); end; function GetDxColor: TColor; const DxDelta: Integer = 20; var R, G, B: Integer; begin Result := GetSysColor(COLOR_BTNFACE); R := GetRValue(Result) + DxDelta; if R > 255 then R := 255; G := GetGValue(Result) + DxDelta; if G > 255 then G := 255; B := GetBValue(Result) + DxDelta; if B > 255 then B := 255; Result := RGB(R, G, B); end; function GetAppPath: string; begin Result := IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName)); end; function GetDirPath(const DirName: string): string; begin Result := IncludeTrailingPathDelimiter(GetAppPath) + DirName; end; function GetFilePath(const FileName: string): string; begin Result := IncludeTrailingPathDelimiter(GetAppPath) + FileName; end; function EncodeAppPath(const FileName: string): string; var I: Integer; S: string; begin I := 0; S := GetAppPath; S := Copy(S, 1, Length(S) - (Length(SDirBin) - Length(SDirRoot) + 1)); Result := ''; while I < Length(FileName) do begin Inc(I); Result := Result + FileName[I]; if CompareStr(Result, S) = 0 then Result := SPathKey; end; end; function DecodeAppPath(const FileName: string): string; var I: Integer; S: string; begin I := 0; S := GetAppPath; S := Copy(S, 1, Length(S) - (Length(SDirBin) - Length(SDirRoot) + 1)); Result := ''; while I < Length(FileName) do begin Inc(I); Result := Result + FileName[I]; if CompareStr(Result, SPathKey) = 0 then Result := S; end; end; procedure FileCopy(const SourceFileName, TargetFileName: string); var SourceStream, TargetStream: TFileStream; begin SourceStream := TFileStream.Create(SourceFileName, fmOpenRead or fmShareDenyNone); try TargetStream := TFileStream.Create(TargetFileName, fmCreate); try TargetStream.CopyFrom(SourceStream, SourceStream.Size); finally TargetStream.Free; end; finally SourceStream.Free; end; end; procedure BackupConfigFile(const CurrentFileName, BackupFileName: string); begin if FileExists(CurrentFileName) then begin if FileExists(BackupFileName) then DeleteFile(BackupFileName); FileCopy(CurrentFileName, BackupFileName); end; end; procedure ForceConfigFile(const FileName: string); var IniFile: TIniFile; Dir: string; begin Dir:=ExtractFilePath(FileName); if not DirectoryExists(Dir) then ForceDirectories(Dir); // Инакше будет бить ошибу 217 IniFile := TIniFile.Create(FileName); try IniFile.WriteString('WARNING', 'README', 'DO NOT EDIT THIS FILE MANUALY'); finally IniFile.Free; end; end; procedure EraseSectionInFile(const FileName, Section: string); var IniFile: TMemIniFile; begin IniFile := TMemIniFile.Create(FileName); try IniFile.EraseSection(Section); finally IniFile.UpdateFile; IniFile.Free; end; end; procedure DeleteKeyInFile(const FileName, Section, Ident: String); var IniFile: TIniFile; begin IniFile := TIniFile.Create(FileName); try IniFile.DeleteKey(Section, Ident); finally IniFile.Free; end; end; type THackMemIniFile=class(TCustomIniFile) private FSections: TStringList; end; procedure SaveStringsToFile(const FileName, Section: string; Source: TStrings;aEraseSection:boolean=False); var IniFile: TMemIniFile; i,j:Integer; Podstava:boolean; begin IniFile := TMemIniFile.Create(FileName); Podstava:=False; if aEraseSection then IniFile.EraseSection(Section); try //Buzz: Делаем очень подлый хак. Зато шустрей не бывает // Да и с точки зрения порчи файла гораздо более устойчивей чем было. I:=THackMemIniFile(iniFile).FSections.IndexOf(Section); if I<0 then begin // Если секции не было или она удалена, то все пофиг Podstava:=True; I:=THackMemIniFile(iniFile).FSections.AddObject(Section, Source) end else begin for J := 0 to Pred(Source.Count) do IniFile.WriteString(Section, Source.Names[J], Source.ValueFromIndex[J]); end; IniFile.UpdateFile; finally if Podstava then THackMemIniFile(iniFile).FSections.Delete(i); // чтоб при разрушении объекта не свалиться // Поскольку мы подсунули свой TStrings и он не должен быть разрушет FreeAndNil(IniFile); end; end; (* Old implementation Buzz: Очень медленно и очень дерьмово procedure SaveStringsToFile(const FileName, Section: string; Source: TStrings; aEraseSection:boolean=False ); var IniFile: TIniFile; I: Integer; begin IniFile := TIniFile.Create(FileName); try for I := 0 to Pred(Source.Count) do IniFile.WriteString(Section, Source.Names[I], Source.ValueFromIndex[I]); finally FreeAndNil(IniFile); end; end; *) (* Old implementation function LoadStringsFromFile(const FileName, Section: string; Dest: TStrings): Boolean; var IniFile: TIniFile; begin IniFile := TIniFile.Create(FileName); try Result := IniFile.SectionExists(Section); if Result then IniFile.ReadSectionValues(Section, Dest); finally FreeAndNil(IniFile); end; end; *) function LoadStringsFromFile(const FileName, Section: string; Dest: TStrings): Boolean; var F: System.TextFile; S: string; Correct: Boolean; SectionStr:String; begin AssignFile(F, FileName); Reset(F); Correct := False; SectionStr:=AnsiUpperCase(Format('[%s]', [Section])); try while not SeekEof(F) do begin Readln(F, S); Correct := AnsiUpperCase(S) = SectionStr; if Correct then Break; end; S := EmptyStr; if Correct then while not SeekEof(F) do begin Readln(F, S); if Pos('[', S) = 1 then Break; Dest.Add(S) end; finally CloseFile(F); end; end; procedure GetPropValues(Source: TPersistent; AParentName: string; AStrings: TStrings; PropNameList: TStrings = nil; Include: Boolean = True); function ComparePropName(const APropName: string): Boolean; begin Result := True; if Assigned(PropNameList) and Include then Result := PropNameList.IndexOf(APropName) <> -1; if Assigned(PropNameList) and not Include then Result := PropNameList.IndexOf(APropName) = -1; if Result and not (Source is TFont) then Result := not ((APropName = 'Name') or (APropName = 'Tag')); end; var I: Integer; PropList: PPropList; ClassTypeInfo: PTypeInfo; ClassTypeData: PTypeData; PropName: string; PropKind: TTypeKind; PropWrite: Boolean; ObjectProp: TObject; S: string; begin if not Assigned(Source) then Exit; ClassTypeInfo := Source.ClassInfo; ClassTypeData := GetTypeData(ClassTypeInfo); if ClassTypeData.PropCount > 0 then begin GetMem(PropList, SizeOf(PPropInfo) * ClassTypeData.PropCount); try GetPropInfos(Source.ClassInfo, PropList); SortPropList(PropList, ClassTypeData.PropCount); for I := 0 to Pred(ClassTypeData.PropCount) do begin PropName := PropList[I]^.Name; PropKind := PropList[I]^.PropType^.Kind; PropWrite := Assigned(PropList[I]^.SetProc); if ComparePropName(PropName) and (PropKind in tkProperties) and PropWrite then begin if PropKind = tkClass then begin ObjectProp := GetObjectProp(Source, PropName); if ObjectProp is TStrings then begin // AStrings.Add(Format('%s.%s=%s', [AParentName, PropName, TStrings(ObjectProp).CommaText])) S := TStrings(ObjectProp).Text; S := StringReplace(S, sLineBreak, SRegistryLineBreak, [rfReplaceAll, rfIgnoreCase]); AStrings.Add(Format('%s.%s=%s', [AParentName, PropName, S])) end else if ObjectProp is TPersistent then GetPropValues(TPersistent(ObjectProp), Format('%s.%s', [AParentName, PropName]), AStrings, PropNameList, Include); end; if PropKind <> tkClass then AStrings.Add(Format('%s.%s=%s', [AParentName, PropName, GetPropValue(Source, PropName, True)])); end; end; finally FreeMem(PropList, SizeOf(PPropInfo) * ClassTypeData.PropCount) end; end; end; procedure SetPropValues(Dest: TPersistent; AParentName: string; AStrings: TStrings; PropNameList: TStrings = nil; Include: Boolean = True); function ComparePropName(const APropName: string): Boolean; begin Result := True; if Assigned(PropNameList) and Include then Result := PropNameList.IndexOf(APropName) <> -1; if Assigned(PropNameList) and not Include then Result := PropNameList.IndexOf(APropName) = -1; if Result and not (Dest is TFont) then Result := not ((APropName = 'Name') or (APropName = 'Tag')); end; var I: Integer; PropList: PPropList; ClassTypeInfo: PTypeInfo; ClassTypeData: PTypeData; PropName: string; PropKind: TTypeKind; PropWrite: Boolean; ObjectProp: TObject; S: string; vPropIndex: Integer; begin if not Assigned(Dest) then Exit; ClassTypeInfo := Dest.ClassInfo; ClassTypeData := GetTypeData(ClassTypeInfo); if ClassTypeData.PropCount > 0 then begin GetMem(PropList, SizeOf(PPropInfo) * ClassTypeData.PropCount); try GetPropInfos(Dest.ClassInfo, PropList); SortPropList(PropList, ClassTypeData.PropCount); for I := 0 to Pred(ClassTypeData.PropCount) do begin PropName := PropList[I]^.Name; PropKind := PropList[I]^.PropType^.Kind; PropWrite := Assigned(PropList[I]^.SetProc); if ComparePropName(PropName) and (PropKind in tkProperties) and PropWrite then begin if PropKind = tkClass then begin ObjectProp := GetObjectProp(Dest, PropName); if ObjectProp is TStrings then begin vPropIndex := AStrings.IndexOfName(Format('%s.%s', [AParentName, PropName])); if vPropIndex <> -1 then begin // TStrings(ObjectProp).CommaText := AStrings.Values[Format('%s.%s', [AParentName, PropName])]; S := AStrings.ValueFromIndex[vPropIndex]; S := StringReplace(S, SRegistryLineBreak, sLineBreak, [rfReplaceAll, rfIgnoreCase]); TStrings(ObjectProp).Text := S; end; end else if ObjectProp is TPersistent then SetPropValues(TPersistent(ObjectProp), Format('%s.%s', [AParentName, PropName]), AStrings, PropNameList, Include); end; if PropKind <> tkClass then begin vPropIndex := AStrings.IndexOfName(Format('%s.%s', [AParentName, PropName])); if vPropIndex <> -1 then SetPropValue(Dest, PropName, AStrings.ValueFromIndex[vPropIndex]); end; end; end; finally FreeMem(PropList, SizeOf(PPropInfo) * ClassTypeData.PropCount) end; end; end; procedure WritePropValuesToFile(const FileName, Section: string; Source: TPersistent; PropNameList: TStrings = nil; Include: Boolean = True); var PropNameValues: TStrings; begin PropNameValues := TStringList.Create; try GetPropValues(Source, Source.ClassName, PropNameValues, PropNameList, Include); SaveStringsToFile(FileName, Section, PropNameValues); finally FreeAndNil(PropNameValues); end; end; procedure ReadPropValuesFromFile(const FileName, Section: string; Dest: TPersistent; PropNameList: TStrings = nil; Include: Boolean = True); var PropNameValues: TStrings; begin PropNameValues := TStringList.Create; try LoadStringsFromFile(FileName, Section, PropNameValues); SetPropValues(Dest, Dest.ClassName, PropNameValues, PropNameList, Include); finally FreeAndNil(PropNameValues); end; end; // ShowMessage(IntToStr(Execute('C:\Programs\AraxisMerge\Merge.exe D:\Programs\WinMerge\1.pas D:\Programs\WinMerge\2.pas', ExtractFilePath(ParamStr(0))))); // From JvUtils.pas function Execute(const CommandLine, WorkingDirectory: string): Integer; var R: Boolean; ProcessInformation: TProcessInformation; StartupInfo: TStartupInfo; ExCode: THandle; begin Result := 0; FillChar(StartupInfo, SizeOf(TStartupInfo), 0); with StartupInfo do begin cb := SizeOf(TStartupInfo); dwFlags := STARTF_USESHOWWINDOW; wShowWindow := SW_SHOW; end; R := CreateProcess( nil, // Pointer to name of executable module PChar(CommandLine), // Pointer to command line string nil, // Pointer to process security attributes nil, // Pointer to thread security attributes False, // handle inheritance flag 0, // creation flags nil, // Pointer to new environment block PChar(WorkingDirectory), // Pointer to current directory name StartupInfo, // Pointer to STARTUPINFO ProcessInformation); // Pointer to PROCESS_INFORMATION if R then while (GetExitCodeProcess(ProcessInformation.hProcess, ExCode) and (ExCode = STILL_ACTIVE)) do Application.ProcessMessages else Result := GetLastError; end; function SendMail(ARecepients, ASubject, AMessage, AFiles: string): Integer; var Msg: MapiMessage; DFile, CFile: MapiFileDesc; ToRec: MapiRecipDesc; Flags: Cardinal; begin ToRec.ulReserved := 0; ToRec.ulRecipClass := 0; ToRec.lpszName := PChar(''); ToRec.lpszAddress := Pchar(ARecepients); ToRec.ulRecipClass := MAPI_TO; ToRec.ulEIDSize := 0; DFile.ulReserved := 0; DFile.flFlags := 0; DFile.nPosition := $FFFFFFFF; DFile.lpszPathName := PChar(AFiles); DFile.lpszFileName := nil; DFile.lpFileType := nil; CFile.ulReserved := 0; CFile.flFlags := 0; CFile.nPosition := $FFFFFFFF; CFile.lpszPathName := ''; CFile.lpszFileName := nil; CFile.lpFileType := nil; Msg.ulReserved := 0; Msg.lpszSubject := PChar(ASubject); Msg.lpszNoteText := PChar(AMessage); Msg.lpszMessageType := nil; Msg.lpszDateReceived := nil; Msg.lpszConversationID := nil; Msg.flFlags := 0; Msg.lpOriginator := nil; Msg.nRecipCount := 1; Msg.lpRecips := @ToRec; Msg.nFileCount := 0; Msg.lpFiles := @CFile; Flags := MAPI_LOGON_UI or MAPI_NEW_SESSION; Flags := Flags or MAPI_DIALOG; Result := MAPISendMail(0, 0, Msg, Flags, 0); end; function GetHintLeftPart(const Hint: string; Separator: string = '|'): string; var I: Integer; begin Result := Hint; I := Pos(Separator, Hint); if I > 0 then Result := Copy(Hint, 0, I - 1); end; function GetHintRightPart(const Hint: string; Separator: string = '|'): string; var I: Integer; begin Result := EmptyStr; I := Pos(Separator, Hint); if I > 0 then Result := Copy(Hint, I + 1, Length(Hint) - I); end; procedure AntiLargeFont(AComponent: TComponent); var I: Integer; FontName: string; begin FontName := 'Tahoma'; if AComponent is TForm then TForm(AComponent).Scaled := False; for I := 0 to Pred(AComponent.ComponentCount) do begin if (AComponent.Components[I] is TControl) and IsPublishedProp(AComponent.Components[I], 'Font') then if TControl(AComponent.Components[I]).Tag <> -1 then TFont(GetObjectProp(AComponent.Components[I], 'Font')).Name := FontName; if (AComponent.Components[I] is TControl) and IsPublishedProp(AComponent.Components[I], 'TitleFont') then if TControl(AComponent.Components[I]).Tag <> -1 then TFont(GetObjectProp(AComponent.Components[I], 'TitleFont')).Name := FontName; if (AComponent.Components[I] is TComponent) then AntiLargeFont(AComponent.Components[I] as TComponent); if Screen.PixelsPerInch > 96 then begin if (AComponent.Components[I] is TToolBar) then TToolBar(AComponent.Components[I]).AutoSize := False; if (AComponent.Components[I] is TControlBar) then TControlBar(AComponent.Components[I]).RowSize := 32; end; end; end; procedure TextToStrings(const AText: string; AList: TStrings; DoClear: Boolean = False; DoInsert: Boolean = False); var P, Start, BeginStr: PChar; S: string; begin with AList do begin BeginUpdate; try if DoClear then Clear; P := Pointer(AText); if DoInsert then begin BeginStr := P; Inc(P, Length(AText) - 1); if P <> nil then while P > BeginStr do begin if P^ = #10 then Dec(P); if P^ = #13 then Dec(P); Start := P; while not (P^ in [#0, #10, #13]) do Dec(P); SetString(S, P + 1, Start - P); Insert(0, S); end; end else begin if P <> nil then while P^ <> #0 do begin Start := P; while not (P^ in [#0, #10, #13]) do Inc(P); SetString(S, Start, P - Start); Add(S); if P^ = #13 then Inc(P); if P^ = #10 then Inc(P); end; end; finally EndUpdate; end; end; end; end.