text
stringlengths
14
6.51M
unit uStatusController; interface uses System.SysUtils, uDMStatus, uRegras, uEnumerador, uDM, Data.DB, Vcl.Forms, uFuncoesSIDomper, uStatusVO, System.Generics.Collections, uConverter; type TStatusController = class private FModel: TDMStatus; FOperacao: TOperacao; procedure Post; public procedure Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean = False); procedure FiltrarCodigo(ACodigo: Integer); procedure FiltrarPrograma(AStatusPrograma: TEnumPrograma; ACampo, ATexto, AAtivo: string; AContem: Boolean = False); procedure LocalizarId(AId: Integer); procedure LocalizarCodigo(ACodigo: integer); overload; procedure LocalizarCodigo(ACodigo: integer; AStatusPrograma: TEnumPrograma); overload; procedure Novo(AIdUsuario: Integer); procedure Editar(Id: Integer; AFormulario: TForm); procedure Salvar(AIdUsuario: Integer); procedure Excluir(AIdUsuario, AId: Integer); procedure Cancelar(); procedure Imprimir(AIdUsuario: Integer); function ProximoId(): Integer; function ProximoCodigo(): Integer; procedure Pesquisar(AId, ACodigo: Integer); overload; procedure Pesquisar(AId, ACodigo: Integer; AStatusPrograma: TEnumPrograma); overload; function CodigoAtual: Integer; function LocalizarPorPrograma(ATipo: Integer): TObjectList<TStatusVO>; property Model: TDMStatus read FModel write FModel; constructor Create(); destructor Destroy; override; end; implementation { TStatusController } procedure TStatusController.Cancelar; begin if FModel.CDSCadastro.State in [dsEdit, dsInsert] then FModel.CDSCadastro.Cancel; end; function TStatusController.CodigoAtual: Integer; begin Result := FModel.CDSCadastroSta_Codigo.AsInteger; end; constructor TStatusController.Create; begin inherited Create; FModel := TDMStatus.Create(nil); end; destructor TStatusController.Destroy; begin FreeAndNil(FModel); inherited; end; procedure TStatusController.Editar(Id: Integer; AFormulario: TForm); var Negocio: TServerMethods1Client; Resultado: Boolean; begin if Id = 0 then raise Exception.Create('Não há Registro para Editar!'); DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Resultado := Negocio.Editar(CStatusPrograma, dm.IdUsuario, Id); FModel.CDSCadastro.Open; TFuncoes.HabilitarCampo(AFormulario, Resultado); FOperacao := opEditar; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TStatusController.Excluir(AIdUsuario, AId: Integer); var Negocio: TServerMethods1Client; begin if AId = 0 then raise Exception.Create('Não há Registro para Excluir!'); DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try Negocio.Excluir(CStatusPrograma, AIdUsuario, AId); FModel.CDSConsulta.Delete; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TStatusController.Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSConsulta.Close; Negocio.Filtrar(CStatusPrograma, ACampo, ATexto, AAtivo, AContem); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TStatusController.FiltrarCodigo(ACodigo: Integer); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSConsulta.Close; Negocio.FiltrarCodigo(CStatusPrograma, ACodigo); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TStatusController.FiltrarPrograma(AStatusPrograma: TEnumPrograma; ACampo, ATexto, AAtivo: string; AContem: Boolean); var Negocio: TServerMethods1Client; iEnum: Integer; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try iEnum := Integer(AStatusPrograma); FModel.CDSConsulta.Close; Negocio.FiltrarStatusPrograma(ACampo, ATexto, AAtivo, iEnum, AContem); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TStatusController.Imprimir(AIdUsuario: Integer); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(dm.Conexao.DBXConnection); try Negocio.Relatorio(CStatusPrograma, AIdUsuario); FModel.Rel.Print; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TStatusController.LocalizarCodigo(ACodigo: integer); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.LocalizarCodigo(CStatusPrograma, ACodigo); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TStatusController.LocalizarCodigo(ACodigo: integer; AStatusPrograma: TEnumPrograma); var Negocio: TServerMethods1Client; iEnum: Integer; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try iEnum := integer(AStatusPrograma); FModel.CDSCadastro.Close; Negocio.LocalizarCodigoStatusPrograma(iEnum, ACodigo); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TStatusController.LocalizarId(AId: Integer); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.LocalizarId(CStatusPrograma, AId); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; function TStatusController.LocalizarPorPrograma( ATipo: Integer): TObjectList<TStatusVO>; var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try Result := TConverte.JSONToObject<TListaStatus>(Negocio.Status_LocalizarPorPrograma(ATipo)); dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TStatusController.Novo(AIdUsuario: Integer); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.Novo(CStatusPrograma, AIdUsuario); FModel.CDSCadastro.Open; FModel.CDSCadastro.Append; FModel.CDSCadastroSta_Codigo.AsInteger := ProximoCodigo(); FOperacao := opIncluir; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TStatusController.Pesquisar(AId, ACodigo: Integer); begin if AId > 0 then LocalizarId(AId) else LocalizarCodigo(ACodigo); end; procedure TStatusController.Pesquisar(AId, ACodigo: Integer; AStatusPrograma: TEnumPrograma); begin if AId > 0 then LocalizarId(AId) else LocalizarCodigo(ACodigo, AStatusPrograma); end; procedure TStatusController.Post; begin if FModel.CDSConsulta.State in [dsEdit, dsInsert] then FModel.CDSConsulta.Post; end; function TStatusController.ProximoCodigo: Integer; var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try Result := StrToInt(Negocio.ProximoCodigo(CStatusPrograma).ToString); dm.Desconectar; finally FreeAndNil(Negocio); end; end; function TStatusController.ProximoId: Integer; var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try Result := StrToInt(Negocio.ProximoId(CStatusPrograma).ToString); dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TStatusController.Salvar(AIdUsuario: Integer); var Negocio: TServerMethods1Client; begin if FModel.CDSCadastroSta_Codigo.AsInteger <= 0 then raise Exception.Create('Informe o Código!'); if Trim(FModel.CDSCadastroSta_Nome.AsString) = '' then raise Exception.Create('Informe o Nome!'); DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try try Post(); Negocio.Salvar(CStatusPrograma, AIdUsuario); FModel.CDSCadastro.ApplyUpdates(0); FOperacao := opNavegar; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; end.
library UnicodePlugin; {$mode objfpc}{$H+} uses SysUtils, Classes, lazUtf8; function IsUtf8(const AString: PAnsiChar): Boolean; stdcall; export; begin Result := False; if Assigned(AString) then Result := FindInvalidUTF8Codepoint(AString, StrLen(AString)) = -1; end; function AnsiToUTF8(const ASource: PAnsiChar; ADest: PAnsiChar): Integer; stdcall; export; var Utf8Str: Utf8String; begin Result := -1; Utf8Str := WinCPToUTF8(RawByteString(ASource)); Result := Length(Utf8Str); if Result = 0 then Exit; if not Assigned(ADest) then Result := Length(Utf8Str) + 1 else StrLCopy(ADest, PAnsiChar(Utf8Str), Result); end; function UTF8ToAnsi(const ASource: PAnsiChar; ADest: PAnsiChar; const ATestOnInvalid: Boolean): Integer; stdcall; export; var AnsiStr: RawByteString; begin Result := -1; if ATestOnInvalid and (FindInvalidUTF8Codepoint(ASource, Length(ASource)) <> -1) then Exit; AnsiStr := UTF8ToWinCP(RawByteString(ASource)); Result := Length(AnsiStr); if Result = 0 then Exit; if not Assigned(ADest) then Result := Length(AnsiStr) + 1 else StrLCopy(ADest, PAnsiChar(AnsiStr), Result); end; function UTF8ToWide(const ASource: PAnsiChar; ADest: PWideChar; const ATestOnInvalid: Boolean): Integer; stdcall; export; var WideStr: WideString; begin Result := -1; if ATestOnInvalid and (FindInvalidUTF8Codepoint(ASource, Length(ASource)) <> -1) then Exit; WideStr := UTF8ToUTF16(RawByteString(ASource)); Result := Length(WideStr); if Result = 0 then Exit; if not Assigned(ADest) then Result := Length(WideStr) + 1 else StrLCopy(ADest, PWideChar(WideStr), Result); end; function WideToUTF8(const ASource: PWideChar; ADest: PAnsiChar): Integer; stdcall; export; var Utf8Str: Utf8String; begin Result := -1; Utf8Str := UTF16ToUTF8(WideString(ASource)); Result := Length(Utf8Str); if Result = 0 then Exit; if not Assigned(ADest) then Result := Length(Utf8Str) + 1 else StrLCopy(ADest, PAnsiChar(Utf8Str), Result); end; { exports } exports UTF8ToAnsi index 1, AnsiToUTF8 index 2, UTF8ToWide index 3, WideToUTF8 index 4, IsUtf8 index 5; {$R *.res} begin end.
unit Svarstykles; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, nrclasses, nrdataproc, nrcomm, System.StrUtils, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinOffice2007Black, dxSkinscxPCPainter, cxContainer, cxEdit, dxLayoutcxEditAdapters, dxLayoutControlAdapters, Vcl.Menus, Vcl.StdCtrls, cxButtons, cxMemo, dxLayoutContainer, cxTextEdit, dxLayoutControl, cxClasses, cxPropertiesStore, System.Actions, Vcl.ActnList, Data.DB, dxmdaset, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, cxDBData, cxCheckBox, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxGridCustomView, cxGrid, cxMaskEdit, cxLabel, cxDBLabel, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013White, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue; type TfrmSvarstykles = class(TForm) nrComm1: TnrComm; nrDataProc_Svarst1: TnrDataProcessor; nrComm2: TnrComm; nrDataProc_Svarst2: TnrDataProcessor; nrComm3: TnrComm; nrDataProc_BarCodRd: TnrDataProcessor; dxLayoutControl1Group_Root: TdxLayoutGroup; dxLayoutControl1: TdxLayoutControl; lcg_Svarstykles1: TdxLayoutGroup; lcg_Svarstykles2: TdxLayoutGroup; lcg_BarCodReader: TdxLayoutGroup; edSvarstikles1: TcxTextEdit; dxLayoutControl1Item1: TdxLayoutItem; edSvarstikles2: TcxTextEdit; dxLayoutControl1Item2: TdxLayoutItem; btnTaraSvarst1: TcxButton; dxLayoutControl1Item4: TdxLayoutItem; btnBrutoSvarst1: TcxButton; dxLayoutControl1Item5: TdxLayoutItem; btnTaraSvarst2: TcxButton; dxLayoutControl1Item6: TdxLayoutItem; btnBrutoSvarst2: TcxButton; dxLayoutControl1Item7: TdxLayoutItem; btnPriimtiBarkoda: TcxButton; dxLayoutControl1Item8: TdxLayoutItem; btnNaujasSverimas: TcxButton; dxLayoutControl1Item9: TdxLayoutItem; cxPropertiesStore: TcxPropertiesStore; ActionList1: TActionList; actTaraSvarst1: TAction; actBrutoSvarst1: TAction; actTaraSvarst2: TAction; actBrutoSvarst2: TAction; actIvestiSverima: TAction; actPriimtiBarkodus: TAction; nrComm4: TnrComm; nrDataProc_TranspSvarst: TnrDataProcessor; dxLayoutControl1Group5: TdxLayoutGroup; lcg_TranspSvarstykles: TdxLayoutGroup; dxLayoutControl1Group8: TdxLayoutGroup; edSvarstyklesTransport: TcxTextEdit; dxLayoutControl1Item10: TdxLayoutItem; btnTransportTara: TcxButton; btnTransportBruto: TcxButton; dxLayoutControl1Item11: TdxLayoutItem; dxLayoutControl1Item12: TdxLayoutItem; dxLayoutControl1Group1: TdxLayoutGroup; actTaraTransporto: TAction; actBrutoTransporto: TAction; dxLayoutControl1Group3: TdxLayoutGroup; edBruto: TcxTextEdit; dxLayoutControl1Item13: TdxLayoutItem; edTara: TcxTextEdit; dxLayoutControl1Item14: TdxLayoutItem; tblBarCodes: TdxMemData; ds_tblBarCodes: TDataSource; tblBarCodesBruto: TFloatField; tblBarCodesTara: TFloatField; tblBarCodesResult: TBooleanField; gtv_BarCodes: TcxGridDBTableView; cxgr_BarCodesLevel: TcxGridLevel; cxgr_BarCodes: TcxGrid; dxLayoutControl1Item3: TdxLayoutItem; gtv_BarCodesLOT: TcxGridDBColumn; gtv_BarCodesPrekKodas: TcxGridDBColumn; gtv_BarCodesBruto: TcxGridDBColumn; gtv_BarCodesTara: TcxGridDBColumn; gtv_BarCodesResult: TcxGridDBColumn; lcg_BarCodManualInp: TdxLayoutGroup; edBarCode: TcxMaskEdit; dxLayoutControl1Item15: TdxLayoutItem; btnIvestiBarKoda: TcxButton; dxLayoutControl1Item16: TdxLayoutItem; tblBarCodesLOT: TIntegerField; tblBarCodesPrekKodas: TIntegerField; tblBarCodesApdorota: TBooleanField; cxButton1: TcxButton; dxLayoutControl1Item17: TdxLayoutItem; dxLayoutControl1Group6: TdxLayoutGroup; gtv_BarCodesApdorota: TcxGridDBColumn; actIsvalyti: TAction; dxLayoutControl1Group2: TdxLayoutGroup; lbPrekesKodas: TcxDBLabel; dxLayoutControl1Item18: TdxLayoutItem; lbPrekGrupeEN: TcxDBLabel; dxLayoutControl1Item19: TdxLayoutItem; lbZaliavuFormaEN: TcxDBLabel; dxLayoutControl1Item20: TdxLayoutItem; lbSpalvaEN: TcxDBLabel; dxLayoutControl1Item21: TdxLayoutItem; lbIpakavimoFormaEN: TcxDBLabel; dxLayoutControl1Item22: TdxLayoutItem; tblBarCodesPastaba: TStringField; gtv_BarCodesPastaba: TcxGridDBColumn; tblBarCodesBarcode: TStringField; gtv_BarCodesBarcode: TcxGridDBColumn; cxButton2: TcxButton; dxLayoutControl1Item23: TdxLayoutItem; cxButton3: TcxButton; dxLayoutControl1Item24: TdxLayoutItem; dxLayoutControl1Group4: TdxLayoutGroup; dxLayoutControl1Group7: TdxLayoutGroup; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure nrDataProc_Svarst1DataPacket(Sender: TObject; Packet: TnrDataPacket); procedure nrDataProc_Svarst2DataPacket(Sender: TObject; Packet: TnrDataPacket); procedure nrDataProc_BarCodRdDataPacket(Sender: TObject; Packet: TnrDataPacket); procedure actTaraSvarst1Execute(Sender: TObject); procedure nrDataProc_TranspSvarstDataPacket(Sender: TObject; Packet: TnrDataPacket); procedure actBrutoSvarst1Execute(Sender: TObject); procedure actTaraSvarst2Execute(Sender: TObject); procedure actBrutoSvarst2Execute(Sender: TObject); procedure actIvestiSverimaExecute(Sender: TObject); procedure actTaraTransportoExecute(Sender: TObject); procedure actBrutoTransportoExecute(Sender: TObject); procedure actPriimtiBarkodusExecute(Sender: TObject); procedure cxMaskEdit1PropertiesChange(Sender: TObject); procedure btnIvestiBarKodaClick(Sender: TObject); procedure actIsvalytiExecute(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private F_svarst1_stabilised: boolean; F_svarst2_stabilised: boolean; F_trsvarst_stabilised: boolean; F_svarst1_weight: real; F_svarst2_weight: real; F_trsvarst_weight: real; F_perkomplektavimas: boolean; F_ds : TDataSource; procedure PrepareComPortSettings(port: Word; settings: string; comport: TnrComm); Function ExtractWeight(str: string; var stbf: boolean): double; Function ExtractWeightAND4328(str: string; var stbf: boolean): double; procedure ReceiveBarCode(barcode: string); public constructor CreateSvarstykles(Owner: TComponent; perkomplektavimas: boolean; ds : TDataSource); procedure SetDataSource; end; var frmSvarstykles: TfrmSvarstykles; implementation {$R *.dfm} uses DataModule, Sandelis, Sandelis_DataModule; constructor TfrmSvarstykles.CreateSvarstykles(Owner: TComponent; perkomplektavimas: boolean; ds : TDataSource); begin F_perkomplektavimas := perkomplektavimas; F_ds := ds; inherited Create(Owner); lbPrekesKodas.DataBinding.DataSource := ds; lbPrekGrupeEN.DataBinding.DataSource := ds; lbZaliavuFormaEN.DataBinding.DataSource := ds; lbSpalvaEN.DataBinding.DataSource := ds; lbIpakavimoFormaEN.DataBinding.DataSource := ds; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmSvarstykles.FormCreate(Sender: TObject); var portnum: integer; porsett: string; n: integer; str: string; begin dm.RestoreFormProperties(Self); tblBarCodes.Active := True; n := dm.br.Get_len; str := StringOfChar('0', n); edBarCode.Properties.EditMask := str + ';1;_'; edBarCode.Text := str; // Открываем порты try portnum := dm.tfdt__workplace_settingsScales1PortNumber.AsInteger; if portnum = 0 then Abort; begin porsett := dm.tfdt__workplace_settingsScales1PortSettings.AsString; // Получаем строку типа: baud=9600 parity=N data=8 stop=1 PrepareComPortSettings(portnum, porsett, nrComm1); // Парсим строку и настраиваем порт 1 nrDataProc_Svarst1.DataPackets[0].Active := False; nrDataProc_Svarst1.DataPackets[0].PacketEnd := #13 + #10; nrDataProc_Svarst1.DataPackets[0].PacketLength := 20; nrDataProc_Svarst1.Timeout := 500; // 0.5 сек nrDataProc_Svarst1.DataPackets[0].Active := True; nrDataProc_Svarst1.Active := True; try nrComm1.Active := True; except ShowMessage('Svarstyklės 1 sąsajos klaida!' + #13 + #10 + 'Patikrinkite nustatimus.'); end; end except lcg_Svarstykles1.Visible := False; end; try portnum := dm.tfdt__workplace_settingsScales2PortNumber.AsInteger; if portnum = 0 then Abort; begin porsett := dm.tfdt__workplace_settingsScales2PortSettings.AsString; // Получаем строку типа: baud=9600 parity=N data=8 stop=1 PrepareComPortSettings(portnum, porsett, nrComm2); // Парсим строку и настраиваем порт 2 nrDataProc_Svarst2.DataPackets[0].Active := False; nrDataProc_Svarst2.DataPackets[0].PacketEnd := #13 + #10; nrDataProc_Svarst2.DataPackets[0].PacketLength := 20; nrDataProc_Svarst2.Timeout := 500; // 0.5 сек nrDataProc_Svarst2.DataPackets[0].Active := True; nrDataProc_Svarst2.Active := True; try nrComm2.Active := True; except ShowMessage('Svarstyklės 2 sąsajos klaida!' + #13 + #10 + 'Patikrinkite nustatimus.'); end; end except lcg_Svarstykles2.Visible := False; end; if F_perkomplektavimas = False then begin try portnum := dm.tfdt__workplace_settingsBarCodeScannerPortNum.AsInteger; if portnum = 0 then Abort; begin porsett := dm.tfdt__workplace_settingsBarCodeScannerSettings.AsString; // Получаем строку типа: baud=9600 parity=N data=8 stop=1 PrepareComPortSettings(portnum, porsett, nrComm3); // Парсим строку и настраиваем порт 3 nrDataProc_BarCodRd.DataPackets[0].Active := False; nrDataProc_BarCodRd.DataPackets[0].PacketEnd := #13 + #10; nrDataProc_BarCodRd.DataPackets[0].PacketLength := dm.br.Get_len + 2; // Длина данных баркода + два служебных символа 0D 0A nrDataProc_BarCodRd.Timeout := 500; // 0.5 сек nrDataProc_BarCodRd.DataPackets[0].Active := True; nrDataProc_BarCodRd.Active := True; try nrComm3.Active := True; except ShowMessage('Barkodo skanėrio sąsajos klaida!' + #13 + #10 + 'Patikrinkite nustatimus.'); end; end except // lcg_BarCodReader.Visible := False; end; end else begin lcg_BarCodReader.Visible := False; lcg_BarCodManualInp.Visible := False; end; try portnum := dm.tfdt__workplace_settingsScalesTransportPortNumber.AsInteger; if portnum = 0 then Abort; begin porsett := dm.tfdt__workplace_settingsScalesTransportPortSettings.AsString; // Получаем строку типа: baud=9600 parity=N data=8 stop=1 PrepareComPortSettings(portnum, porsett, nrComm4); // Парсим строку и настраиваем порт 4 nrDataProc_TranspSvarst.DataPackets[0].Active := False; nrDataProc_TranspSvarst.DataPackets[0].PacketEnd := #13 + #10; nrDataProc_TranspSvarst.DataPackets[0].PacketLength := 18; nrDataProc_TranspSvarst.Timeout := 500; // 0.5 сек nrDataProc_TranspSvarst.DataPackets[0].Active := True; nrDataProc_TranspSvarst.Active := True; try nrComm4.Active := True; except ShowMessage('Transporto svarstyklės sąsajos klaida!' + #13 + #10 + 'Patikrinkite nustatimus.'); end; end except lcg_TranspSvarstykles.Visible := False; end; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmSvarstykles.PrepareComPortSettings(port: Word; settings: string; comport: TnrComm); var slist: TStringList; ch: char; sstr: string; begin slist := TStringList.Create; try slist.Delimiter := ' '; slist.NameValueSeparator := '='; settings := ReplaceStr(settings, ' ', #13 + #10); // #13+#10); slist.Text := settings; comport.ComPortNo := port; comport.BaudRate := StrToInt(slist.Values['baud']); comport.ByteSize := StrToInt(slist.Values['data']); ch := slist.Values['parity'][1]; case ch of // (pNone, pOdd, pEven, pMark, pSpace); 'N': comport.Parity := pNone; 'O': comport.Parity := pOdd; 'E': comport.Parity := pEven; 'M': comport.Parity := pMark; 'S': comport.Parity := pSpace; end; sstr := slist.Values['stop']; if sstr = '1' then comport.StopBits := sbOne else if sstr = '1.5' then comport.StopBits := sbOneAndHalf else comport.StopBits := sbTwo; finally slist.Free; end; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmSvarstykles.actBrutoSvarst1Execute(Sender: TObject); begin edBruto.Text := edSvarstikles1.Text; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmSvarstykles.actBrutoSvarst2Execute(Sender: TObject); begin edBruto.Text := edSvarstikles2.Text; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmSvarstykles.actTaraSvarst1Execute(Sender: TObject); begin edTara.Text := edSvarstikles1.Text; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmSvarstykles.actTaraSvarst2Execute(Sender: TObject); begin edTara.Text := edSvarstikles2.Text; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmSvarstykles.actTaraTransportoExecute(Sender: TObject); var tara: single; begin tara := 0; frmSandelis.ts_Dokumentas.Show; try tara := StrToFloat(edSvarstyklesTransport.Text); except ShowMessage('Nekorektiškai įvesta transporto tara!'); Abort; end; frmSandelis.NewTranspTara(tara); end; procedure TfrmSvarstykles.cxMaskEdit1PropertiesChange(Sender: TObject); begin end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmSvarstykles.actBrutoTransportoExecute(Sender: TObject); var bruto: single; begin bruto := 0; frmSandelis.ts_Dokumentas.Show; try bruto := StrToFloat(edSvarstyklesTransport.Text); except ShowMessage('Nekorektiškai įvesta transporto bruto!'); Abort; end; frmSandelis.NewTranspBruto(bruto); end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmSvarstykles.actIvestiSverimaExecute(Sender: TObject); var bruto: single; tara: single; begin bruto := 0; tara := 0; frmSandelis.ts_Sverimai.Show; try bruto := StrToFloat(edBruto.Text); tara := StrToFloat(edTara.Text); except ShowMessage('Nekorektiškai įvestos bruto arba tara!'); Abort; end; frmSandelis.NewSverimas(bruto, tara, F_ds.DataSet.FieldByName('SandPrekID').Value); end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmSvarstykles.actPriimtiBarkodusExecute(Sender: TObject); var iskurkodas: string; vbarc: Variant; begin // Установить место откуда в данном документе склада перемещаются товары iskurkodas := frmSandelis.vietos_kodas; // Получить список товаров в заданном месте в данный момент with frmSandelis.sdm.sp_Atsargos_Fakt_by_DateVietos do begin if Active = True then Active := False; ParamByName('@Date').Value := Now(); ParamByName('@VietosKodas').Value := iskurkodas; Active := True; end; // Организуем цикл по всем введенным баркодам with tblBarCodes do begin First; while not EOF do begin if tblBarCodesApdorota.Value = False then begin // Ищем код товара в таблице товаров данного документа if frmSandelis.sdm.sp_Sandeliavimas_Prekes.Locate('PrekesKodas', tblBarCodesPrekKodas.Value, []) = True then begin // Проверяем нет повторяем ли запись уже принятого баркода vbarc := frmSandelis.sdm.sp_Sandelis_Prekes_Sverimai.Lookup('Barcode', VarArrayOf([String(tblBarCodesBarcode.Value)]), 'Barcode'); if VarIsNull(vbarc) then begin // Записываем данные из баркода в таблицу взвешиваний frmSandelis.sdm.sp_Sandelis_Prekes_Sverimai.Append; frmSandelis.sdm.sp_Sandelis_Prekes_SverimaiSandPrekID.Value := frmSandelis.sdm.sp_Sandelis_Prekes_SverimaiSandPrekID.Value; frmSandelis.sdm.sp_Sandelis_Prekes_SverimaiBruto.Value := tblBarCodesBruto.Value; frmSandelis.sdm.sp_Sandelis_Prekes_SverimaiTara.Value := tblBarCodesTara.Value; frmSandelis.sdm.sp_Sandelis_Prekes_SverimaiNumeris.Value := frmSandelis.GetNaujoSverimoNumeri; frmSandelis.sdm.sp_Sandelis_Prekes_SverimaiPastaba.Value := String(tblBarCodesPastaba.Value); frmSandelis.sdm.sp_Sandelis_Prekes_SverimaiBarcode.Value := String(tblBarCodesBarcode.Value); frmSandelis.sdm.sp_Sandelis_Prekes_Sverimai.Post; Edit; tblBarCodesResult.Value := True; Post; end else begin Edit; tblBarCodesResult.Value := False; Post; end; end else begin // Ищем код товара в таблице всех доступных товаров Edit; tblBarCodesResult.Value := False; Post; end; Edit; tblBarCodesApdorota.Value := True; Post; end; Next; end; end; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmSvarstykles.actIsvalytiExecute(Sender: TObject); begin tblBarCodes.Active := False; tblBarCodes.Active := True; end; // ----------------------------------------------------------------------- // Извлекаем вес из строки формата "ST,GS,+000.000 kg" // // В переменной stbf возвращается флаг стабилизации // // ----------------------------------------------------------------------- Function TfrmSvarstykles.ExtractWeight(str: string; var stbf: boolean): double; var s: string; stb: string; i: integer; begin i := Pos(',', str); s := copy(str, i + 1, Length(str) - i); stb := copy(str, 1, i - 1); if stb = 'ST' then stbf := True else stbf := False; i := Pos(',', s); s := copy(s, i + 1, Length(str) - i); i := Pos(' ', s); s := copy(s, 1, i - 1); try ExtractWeight := StrToFloat(s); except ExtractWeight := 0; end; end; // ----------------------------------------------------------------------- // Извлекаем вес из строки формата "ST,GS,+00000.0kg" // // В переменной stbf возвращается флаг стабилизации // // ----------------------------------------------------------------------- Function TfrmSvarstykles.ExtractWeightAND4328(str: string; var stbf: boolean): double; var s: string; stb: string; i: integer; begin i := Pos(',', str); s := copy(str, i + 1, Length(str) - i); stb := copy(str, 1, i - 1); if stb = 'ST' then stbf := True else stbf := False; i := Pos(',', s); s := copy(s, i + 1, 8); try ExtractWeightAND4328 := StrToFloat(s); except ExtractWeightAND4328 := 0; end; end; // ----------------------------------------------------------------------- // Реакция на строку баркода // ----------------------------------------------------------------------- procedure TfrmSvarstykles.ReceiveBarCode(barcode: string); begin try dm.br.Decode_scan_string(barcode); except ShowMessage('Neteisingas brūkšninio kodo formatas!'); Abort; end; tblBarCodes.Append; tblBarCodesLOT.Value := dm.br.LOT; tblBarCodesPrekKodas.Value := dm.br.kodas; tblBarCodesPastaba.Value := AnsiString(dm.br.Get_pastaba); tblBarCodesBruto.Value := dm.br.bruto; tblBarCodesTara.Value := dm.br.tara; tblBarCodesBarcode.Value := AnsiString(dm.br.in_str); tblBarCodesResult.Value := False; tblBarCodesApdorota.Value := False; tblBarCodes.Post; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmSvarstykles.btnIvestiBarKodaClick(Sender: TObject); begin ReceiveBarCode(edBarCode.Text); end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmSvarstykles.nrDataProc_Svarst1DataPacket(Sender: TObject; Packet: TnrDataPacket); begin if Packet.Index = 0 then begin F_svarst1_weight := ExtractWeight(String(Packet.Data), F_svarst1_stabilised); edSvarstikles1.Text := format('%.2f', [F_svarst1_weight]); if F_svarst1_stabilised then begin edSvarstikles1.Style.Color := clWindow; end else begin edSvarstikles1.Style.Color := clRed; end; end; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmSvarstykles.nrDataProc_Svarst2DataPacket(Sender: TObject; Packet: TnrDataPacket); begin if Packet.Index = 0 then begin F_svarst2_weight := ExtractWeight(String(Packet.Data), F_svarst2_stabilised); edSvarstikles2.Text := format('%.2f', [F_svarst2_weight]); if F_svarst2_stabilised then begin edSvarstikles2.Style.Color := clWindow end else begin edSvarstikles2.Style.Color := clRed; end; end; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmSvarstykles.nrDataProc_TranspSvarstDataPacket(Sender: TObject; Packet: TnrDataPacket); begin if Packet.Index = 0 then begin F_trsvarst_weight := ExtractWeightAND4328(String(Packet.Data), F_trsvarst_stabilised) * 1000; edSvarstyklesTransport.Text := format('%.3f', [F_trsvarst_weight]); if F_trsvarst_stabilised then begin edSvarstyklesTransport.Style.Color := clWindow end else begin edSvarstyklesTransport.Style.Color := clRed; end; end; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmSvarstykles.nrDataProc_BarCodRdDataPacket(Sender: TObject; Packet: TnrDataPacket); var s: string; begin if Packet.Index = 0 then begin s := String(Packet.Data); ReceiveBarCode(s); end; end; // ------------------------------------------------------ // Установить источник данных о товарах // ------------------------------------------------------ procedure TfrmSvarstykles.SetDataSource; begin end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmSvarstykles.FormClose(Sender: TObject; var Action: TCloseAction); begin dm.SaveFormProperties(Self); nrComm1.Active := False; nrComm2.Active := False; nrComm3.Active := False; nrComm4.Active := False; Action := caFree; end; // ------------------------------------------------------ // // ------------------------------------------------------ procedure TfrmSvarstykles.FormDestroy(Sender: TObject); begin frmSvarstykles := Nil; end; procedure TfrmSvarstykles.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); //var str : string; begin case Key of VK_F1: actTaraSvarst1.Execute; VK_F2: actBrutoSvarst1.Execute; VK_F3: actTaraSvarst2.Execute; VK_F4: actBrutoSvarst2.Execute; VK_F5: actTaraTransporto.Execute; VK_F6: actBrutoTransporto.Execute; VK_F7: actPriimtiBarkodus.Execute; VK_F8: actIvestiSverima.Execute; VK_F9: frmSandelis.actSpausdSverMazasLpd.Execute; VK_F10: frmSandelis.actSpausdSverDidelisLipd.Execute; end; // str := format('Pressed key %x ',[Key]); // ShowMessage(str); end; procedure TfrmSvarstykles.FormKeyPress(Sender: TObject; var Key: Char); //var str : string; begin // str := format('Pressed key %d ',[Key]); // ShowMessage(str); end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.2 2004.05.20 11:38:10 AM czhower IdStreamVCL } { Rev 1.1 2004.02.03 3:15:54 PM czhower Updates to move to System. } { Rev 1.0 2004.02.03 2:36:04 PM czhower Move } unit IdResourceStrings; interface resourcestring RSInvalidCodePage = 'Invalid codepage (%d)'; RSInvalidCharSet = 'Invalid character set (%s)'; RSInvalidCharSetConv = 'Invalid character set conversion (%s <-> %s)'; RSInvalidCharSetConvWithFlags = 'Invalid character set conversion (%s <-> %s, %s)'; //IdSys RSFailedTimeZoneInfo = 'Failed attempting to retrieve time zone information.'; // Winsock RSWinsockCallError = 'Error on call to Winsock2 library function %s'; RSWinsockLoadError = 'Error on loading Winsock2 library (%s)'; {CH RSWinsockInitializationError = 'Winsock Initialization Error.'; } // Status RSStatusResolving = 'Resolving hostname %s.'; RSStatusConnecting = 'Connecting to %s.'; RSStatusConnected = 'Connected.'; RSStatusDisconnecting = 'Disconnecting.'; RSStatusDisconnected = 'Disconnected.'; RSStatusText = '%s'; // Stack RSStackError = 'Socket Error # %d' + #13#10 + '%s'; RSStackEINTR = 'Interrupted system call.'; RSStackEBADF = 'Bad file number.'; RSStackEACCES = 'Access denied.'; RSStackEFAULT = 'Buffer fault.'; RSStackEINVAL = 'Invalid argument.'; RSStackEMFILE = 'Too many open files.'; RSStackEWOULDBLOCK = 'Operation would block.'; RSStackEINPROGRESS = 'Operation now in progress.'; RSStackEALREADY = 'Operation already in progress.'; RSStackENOTSOCK = 'Socket operation on non-socket.'; RSStackEDESTADDRREQ = 'Destination address required.'; RSStackEMSGSIZE = 'Message too long.'; RSStackEPROTOTYPE = 'Protocol wrong type for socket.'; RSStackENOPROTOOPT = 'Bad protocol option.'; RSStackEPROTONOSUPPORT = 'Protocol not supported.'; RSStackESOCKTNOSUPPORT = 'Socket type not supported.'; RSStackEOPNOTSUPP = 'Operation not supported on socket.'; RSStackEPFNOSUPPORT = 'Protocol family not supported.'; RSStackEAFNOSUPPORT = 'Address family not supported by protocol family.'; RSStackEADDRINUSE = 'Address already in use.'; RSStackEADDRNOTAVAIL = 'Cannot assign requested address.'; RSStackENETDOWN = 'Network is down.'; RSStackENETUNREACH = 'Network is unreachable.'; RSStackENETRESET = 'Net dropped connection or reset.'; RSStackECONNABORTED = 'Software caused connection abort.'; RSStackECONNRESET = 'Connection reset by peer.'; RSStackENOBUFS = 'No buffer space available.'; RSStackEISCONN = 'Socket is already connected.'; RSStackENOTCONN = 'Socket is not connected.'; RSStackESHUTDOWN = 'Cannot send or receive after socket is closed.'; RSStackETOOMANYREFS = 'Too many references, cannot splice.'; RSStackETIMEDOUT = 'Connection timed out.'; RSStackECONNREFUSED = 'Connection refused.'; RSStackELOOP = 'Too many levels of symbolic links.'; RSStackENAMETOOLONG = 'File name too long.'; RSStackEHOSTDOWN = 'Host is down.'; RSStackEHOSTUNREACH = 'No route to host.'; RSStackENOTEMPTY = 'Directory not empty'; RSStackHOST_NOT_FOUND = 'Host not found.'; RSStackClassUndefined = 'Stack Class is undefined.'; RSStackAlreadyCreated = 'Stack already created.'; // Other RSAntiFreezeOnlyOne = 'Only one TIdAntiFreeze can exist per application.'; RSCannotSetIPVersionWhenConnected = 'Cannot change IPVersion when connected'; RSCannotBindRange = 'Can not bind in port range (%d - %d)'; RSConnectionClosedGracefully = 'Connection Closed Gracefully.'; RSCorruptServicesFile = '%s is corrupt.'; RSCouldNotBindSocket = 'Could not bind socket. Address and port are already in use.'; RSInvalidPortRange = 'Invalid Port Range (%d - %d)'; RSInvalidServiceName = '%s is not a valid service.'; RSIPv6Unavailable = 'IPv6 unavailable'; RSInvalidIPv6Address = '%s is not a valid IPv6 address'; RSIPVersionUnsupported = 'The requested IPVersion / Address family is not supported.'; RSNotAllBytesSent = 'Not all bytes sent.'; RSPackageSizeTooBig = 'Package Size Too Big.'; RSSetSizeExceeded = 'Set Size Exceeded.'; RSNoEncodingSpecified = 'No encoding specified.'; {CH RSStreamNotEnoughBytes = 'Not enough bytes read from stream.'; } RSEndOfStream = 'End of stream: Class %s at %d'; //DNS Resolution error messages RSMaliciousPtrRecord = 'Malicious PTR Record'; implementation end.
unit WinSockRDOServerClientConnection; interface uses SmartThreads, Classes, ComObj, Windows, RDOInterfaces, SocketComp, SyncObjs; type TWinSockRDOServerClientConnection = class( TInterfacedObject, IRDOConnection, IRDOServerClientConnection ) public constructor Create( Socket : IWinSocketWrap ); destructor Destroy; override; protected // IRDOConnection function Alive : boolean; function SendReceive( const QueryText : string; out ErrorCode : integer; TimeOut : integer ) : string; stdcall; procedure Send( const QueryText : string ); stdcall; function GetRemoteAddress : string; stdcall; function GetLocalAddress : string; stdcall; function GetLocalHost : string; stdcall; function GetLocalPort : integer; stdcall; function GetOnConnect : TRDOClientConnectEvent; procedure SetOnConnect( OnConnectHandler : TRDOClientConnectEvent ); function GetOnDisconnect : TRDOClientDisconnectEvent; procedure SetOnDisconnect( OnDisconnectHandler : TRDOClientDisconnectEvent ); protected // IRDOServerClientConnection procedure OnQueryResultArrival( const QueryResult : string ); private fUnsentQueries : TList; fSentQueries : TList; fSenderThread : TSmartThread; fUnsentQueriesLock : TCriticalSection; fSentQueriesLock : TCriticalSection; fSocket : IWinSocketWrap;//TCustomWinSocket; fUnsentQueryWaiting : THandle; fTerminateEvent : THandle; fOnConnect : TRDOClientConnectEvent; fOnDisconnect : TRDOClientDisconnectEvent; fData : pointer; private function GetTimeOut : integer; procedure SetTimeOut(TimeOut : integer); procedure SetData(data : pointer); function GetData : pointer; end; implementation uses SysUtils, RDOUtils, RDOProtocol, {$IFDEF Logs} LogFile, {$ENDIF} ErrorCodes; // Query id generation routines and variables var LastQueryId : word; function GenerateQueryId : integer; begin Result := LastQueryId; LastQueryId := ( LastQueryId + 1 ) mod 65536 end; type TQueryToSend = record Id : word; Text : string; WaitForAnsw : boolean; Result : string; Event : THandle; ErrorCode : integer; end; PQueryToSend = ^TQueryToSend; // Delphi classes associated to the threads in charge of the connection type TSenderThread = class( TSmartThread ) private fConnection : TWinSockRDOServerClientConnection; constructor Create( theConnection : TWinSockRDOServerClientConnection ); protected procedure Execute; override; end; // TSenderThread constructor TSenderThread.Create( theConnection : TWinSockRDOServerClientConnection ); begin fConnection := theConnection; inherited Create( false ) end; procedure TSenderThread.Execute; var QueryToSend : PQueryToSend; SenderThreadEvents : array [ 1 .. 2 ] of THandle; WinSocket : TCustomWinSocket; begin with fConnection do begin SenderThreadEvents[ 1 ] := fUnsentQueryWaiting; SenderThreadEvents[ 2 ] := fTerminateEvent; while not Terminated do begin WaitForMultipleObjects( 2, @SenderThreadEvents[ 1 ], false, INFINITE ); fUnsentQueriesLock.Acquire; try if fUnsentQueries.Count <> 0 then begin QueryToSend := fUnsentQueries[ 0 ]; fUnsentQueries.Delete( 0 ) end else begin QueryToSend := nil; ResetEvent( fUnsentQueryWaiting ) end finally fUnsentQueriesLock.Release end; if QueryToSend <> nil then if QueryToSend.WaitForAnsw then begin fSentQueriesLock.Acquire; try fSentQueries.Add( QueryToSend ) finally fSentQueriesLock.Release end; try fSocket.Lock; try WinSocket := fSocket.getSocket; if WinSocket <> nil then WinSocket.SendText( CallId + Blank + IntToStr( QueryToSend.Id ) + Blank + QueryToSend.Text ); finally fSocket.Unlock; end; except {$IFDEF Logs} LogThis( 'Error sending query' ); {$ENDIF} fSentQueriesLock.Acquire; try fSentQueries.Remove( QueryToSend ) finally fSentQueriesLock.Release end; QueryToSend.ErrorCode := errSendError; SetEvent( QueryToSend.Event ) end end else begin try fSocket.Lock; try WinSocket := fSocket.getSocket; if WinSocket <> nil then WinSocket.SendText( CallId + Blank + QueryToSend.Text ); finally fSocket.Unlock; end; except {$IFDEF Logs} LogThis( 'Error sending query' ); {$ENDIF} end; Dispose( QueryToSend ) end end end end; // TWinSockRDOServerClientConnection constructor TWinSockRDOServerClientConnection.Create(Socket : IWinSocketWrap); begin inherited Create; fSocket := Socket; fUnSentQueriesLock := TCriticalSection.Create; fSentQueriesLock := TCriticalSection.Create; fUnsentQueries := TList.Create; fSentQueries := TList.Create; fSenderThread := TSenderThread.Create( Self ); fUnsentQueryWaiting := CreateEvent( nil, true, false, nil ); fTerminateEvent := CreateEvent( nil, true, false, nil ) end; destructor TWinSockRDOServerClientConnection.Destroy; begin fSocket.Invalidate; SetEvent( fTerminateEvent ); fSenderThread.Free; fUnSentQueriesLock.Free; fSentQueriesLock.Free; fUnsentQueries.Free; fSentQueries.Free; CloseHandle( fUnsentQueryWaiting ); CloseHandle( fTerminateEvent ); inherited end; function TWinSockRDOServerClientConnection.Alive : boolean; begin result := fSocket.isValid; end; function TWinSockRDOServerClientConnection.SendReceive( const QueryText : string; out ErrorCode : integer; TimeOut : integer ) : string; var theQuery : PQueryToSend; WaitRes : cardinal; begin try New( theQuery ); try theQuery.Id := GenerateQueryId; theQuery.Text := QueryText; {$IFDEF Logs} LogThis( 'Sending and waiting: ' + QueryText ); {$ENDIF} theQuery.WaitForAnsw := true; theQuery.Result := ''; theQuery.Event := CreateEvent( nil, false, false, nil ); try theQuery.ErrorCode := errNoError; fUnsentQueriesLock.Acquire; try fUnsentQueries.Add( theQuery ); if fUnsentQueries.Count = 1 then SetEvent( fUnsentQueryWaiting ); fUnsentQueriesLock.Release; WaitRes := WaitForSingleObject( theQuery.Event, TimeOut ); if WaitRes = WAIT_OBJECT_0 then begin Result := theQuery.Result; ErrorCode := theQuery.ErrorCode; {$IFDEF Logs} LogThis( 'Result : ' + Result ) {$ENDIF} end else begin Result := ''; {$IFDEF Logs} LogThis( 'Query timed out' ); {$ENDIF} ErrorCode := errQueryTimedOut; fSentQueriesLock.Acquire; try fSentQueries.Remove( theQuery ) finally fSentQueriesLock.Release end end except fUnsentQueriesLock.Release; ErrorCode := errQueryQueueOverflow end finally CloseHandle( theQuery.Event ) end finally Dispose( theQuery ) end except ErrorCode := errUnknownError end end; procedure TWinSockRDOServerClientConnection.Send( const QueryText : string ); var theQuery : PQueryToSend; begin New( theQuery ); theQuery.Text := QueryText; {$IFDEF Logs} LogThis( 'Sending : ' + QueryText ); {$ENDIF} theQuery.WaitForAnsw := false; fUnsentQueriesLock.Acquire; try try fUnsentQueries.Add( theQuery ); if fUnsentQueries.Count = 1 then SetEvent( fUnsentQueryWaiting ) except Dispose( theQuery ) end finally fUnsentQueriesLock.Release end end; function TWinSockRDOServerClientConnection.GetRemoteAddress : string; var WinSocket : TCustomWinSocket; begin try fSocket.Lock; try WinSocket := fSocket.getSocket; if WinSocket <> nil then Result := WinSocket.RemoteAddress else Result := ''; finally fSocket.Unlock; end; except Result := ''; end; end; function TWinSockRDOServerClientConnection.GetLocalAddress : string; var WinSocket : TCustomWinSocket; begin try fSocket.Lock; try WinSocket := fSocket.getSocket; if WinSocket <> nil then Result := WinSocket.LocalAddress else Result := ''; finally fSocket.Unlock; end; except Result := ''; end; end; function TWinSockRDOServerClientConnection.GetLocalHost : string; var WinSocket : TCustomWinSocket; begin try fSocket.Lock; try WinSocket := fSocket.getSocket; if WinSocket <> nil then Result := WinSocket.LocalHost else Result := ''; finally fSocket.Unlock; end; except Result := ''; end; end; function TWinSockRDOServerClientConnection.GetLocalPort : integer; var WinSocket : TCustomWinSocket; begin try fSocket.Lock; try WinSocket := fSocket.getSocket; if WinSocket <> nil then Result := WinSocket.LocalPort else Result := 0; finally fSocket.Unlock; end; except Result := 0; end; end; function TWinSockRDOServerClientConnection.GetOnConnect : TRDOClientConnectEvent; begin result := fOnConnect; end; procedure TWinSockRDOServerClientConnection.SetOnConnect( OnConnectHandler : TRDOClientConnectEvent ); begin fOnConnect := OnConnectHandler; end; function TWinSockRDOServerClientConnection.GetOnDisconnect : TRDOClientDisconnectEvent; begin result := fOnDisconnect; end; procedure TWinSockRDOServerClientConnection.SetOnDisconnect( OnDisconnectHandler : TRDOClientDisconnectEvent ); begin fOnDisconnect := OnDisconnectHandler; end; procedure TWinSockRDOServerClientConnection.OnQueryResultArrival( const QueryResult : string ); function FindServicedQuery( QueryText : string ) : PQueryToSend; var CharIdx : integer; IdDigits : string; QueryId : integer; QueryIdx : integer; SentQueries : integer; ServicedQuery : PQueryToSend; QueryTextLen : integer; begin IdDigits := ''; CharIdx := 1; SkipSpaces( QueryText, CharIdx ); IdDigits := ReadNumber( QueryText, CharIdx ); try QueryId := StrToInt( IdDigits ); except QueryId := -1 end; if QueryId <> -1 then begin QueryIdx := 0; SentQueries := fSentQueries.Count; while ( QueryIdx < SentQueries ) and ( QueryId <> PQueryToSend( fSentQueries[ QueryIdx ] ).Id ) do inc( QueryIdx ); if QueryIdx < SentQueries then begin ServicedQuery := fSentQueries[ QueryIdx ]; QueryTextLen := Length( QueryText ); while CharIdx <= QueryTextLen do begin ServicedQuery.Result := ServicedQuery.Result + QueryText[ CharIdx ]; inc( CharIdx ) end; Result := ServicedQuery end else Result := nil end else Result := nil; end; var ServicedQuery : PQueryToSend; begin fSentQueriesLock.Acquire; try ServicedQuery := FindServicedQuery( QueryResult ); if ServicedQuery <> nil then begin fSentQueries.Remove( ServicedQuery ); ServicedQuery.ErrorCode := errNoError; SetEvent( ServicedQuery.Event ) end finally fSentQueriesLock.Release end end; function TWinSockRDOServerClientConnection.GetTimeOut : integer; begin result := 60*1000; end; procedure TWinSockRDOServerClientConnection.SetTimeOut(TimeOut : integer); begin end; procedure TWinSockRDOServerClientConnection.SetData(data : pointer); begin fData := data; end; function TWinSockRDOServerClientConnection.GetData : pointer; begin result := fData; end; end.
unit DomainInterfaces; {$mode objfpc}{$H+} interface type ITest = interface function GetStringValue() : string; procedure SetStringValue(const Value: string); property StringValue : string read GetStringValue write SetStringValue; end; implementation end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$I ..\ElPack.inc} unit frmItemsProp; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, {$ifdef VCL_6_USED} DesignIntf, DesignEditors, DesignWindows, DsnConst, {$else} DsgnIntf, {$endif} Buttons, ExtCtrls, ElTree, frmItemCol, Dialogs, {$IFDEF ELPACK_COMPLETE} ElTreeCombo, {$ENDIF} ElVCLUtils, ElXPThemedControl; type TItemsPropDlg = class(TForm) ItemsGB : TGroupBox; OpenDlg : TOpenDialog; SaveDlg : TSaveDialog; Tree : TElTree; Panel1: TPanel; OKBtn: TButton; CancelBtn: TButton; ApplyBtn: TButton; Panel2: TPanel; NewItemBtn: TButton; SubitemBtn: TButton; DeleteBtn: TButton; SaveBtn: TButton; LoadBtn: TButton; EditBtn: TButton; MoveRightBtn: TButton; MoveLeftBtn: TButton; MoveDownBtn: TButton; MoveUpBtn: TButton; DuplicateBtn: TButton; procedure DeleteBtnClick(Sender : TObject); procedure SubitemBtnClick(Sender : TObject); procedure TreeItemFocused(Sender : TObject); procedure NewItemBtnClick(Sender : TObject); procedure EditBtnClick(Sender : TObject); procedure OKBtnClick(Sender : TObject); procedure SaveBtnClick(Sender : TObject); procedure LoadBtnClick(Sender : TObject); procedure TreeStartDrag(Sender : TObject; var DragObject : TDragObject); procedure TreeDragOver(Sender, Source : TObject; X, Y : Integer; State : TDragState; var Accept : Boolean); procedure TreeDragDrop(Sender, Source : TObject; X, Y : Integer); procedure FormCreate(Sender : TObject); procedure TreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure MoveRightBtnClick(Sender: TObject); procedure MoveLeftBtnClick(Sender: TObject); procedure MoveUpBtnClick(Sender: TObject); procedure MoveDownBtnClick(Sender: TObject); procedure TreeDblClick(Sender: TObject); procedure DuplicateBtnClick(Sender: TObject); private { Private declarations } FDragItem : TElTreeItem; // procedure SetItems(value : TElTreeItems); // function GetItems:TElTreeItems; public { Public declarations } AComp : TComponent; DTreeItems : TElTreeItems; end; TElTreeItemsProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes : TPropertyAttributes; override; function GetValue : string; override; end; var ItemsPropDlg : TItemsPropDlg; implementation {$R *.DFM} type TElDragObject = class(TDragControlObject) function GetDragCursor(Accepted : Boolean; X, Y : Integer) : TCursor; override; end; function TElDragObject.GetDragCursor(Accepted : Boolean; X, Y : Integer) : TCursor; begin if Control is TElTree then begin if ((Control as TElTree).GetItemAtY(Y) <> nil) or (Accepted) then Result := (Control as TElTree).DragCursor else Result := crNoDrop; end else result := inherited GetDragCursor(Accepted, X, Y); end; procedure TElTreeItemsProperty.Edit; var Editor : TItemsPropDlg; begin Editor := TItemsPropDlg.Create(Application); try Editor.AComp := TComponent(GetComponent(0)); {$IFDEF ELPACK_COMPLETE} if Editor.AComp is TElTreeCombo then begin Editor.DTreeItems := TElTreeCombo(Editor.AComp).Items; end else {$ENDIF} Editor.DTreeItems := TCustomElTree(Editor.AComp).Items; Editor.Tree.Items := Editor.DTreeItems; Editor.ShowModal; finally Editor.Free; end; end; function TElTreeItemsProperty.GetAttributes; begin Result := [paDialog, paReadOnly]; end; function TElTreeItemsProperty.GetValue; begin FmtStr(Result, '(%s)', [GetPropType^.Name]); end; // =========================================================================== procedure TItemsPropDlg.DeleteBtnClick(Sender : TObject); var Form : TCustomForm; begin if Tree.ItemFocused <> nil then Tree.Items.DeleteItem(Tree.ItemFocused); Form := GetOwnerForm(AComp); if (Form <> nil) and (Form.Designer <> nil) then Form.Designer.Modified; end; procedure TItemsPropDlg.SubitemBtnClick(Sender : TObject); var TSI : TElTreeItem; var Form : TCustomForm; begin if Tree.ItemFocused <> nil then begin Tree.ItemFocused.Expanded := true; TSI := Tree.Items.AddItem(Tree.ItemFocused); TSI.Text := 'Item ' +IntToStr(TSI.AbsoluteIndex); Tree.ItemFocused := TSI; Tree.EnsureVisible(TSI); Form := GetOwnerForm(AComp); if (Form <> nil) and (Form.Designer <> nil) then Form.Designer.Modified; end; end; procedure TItemsPropDlg.TreeItemFocused(Sender : TObject); var b : boolean; begin b := Tree.ItemFocused <> nil; SubItemBtn.Enabled := b; EditBtn.Enabled := b; DeleteBtn.Enabled := b; MoveUpBtn.Enabled := b; MoveDownBtn.Enabled := b; MoveLeftBtn.Enabled := b; MoveRightBtn.Enabled := b; DuplicateBtn.Enabled := b; end; procedure TItemsPropDlg.NewItemBtnClick(Sender : TObject); var TSI : TElTreeItem; var Form : TCustomForm; begin TSI := Tree.Items.AddItem(nil); TSI.Text := 'Item ' +IntToStr(TSI.AbsoluteIndex); Tree.ItemFocused := TSI; Tree.EnsureVisible(TSI); Form := GetOwnerForm(AComp); if (Form <> nil) and (Form.Designer <> nil) then Form.Designer.Modified; end; procedure TItemsPropDlg.EditBtnClick(Sender : TObject); var T : TItemColDlg; var Form : TCustomForm; begin if Tree.ItemFocused = nil then exit; T := nil; try T := TItemColDlg.Create(self); T.Item := Tree.ItemFocused; T.SetData; if T.ShowModal = mrOk then begin T.GetData; Form := GetOwnerForm(AComp); if (Form <> nil) and (Form.Designer <> nil) then Form.Designer.Modified; end; Tree.SetFocus; finally T.Free; end; end; procedure TItemsPropDlg.OKBtnClick(Sender : TObject); begin if Tree.Items = nil then MessageBox(0, 'Serious error in ElTreeItems editor. Please report to EldoS', nil, 0) else DTreeItems.Assign(Tree.Items); end; procedure TItemsPropDlg.SaveBtnClick(Sender : TObject); var T : TFileStream; begin if not SaveDlg.Execute then exit; T := nil; try T := TFileStream.Create(SaveDlg.FileName, fmCreate or fmShareDenyWrite); Tree.Items.SaveToStream(T); finally T.Free; end; end; procedure TItemsPropDlg.LoadBtnClick(Sender : TObject); var T : TFileStream; var Form : TCustomForm; begin if not OpenDlg.Execute then exit; T := nil; try T := TFileStream.Create(OpenDlg.FileName, fmOpenRead or fmShareDenyWrite); Tree.Items.LoadFromStream(T); Form := GetOwnerForm(AComp); if (Form <> nil) and (Form.Designer <> nil) then Form.Designer.Modified; finally T.Free; end; end; procedure TItemsPropDlg.TreeStartDrag(Sender : TObject; var DragObject : TDragObject); begin FDragItem := Tree.ItemFocused; DragObject := TElDragObject.Create(Tree); end; procedure TItemsPropDlg.TreeDragOver(Sender, Source : TObject; X, Y : Integer; State : TDragState; var Accept : Boolean); var TSI : TElTreeItem; begin Accept := false; if (Source <> Tree) and ((not (Source is TDragControlObject)) or (TDragControlObject(Source).Control <> Tree)) then exit; TSI := Tree.GetItemAtY(Y); if (TSI <> nil) and (not TSI.IsUnder(FDragItem)) then Accept := true; end; procedure TItemsPropDlg.TreeDragDrop(Sender, Source : TObject; X, Y : Integer); var TSI : TElTreeItem; var Form : TCustomForm; begin TSI := Tree.GetItemAtY(Y); if (TSI <> nil) and (not TSI.IsUnder(FDragItem)) then FDragItem.MoveToIns(TSI.Parent, TSI.Index); Form := GetOwnerForm(AComp); if (Form <> nil) and (Form.Designer <> nil) then Form.Designer.Modified; end; procedure TItemsPropDlg.FormCreate(Sender : TObject); begin TreeItemFocused(self); end; procedure TItemsPropDlg.TreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_LEFT) and (Shift = [ssCtrl]) then MoveLeftBtnClick(Self) else if (Key = VK_RIGHT) and (Shift = [ssCtrl]) then MoveRightBtnClick(Self) else if (Key = VK_UP) and (Shift = [ssCtrl]) then MoveUpBtnClick(Self) else if (Key = VK_DOWN) and (Shift = [ssCtrl]) then MoveDownBtnClick(Self); end; procedure TItemsPropDlg.MoveRightBtnClick(Sender: TObject); var Item : TElTreeItem; begin if (Tree.ItemFocused <> nil) then begin Item := Tree.ItemFocused; if Item.GetPrevSibling <> nil then Item.MoveToIns(Item.GetPrevSibling, 0); end; end; procedure TItemsPropDlg.MoveLeftBtnClick(Sender: TObject); var Item : TElTreeItem; begin if (Tree.ItemFocused <> nil) then begin Item := Tree.ItemFocused; if Item.Parent <> nil then begin Item.MoveToIns(Item.Parent.Parent, Item.Parent.Index + 1); end; end; end; procedure TItemsPropDlg.MoveUpBtnClick(Sender: TObject); var Item : TElTreeItem; begin if (Tree.ItemFocused <> nil) then begin Item := Tree.ItemFocused; if Item.Index > 0 then Item.MoveToIns(Item.Parent, Item.Index - 1); end; end; procedure TItemsPropDlg.MoveDownBtnClick(Sender: TObject); var Item : TElTreeItem; begin if (Tree.ItemFocused <> nil) then begin Item := Tree.ItemFocused; if Item.GetNextSibling <> nil then Item.MoveToIns(Item.Parent, Item.GetNextSibling.Index); end; end; procedure TItemsPropDlg.TreeDblClick(Sender: TObject); var HS : integer; Item : TElTreeItem; ItemPart: TSTItemPart; P : TPoint; begin GetCursorPos(P); P := Tree.ScreenToClient(P); Item := Tree.GetItemAt(P.x, P.Y, ItemPart, HS); if Item <> nil then begin Tree.ItemFocused := Item; EditBtnClick(Self); end; end; procedure TItemsPropDlg.DuplicateBtnClick(Sender: TObject); var Item, Item1 : TElTreeItem; begin if (Tree.ItemFocused <> nil) then begin Item := Tree.ItemFocused; Item1 := Tree.Items.InsertItem(Item.Index + 1, Item.Parent); Item1.Assign(Item); Item1.Text := 'Item ' +IntToStr(Item1.AbsoluteIndex); Tree.ItemFocused := Item1; Tree.EnsureVisible(Item1); end; end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls; type { TFrmMain } TFrmMain = class(TForm) btnSubmit: TButton; btnClear: TButton; edFirst: TEdit; edSecond: TEdit; edAnswer: TEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; rBtnAdd: TRadioButton; rBtnSub: TRadioButton; rBtnMult: TRadioButton; rBtnDiv: TRadioButton; rgpOperator: TRadioGroup; procedure btnClearClick(Sender: TObject); procedure btnSubmitClick(Sender: TObject); private { private declarations } public { public declarations } end; var FrmMain: TFrmMain; implementation {$R *.lfm} { TFrmMain } procedure TFrmMain.btnSubmitClick(Sender: TObject); begin try if rBtnAdd.Checked = True then edAnswer.Text := FloatToStr(StrToFloat(edFirst.Text) + StrToFloat(edSecond.Text)) else if rBtnSub.Checked = True then edAnswer.Text := FloatToStr(StrToFloat(edFirst.Text) - StrToFloat(edSecond.Text)) else if rBtnMult.Checked = True then edAnswer.Text := FloatToStr(StrToFloat(edFirst.Text) * StrToFloat(edSecond.Text)) else if rBtnDiv.Checked = True then edAnswer.Text := FloatToStr(StrToFloat(edFirst.Text) / StrToFloat(edSecond.Text)) else ShowMessage('Please Select an Operator'); except on E: Exception do ShowMessage(E.Message + '. Please Check Your Numbers'); end; end; procedure TFrmMain.btnClearClick(Sender: TObject); begin edFirst.Clear; edSecond.Clear; edAnswer.Clear; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpDerSequenceParser; {$I ..\Include\CryptoLib.inc} interface uses ClpIAsn1StreamParser, ClpIAsn1SequenceParser, ClpIProxiedInterface, ClpIDerSequenceParser, ClpDerSequence; type TDerSequenceParser = class(TInterfacedObject, IAsn1SequenceParser, IAsn1Convertible, IDerSequenceParser) strict private var F_parser: IAsn1StreamParser; public constructor Create(const parser: IAsn1StreamParser); function ReadObject(): IAsn1Convertible; inline; function ToAsn1Object(): IAsn1Object; inline; end; implementation { TDerSequenceParser } constructor TDerSequenceParser.Create(const parser: IAsn1StreamParser); begin F_parser := parser; end; function TDerSequenceParser.ReadObject: IAsn1Convertible; begin result := F_parser.ReadObject(); end; function TDerSequenceParser.ToAsn1Object: IAsn1Object; begin result := TDerSequence.Create(F_parser.ReadVector()); end; end.
{******************************************************************} { } { Borland Delphi Runtime Library } { RAS functions interface unit } { } { Portions created by Microsoft are } { Copyright (C) 1995-1999 Microsoft Corporation. } { All Rights Reserved. } { } { The original file is: rasshost.h, released 24 Apr 1998. } { The original Pascal code is: RasShost.pas, released 13 Jan 2000. } { The initial developer of the Pascal code is Petr Vones } { (petr.v@mujmail.cz). } { } { Portions created by Petr Vones are } { Copyright (C) 2000 Petr Vones } { } { Obtained through: } { } { Joint Endeavour of Delphi Innovators (Project JEDI) } { } { You may retrieve the latest version of this file at the Project } { JEDI home page, located at http://delphi-jedi.org } { } { The contents of this file are used with permission, subject to } { the Mozilla Public License Version 1.1 (the "License"); you may } { not use this file except in compliance with the License. You may } { obtain a copy of the License at } { http://www.mozilla.org/MPL/MPL-1.1.html } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or } { implied. See the License for the specific language governing } { rights and limitations under the License. } { } {******************************************************************} unit RasShost; {$I RAS.INC} {$ALIGN ON} {$MINENUMSIZE 4} interface uses Windows, LmCons, RasSapi; (*$HPPEMIT '#include <rassapi.h>'*) (*$HPPEMIT '#include <mprapi.h>'*) // Description: This header defines the interface between third party security // DLLs and the RAS server. type PHPort = ^THPort; HPORT = DWORD; {$EXTERNALSYM HPORT} THPort = HPORT; PSecurityMessage = ^TSecurityMessage; _SECURITY_MESSAGE = record dwMsgId: DWORD; hPort: THPort; dwError: DWORD; // Should be non-zero only if error // occurred during the security dialog. // Should contain errors from winerror.h // or raserror.h UserName: packed array[0..UNLEN] of Char; // Should always contain username if // dwMsgId is SUCCESS/FAILURE Domain: packed array[0..DNLEN] of Char; // Should always contain domain if // dwMsgId is SUCCESS/FAILURE end; {$EXTERNALSYM _SECURITY_MESSAGE} TSecurityMessage = _SECURITY_MESSAGE; SECURITY_MESSAGE = _SECURITY_MESSAGE; {$EXTERNALSYM SECURITY_MESSAGE} // Values for dwMsgId in SECURITY_MESSAGE structure const SECURITYMSG_SUCCESS = 1; {$EXTERNALSYM SECURITYMSG_SUCCESS} SECURITYMSG_FAILURE = 2; {$EXTERNALSYM SECURITYMSG_FAILURE} SECURITYMSG_ERROR = 3; {$EXTERNALSYM SECURITYMSG_ERROR} // Used by RasSecurityGetInfo call type PRasSecurityInfo = ^TRasSecurityInfo; _RAS_SECURITY_INFO = record LastError: DWORD; // SUCCESS = receive completed // PENDING = receive pending // else completed with error BytesReceived: DWORD; // only valid if LastError == SUCCESS DeviceName: packed array[0..RASSAPI_MAX_DEVICE_NAME] of Char; end; {$EXTERNALSYM _RAS_SECURITY_INFO} TRasSecurityInfo = _RAS_SECURITY_INFO; RAS_SECURITY_INFO = _RAS_SECURITY_INFO; {$EXTERNALSYM RAS_SECURITY_INFO} TRasSecurityProc = function: DWORD; stdcall; RASSECURITYPROC = TRasSecurityProc; {$EXTERNALSYM RASSECURITYPROC} // Called by third party DLL to notify the supervisor of termination of // the security dialog TRasSecurityDialogComplete = procedure (pSecMsg: PSecurityMessage); stdcall; // Called by supervisor into the security DLL to notify it to begin the // security dialog for a client. // // Should return errors from winerror.h or raserror.h TRasSecurityDialogBegin = function (hPort: THPort; pSendBuf: PByte; SendBufSize: DWORD; pRecvBuf: PByte; RecvBufSize: DWORD; RasSecurityDialogComplete: TRasSecurityDialogComplete): DWORD; stdcall; // Called by supervisor into the security DLL to notify it to stop the // security dialog for a client. If this call returns an error, then it is not // neccesary for the dll to call RasSecurityDialogComplete. Otherwise the DLL // must call RasSecurityDialogComplete. // // Should return errors from winerror.h or raserror.h TRasSecurityDialogEnd = function (hPort: THPort): DWORD; stdcall; // The following entrypoints should be loaded by calling GetProcAddress from // RasMan.lib // // Called to send data to remote host // Will return errors from winerror.h or raserror.h TRasSecurityDialogSend = function (hPort: THPort; pBuffer: PByte; BufferLength: DWORD): DWORD; stdcall; // Called to receive data from remote host // Will return errors from winerror.h or raserror.h TRasSecurityDialogReceive = function (hPort: THPort; pBuffer: PByte; var pBufferLength: DWORD; Timeout: DWORD; hEvent: THandle): DWORD; stdcall; // Called to get Information about port. // Will return errors from winerror.h or raserror.h TRasSecurityDialogGetInfo = function (hPort: THPort; pBuffer: PRasSecurityInfo): DWORD; stdcall; var RasSecurityDialogGetInfo: TRasSecurityDialogGetInfo = nil; {$EXTERNALSYM RasSecurityDialogGetInfo} RasSecurityDialogSend: TRasSecurityDialogSend = nil; {$EXTERNALSYM RasSecurityDialogSend} RasSecurityDialogReceive: TRasSecurityDialogReceive = nil; {$EXTERNALSYM RasSecurityDialogReceive} function RasmanCheckAPI: Boolean; implementation const rasmanlib = 'rasman.dll'; var LibHandle: THandle = 0; function RasmanCheckAPI: Boolean; begin Result := (LibHandle <> 0); end; function RasmanInitAPI: Boolean; begin if LibHandle = 0 then LibHandle := LoadLibrary(rasmanlib); if LibHandle <> 0 then begin @RasSecurityDialogGetInfo := GetProcAddress(LibHandle, 'RasSecurityDialogGetInfo'); @RasSecurityDialogSend := GetProcAddress(LibHandle, 'RasSecurityDialogSend'); @RasSecurityDialogReceive := GetProcAddress(LibHandle, 'RasSecurityDialogReceive'); Result := True; end else Result := False; end; function RasmanFreeAPI: Boolean; begin if LibHandle <> 0 then Result := FreeLibrary(LibHandle) else Result := True; LibHandle := 0; end; initialization RasmanInitAPI; finalization RasmanFreeAPI; end.
{ Subroutine SST_W_C_TERM (TERM, ADDR_CNT, ENCLOSE) * * Write the term indicated by the term descriptor TERM. ADDR_CNT indicates * how many times the "address of" should be taken of the term. It may * be negative to indicate pointer dereferences. * ENCLOSE indicates whether the final expression should be enclosed in * parentheses. Values of ENCLOSE can be: * * ENCLOSE_YES_K - Enclose in parentheses, if neccessary, to make the * entire expression be one term. * * ENCLOSE_NO_K - Don't enclose expression in parentheses, even if is is * written as more than one term with operators in between. } module sst_W_C_TERM; define sst_w_c_term; %include 'sst_w_c.ins.pas'; procedure sst_w_c_term ( {write a term in an expression} in term: sst_exp_term_t; {descriptor for term to write} in addr_cnt: sys_int_machine_t; {number of times to take address of} in enclose: enclose_k_t); {enclose in () yes/no} const max_msg_parms = 1; {max parameters we can pass to a message} type permit_k_t = (permit_adr, permit_upt); {pointer diddle permission flags} permit_s_t = set of permit_k_t; var r2: double; {for intermediate calculations} i: sys_int_machine_t; {scratch integer and loop counter} imax: sys_int_max_t; {scratch integer for number conversion} ifarg_p: sst_exp_chain_p_t; {points to curr argument of intrinsic func} exp_p: sst_exp_p_t; {scratch pointer to expression descriptor} arg_p: sst_proc_arg_p_t; {points to current function argument desc} argt_p: sst_proc_arg_p_t; {points to current function argument template} ele_p: sst_ele_exp_p_t; {points to current set element descriptor} dt_p: sst_dtype_p_t; {scratch pointer to data type descriptor} sym_p: sst_symbol_p_t; {scratch pointer to symbol descriptor} exp: sst_exp_t; {for enclosing term in whole expression} term_p: sst_exp_term_p_t; {points to call argument for compiler bug} token: string_var32_t; {scratch token for number conversion} op1: sst_op1_k_t; {saved copy of term's unary operator} enc: enclose_k_t; {internal ENCLOSE flag} perm: permit_s_t; {scratch permission flags} all_done: boolean; {TRUE if DO_ADDR_CNT finished whole term} set_empty: boolean; {TRUE if set expression is empty} pushed_armode: boolean; {TRUE if pushed ARMODE in ifunc code} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; stat: sys_err_t; {error status code} label write_const, const_done, ifunc_done; { *************************** * * Local subroutine DO_ADDR_CNT (CNT, PERMITTED) * * Write the leading "*" or "&" symbols as neccesary. CNT is the number of * times the "address of" operator needs to be written. Negative values * indicate the number of times the "pointer dereference" operator needs to * be written. If anything is written, ENC is set to indicate that the * whole expression must be enclosed, if neccessary. * * PERMITTED is a set indicating which pointer/address operations are permitted * without the need for an implicit variable. Valid values of the set are: * * PERMIT_ADR - The "address of" operator is permitted one level. * * PERMIT_UPT - Unpointer (dereference pointer) operations are allowed. * * In cases where an implicit variable is created, this routine will handle * the entire term. In that case ALL_DONE is set to TRUE to indicate that * the caller should just RETURN. } procedure do_addr_cnt ( in cnt: sys_int_machine_t; {number of "address of" operations wanted} in permitted: permit_s_t); {set of pointer diddle permission flags} var cnt_left: sys_int_machine_t; {number of "address of"s left to do} v: sst_var_t; {descriptor for implicit variable} implicit_var: boolean; {TRUE if implicit variable needed} begin all_done := false; {init to whole term not handled here} if cnt = 0 then return; {nothing needs to be done ?} cnt_left := cnt; {init number of "address of"s left to do} if cnt_left > 0 then begin {"address of"s are requested} sst_w.appendn^ ('&', 1); {do only one address of at a time} implicit_var := not (permit_adr in permitted); cnt_left := cnt - 1; {one less "address of" left to do} end else begin {pointer dereferences requested} while cnt_left < 0 do begin {once for each time to dereference pointer} sst_w.appendn^ ('*', 1); cnt_left := cnt_left + 1; {one less pointer dereference left to do} end; implicit_var := not (permit_upt in permitted); end; ; if implicit_var or (cnt_left <> 0) then begin {create implicit variable for term ?} sst_w_c_implicit_var ( {create and declare implicit variable} term_p^.dtype_p^, {data type for implicit variable} v); {filled in variable reference descriptor} sst_w_c_pos_push (sment_type_exec_k); {position for write before curr statement} sst_w_c_sment_start; {start assignment statement} sst_w.append_sym_name^ (v.mod1.top_sym_p^); {write name of implicit variable} sst_w.delimit^; sst_w.appendn^ ('=', 1); sst_w.delimit^; sst_w_c_term (term_p^, cnt_left, enclose_no_k); {write the term's value} sst_w_c_sment_end; sst_w_c_pos_pop; {restore original writing position} sst_w.append_sym_name^ (v.mod1.top_sym_p^); {write var name for term value} all_done := true; {indicate that whole term finished} return; end; enc := enclose_yes_k; {now needs to look like just one term} end; { *************************** * * Local subroutine MINMAX (ARG1, N_ARGS, DTYPE, IFUNC_ID) * * Write out the equivalent of a MIN or MAX function. ARG1 is the descriptor * for the first argument to the MIN/MAX function. N_ARGS is the number of * arguments in the chain that need to be handled. IFUNC_ID is the intrinsic * function ID, which indicates whether this is a MIN or MAX function. * It must be either SST_IFUNC_MAX_K or SST_IFUNC_MIN_K. DTYPE must be the * data type descriptor for the result of the whole MIN or MAX function. } procedure minmax ( in arg1: sst_exp_chain_t; {descriptor for first intrinsic func argument} in n_args: sys_int_machine_t; {number of arguments to handle} in dtype: sst_dtype_t; {data type of whole MIN or MAX function} in ifunc_id: sst_ifunc_k_t); {identifies MIN or MAX function} var sym1_p, sym2_p: sst_symbol_p_t; {pointer to arg1,arg2 implicit vars, if any} exp1_p, exp2_p: sst_exp_p_t; {pointers to arg1,arg2 expression descriptors} v: sst_var_t; {scratch descriptor for implicit variable} begin exp1_p := arg1.exp_p; {get pointer to argument 1 expression} exp2_p := arg1.next_p^.exp_p; {get pointer to argument 2 expression} sst_w_c_exp_implicit (exp1_p^, sym1_p); {make implicit var for arg1, if needed} if n_args <= 2 then begin {handle all call args directly} sst_w_c_exp_implicit (exp2_p^, sym2_p); {make implicit var for arg2, if needed} end else begin {too many args, handle remainder recursively} sst_w_c_implicit_var (dtype, v); {make implicit var for second term} sym2_p := v.mod1.top_sym_p; {save symbol pointer to implicit variable} sst_w_c_pos_push (sment_type_exec_k); {position for write before curr statement} sst_w_c_sment_start; {start assignment statement} sst_w.append_sym_name^ (sym2_p^); {write name of implicit variable} sst_w.delimit^; sst_w.appendn^ ('=', 1); sst_w.delimit^; minmax ( {write value of arguments 2-N} arg1.next_p^, n_args-1, dtype, ifunc_id); sst_w_c_sment_end; {close assignment to implicit var statement} sst_w_c_pos_pop; {restore original writing position} end ; { * The function has now been resolved to 2 arguments. An implicit variable * may have been created for each argument, which is indicated by the * SYMn_P pointer not being NIL. When the pointer is NIL, then the argument * is to be referenced directly by the expression pointed to by EXPn_P. * * A MAX expression has the form: * * (arg1 > arg2) ? arg1 : arg2 * * The ">" is replaced by a "<" for a MIN expression. } sst_w.appendn^ ('(', 1); if sym1_p = nil {write argument 1 value} then sst_w_c_exp (exp1_p^, 0, nil, enclose_yes_k) else sst_w.append_sym_name^ (sym1_p^); sst_w.delimit^; if ifunc_id = sst_ifunc_max_k {write operator based on MIN/MAX choice} then sst_w.appendn^ ('>', 1) else sst_w.appendn^ ('<', 1); sst_w.delimit^; if sym2_p = nil {write argument 2 value} then sst_w_c_exp (exp2_p^, 0, nil, enclose_yes_k) else sst_w.append_sym_name^ (sym2_p^); sst_w.appendn^ (')', 1); sst_w.delimit^; sst_w.appendn^ ('?', 1); sst_w.delimit^; if sym1_p = nil {write argument 1 value} then sst_w_c_exp (exp1_p^, 0, nil, enclose_yes_k) else sst_w.append_sym_name^ (sym1_p^); sst_w.delimit^; sst_w.appendn^ (':', 1); sst_w.delimit^; if sym2_p = nil {write argument 2 value} then sst_w_c_exp (exp2_p^, 0, nil, enclose_yes_k) else sst_w.append_sym_name^ (sym2_p^); end; { *************************** * * Start of main routine. } begin token.max := sizeof(token.str); {init local var string} term_p := addr(term); {work around compiler bug} enc := enclose; {init internal ENCLOSE flag to caller's} { * Handle unary operator applied to this term. We will only deal with the * unary operator if the term is not a constant. In that case, the constant * value will already reflect the unary operator. } if {need to deal with preceeding unary op ?} (term.op1 <> sst_op1_none_k) and (term.ttype <> sst_term_const_k) then begin do_addr_cnt (addr_cnt, []); if all_done then return; if enc = enclose_yes_k then sst_w.appendn^ ('(', 1); {open paren, if needed} case term.op1 of {which operator is it ?} sst_op1_minus_k: sst_w.appendn^ ('-', 1); {arithmetic negation} sst_op1_not_k: sst_w.appendn^ ('!', 1); {logical negation} sst_op1_1comp_k: sst_w.appendn^ ('~', 1); {one's complement (flip all the bits)} otherwise sys_msg_parm_int (msg_parm[1], ord(term.op1)); sys_message_bomb ('sst', 'operator_unknown_unary', msg_parm, 1); end; {end of unary operator cases} term_p := addr(term); {allow temp writing term although declared IN} op1 := term.op1; {save unary operator ID} term_p^.op1 := sst_op1_none_k; {temporarily shut off unary operator} sst_w_c_term (term, 0, enclose_yes_k); {write the body of the term} term_p^.op1 := op1; {restore unary operator ID} if enc = enclose_yes_k then sst_w.appendn^ (')', 1); {close paren, if needed} return; end; {done handling unary operator exists case} { * This term has no unary operator we need to worry about. } case term.ttype of {what kind of term is this ?} { ********************************************* * * Term is a constant. } sst_term_const_k: begin do_addr_cnt (addr_cnt, []); if all_done then return; write_const: {jump here to just write constant value} { * Check for FIRSTOF(integer) constant value. Many C compilers have trouble * with this. Instead of writing this value directly, we will set a static * variable to this value, and then use the variable. } imax := lshft(1, sst_dtype_int_max_p^.bits_min - 1); {make FIRSTOF(integer)} if {special integer compiler doesn't do right ?} (term.val.dtype = sst_dtype_int_k) and {constant is of integer type ?} (term.val.int_val = imax) and {value is the nasty integer ?} (frame_scope_p^.sment_type = sment_type_exec_k) {in executable code ?} then begin exp.str_h := term.str_h; {make expression of this term} exp.dtype_p := term.dtype_p; exp.dtype_hard := term.dtype_hard; exp.val_eval := term.val_eval; exp.val_fnd := term.val_fnd; exp.val := term.val; exp.rwflag := term.rwflag; exp.term1 := term; sst_w_c_exp_explicit (exp, exp.dtype_p^, sym_p); {create static variable} sst_w.append_sym_name^ (sym_p^); {write name of var instead of const value} goto const_done; end; sst_w_c_value ( {write term's constant value} term.val, {constant value descriptor} enc); {enclose in () yes/no flag} const_done: {all done writing constant value} end; { ********************************************* * * Term is a variable reference. } sst_term_var_k: begin sst_w_c_var (term.var_var_p^, addr_cnt); {write variable reference} end; { ********************************************* * * Term is a function call. } sst_term_func_k: begin do_addr_cnt (addr_cnt, [permit_upt]); if all_done then return; sst_w_c_var (term.func_var_p^, 0); {write function reference} sst_w.appendn^ ('(', 1); {start function arguments} if term.func_proc_p^.n_args > 0 then begin {function has arguments ?} sst_w.allow_break^; arg_p := term.func_proc_p^.first_arg_p; {init curr argument to first in list} argt_p := term.func_proct_p^.first_arg_p; {init curr argument template} while (arg_p <> nil) or (argt_p <> nil) do begin {once for each function arg} sst_w_c_arg (arg_p, argt_p); {write this call argument} if (arg_p <> nil) or (argt_p <> nil) then begin {another argument follows ?} sst_w.appendn^ (',', 1); sst_w.delimit^; end; end; {back to do this new call argument} end; {done handling call arguments} sst_w.appendn^ (')', 1); {close argument list} end; { ********************************************* * * Term is an intrinsic function to the translator. * * For the cases where the SST function maps directly to the target language * function, write the function and then fall thru to the end of the * case statement. * * Cases that don't map directly to target language functions need to handle * everything directly, and then jump to IFUNC_DONE. } sst_term_ifunc_k: begin ifarg_p := term.ifunc_args_p; {init current argument to first argument} pushed_armode := false; {init to not pushed array interpret mode} case term.ifunc_id of { ********************** } sst_ifunc_abs_k: begin {absolute value} do_addr_cnt (addr_cnt, []); if all_done then return; dt_p := ifarg_p^.exp_p^.dtype_p; {get argument's data type} while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p; {base dtype} if dt_p^.dtype = sst_dtype_float_k then begin {argument is floating point, use FABS} sst_w_c_intrinsic (intr_fabs_k); end else begin {argument is integer, use ABS} sst_w_c_intrinsic (intr_abs_k); end ; end; { ********************** } sst_ifunc_addr_k: begin {address of} sst_w_c_exp (ifarg_p^.exp_p^, addr_cnt + 1, nil, enc); goto ifunc_done; end; { ********************** } sst_ifunc_align_k: begin {minimum alignment needed for arg1} do_addr_cnt (addr_cnt, []); if all_done then return; goto write_const; end; { ********************** } sst_ifunc_atan_k: begin {arctangent given slope as ratio of 2 numbers} do_addr_cnt (addr_cnt, []); if all_done then return; exp_p := ifarg_p^.next_p^.exp_p; {get pointer to second arg expression} r2 := 0; {init value so as to use ATAN2} if exp_p^.val_fnd then begin {constant value known for second arg ?} case exp_p^.val.dtype of {what data type is constant ?} sst_dtype_int_k: r2 := exp_p^.val.int_val; sst_dtype_float_k: r2 := exp_p^.val.float_val; end; {end of arg 2 constant data type cases} end; if r2 = 1.0 then begin {second argument is 1.0, use ATAN} sst_w_c_intrinsic (intr_atan_k); sst_w.appendn^ ('(', 1); sst_w.allow_break^; sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_no_k); sst_w.appendn^ (')', 1); goto ifunc_done; end else begin {second arg not known to be 1.0, use ATAN2} sst_w_c_intrinsic (intr_atan2_k); end ; end; { ********************** } sst_ifunc_char_k: begin {convert integer to char, ignore high bits} sst_w_c_exp (ifarg_p^.exp_p^, addr_cnt, sst_dtype_char_p, enc); goto ifunc_done; end; { ********************** } sst_ifunc_cos_k: begin {cosine, argument in radians} do_addr_cnt (addr_cnt, []); if all_done then return; sst_w_c_intrinsic (intr_cos_k); end; { ********************** } sst_ifunc_dec_k: begin {next smaller value of} do_addr_cnt (addr_cnt, []); if all_done then return; if enc = enclose_yes_k then sst_w.appendn^ ('(', 1); {open paren, if needed} sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_yes_k); i := 1; {set delta amount value} string_f_int (token, i); {make delta amount string} sst_w.delimit^; sst_w.appendn^ ('-', 1); sst_w.delimit^; sst_w.append^ (token); if enc = enclose_yes_k then sst_w.appendn^ (')', 1); {close paren, if needed} goto ifunc_done; end; { ********************** } sst_ifunc_exp_k: begin {E to power of argument} do_addr_cnt (addr_cnt, []); if all_done then return; sst_w_c_intrinsic (intr_exp_k); end; { ********************** } sst_ifunc_first_k: begin {first possible value of} do_addr_cnt (addr_cnt, []); if all_done then return; goto write_const; end; { ********************** } sst_ifunc_inc_k: begin {next greater value of} do_addr_cnt (addr_cnt, []); if all_done then return; if enc = enclose_yes_k then sst_w.appendn^ ('(', 1); {open paren, if needed} sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_yes_k); i := 1; {set delta amount value} string_f_int (token, i); {make delta amount string} sst_w.delimit^; sst_w.appendn^ ('+', 1); sst_w.delimit^; sst_w.append^ (token); if enc = enclose_yes_k then sst_w.appendn^ (')', 1); {close paren, if needed} goto ifunc_done; end; { ********************** } sst_ifunc_int_near_k: begin {convert to integer, round to nearest} do_addr_cnt (addr_cnt, []); if all_done then return; sst_w.appendn^ ('(int)', 5); sst_w_c_intrinsic (intr_floor_k); sst_w.appendn^ ('(', 1); sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_yes_k); sst_w.delimit^; sst_w.appendn^ ('+', 1); sst_w.delimit^; sst_w.appendn^ ('0.5)', 4); goto ifunc_done; end; { ********************** } sst_ifunc_int_zero_k: begin {convert to integer, round towards zero} do_addr_cnt (addr_cnt, []); if all_done then return; sst_w.appendn^ ('(int)', 5); sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_yes_k); goto ifunc_done; end; { ********************** } sst_ifunc_last_k: begin {last possible value of} do_addr_cnt (addr_cnt, []); if all_done then return; goto write_const; end; { ********************** } sst_ifunc_ln_k: begin {logarithm base E} do_addr_cnt (addr_cnt, []); if all_done then return; sst_w_c_intrinsic (intr_log_k); end; { ********************** * * MIN and MAX functions. These are handled similarly. } sst_ifunc_max_k, {maximum value of all arguments} sst_ifunc_min_k: begin {minimum value of all arguments} do_addr_cnt (addr_cnt, []); if all_done then return; if enc = enclose_yes_k then sst_w.appendn^ ('(', 1); {open paren, if needed} i := 1; {init number of arguments counted} while ifarg_p^.next_p <> nil do begin {once for each argument after first} i := i + 1; {count one more argument} ifarg_p := ifarg_p^.next_p; {advance to next argument in list} end; { * I is the number of arguments to this function. } minmax ( {write this MIN or MAX function} term.ifunc_args_p^, {descriptor for first argument} i, {number of arguments} term.dtype_p^, {final resulting data type of intrinsic func} term.ifunc_id); {selects MIN or MAX function} if enc = enclose_yes_k then sst_w.appendn^ (')', 1); {close paren, if needed} goto ifunc_done; end; { ********************** } sst_ifunc_offset_k: begin {offset of field within record} do_addr_cnt (addr_cnt, []); if all_done then return; goto write_const; end; { ********************** } sst_ifunc_ord_val_k: begin {ordinal value of} sst_w_c_exp (ifarg_p^.exp_p^, addr_cnt, nil, enc); goto ifunc_done; end; { ********************** * * Arbitrary logical shift of ARG1 by ARG2 bits to the right. ARG2 may * be negative to indicate a shift to the left. This expression can take * three forms. If ARG2 has a known value, and is positive: * * (unsigned int)arg1 >> arg2 * * If ARG2 has a know value and is negative then: * * arg1 << arg2 * * If ARG2 does not have a known value then: * * (arg2 > 0) ? ((unsigned int)arg1 >> arg2) : (arg1 << -arg2) * * In this case, ARG2 will have to be assigned to an implicit variable * if it is not a simple expression. } sst_ifunc_shift_lo_k: begin {logical shift arg1 by arg2 bits right} do_addr_cnt (addr_cnt, []); if all_done then return; if enc = enclose_yes_k then sst_w.appendn^ ('(', 1); {open paren, if needed} if ifarg_p^.next_p^.exp_p^.val_fnd then begin {ARG2 has known constant value ?} if ifarg_p^.next_p^.exp_p^.val.int_val < 0 then begin {ARG2 is negative, shift left} sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_yes_k); sst_w.delimit^; sst_w.appendn^ ('<<', 2); sst_w.delimit^; sst_w_c_exp (ifarg_p^.next_p^.exp_p^, 0, nil, enclose_yes_k); end else begin {ARG2 is positive, shift right} sst_w.appendn^ ('(unsigned int)', 14); sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_yes_k); sst_w.delimit^; sst_w.appendn^ ('>>', 2); sst_w.delimit^; sst_w_c_exp (ifarg_p^.next_p^.exp_p^, 0, nil, enclose_yes_k); end ; end else begin {value of ARG2 is not known} sst_w_c_exp_implicit ( {create implicit var for ARG2 if needed} ifarg_p^.next_p^.exp_p^, sym_p); sst_w.appendn^ ('(', 1); if sym_p = nil {write ARG2 value} then sst_w_c_exp (ifarg_p^.next_p^.exp_p^, 0, nil, enclose_yes_k) else sst_w.append_sym_name^ (sym_p^); sst_w.delimit^; sst_w.appendn^ ('>', 1); sst_w.delimit^; sst_w.appendn^ ('0', 1); sst_w.appendn^ (')', 1); sst_w.delimit^; sst_w.appendn^ ('?', 1); sst_w.delimit^; sst_w.appendn^ ('((unsigned int)', 15); sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_yes_k); sst_w.delimit^; sst_w.appendn^ ('>>', 2); sst_w.delimit^; if sym_p = nil {write ARG2 value} then sst_w_c_exp (ifarg_p^.next_p^.exp_p^, 0, nil, enclose_yes_k) else sst_w.append_sym_name^ (sym_p^); sst_w.appendn^ (')', 1); sst_w.delimit^; sst_w.appendn^ (':', 1); sst_w.delimit^; sst_w.appendn^ ('(', 1); sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_yes_k); sst_w.delimit^; sst_w.appendn^ ('<<', 2); sst_w.delimit^; sst_w.appendn^ ('-', 1); if sym_p = nil {write ARG2 value} then sst_w_c_exp (ifarg_p^.next_p^.exp_p^, 0, nil, enclose_yes_k) else sst_w.append_sym_name^ (sym_p^); sst_w.appendn^ (')', 1); end ; if enc = enclose_yes_k then sst_w.appendn^ (')', 1); {close paren, if needed} goto ifunc_done; end; { ********************** } sst_ifunc_shiftl_lo_k: begin {logical shift left arg1 by arg2 bits} do_addr_cnt (addr_cnt, []); if all_done then return; if enc = enclose_yes_k then sst_w.appendn^ ('(', 1); {open paren, if needed} sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_yes_k); ifarg_p := ifarg_p^.next_p; {advance to second argument} sst_w.delimit^; sst_w.appendn^ ('<<', 2); sst_w.delimit^; sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_yes_k); if enc = enclose_yes_k then sst_w.appendn^ (')', 1); {close paren, if needed} goto ifunc_done; end; { ********************** } sst_ifunc_shiftr_ar_k: begin {arithmetic shift right arg1 by arg2 bits} do_addr_cnt (addr_cnt, []); if all_done then return; if enc = enclose_yes_k then sst_w.appendn^ ('(', 1); {open paren, if needed} sst_w.appendn^ ('(signed int)', 12); sst_w.allow_break^; sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_yes_k); ifarg_p := ifarg_p^.next_p; {advance to second argument} sst_w.delimit^; sst_w.appendn^ ('>>', 2); sst_w.delimit^; sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_yes_k); if enc = enclose_yes_k then sst_w.appendn^ (')', 1); {close paren, if needed} goto ifunc_done; end; { ********************** } sst_ifunc_shiftr_lo_k: begin {logical shift right arg1 by arg2 bits} do_addr_cnt (addr_cnt, []); if all_done then return; if enc = enclose_yes_k then sst_w.appendn^ ('(', 1); {open paren, if needed} sst_w.appendn^ ('(unsigned int)', 14); sst_w.allow_break^; sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_yes_k); ifarg_p := ifarg_p^.next_p; {advance to second argument} sst_w.delimit^; sst_w.appendn^ ('>>', 2); sst_w.delimit^; sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_yes_k); if enc = enclose_yes_k then sst_w.appendn^ (')', 1); {close paren, if needed} goto ifunc_done; end; { ********************** } sst_ifunc_sin_k: begin {sine, arguments in radians} do_addr_cnt (addr_cnt, []); if all_done then return; sst_w_c_intrinsic (intr_sin_k); end; { ********************** } sst_ifunc_size_align_k: begin {align-padded size in machine addresses} do_addr_cnt (addr_cnt, []); if all_done then return; dt_p := ifarg_p^.exp_p^.dtype_p; {resolve base argument data type} while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p; { * The C sizeof function doesn't work the way we want on arrays. Since * array identifiers are actually implicit pointers, SIZEOF returns * the size of a pointer, not the array. Dereferencing the pointer doesn't * work either, since it is a pointer to the first element, not the whole * array. } if dt_p^.dtype = sst_dtype_array_k then begin {argument has ARRAY data type ?} goto write_const; end; if {argument is element of array data type ?} (ifarg_p^.exp_p^.term1.ttype = sst_term_var_k) and then (ifarg_p^.exp_p^.term1.var_var_p^.vtype = sst_vtype_dtype_k) and (ifarg_p^.exp_p^.term1.var_var_p^.mod1.next_p <> nil) then goto write_const; sst_w_c_armode_push (array_whole_k); {array identifier represents whole array} pushed_armode := true; {remember to pop mode later} sst_w.appendn^ ('sizeof', 6); end; { ********************** } sst_ifunc_size_char_k: begin {number of characters that can fit} do_addr_cnt (addr_cnt, []); if all_done then return; goto write_const; end; { ********************** } sst_ifunc_size_min_k: begin {minimum size of in machine addresses} do_addr_cnt (addr_cnt, []); if all_done then return; goto write_const; end; { ********************** * * The C language has no explicit function that takes the square of a value. * This will take the form: * * arg * arg * * An implicit variable will be created for ARG when it is not a simple * expression. } sst_ifunc_sqr_k: begin {square of} do_addr_cnt (addr_cnt, []); if all_done then return; if enc = enclose_yes_k then sst_w.appendn^ ('(', 1); {open paren, if needed} sst_w_c_exp_implicit (ifarg_p^.exp_p^, sym_p); {make implicit variable, if needed} if sym_p = nil then sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_yes_k) else sst_w.append_sym_name^ (sym_p^); sst_w.delimit^; sst_w.appendn^ ('*', 1); sst_w.delimit^; if sym_p = nil then sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_yes_k) else sst_w.append_sym_name^ (sym_p^); if enc = enclose_yes_k then sst_w.appendn^ (')', 1); {close paren, if needed} goto ifunc_done; end; { ********************** } sst_ifunc_sqrt_k: begin {square root of} do_addr_cnt (addr_cnt, []); if all_done then return; sst_w_c_intrinsic (intr_sqrt_k); end; { ********************** } sst_ifunc_xor_k: begin {exclusive or} do_addr_cnt (addr_cnt, []); if all_done then return; if enc = enclose_yes_k then sst_w.appendn^ ('(', 1); {open paren, if needed} while ifarg_p <> nil do begin {once for each argument to intrinsic function} sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_yes_k); ifarg_p := ifarg_p^.next_p; {advance to next argument in chain} if ifarg_p <> nil then begin {an argument follows the one we just wrote} sst_w.delimit^; sst_w.appendn^ ('^', 1); sst_w.delimit^; end; end; {back to handle this new argument} if enc = enclose_yes_k then sst_w.appendn^ (')', 1); {close paren, if needed} goto ifunc_done; end; { ********************** * * Intrinsic function is set inversion (the existance of every set element * is flipped). This will be written as the full set with the specified * elements removed. This will have the form: * * full_set ^ arg * * when an argument expression exists. Otherwise it will have the form: * * full_set * * FULL_SET will be a hexadecimal constant. } sst_ifunc_setinv_k: begin set_empty := {true if ARG is definately the nullset} (ifarg_p^.exp_p^.term1.ttype = sst_term_set_k) and (ifarg_p^.exp_p^.term1.set_first_p = nil); if set_empty then begin {we will just write FULL_SET value ?} enc := enclose_no_k; {no need to enclose in parenthesis} end; do_addr_cnt (addr_cnt, []); if all_done then return; if enc = enclose_yes_k then sst_w.appendn^ ('(', 1); {open paren, if needed} imax := ~lshft(-1, term.dtype_p^.bits_min); {make set value for all elements exist} string_f_int_max_base ( {convert full set value to hexadecimal string} token, {output string} imax, {input number} 16, {number base} (term.dtype_p^.bits_min + 3) div 4, {number of digits to create} [string_fi_leadz_k, string_fi_unsig_k], {write leading zeros, input is unsigned} stat); {error return status} sys_error_abort (stat, '', '', nil, 0); sst_w.appendn^ ('0x', 2); {header for hexadecimal constant} sst_w.append^ (token); if not set_empty then begin {argument exists ?} sst_w.delimit^; sst_w.appendn^ ('^', 1); sst_w.delimit^; sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_yes_k); end; if enc = enclose_yes_k then sst_w.appendn^ (')', 1); {close paren, if needed} goto ifunc_done; end; { ********************** } otherwise sys_msg_parm_int (msg_parm[1], ord(term.ifunc_id)); syo_error (term.str_h, 'sst', 'func_intrinsic_unknown', msg_parm, 1); end; {end of intrinsic function ID cases} { ********************** * * All the intrinsic functions that fall thru here map directly to C * functions. The function name has been written. Now write the function * arguments list. } sst_w.appendn^ ('(', 1); {open parenthesis for argument list} while ifarg_p <> nil do begin {once for each argument} sst_w_c_exp (ifarg_p^.exp_p^, 0, nil, enclose_no_k); ifarg_p := ifarg_p^.next_p; {advance to next argument in chain} if ifarg_p <> nil then begin {an argument follows the one we just wrote} sst_w.appendn^ (',', 1); sst_w.allow_break^; end; end; {back to handle this new argument} sst_w.appendn^ (')', 1); {close parenthesis for argument list} ifunc_done: {jump here on done writing intrinsic function} if pushed_armode then begin {push ARMODE earlier ?} sst_w_c_armode_pop; {restore original ARMODE} end; end; {done with term is an intrinsic function} { ********************************************* * * Term is a type-casting function. * * If EXP is the expresssion being type cast, and TYPE is the casting data type, * then this will take the form: * * *(type *)&exp * * The native C type casting functions CONVERT from one data type to another; * they don't RE-TYPE the same bit pattern. Therefore, we have to get a pointer * to the original expression, cast it to be a pointer to the desired type, and * then dereference the result. * * If the original expression already is a pointer, then it will be type-cast * directly: * * (type)exp } sst_term_type_k: begin if sst_w_c_exp_adrable(term.type_exp_p^) {allowed to take address of argument ?} then perm := [permit_adr] else perm := []; do_addr_cnt (addr_cnt, perm); if all_done then return; dt_p := term.type_exp_p^.dtype_p; {resolve base data type of expression} while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p; if dt_p^.dtype = sst_dtype_pnt_k then begin {expression data type is POINTER} sst_w.appendn^ ('(', 1); sst_w.append_sym_name^ (term.type_dtype_p^.symbol_p^); sst_w.appendn^ (')', 1); sst_w_c_exp (term.type_exp_p^, 0, nil, enclose_yes_k); end else begin {expression is not a pointer} sst_w.appendn^ ('*(', 2); sst_w.append_sym_name^ (term.type_dtype_p^.symbol_p^); sst_w.delimit^; sst_w.appendn^ ('*)', 2); sst_w_c_exp (term.type_exp_p^, 1, nil, enclose_yes_k); end ; end; { ********************************************* * * Term is a SET. } sst_term_set_k: begin do_addr_cnt (addr_cnt, []); if all_done then return; ele_p := term.set_first_p; {init current set element to first in list} if ele_p = nil then begin {set expression is the null set ?} sst_w_c_intrinsic (intr_nullset_k); return; end; if ele_p^.next_p = nil then begin {only one element in this set ?} enc := enclose_no_k; {no need to enclose one element in parens} end; if enc = enclose_yes_k then sst_w.appendn^ ('(', 1); {open paren, if needed} while ele_p <> nil do begin {once for each set element} if ele_p^.last_p <> nil { * This element is actually a range of element values. If ELE1 and ELE2 * are the starting and ending element values of the range this will look like: * * ((-1 << ele1) & ~(-2 << ele2)) } then begin sst_w.appendn^ ('((-1', 4); sst_w.delimit^; sst_w.appendn^ ('<<', 2); sst_w.delimit^; sst_w_c_exp (ele_p^.first_p^, 0, nil, enclose_yes_k); sst_w.appendn^ (')', 1); sst_w.delimit^; sst_w.appendn^ ('&', 1); sst_w.delimit^; sst_w.appendn^ ('~(-2', 4); sst_w.delimit^; sst_w.appendn^ ('<<', 2); sst_w.delimit^; sst_w_c_exp (ele_p^.last_p^, 0, nil, enclose_yes_k); sst_w.appendn^ ('))', 2); end { * The expression for this element contains only one element. It will look * like this: * * (1 << ele) } else begin sst_w.appendn^ ('(1', 2); sst_w.delimit^; sst_w.appendn^ ('<<', 2); sst_w.delimit^; sst_w_c_exp (ele_p^.first_p^, 0, nil, enclose_yes_k); sst_w.appendn^ (')', 1); end ; ele_p := ele_p^.next_p; {advance to next element in this set} if ele_p <> nil then begin {this was not last element in set ?} sst_w.delimit^; sst_w.appendn^ ('|', 1); {all the elements are ORed together} sst_w.delimit^; end; end; {back and do next element in set} if enc = enclose_yes_k then sst_w.appendn^ (')', 1); {close paren, if needed} end; { ********************************************* * * Term is nested expression. } sst_term_exp_k: begin sst_w_c_exp (term.exp_exp_p^, addr_cnt, nil, enclose); {write nested expression} end; { ********************************************* * * Unexpected term type. } otherwise sys_msg_parm_int (msg_parm[1], ord(term.ttype)); sys_message_bomb ('sst', 'term_type_unknown', msg_parm, 1); end; {end of term type cases} end;
{ Clever Internet Suite Copyright (C) 2014 Clever Components All Rights Reserved www.CleverComponents.com } unit clConfig; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes; {$ELSE} System.Classes; {$ENDIF} type TclConfig = class; TclConfigObject = class public constructor Create; virtual; end; TclConfigObjectClass = class of TclConfigObject; TclConfig = class private FNames: TStrings; FTypes: TStrings; public constructor Create; destructor Destroy; override; procedure Clear; procedure SetConfig(const AName, AValue: string); procedure SetType(const AName: string; AType: TclConfigObjectClass); function GetConfig(const AName: string): string; virtual; function CreateInstance(const AName: string): TclConfigObject; virtual; end; implementation { TclConfigObject } constructor TclConfigObject.Create; begin inherited Create(); end; { TclConfig } procedure TclConfig.SetConfig(const AName, AValue: string); begin FNames.Values[AName] := AValue; end; procedure TclConfig.SetType(const AName: string; AType: TclConfigObjectClass); var ind: Integer; begin ind := FTypes.IndexOf(AName); if (AType <> nil) then begin if (ind < 0) then begin ind := FTypes.Add(AName); end; FTypes.Objects[ind] := TObject(AType); end else begin if (ind >= 0) then begin FTypes.Delete(ind); end; end; end; procedure TclConfig.Clear; begin FNames.Clear(); FTypes.Clear(); end; constructor TclConfig.Create; begin inherited Create(); FNames := TStringList.Create(); {$IFDEF DELPHI7} FNames.NameValueSeparator := '='; {$ENDIF} FTypes := TStringList.Create(); end; function TclConfig.CreateInstance(const AName: string): TclConfigObject; var ind: Integer; begin ind := FTypes.IndexOf(AName); if (ind > - 1) then begin Result := TclConfigObjectClass(FTypes.Objects[ind]).Create(); end else begin Result := nil; end; end; destructor TclConfig.Destroy; begin FTypes.Free(); FNames.Free(); inherited Destroy(); end; function TclConfig.GetConfig(const AName: string): string; begin Result := FNames.Values[AName]; end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type { TfrmIconSpacing } TfrmIconSpacing = class(TForm) btnSave: TButton; edtOwn: TEdit; rbtnWindow10: TRadioButton; rbtnWindows7: TRadioButton; rbtnOwn: TRadioButton; procedure btnSaveClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure rbtnWindow10Change(Sender: TObject); private function GetIconVerticalSpacing: String; function SaveIconVerticalSpacing(IconVerticalSpacing: String): Boolean; public { public declarations } end; var frmIconSpacing: TfrmIconSpacing; implementation {$R *.lfm} uses Registry; procedure TfrmIconSpacing.FormActivate(Sender: TObject); var IconVerticalSpacing: String; begin IconVerticalSpacing := GetIconVerticalSpacing; if IconVerticalSpacing = '-1710' then begin rbtnWindow10.Checked := true; edtOwn.Enabled := false; end else if IconVerticalSpacing = '-1125' then begin rbtnWindows7.Checked := true; edtOwn.Enabled := false; end else begin rbtnOwn.Checked := true; edtOwn.Text := IconVerticalSpacing; edtOwn.Enabled := true; end; end; procedure TfrmIconSpacing.btnSaveClick(Sender: TObject); var IconVerticalSpacing: String; IconVerticalSpacingInteger: Integer; begin if rbtnWindow10.Checked then IconVerticalSpacing := '-1710' else if rbtnWindows7.Checked then IconVerticalSpacing := '-1125' else IconVerticalSpacing := edtOwn.Text; IconVerticalSpacingInteger := StrToInt(IconVerticalSpacing); if (IconVerticalSpacingInteger > -480) or (IconVerticalSpacingInteger < -2730) then ShowMessage('Die Werte müssen zwischen -480 und -2730 liegen.') else if SaveIconVerticalSpacing(IconVerticalSpacing) then ShowMessage('Speichern erfolgreich, bitte ab- und anmelden.') else ShowMessage('Es ist ein Fehler aufgetreten.') end; procedure TfrmIconSpacing.rbtnWindow10Change(Sender: TObject); var SelectedRadioButton: TRadioButton; begin SelectedRadioButton := Sender as TRadioButton; if SelectedRadioButton = rbtnOwn then begin edtOwn.Enabled := true; edtOwn.SetFocus; end else begin edtOwn.Enabled := false; end; end; function TfrmIconSpacing.GetIconVerticalSpacing: String; var Registry: TRegistry; begin GetIconVerticalSpacing := ''; Registry := TRegistry.Create; try Registry.RootKey := HKEY_CURRENT_USER; if Registry.OpenKeyReadOnly('\Control Panel\Desktop\WindowMetrics') then GetIconVerticalSpacing := Registry.ReadString('IconVerticalSpacing') finally Registry.Free; end; end; function TfrmIconSpacing.SaveIconVerticalSpacing(IconVerticalSpacing: String): Boolean; var Registry: TRegistry; begin SaveIconVerticalSpacing := false; Registry := TRegistry.Create; try Registry.RootKey := HKEY_CURRENT_USER; if Registry.OpenKey('\Control Panel\Desktop\WindowMetrics', true) then Registry.WriteString('IconVerticalSpacing', IconVerticalSpacing); SaveIconVerticalSpacing := true; finally Registry.Free; end; end; end.
{ *********************************************************** } { * TForge Library * } { * Copyright (c) Sergey Kasandrov 1997, 2018 * } { *********************************************************** } unit tfEvpAES; interface {$I TFL.inc} uses tfTypes, tfOpenSSL, tfCipherInstances; type PEvpAESInstance = ^TEvpAESInstance; TEvpAESInstance = record private {$HINTS OFF} FVTable: Pointer; FRefCount: Integer; FAlgID: TAlgID; FKeyFlags: TKeyFlags; FCtx: PEVP_CIPHER_CTX; // FInit: TEVP_CipherInit; FUpdate: TEVP_CipherUpdate; FFinal: TEVP_CipherFinal; {$HINTS ON} public (* class function GetBlockSize(Inst: PEvpAESInstance): Integer; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetIsBlockCipher(Inst: Pointer): Boolean; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; *) class function ExpandKeyIV(Inst: PEvpAESInstance; Key: PByte; KeySize: Cardinal; IV: PByte; IVSize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; end; function GetEvpAESInstance(var Inst: PEvpAESInstance; AlgID: TAlgID): TF_RESULT; implementation uses tfRecords, tfHelpers, tfEvpCiphers; const AES_BLOCK_SIZE = 16; // 16 bytes = 128 bits const EvpAESCipherVTable: array[0..25] of Pointer = ( @TForgeInstance.QueryIntf, @TForgeInstance.Addref, @TForgeInstance.SafeRelease, @TEvpCipherInstance.Burn, @TEvpCipherInstance.Clone, @TEvpCipherInstance.ExpandKey, @TEvpAESInstance.ExpandKeyIV, @TEvpCipherInstance.ExpandKeyNonce, @TCipherInstance.GetBlockSize128, @TEvpCipherInstance.EncryptUpdate, @TEvpCipherInstance.DecryptUpdate, @TCipherInstance.BlockMethodStub, @TCipherInstance.BlockMethodStub, @TCipherInstance.BlockMethodStub, @TCipherInstance.DataMethodStub, @TCipherInstance.EncryptStub, @TCipherInstance.EncryptStub, @TCipherInstance.IsBlockCipher, @TCipherInstance.IncBlockNoStub, @TCipherInstance.IncBlockNoStub, @TCipherInstance.IncBlockNoStub, @TCipherInstance.DataMethodStub, @TCipherInstance.SetNonceStub, @TCipherInstance.DataMethodStub, @TCipherInstance.GetNonceStub, @TCipherInstance.GetIVPointerStub ); function GetEvpAESInstance(var Inst: PEvpAESInstance; AlgID: TAlgID): TF_RESULT; var Padding: Cardinal; KeyMode: Cardinal; KeyDir: Cardinal; Tmp: PEvpAESInstance; begin KeyDir:= AlgID and TF_KEYDIR_MASK; if (KeyDir <> TF_KEYDIR_ENCRYPT) and (KeyDir <> TF_KEYDIR_DECRYPT) then begin Result:= TF_E_INVALIDARG; Exit; end; Padding:= AlgID and TF_PADDING_MASK; if Padding = TF_PADDING_DEFAULT then Padding:= TF_PADDING_PKCS; if (Padding <> TF_PADDING_NONE) and (Padding <> TF_PADDING_PKCS) then begin Result:= TF_E_NOTIMPL; Exit; end; KeyMode:= AlgID and TF_KEYMODE_MASK; case KeyMode of TF_KEYMODE_ECB, TF_KEYMODE_CBC, TF_KEYMODE_CFB, TF_KEYMODE_OFB, TF_KEYMODE_CTR, TF_KEYMODE_GCM: ; else Result:= TF_E_NOTIMPL; Exit; end; try Tmp:= AllocMem(SizeOf(TEvpAESInstance)); Tmp^.FVTable:= @EvpAESCipherVTable; Tmp^.FRefCount:= 1; Tmp^.FAlgID:= AlgID; TForgeHelper.Free(Inst); Inst:= Tmp; Result:= TF_S_OK; except Result:= TF_E_OUTOFMEMORY; end; end; { TEvpAESInstance } class function TEvpAESInstance.ExpandKeyIV(Inst: PEvpAESInstance; Key: PByte; KeySize: Cardinal; IV: PByte; IVSize: Cardinal): TF_RESULT; var RC: Integer; KeyDir: Cardinal; KeyMode: Cardinal; Padding: Cardinal; PCipher: PEVP_CIPHER; begin if Inst.FCtx <> nil then begin EVP_CIPHER_CTX_free(Inst.FCtx); Inst.FCtx:= nil; end; if (IV <> nil) and (IVSize <> AES_BLOCK_SIZE) then begin Result:= TF_E_INVALIDARG; Exit; end; { if (KeySize <> 16) and (KeySize <> 24) and (KeySize <> 32) then begin Result:= TF_E_INVALIDARG; Exit; end; } KeyMode:= Inst.FAlgID and TF_KEYMODE_MASK; PCipher:= nil; case KeyMode of TF_KEYMODE_ECB: case KeySize of 16: PCipher:= EVP_aes_128_ecb(); 24: PCipher:= EVP_aes_192_ecb(); 32: PCipher:= EVP_aes_256_ecb(); end; TF_KEYMODE_CBC: case KeySize of 16: PCipher:= EVP_aes_128_cbc(); 24: PCipher:= EVP_aes_192_cbc(); 32: PCipher:= EVP_aes_256_cbc(); end; TF_KEYMODE_CFB: case KeySize of 16: PCipher:= EVP_aes_128_cfb(); 24: PCipher:= EVP_aes_192_cfb(); 32: PCipher:= EVP_aes_256_cfb(); end; TF_KEYMODE_OFB: case KeySize of 16: PCipher:= EVP_aes_128_ofb(); 24: PCipher:= EVP_aes_192_ofb(); 32: PCipher:= EVP_aes_256_ofb(); end; TF_KEYMODE_CTR: case KeySize of 16: PCipher:= EVP_aes_128_ctr(); 24: PCipher:= EVP_aes_192_ctr(); 32: PCipher:= EVP_aes_256_ctr(); end; TF_KEYMODE_GCM: case KeySize of 16: PCipher:= EVP_aes_128_gcm(); 24: PCipher:= EVP_aes_192_gcm(); 32: PCipher:= EVP_aes_256_gcm(); end; end; if PCipher = nil then begin Result:= TF_E_UNEXPECTED; Exit; end; Inst.FCtx:= EVP_CIPHER_CTX_new(); if Inst.FCtx = nil then begin Result:= TF_E_OSSL; Exit; end; KeyDir:= Inst.FAlgID and TF_KEYDIR_MASK; if KeyDir = TF_KEYDIR_ENCRYPT then begin RC:= EVP_EncryptInit_ex(Inst.FCtx, PCipher, nil, Key, IV); if RC = 1 then begin @Inst.FUpdate:= @EVP_EncryptUpdate; @Inst.FFinal:= @EVP_EncryptFinal_ex; end; end else if KeyDir = TF_KEYDIR_DECRYPT then begin RC:= EVP_DecryptInit_ex(Inst.FCtx, PCipher, nil, Key, IV); if RC = 1 then begin @Inst.FUpdate:= @EVP_DecryptUpdate; @Inst.FFinal:= @EVP_DecryptFinal_ex; end; end else begin EVP_CIPHER_CTX_free(Inst.FCtx); Inst.FCtx:= nil; Result:= TF_E_UNEXPECTED; Exit; end; if RC <> 1 then begin EVP_CIPHER_CTX_free(Inst.FCtx); Inst.FCtx:= nil; Result:= TF_E_OSSL; Exit; end; Padding:= Inst.FAlgID and TF_PADDING_MASK; case Padding of TF_PADDING_DEFAULT: ; TF_PADDING_NONE: EVP_CIPHER_CTX_set_padding(Inst.FCtx, 0); TF_PADDING_PKCS: EVP_CIPHER_CTX_set_padding(Inst.FCtx, 1); else EVP_CIPHER_CTX_free(Inst.FCtx); Inst.FCtx:= nil; Result:= TF_E_UNEXPECTED; Exit; end; Result:= TF_S_OK; end; { class function TEvpAESInstance.GetBlockSize(Inst: PEvpAESInstance): Integer; begin Result:= AES_BLOCK_SIZE; end; class function TEvpAESInstance.GetIsBlockCipher(Inst: Pointer): Boolean; begin Result:= True; end; } end.
unit uFormaPagtoItemVO; interface uses System.SysUtils; type TFormaPagtoItemVO = class private FObs: string; FId: Integer; FDias: Integer; FIdFormaPagto: Integer; procedure SetDias(const Value: Integer); procedure SetId(const Value: Integer); procedure SetIdFormaPagto(const Value: Integer); procedure SetObs(const Value: string); public property Id: Integer read FId write SetId; property IdFormaPagto: Integer read FIdFormaPagto write SetIdFormaPagto; property Dias: Integer read FDias write SetDias; property Obs: string read FObs write SetObs; end; implementation { TFormaPagtoItem } procedure TFormaPagtoItemVO.SetDias(const Value: Integer); begin if Value < 0 then raise Exception.Create('Dias deve ser maior ou igual a Zero!'); FDias := Value; end; procedure TFormaPagtoItemVO.SetId(const Value: Integer); begin FId := Value; end; procedure TFormaPagtoItemVO.SetIdFormaPagto(const Value: Integer); begin FIdFormaPagto := Value; end; procedure TFormaPagtoItemVO.SetObs(const Value: string); begin FObs := Value; end; end.
unit AutoMapper.TypePair; interface type TTypePair = record class operator Equal(a: TTypePair; b: TTypePair) : Boolean; class operator NotEqual(a: TTypePair; b: TTypePair) : Boolean; private FSourceType : string; FDestinationType : string; public constructor Create(const ASourceType, ADestinationType: string); property SourceType: string read FSourceType; property DestinationType: string read FDestinationType; function Equals(const other: TTypePair): boolean; overload; function GetHashCode: integer; overload; class function New<TSource, TDestination>: TTypePair; static; end; THashCodeCombiner = class class function Combine<T1, T2>(const obj1: T1; const obj2: T2): integer; overload; class function Combine<T1: Class; T2: Class>: integer; overload; class function CombineCodes(const h1, h2: integer): integer; end; implementation uses AutoMapper.Exceptions , System.SysUtils , System.Rtti ; { THashCodeCombiner } class function THashCodeCombiner.Combine<T1, T2>(const obj1: T1; const obj2: T2): integer; var Ctx: TRttiContext; begin Ctx := TRttiContext.Create; Result := CombineCodes(Ctx.GetType(@obj1).GetHashCode, Ctx.GetType(@obj2).GetHashCode); Ctx.Free; end; class function THashCodeCombiner.Combine<T1, T2>: integer; var Ctx: TRttiContext; begin Ctx := TRttiContext.Create; Result := CombineCodes(Ctx.GetType(T1).GetHashCode, Ctx.GetType(T2).GetHashCode); Ctx.Free; end; class function THashCodeCombiner.CombineCodes(const h1, h2: integer): integer; begin Result := ((h1 shl 5) + h1) xor h2; end; { TTypePair } constructor TTypePair.Create(const ASourceType, ADestinationType: string); begin if ASourceType = ADestinationType then raise TTypePairCreateException.Create('SourceType equals DestinationType'); if ASourceType.IsEmpty then raise TTypePairCreateException.Create('SourceType is nil'); if ADestinationType.IsEmpty then raise TTypePairCreateException.Create('DestinationType is nil'); FSourceType := ASourceType; FDestinationType := ADestinationType; end; class operator TTypePair.Equal(a, b: TTypePair): Boolean; begin result := a.Equals(b); end; function TTypePair.Equals(const other: TTypePair): boolean; begin Result := (FSourceType = other.FSourceType) and (FDestinationType = other.FDestinationType); end; function TTypePair.GetHashCode: integer; begin Result := THashCodeCombiner.CombineCodes(FSourceType.GetHashCode, FDestinationType.GetHashCode); end; class function TTypePair.New<TSource, TDestination>: TTypePair; var Ctx: TRttiContext; SourceType, DestType: TRttiType; begin Ctx := TRttiContext.Create; SourceType := Ctx.GetType(TypeInfo(TSource)); DestType := Ctx.GetType(TypeInfo(TDestination)); Result := TTypePair.Create(SourceType.QualifiedName, DestType.QualifiedName); end; class operator TTypePair.NotEqual(a, b: TTypePair): Boolean; begin result := not a.Equals(b); end; end.
unit GX_SourceExport; // Original Author: ArentJan Banck <ajbanck@davilex.nl> {$I GX_CondDefine.inc} interface uses Classes, Graphics, Controls, Forms, Dialogs, ActnList, ComCtrls, Menus, StdCtrls, ExtCtrls, ToolWin, SynEdit, // This expert requires SynEdit from http://synedit.sf.net/ GX_Experts, GX_ConfigurationInfo, GX_BaseForm; type TGXCopyFormat = (cfText, cfHTMLFragment, cfRTFFragment); TSourceExportExpert = class; TfmSourceExport = class(TfmBaseForm) pnlFooter: TPanel; dlgSave: TSaveDialog; edtTitle: TEdit; lblTitle: TLabel; pmuCopy: TPopupMenu; mitCopyHtml: TMenuItem; mitCopyRtf: TMenuItem; mitCopy: TMenuItem; Actions: TActionList; actFileRefresh: TAction; actFileSave: TAction; actCopy: TAction; actCopyTextRtfHtml: TAction; actCopyHtmlFragment: TAction; actCopyRtfFragment: TAction; actFilePrint: TAction; actFileConfigure: TAction; actHelpHelp: TAction; actFileExit: TAction; pnlEditor: TPanel; pnlButtons: TPanel; pnlButtonsRight: TPanel; btnClose: TButton; btnConfig: TButton; btnPrint: TButton; btnCopy: TButton; btnSave: TButton; ToolBar: TToolBar; tbnRefresh: TToolButton; tbnSave: TToolButton; tbnCopy: TToolButton; ToolButton3: TToolButton; tbnPrint: TToolButton; ToolButton2: TToolButton; tbnConfigure: TToolButton; ToolButton1: TToolButton; tbnHelp: TToolButton; procedure actHelpExecute(Sender: TObject); procedure FormActivate(Sender: TObject); procedure actRefreshExecute(Sender: TObject); procedure actPrintExecute(Sender: TObject); procedure actSaveExecute(Sender: TObject); procedure actConfigureExecute(Sender: TObject); procedure actExitExecute(Sender: TObject); procedure actCopyHtmlExecute(Sender: TObject); procedure actCopyExecute(Sender: TObject); procedure actCopyRtfExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure actCopyTextRtfHtmlExecute(Sender: TObject); private FEditor: TSynEdit; procedure LoadSettings; procedure CopyToClipboard(CopyFormat: TGXCopyFormat); function FillEditControlWithIdeData: Boolean; public constructor Create(AOwner: TComponent); override; end; TSourceExportExpert = class(TGX_Expert) private // Persistent configuration options FDefaultCopyFormat: TGXCopyFormat; FSaveDir: string; FSaveFilter: Integer; FBackgroundColor: TColor; protected procedure InternalLoadSettings(Settings: TExpertSettings); override; procedure InternalSaveSettings(Settings: TExpertSettings); override; public constructor Create; override; destructor Destroy; override; function GetActionCaption: string; override; class function GetName: string; override; procedure Configure; override; procedure Execute(Sender: TObject); override; procedure UpdateAction(Action: TCustomAction); override; end; implementation {$R *.dfm} uses SysUtils, Windows, Clipbrd, SynEditExport, SynExportHtml, SynExportRtf, SynEditPrint, GX_GenericUtils, GX_GxUtils, GX_OtaUtils, GX_IdeUtils, GX_SynMemoUtils, GX_SourceExportOptions, GX_SharedImages, SynUnicode; const HighlighterDefaultRegKey = '\SourceExport\Highlighters\'; var SourceExportExpert: TSourceExportExpert = nil; function TfmSourceExport.FillEditControlWithIdeData: Boolean; var Lines: TGXUnicodeString; begin Assert(Assigned(FEditor)); FEditor.ClearAll; SetSynEditHighlighter(FEditor, GetGXHighlighterForCurrentSourceEditor); Result := GxOtaGetActiveEditorTextAsUnicodeString(Lines); FEditor.Lines.Text := Lines; end; procedure TfmSourceExport.LoadSettings; resourcestring SCopyText = 'Copy'; SCopyHTML = 'Copy as HTML'; SCopyRTF = 'Copy as RTF'; var CaptionText: string; begin Assert(Assigned(SourceExportExpert)); Assert(Assigned(FEditor)); FEditor.Highlighter.LoadFromRegistry(HKEY_CURRENT_USER, ConfigInfo.GetGExpertsIdeRootRegistryKey + HighlighterDefaultRegKey + FEditor.Highlighter.LanguageName); case SourceExportExpert.FDefaultCopyFormat of cfText: CaptionText := SCopyText; cfHTMLFragment: CaptionText := SCopyHTML; cfRTFFragment: CaptionText := SCopyRTF; else Assert(False, 'Invalid TGXCopyFormat'); end; btnCopy.Caption := '&' + CaptionText; tbnCopy.Hint := CaptionText; mitCopy.Default := True; end; procedure TfmSourceExport.FormActivate(Sender: TObject); resourcestring SDialogFragmentExportTitle = 'Fragment of %s'; var CurrentModuleFileName: string; HasBlockSelection: Boolean; begin CurrentModuleFileName := ExtractFileName(GxOtaGetTopMostEditBufferFileName); HasBlockSelection := FillEditControlWithIdeData; LoadSettings; if HasBlockSelection then edtTitle.Text := Format(SDialogFragmentExportTitle, [CurrentModuleFileName]) else edtTitle.Text := CurrentModuleFileName; end; procedure TfmSourceExport.actRefreshExecute(Sender: TObject); begin FillEditControlWithIdeData; LoadSettings; end; procedure TfmSourceExport.actSaveExecute(Sender: TObject); resourcestring SDialogTitle = 'Save %s As'; var Exporter: TSynCustomExporter; Cursor: IInterface; begin Assert(Assigned(SourceExportExpert)); dlgSave.Title := Format(SDialogTitle, [edtTitle.Text]); dlgSave.FileName := ChangeFileExt(edtTitle.Text, ''); dlgSave.InitialDir := SourceExportExpert.FSaveDir; dlgSave.FilterIndex := SourceExportExpert.FSaveFilter; if GetOpenSaveDialogExecute(dlgSave) then begin Cursor := TempHourGlassCursor; SourceExportExpert.FSaveDir := ExtractFilePath(ExpandFileName(dlgSave.FileName)); SourceExportExpert.FSaveFilter := dlgSave.FilterIndex; if dlgSave.FilterIndex = 1 then Exporter := TSynExporterHTML.Create(nil) else Exporter := TSynExporterRTF.Create(nil); try Exporter.Title := ExtractFileName(dlgSave.FileName); Exporter.UseBackground := True; Exporter.Highlighter := FEditor.Highlighter; Exporter.ExportAsText := True; Exporter.Color := SourceExportExpert.FBackgroundColor; Application.ProcessMessages; Exporter.ExportAll(FEditor.Lines); Exporter.SaveToFile(dlgSave.FileName); finally FreeAndNil(Exporter); end; end; end; procedure TfmSourceExport.CopyToClipboard(CopyFormat: TGXCopyFormat); procedure ExportToClipboard(Exporter: TSynCustomExporter; AsText: Boolean); begin if Exporter = nil then begin Clipboard.AsText := FEditor.Lines.Text; Exit; end; if AsText and (Exporter is TSynExporterHTML) then (Exporter as TSynExporterHTML).CreateHTMLFragment := True; Exporter.Title := edtTitle.Text; Exporter.ExportAsText := AsText; Exporter.Highlighter := FEditor.Highlighter; Exporter.UseBackground := True; Exporter.ExportAll(FEditor.Lines); Exporter.CopyToClipboard; end; var HtmlExporter: TSynCustomExporter; RtfExporter: TSynCustomExporter; begin Assert(Assigned(FEditor)); HtmlExporter := nil; RtfExporter := nil; try HtmlExporter := TSynExporterHTML.Create(nil); RtfExporter := TSynExporterRTF.Create(nil); case CopyFormat of cfText: begin Clipboard.Open; try ExportToClipboard(nil, False); ExportToClipboard(HtmlExporter, False); ExportToClipboard(RtfExporter, False); finally Clipboard.Close; end; end; cfHTMLFragment: ExportToClipboard(HtmlExporter, True); cfRTFFragment: ExportToClipboard(RtfExporter, True); else Assert(False, 'Unknown export type'); end; finally FreeAndNil(HtmlExporter); FreeAndNil(RtfExporter); end; end; procedure TfmSourceExport.actCopyHtmlExecute(Sender: TObject); begin CopyToClipboard(cfHTMLFragment); end; procedure TfmSourceExport.actCopyRtfExecute(Sender: TObject); begin CopyToClipboard(cfRTFFragment); end; procedure TfmSourceExport.actCopyExecute(Sender: TObject); begin Assert(Assigned(SourceExportExpert)); CopyToClipboard(SourceExportExpert.FDefaultCopyFormat); end; procedure TfmSourceExport.actPrintExecute(Sender: TObject); var SynPrint: TSynEditPrint; Cursor: IInterface; begin Assert(Assigned(FEditor)); Assert(Assigned(SourceExportExpert)); Cursor := TempHourGlassCursor; SynPrint := TSynEditPrint.Create(nil); try SynPrint.SynEdit := FEditor; SynPrint.Highlight := (Assigned(FEditor.Highlighter)); SynPrint.Colors := True; SynPrint.TabWidth := 4; SynPrint.Wrap := True; SynPrint.Title := edtTitle.Text; SynPrint.Print finally FreeAndNil(SynPrint); end; end; procedure TfmSourceExport.actConfigureExecute(Sender: TObject); begin Assert(Assigned(SourceExportExpert)); SourceExportExpert.Configure; LoadSettings; end; procedure TfmSourceExport.actHelpExecute(Sender: TObject); begin GxContextHelp(Self, 26); end; procedure TfmSourceExport.actExitExecute(Sender: TObject); begin Close; end; procedure TfmSourceExport.FormClose(Sender: TObject; var Action: TCloseAction); begin Assert(Assigned(SourceExportExpert)); SourceExportExpert.SaveSettings; end; procedure TfmSourceExport.actCopyTextRtfHtmlExecute(Sender: TObject); begin CopyToClipboard(cfText); // This copies all registered clipboard formats at once end; constructor TfmSourceExport.Create(AOwner: TComponent); begin inherited; SetToolbarGradient(ToolBar); // Destroyed with form FEditor := TSynEdit.Create(Self); with FEditor do begin Lines.Clear; Parent := pnlEditor; Align := alClient; TabOrder := 0; Gutter.Width := 0; TabWidth := 4; Options := Options - [eoScrollPastEof, eoScrollPastEol]; end; dlgSave.Options := dlgSave.Options + [ofEnableSizing]; end; { TSourceExportExpert } constructor TSourceExportExpert.Create; begin inherited Create; SourceExportExpert := Self; end; procedure TSourceExportExpert.Execute(Sender: TObject); var Dlg: TfmSourceExport; begin Dlg := TfmSourceExport.Create(nil); try SetFormIcon(Dlg); Dlg.ShowModal; finally FreeAndNil(Dlg); end; end; procedure TSourceExportExpert.InternalLoadSettings(Settings: TExpertSettings); var NewCopyFormat: TGXCopyFormat; begin inherited InternalLoadSettings(Settings); // Do not localize. NewCopyFormat := TGXCopyFormat(Settings.ReadEnumerated('Copy Format', TypeInfo(TGXCopyFormat), 0)); Assert(NewCopyFormat in [Low(TGXCopyFormat)..High(TGXCopyFormat)]); FDefaultCopyFormat := NewCopyFormat; FSaveDir := Settings.ReadString('Save Directory', ''); FSaveFilter := Settings.ReadInteger('Save Format', 1); FBackgroundColor := Settings.ReadInteger('Background', GetIdeEditorBackgroundColor); end; procedure TSourceExportExpert.InternalSaveSettings(Settings: TExpertSettings); begin inherited InternalSaveSettings(Settings); // Do not localize. Settings.WriteInteger('Copy Format', Ord(FDefaultCopyFormat)); Settings.WriteString('Save Directory', FSaveDir); Settings.WriteInteger('Save Format', FSaveFilter); Settings.WriteInteger('Background', FBackgroundColor); end; procedure TSourceExportExpert.Configure; var Dlg: TfmSourceExportOptions; HighlighterRegKey: string; NewCopyFormat: TGXCopyFormat; begin Dlg := TfmSourceExportOptions.Create(nil); try HighlighterRegKey := ConfigInfo.GetGExpertsIdeRootRegistryKey + HighlighterDefaultRegKey + Dlg.SynSampleEditor.Highlighter.LanguageName; Dlg.rbxCopySettings.ItemIndex := Ord(FDefaultCopyFormat); Dlg.SynSampleEditor.Highlighter.LoadFromRegistry(HKEY_CURRENT_USER, HighlighterRegKey); Dlg.BackgroundColor := FBackgroundColor; if Dlg.ShowModal = mrOk then begin Dlg.SynSampleEditor.Highlighter.SaveToRegistry(HKEY_CURRENT_USER, HighlighterRegKey); NewCopyFormat := TGXCopyFormat(Dlg.rbxCopySettings.ItemIndex); Assert(NewCopyFormat in [Low(TGXCopyFormat)..High(TGXCopyFormat)]); FDefaultCopyFormat := NewCopyFormat; FBackgroundColor := Dlg.BackgroundColor; SaveSettings; end; finally FreeAndNil(Dlg); end; end; function TSourceExportExpert.GetActionCaption: string; resourcestring SMenuCaption = '&Source Export...'; begin Result := SMenuCaption; end; class function TSourceExportExpert.GetName: string; begin Result := 'SourceExport'; // Do not localize. end; destructor TSourceExportExpert.Destroy; begin SourceExportExpert := nil; inherited Destroy; end; procedure TSourceExportExpert.UpdateAction(Action: TCustomAction); const SAllowableFileExtensions = '.pas;.inc;.dpr;.txt;.cpp;.hpp;.c;.h;.sql;.htm;.html;.aspx'; begin Action.Enabled := FileMatchesExtensions(GxOtaGetCurrentSourceFile, SAllowableFileExtensions); end; initialization RegisterGX_Expert(TSourceExportExpert); end.
namespace Sugar.Xml; interface uses {$IF COOPER} org.w3c.dom, {$ELSEIF ECHOES} System.Xml.Linq, {$ELSEIF TOFFEE} Foundation, {$ENDIF} Sugar; type XmlAttribute = public class (XmlNode) {$IF NOT TOFFEE} private property &Attribute: {$IF COOPER}Attr{$ELSEIF ECHOES}XAttribute{$ENDIF} read Node as {$IF COOPER}Attr{$ELSEIF ECHOES}XAttribute{$ENDIF}; {$ENDIF} public property NodeType: XmlNodeType read XmlNodeType.Attribute; override; {$IF ECHOES} property Name: String read Attribute.Name.ToString; override; property Value: String read Attribute.Value write Attribute.Value; override; property LocalName: String read Attribute.Name.LocalName; override; {$ENDIF} {$IF ECHOES} property OwnerElement: XmlElement read iif(Attribute.Parent = nil, nil, new XmlElement(Attribute.Parent)); {$ELSEIF TOFFEE} property OwnerElement: XmlElement read iif(Node^.parent = nil, nil, new XmlElement(^libxml.__struct__xmlNode(Node^.parent), OwnerDocument)); {$ELSEIF COOPER} property OwnerElement: XmlElement read iif(Attribute.OwnerElement = nil, nil, new XmlElement(Attribute.OwnerElement)); {$ENDIF} end; implementation end.
unit TycoonVotes; interface uses SysUtils, Collection, Persistent, BackupInterfaces; type TVoteInfo = class fLocation : TObject; fTycoon : TObject; end; TVoteSystem = class(TPersistent) public constructor Create; destructor Destroy; override; private fVotes : TCollection; private function FindInfo(Loc : TObject) : TVoteInfo; function GetVote(Loc : TObject) : TObject; procedure SetVote(Loc, Tycoon : TObject); public property Votes[Location : TObject] : TObject read GetVote write SetVote; default; protected procedure LoadFromBackup(Reader : IBackupReader); override; procedure StoreToBackup (Writer : IBackupWriter); override; public procedure Clear; procedure ClearVotes(Tycoon : TObject); procedure UpdateLocation(OldLoc, NewLoc : TObject); end; procedure RegisterBackup; implementation // TVoteSystem constructor TVoteSystem.Create; begin inherited Create; fVotes := TCollection.Create(0, rkBelonguer); end; destructor TVoteSystem.Destroy; begin fVotes.Free; inherited; end; function TVoteSystem.FindInfo(Loc : TObject) : TVoteInfo; var i : integer; begin i := pred(fVotes.Count); while (i >= 0) and (TVoteInfo(fVotes[i]).fLocation <> Loc) do dec(i); if i >= 0 then result := TVoteInfo(fVotes[i]) else result := nil; end; function TVoteSystem.GetVote(Loc : TObject) : TObject; var Info : TVoteInfo; begin Info := FindInfo(Loc); if Info <> nil then result := Info.fTycoon else result := nil; end; procedure TVoteSystem.SetVote(Loc, Tycoon : TObject); var Info : TVoteInfo; begin Info := FindInfo(Loc); if Info <> nil then Info.fTycoon := Tycoon else begin Info := TVoteInfo.Create; Info.fLocation := Loc; Info.fTycoon := Tycoon; fVotes.Insert(Info); end; end; procedure TVoteSystem.LoadFromBackup(Reader : IBackupReader); var i : integer; aux : string; cnt : integer; Info : TVoteInfo; begin cnt := Reader.ReadInteger('vCount', 0); fVotes := TCollection.Create(cnt, rkBelonguer); for i := 0 to pred(cnt) do begin aux := IntToStr(i); Info := TVoteInfo.Create; Reader.ReadObject('loc' + aux, Info.fLocation, nil); Reader.ReadObject('tyc' + aux, Info.fTycoon, nil); fVotes.Insert(Info); end; end; procedure TVoteSystem.StoreToBackup(Writer : IBackupWriter); var i : integer; aux : string; begin Writer.WriteInteger('vCount', fVotes.Count); for i := 0 to pred(fVotes.Count) do with TVoteInfo(fVotes[i]) do begin aux := IntToStr(i); Writer.WriteObjectRef('loc' + aux, fLocation); Writer.WriteObjectRef('tyc' + aux, fTycoon); end; end; procedure TVoteSystem.Clear; begin fVotes.DeleteAll; end; procedure TVoteSystem.ClearVotes(Tycoon : TObject); var i : integer; begin for i := 0 to pred(fVotes.Count) do if TVoteInfo(fVotes[i]).fTycoon = Tycoon then TVoteInfo(fVotes[i]).fTycoon := nil; end; procedure TVoteSystem.UpdateLocation(OldLoc, NewLoc : TObject); var VoteInfo : TVoteInfo; begin VoteInfo := FindInfo(OldLoc); if VoteInfo <> nil then VoteInfo.fLocation := NewLoc; end; procedure RegisterBackup; begin RegisterClass(TVoteSystem); end; end.
program TESTSETS ( OUTPUT ) ; const CH_CONST = X'4f' ; CH_BLANK = X'20' ; I_NEGATIV1 = - 13 ; I_NEGATIV2 = - 15 ; type OPTYPE = ( PCTS , PCTI , PLOD , PSTR , PLDA , PLOC , PSTO , PLDC , PLAB , PIND , PINC , PPOP , PCUP , PENT , PRET , PCSP , PIXA , PEQU , PNEQ , PGEQ , PGRT , PLEQ , PLES , PUJP , PFJP , PXJP , PCHK , PNEW , PADI , PADR , PSBI , PSBR , PSCL , PFLT , PFLO , PTRC , PNGI , PNGR , PSQI , PSQR , PABI , PABR , PNOT , PAND , PIOR , PDIF , PINT , PUNI , PINN , PMOD , PODD , PMPI , PMPR , PDVI , PDVR , PMOV , PLCA , PDEC , PSTP , PSAV , PRST , PCHR , PORD , PDEF , PRND , PCRD , PXPO , PBGN , PEND , PASE , PSLD , PSMV , PMST , PUXJ , PXLB , PCST , PDFC , PPAK , PADA , PSBA , UNDEF_OP ) ; SET1 = set of CHAR ; SET2 = set of 'A' .. 'I' ; SET3 = set of '0' .. '9' ; FARBE = ( ROT , GELB , GRUEN , BLAU ) ; SET4 = set of FARBE ; SET5 = set of 10 .. 50 ; SET6 = set of 0 .. 255 ; SET7 = set of 100 .. 200 ; SET8 = set of 10000 .. 11000 ; SET9 = set of 300 .. 400 ; SET10 = set of 0 .. 300 ; SET11 = set of - 20 .. - 10 ; SET12 = set of OPTYPE ; TARRAY = array [ - 20 .. - 10 ] of INTEGER ; const X1 : SET1 = [ 'A' .. 'J' , 'S' .. 'Z' ] ; X2 : SET1 = [ '3' .. '7' ] ; X3 : SET8 = [ 10500 .. 10600 ] ; X4 : array [ 1 .. 3 ] of SET8 = ( [ 10100 .. 10200 ] , [ 10220 .. 10300 ] , [ 10500 .. 10600 ] ) ; X5 : array [ 1 .. 5 ] of SET1 = ( [ '0' .. '9' ] , [ 'A' .. 'F' ] , [ 'J' .. 'M' ] , [ '0' .. '5' ] , [ 'S' .. 'V' ] ) ; var S1 : SET1 ; S2 : SET2 ; S3 : SET3 ; S4 : SET4 ; S5 : SET5 ; S6 : SET6 ; S : SET6 ; S7 : SET7 ; S8 : SET8 ; S9 : SET9 ; S10 : SET10 ; S11 : SET11 ; S12 : SET12 ; I : INTEGER ; CH : CHAR ; R : REAL ; S21 : SET1 ; S24 : SET4 ; procedure PRINT_SET ( S : SET1 ) ; var C : CHAR ; CP : -> CHAR ; I : INTEGER ; begin (* PRINT_SET *) WRITE ( 'set: ' ) ; for C := CHR ( 0 ) to CHR ( 255 ) do if C in S then WRITE ( C ) ; WRITELN ; WRITE ( 'set in hex: ' ) ; CP := ADDR ( S ) ; for I := 1 to 32 do begin WRITE ( ORD ( CP -> ) : 1 , ' ' ) ; CP := PTRADD ( CP , 1 ) ; end (* for *) ; WRITELN ; end (* PRINT_SET *) ; procedure PRINT_SET2 ( S : SET6 ) ; var C : INTEGER ; CP : -> CHAR ; I : INTEGER ; begin (* PRINT_SET2 *) WRITE ( 'set: ' ) ; for C := 0 to 255 do if C in S then WRITE ( C ) ; WRITELN ; WRITE ( 'set in hex: ' ) ; CP := ADDR ( S ) ; for I := 1 to 32 do begin WRITE ( ORD ( CP -> ) : 1 , ' ' ) ; CP := PTRADD ( CP , 1 ) ; end (* for *) ; WRITELN ; end (* PRINT_SET2 *) ; begin (* HAUPTPROGRAMM *) WRITELN ( '-13 div 8 = ' , - 13 DIV 8 ) ; WRITELN ( '-13 mod 8 = ' , - 13 MOD 8 ) ; I := - 17 + 13 ; WRITELN ( 'i sollte -4 sein: ' , I ) ; R := - 3.2 + 0.4 ; WRITELN ( 'r sollte -2.8 sein: ' , R : 6 : 1 ) ; CH := 'A' ; S1 := [ 'J' .. 'R' , CH ] ; CH := 'A' ; S1 := [ 'B' , CH , 'A' .. 'R' , CH ] ; CH := 'A' ; S1 := X1 ; S1 := X2 ; /*********************************/ /* S1 := [ 'B', CH .. 'R', CH ]; */ /*********************************/ CH := 'A' ; /*******************************/ /* S1 := [ 'B' , 'A' .. CH ] ; */ /*******************************/ S1 := [ 'B' , 'A' .. CH_CONST ] ; S1 := [ 'B' , CH_BLANK .. 'A' ] ; S1 := [ 'J' .. 'R' ] ; (**********************************) (* PRINT_SET ( [ 'A' .. 'D' ] ) ; *) (**********************************) PRINT_SET ( S1 ) ; CH := 'X' ; S1 := [ CH ] ; PRINT_SET ( S1 ) ; S2 := [ 'C' .. 'E' ] ; PRINT_SET ( S2 ) ; S3 := [ '1' .. '6' ] ; S3 := S3 + [ '7' ] ; S3 := S3 - [ '5' ] ; PRINT_SET ( S3 ) ; S4 := [ GELB , BLAU ] ; S5 := [ 20 .. 30 ] ; S := S5 ; PRINT_SET2 ( S ) ; S6 := S5 ; S5 := S6 ; S := S6 ; PRINT_SET2 ( S ) ; S7 := [ 120 .. 140 ] ; S := S7 ; PRINT_SET2 ( S ) ; S11 := [ I_NEGATIV1 , I_NEGATIV2 ] ; S11 := [ - 13 , - 15 , - 17 .. - 12 ] ; S12 := [ PADI , PADA ] ; for I := - 20 to - 10 do if I in S11 then WRITE ( I : 1 ) ; WRITELN ; S8 := [ 10100 .. 10200 , 10300 .. 10400 ] ; /**************************/ /* weitere aktionen: term */ /**************************/ S1 := X1 ; S1 := [ 'B' .. 'F' , 'T' , 'V' ] ; S1 := [ x'42' .. 'F' , 'T' , 'V' ] ; S1 := X1 * [ 'B' .. 'F' , 'T' , 'V' ] ; S1 := S21 ; S4 := [ GELB , BLAU ] ; S24 := [ ROT ] ; S4 := [ GELB , BLAU ] * S24 ; end (* HAUPTPROGRAMM *) .
{======================================================================================================================= RkDBAddress Unit RK Components - Component Source Unit Components Description ---------------------------------------------------------------------------------------------------------------------- TRzDBAddress This TRkDBAddress component is comprised of the following edit fields: First Name, Last Name, Street, City, and ZIP. The State field is actually a combo box which is populated with the 50 states including the District of Columbia. The edit fields are data-aware, and thus this component can be hooked up to a DataSource. Copyright © 1995-2003 by Ray Konopka. All Rights Reserved. =======================================================================================================================} //{$I RkComps.inc} unit RkDBAddress; interface uses Classes, Messages, Controls, StdCtrls, DB, DBCtrls, Graphics, ExtCtrls, RkDBAddress_Common; type TRkDBAddress = class; {==========================================} {== Aggregate Property Class Definitions ==} {==========================================} TRkDataFields = class( TPersistent ) private FAddress: TRkDBAddress; protected { Property Access Methods } function GetDataSource: TDataSource; function GetDataField( Index: Integer ): TRkDataField; procedure SetDataField( Index: Integer; const Value: TRkDataField ); public constructor Create( Address: TRkDBAddress ); published property DataSource: TDataSource // In D6, this property shows up in OI read GetDataSource; property FirstName: string index 1 read GetDataField write SetDataField; property LastName: string index 2 read GetDataField write SetDataField; property Address1: string index 3 read GetDataField write SetDataField; property Address2: string index 4 read GetDataField write SetDataField; property City: string index 5 read GetDataField write SetDataField; property State: string index 6 read GetDataField write SetDataField; property ZIP: string index 7 read GetDataField write SetDataField; end; TRkFieldCaptions = class( TPersistent ) private FAddress: TRkDBAddress; protected { Property Access Methods } function GetFieldCaption( Index: Integer ): string; procedure SetFieldCaption( Index: Integer; const Value: string ); public constructor Create( Address: TRkDBAddress ); published property FirstName: string index 1 read GetFieldCaption write SetFieldCaption; property LastName: string index 2 read GetFieldCaption write SetFieldCaption; property Address: string index 3 read GetFieldCaption write SetFieldCaption; property City: string index 4 read GetFieldCaption write SetFieldCaption; property State: string index 5 read GetFieldCaption write SetFieldCaption; property ZIP: string index 6 read GetFieldCaption write SetFieldCaption; end; TRkDBAddress = class( TWinControl ) private FEdtFirstName: TDBEdit; FLblFirstName: TLabel; FEdtLastName: TDBEdit; FLblLastName: TLabel; FEdtAddress1: TDBEdit; FEdtAddress2: TDBEdit; FLblAddress: TLabel; FEdtCity: TDBEdit; FLblCity: TLabel; FCbxState: TDBComboBox; FLblState: TLabel; FEdtZIP: TDBEdit; FLblZIP: TLabel; FDataFields: TRkDataFields; // Reference to Aggregate Property Class FFieldCaptions: TRkFieldCaptions; // Reference to Aggregate Property Class FStateList: TStrings; // Defaults to a list of state abbreviations FLabelPosition: TRkLabelPosition; FOnChange: TRkEditChangeEvent; // Change event for all fields function GetCharCase: TEditCharCase; procedure SetCharCase( Value: TEditCharCase ); function GetFieldColor: TColor; procedure SetFieldColor( Value: TColor ); function GetDataSource: TDataSource; procedure SetDataSource( Value: TDataSource ); procedure SetLabelPosition( Value: TRkLabelPosition ); procedure SetStateList( Value: TStrings ); function CreateEdit: TDBEdit; function CreateLabel( ACaption: TCaption ): TLabel; function CreateCombo: TDBComboBox; procedure CreateStateList; procedure DoChange( Sender: TObject ); function GetFontHeight( Font: TFont ): Integer; procedure WMSize( var Msg: TWMSize ); message wm_Size; procedure CMFontChanged( var Msg: TMessage ); message cm_FontChanged; protected procedure Change( Field: TRkEditField; Text: string ); dynamic; procedure CreateWnd; override; procedure PositionControls; virtual; procedure Resize; override; procedure SetDataFields( Value: TRkDataFields ); virtual; procedure SetFieldCaptions( Value: TRkFieldCaptions ); virtual; public constructor Create( AOwner: TComponent ); override; destructor Destroy; override; property EdtFirstName: TDBEdit read FEdtFirstName; published property CharCase: TEditCharCase read GetCharCase write SetCharCase; property FieldColor: TColor read GetFieldColor write SetFieldColor; property DataSource: TDataSource read GetDataSource write SetDataSource; property DataFields: TRkDataFields read FDataFields write SetDataFields; property FieldCaptions: TRkFieldCaptions read FFieldCaptions write SetFieldCaptions; property LabelPosition: TRkLabelPosition read FLabelPosition write SetLabelPosition default lpOnTop; property StateList: TStrings read FStateList write SetStateList; property OnChange: TRkEditChangeEvent read FOnChange write FOnChange; property Font; property ParentFont; end; implementation uses Windows; resourcestring SAddrFirstName = 'First Name'; SAddrLastName = 'Last Name'; SAddrAddress = 'Address'; SAddrCity = 'City'; SAddrState = 'State'; SAddrZIP = 'ZIP'; {===========================} {== TRkDataFields Methods ==} {===========================} constructor TRkDataFields.Create( Address: TRkDBAddress ); begin inherited Create; FAddress := Address; end; function TRkDataFields.GetDataSource: TDataSource; begin Result := FAddress.DataSource; end; function TRkDataFields.GetDataField( Index: Integer ): TRkDataField; begin case Index of 1: Result := FAddress.FEdtFirstName.DataField; 2: Result := FAddress.FEdtLastName.DataField; 3: Result := FAddress.FEdtAddress1.DataField; 4: Result := FAddress.FEdtAddress2.DataField; 5: Result := FAddress.FEdtCity.DataField; 6: Result := FAddress.FCbxState.DataField; 7: Result := FAddress.FEdtZIP.DataField; end; end; procedure TRkDataFields.SetDataField( Index: Integer; const Value: TRkDataField ); begin case Index of 1: FAddress.FEdtFirstName.DataField := Value; 2: FAddress.FEdtLastName.DataField := Value; 3: FAddress.FEdtAddress1.DataField := Value; 4: FAddress.FEdtAddress2.DataField := Value; 5: FAddress.FEdtCity.DataField := Value; 6: FAddress.FCbxState.DataField := Value; 7: FAddress.FEdtZIP.DataField := Value; end; end; {==============================} {== TRkFieldCaptions Methods ==} {==============================} constructor TRkFieldCaptions.Create( Address: TRkDBAddress ); begin inherited Create; FAddress := Address; end; function TRkFieldCaptions.GetFieldCaption( Index: Integer ): string; begin case Index of 1: Result := FAddress.FLblFirstName.Caption; 2: Result := FAddress.FLblLastName.Caption; 3: Result := FAddress.FLblAddress.Caption; 4: Result := FAddress.FLblCity.Caption; 5: Result := FAddress.FLblState.Caption; 6: Result := FAddress.FLblZIP.Caption; end; end; procedure TRkFieldCaptions.SetFieldCaption( Index: Integer; const Value: string ); begin case Index of 1: FAddress.FLblFirstName.Caption := Value; 2: FAddress.FLblLastName.Caption := Value; 3: FAddress.FLblAddress.Caption := Value; 4: FAddress.FLblCity.Caption := Value; 5: FAddress.FLblState.Caption := Value; 6: FAddress.FLblZIP.Caption := Value; end; end; {==========================} {== TRkDBAddress Methods ==} {==========================} constructor TRkDBAddress.Create( AOwner: TComponent ); begin inherited Create( AOwner ); // Don't allow other controls to be dropped onto the address component ControlStyle := ControlStyle - [csAcceptsControls ]; // Clean up is handled when the TComponent ancestor class frees // all components on the Components list. FLblFirstName := CreateLabel( SAddrFirstName ); FEdtFirstName := CreateEdit; FLblLastName := CreateLabel( SAddrLastName ); FEdtLastName := CreateEdit; FLblAddress := CreateLabel( SAddrAddress ); FEdtAddress1 := CreateEdit; FEdtAddress2 := CreateEdit; FLblCity := CreateLabel( SAddrCity ); FEdtCity := CreateEdit; FLblState := CreateLabel( SAddrState ); FCbxState := CreateCombo; FLblZIP := CreateLabel( SAddrZIP ); FEdtZIP := CreateEdit; CreateStateList; FDataFields := TRkDataFields.Create( Self ); FFieldCaptions := TRkFieldCaptions.Create( Self ); Width := 382; Height := 78; LabelPosition := lpOnTop; PositionControls; end; {= TRkDBAddress.Create =} destructor TRkDBAddress.Destroy; begin // No need to destroy the embedded components, because the inherited // destructor will destroy all components on the Components list. // FStateList is not on that list, so we need to destroy it here. FStateList.Free; inherited Destroy; end; function TRkDBAddress.CreateLabel( ACaption: TCaption ): TLabel; begin Result := TLabel.Create( Self ); // Labels are owned by the container Result.Parent := Self; Result.Visible := True; Result.Caption := ACaption; end; function TRkDBAddress.CreateEdit: TDBEdit; begin Result := TDBEdit.Create( Self ); Result.Parent := Self; Result.Visible := True; // Assign OnChange event of each Edit field to point to // TRkDBAddress.DoChange method Result.OnChange := DoChange; end; function TRkDBAddress.CreateCombo: TDBComboBox; begin Result := TDBComboBox.Create( Self ); Result.Parent := Self; Result.Visible := True; Result.Sorted := True; end; procedure TRkDBAddress.CreateWnd; begin inherited CreateWnd; // When CreateWnd is called, the Items list of FCbxState is cleared. // Therefore, the contents of the FStateList are copied back into // FCbxState. // Plus, you cannot add items to a ComboBox until its Parent's window // handle has been allocated. Therefore, this code also serves to // initially populate the ComboBox with state names. FCbxState.Items.Assign( FStateList ); end; procedure TRkDBAddress.CreateStateList; begin FStateList := TStringList.Create; FStateList.BeginUpdate; try FStateList.Add( 'AK' ); // Alaska FStateList.Add( 'AL' ); // Alabama FStateList.Add( 'AR' ); // Arkansas FStateList.Add( 'AZ' ); // Arizona FStateList.Add( 'CA' ); // California FStateList.Add( 'CO' ); // Colorado FStateList.Add( 'CT' ); // Connecticut FStateList.Add( 'DC' ); // District of Columbia FStateList.Add( 'DE' ); // Delaware FStateList.Add( 'FL' ); // Florida FStateList.Add( 'GA' ); // Georgia FStateList.Add( 'HI' ); // Hawaii FStateList.Add( 'IA' ); // Iowa FStateList.Add( 'ID' ); // Idaho FStateList.Add( 'IL' ); // Illinois FStateList.Add( 'IN' ); // Indiana FStateList.Add( 'KS' ); // Kansas FStateList.Add( 'KY' ); // Kentucky FStateList.Add( 'LA' ); // Louisiana FStateList.Add( 'MA' ); // Massachusetts FStateList.Add( 'MD' ); // Maryland FStateList.Add( 'ME' ); // Maine FStateList.Add( 'MI' ); // Michigan FStateList.Add( 'MN' ); // Minnesota FStateList.Add( 'MO' ); // Missouri FStateList.Add( 'MS' ); // Mississippi FStateList.Add( 'MT' ); // Montana FStateList.Add( 'NC' ); // North Carolina FStateList.Add( 'ND' ); // North Dakota FStateList.Add( 'NE' ); // Nebraska FStateList.Add( 'NH' ); // New Hampshire FStateList.Add( 'NJ' ); // New Jersey FStateList.Add( 'NM' ); // New Mexico FStateList.Add( 'NV' ); // Nevada FStateList.Add( 'NY' ); // New York FStateList.Add( 'OH' ); // Ohio FStateList.Add( 'OK' ); // Oklahoma FStateList.Add( 'OR' ); // Oregon FStateList.Add( 'PA' ); // Pennsylvania FStateList.Add( 'RI' ); // Rhode Island FStateList.Add( 'SC' ); // South Carolina FStateList.Add( 'SD' ); // South Dakota FStateList.Add( 'TN' ); // Tennessee FStateList.Add( 'TX' ); // Texas FStateList.Add( 'UT' ); // Utah FStateList.Add( 'VA' ); // Virginia FStateList.Add( 'VT' ); // Vermont FStateList.Add( 'WA' ); // Washington FStateList.Add( 'WI' ); // Wisconsin FStateList.Add( 'WV' ); // West Virginia FStateList.Add( 'WY' ); // Wyoming finally FStateList.EndUpdate; end; end; {= TRkDBAddress.CreateStateList =} procedure TRkDBAddress.SetStateList( Value: TStrings ); begin FStateList.Assign( Value ); end; procedure TRkDBAddress.Change( Field: TRkEditField; Text: string ); begin if Assigned( FOnChange ) then FOnChange( Field, Text ); end; {========================================================================= TRkDBAddress.DoChange This method gets called if the OnChange event occurs for any of the edit fields contained in this component. The Change event dispatch method is called to surface those events to the user. =========================================================================} procedure TRkDBAddress.DoChange( Sender: TObject ); var Field: TRkEditField; begin if Sender = FEdtFirstName then Field := efFirstName else if Sender = FEdtLastName then Field := efLastName else if Sender = FEdtAddress1 then Field := efAddress1 else if Sender = FEdtAddress2 then Field := efAddress2 else if Sender = FEdtCity then Field := efCity else if Sender = FCbxState then Field := efState else Field := efZIP; if Sender = FCbxState then Change( Field, TDBComboBox( Sender ).Text ) else Change( Field, TDBEdit( Sender ).Text ); end; function TRkDBAddress.GetCharCase: TEditCharCase; begin Result := FEdtFirstName.CharCase; end; procedure TRkDBAddress.SetCharCase( Value: TEditCharCase ); begin if Value <> FEdtFirstName.CharCase then begin FEdtFirstName.CharCase := Value; FEdtLastName.CharCase := Value; FEdtAddress1.CharCase := Value; FEdtAddress2.CharCase := Value; FEdtCity.CharCase := Value; FEdtZIP.CharCase := Value; end; end; function TRkDBAddress.GetFieldColor: TColor; begin Result := FEdtFirstName.Color; end; procedure TRkDBAddress.SetFieldColor( Value: TColor ); begin if Value <> FEdtFirstName.Color then begin FEdtFirstName.Color := Value; FEdtLastName.Color := Value; FEdtAddress1.Color := Value; FEdtAddress2.Color := Value; FEdtCity.Color := Value; FCbxState.Color := Value; FEdtZIP.Color := Value; end; end; function TRkDBAddress.GetDataSource: TDataSource; begin // Use FEdtFirstName to get current DataSource Result := FEdtFirstName.DataSource; end; procedure TRkDBAddress.SetDataSource( Value: TDataSource ); begin if Value <> FEdtFirstName.DataSource then begin // Assign All Internal Controls to Same DataSource FEdtFirstName.DataSource := Value; FEdtLastName.DataSource := Value; FEdtAddress1.DataSource := Value; FEdtAddress2.DataSource := Value; FEdtCity.DataSource := Value; FCbxState.DataSource := Value; FEdtZIP.DataSource := Value; end; end; procedure TRkDBAddress.SetDataFields( Value: TRkDataFields ); begin FDataFields.Assign( Value ); end; procedure TRkDBAddress.SetFieldCaptions( Value: TRkFieldCaptions ); begin FFieldCaptions.Assign( Value ); end; function TRkDBAddress.GetFontHeight( Font: TFont ): Integer; var Canvas: TCanvas; begin Canvas := TCanvas.Create; try Canvas.Handle := GetDC( 0 ); try Canvas.Font := Font; Result := Canvas.TextHeight( 'Yy' ); finally ReleaseDC( 0, Canvas.Handle ); end; finally Canvas.Free; end; end; procedure TRkDBAddress.PositionControls; var FldH: Integer; LblH: Integer; Line2, Line3, Line4: Integer; begin LblH := GetFontHeight( Font ); FldH := LblH + GetSystemMetrics( sm_CyBorder ) * 4 + 4; if FLabelPosition = lpOnLeft then begin Line2 := FldH + 4; Line3 := 2 * Line2; Line4 := 3 * Line2; // Arrange fields and labels so that labels are located to the // left of each field FLblFirstName.SetBounds( 0, 2, 65, LblH ); FEdtFirstName.SetBounds( 65, 0, 105, FldH ); FLblLastName.SetBounds( 170, 2, 63, LblH ); FLblLastName.Alignment := taRightJustify; FEdtLastName.SetBounds( 235, 0, 140, FldH ); FLblAddress.SetBounds( 0, Line2 + 2, 65, LblH ); FEdtAddress1.SetBounds( 65, Line2, 310, FldH ); FEdtAddress2.SetBounds( 65, Line3, 310, FldH ); FLblCity.SetBounds( 0, Line4 + 2, 65, LblH ); FEdtCity.SetBounds( 65, Line4, 125, FldH ); FLblState.SetBounds( 190, Line4 + 2, 43, LblH ); FLblState.Alignment := taRightJustify; FCbxState.SetBounds( 235, Line4, 60, FldH ); FLblZIP.SetBounds( 295, Line4 + 2, 28, LblH ); FLblZIP.Alignment := taRightJustify; FEdtZIP.SetBounds( 325, Line4, 50, FldH ); end else // lpOnTop begin Line2 := LblH + FldH + 2; Line3 := 2 * Line2 + 2; Line4 := Line3 + FldH + 2; // Arrange fields and labels so that labels are located above // each field FLblFirstName.SetBounds( 0, 0, 120, LblH ); FEdtFirstName.SetBounds( 0, LblH, 120, FldH ); FLblLastName.SetBounds( 130, 0, 150, LblH ); FLblLastName.Alignment := taLeftJustify; FEdtLastName.SetBounds( 130, LblH, 150, FldH ); FLblAddress.SetBounds( 0, Line2, 280, LblH ); FEdtAddress1.SetBounds( 0, Line2 + LblH, 280, FldH ); FEdtAddress2.SetBounds( 0, Line3, 280, FldH ); FLblCity.SetBounds( 0, Line4, 121, LblH ); FEdtCity.SetBounds( 0, Line4 + LblH, 121, FldH ); FLblState.SetBounds( 130, Line4, 70, LblH ); FLblState.Alignment := taLeftJustify; FCbxState.SetBounds( 130, Line4 + LblH, 70, FldH ); FLblZIP.SetBounds( 210, Line4, 70, LblH ); FLblZIP.Alignment := taLeftJustify; FEdtZIP.SetBounds( 210, Line4 + LblH, 70, FldH ); end; Resize; end; {= TRkDBAddress.PositionControls =} procedure TRkDBAddress.SetLabelPosition( Value: TRkLabelPosition ); begin if FLabelPosition <> Value then begin FLabelPosition := Value; PositionControls; end; end; procedure TRkDBAddress.WMSize( var Msg: TWMSize ); begin inherited; Resize; end; procedure TRkDBAddress.Resize; var FldH: Integer; LblH: Integer; begin inherited Resize; LblH := GetFontHeight( Font ); FldH := LblH + GetSystemMetrics( sm_CyBorder ) * 4 + 4; if FLabelPosition = lpOnLeft then begin Width := 375; Height := ( 4 * FldH ) + 3 * 4; end else begin Width := 280; Height := ( 4 * FldH ) + ( 3 * LblH ) + 8 {4 * LblH + 4 * FldH + 4}; end; end; procedure TRkDBAddress.CMFontChanged( var Msg: TMessage ); begin inherited; // If the font changes, update the position and size of the controls PositionControls; end; end.
unit uBox2DImport; interface uses glr_render2d, glr_math, UPhysics2D, UPhysics2DTypes; const //Коэффициент соотношения размеров физических объектов и объектов на экране //(для внутренних расчетов) //Категорически не рекомендуется изменять без понимания, ЗАЧЕМ C_COEF = 1 / 40; C_COEF_INV = 40; type {Класс box2d-мира} Tglrb2World = class; Tglrb2SimulationEvent = procedure (const FixedDeltaTime: Double) of object; Tglrb2OnContactEvent = procedure (var contact: Tb2Contact) of object; Tglrb2OnPreSolveEvent = procedure (var contact: Tb2Contact; const oldManifold: Tb2Manifold) of object; Tglrb2OnPostSolveEvent = procedure (var contact: Tb2Contact; const impulse: Tb2ContactImpulse) of object; Tglrb2ContactListener = class(Tb2ContactListener) private world: Tglrb2World; public procedure BeginContact(var contact: Tb2Contact); override; procedure EndContact(var contact: Tb2Contact); override; procedure PreSolve(var contact: Tb2Contact; const oldManifold: Tb2Manifold); override; procedure PostSolve(var contact: Tb2Contact; const impulse: Tb2ContactImpulse); override; end; { Tglrb2World } Tglrb2World = class(Tb2World) private FContactListener: Tglrb2ContactListener; FOnBeginContact, FOnEndContact: array of Tglrb2OnContactEvent; FBefore, FAfter: Tglrb2SimulationEvent; FStep, FPhysicTime, FSimulationTime: Single; FIter: Integer; public constructor Create(const gravity: TVector2; doSleep: Boolean; aStep: Single; aIterations: Integer); reintroduce; destructor Destroy; override; procedure Update(const DeltaTime: Double); property OnAfterSimulation: Tglrb2SimulationEvent read FAfter write FAfter; property OnBeforeSimulation: Tglrb2SimulationEvent read FBefore write FBefore; //todo: add/remove for pre and post solves procedure AddOnBeginContact(aEvent: Tglrb2OnContactEvent); procedure AddOnEndContact(aEvent: Tglrb2OnContactEvent); procedure RemoveOnBeginContact(aEvent: Tglrb2OnContactEvent); procedure RemoveOnEndContact(aEvent: Tglrb2OnContactEvent); end; { box2d } Box2D = class public class procedure SyncObjects(b2Body: Tb2Body; renderObject: TglrSprite; aPositionsOnly: Boolean = False); class procedure ReverseSyncObjects(renderObject: TglrSprite; b2Body: Tb2Body); class function ConvertB2ToGL(aVec: TVector2): TglrVec2f; class function ConvertGLToB2(aVec: TglrVec2f): TVector2; class function Box(b2World: Tb2World; const aSprite: TglrSprite; d, f, r: Double; mask, category: UInt16; group: SmallInt): Tb2Body; overload; class function Box(b2World: Tb2World; aPos, aSize: TglrVec2f; aRot: Single; d, f, r: Double; mask, category: UInt16; group: SmallInt): Tb2Body; overload; class function BoxSensor(b2World: Tb2World; aPos: TglrVec2f; aSize: TglrVec2f; aRot: Single; mask, cat: Word; IsStatic: Boolean): Tb2Body; class function BoxStatic(b2World: Tb2World; const aSprite: TglrSprite; d, f, r: Double; mask, category: UInt16; group: SmallInt): Tb2Body; overload; class function BoxStatic(b2World: Tb2World; aPos, aSize: TglrVec2f; aRot: Single; d, f, r: Double; mask, category: UInt16; group: SmallInt): Tb2Body; overload; class function Circle(b2World: Tb2World; aRad: Double; aPos: TglrVec2f; d, f, r: Double; mask, category: UInt16; group: SmallInt): Tb2Body; overload; class function Circle(b2World: Tb2World; const aSprite: TglrSprite; d, f, r: Double; mask, category: UInt16; group: SmallInt): Tb2Body; overload; class function CircleSensor(b2World: Tb2World; aPos: TglrVec2f; aSize: Single; mask, cat: Word; IsStatic: Boolean): Tb2Body; class function ChainStatic(b2World: Tb2World; aPos: TglrVec2f; aVertices: array of TglrVec2f; d, f, r: Double; mask, category: UInt16; group: SmallInt): Tb2Body; class function Polygon(b2World: Tb2World; aPos: TglrVec2f; aVertices: array of TglrVec2f; d, f, r: Double; mask, category: UInt16; group: SmallInt): Tb2Body; end; implementation { Tdfb2World } procedure Tglrb2World.AddOnBeginContact(aEvent: Tglrb2OnContactEvent); var l: Integer; begin if not Assigned(aEvent) then Exit(); l := Length(FOnBeginContact); SetLength(FOnBeginContact, l + 1); FOnBeginContact[l] := aEvent; end; procedure Tglrb2World.AddOnEndContact(aEvent: Tglrb2OnContactEvent); var l: Integer; begin if not Assigned(aEvent) then Exit(); l := Length(FOnEndContact); SetLength(FOnEndContact, l + 1); FOnEndContact[l] := aEvent; end; constructor Tglrb2World.Create(const gravity: TVector2; doSleep: Boolean; aStep: Single; aIterations: Integer); begin inherited Create(gravity{, doSleep}); FStep := aStep; FIter := aIterations; FContactListener := Tglrb2ContactListener.Create(); FContactListener.world := Self; Self.SetContactListener(FContactListener); end; destructor Tglrb2World.Destroy; begin FContactListener.Free(); inherited Destroy; end; procedure Tglrb2World.RemoveOnBeginContact(aEvent: Tglrb2OnContactEvent); var i: Integer; begin //todo: test it for i := 0 to High(FOnBeginContact) do if @FOnBeginContact[i] = @aEvent then begin FOnBeginContact[i] := nil; if i <> High(FOnBeginContact) then Move(FOnBeginContact[i + 1], FOnBeginContact[i], SizeOf(Tglrb2OnContactEvent) * (Length(FOnBeginContact) - (i + 1))); SetLength(FOnBeginContact, Length(FOnBeginContact) - 1); end; end; procedure Tglrb2World.RemoveOnEndContact(aEvent: Tglrb2OnContactEvent); var i: Integer; begin //todo: test it for i := 0 to High(FOnEndContact) do if @FOnEndContact[i] = @aEvent then begin FOnEndContact[i] := nil; if i <> High(FOnEndContact) then Move(FOnEndContact[i + 1], FOnEndContact[i], SizeOf(Tglrb2OnContactEvent) * (Length(FOnEndContact) - (i + 1))); SetLength(FOnEndContact, Length(FOnEndContact) - 1); end; end; procedure Tglrb2World.Update(const DeltaTime: Double); begin FPhysicTime := FPhysicTime + DeltaTime; while FSimulationTime <= FPhysicTime do begin FSimulationTime := FSimulationTime + FStep; if Assigned(FBefore) then FBefore(FStep); Step(FStep, FIter, FIter, False); if Assigned(FAfter) then FAfter(FStep); end; end; class procedure Box2D.SyncObjects(b2Body: Tb2Body; renderObject: TglrSprite; aPositionsOnly: Boolean); var pos2d: TglrVec2f; begin pos2d := Vec2f(b2Body.GetPosition.x, b2Body.GetPosition.y) * C_COEF_INV; renderObject.Position.x := pos2d.x; renderObject.Position.y := pos2d.y; if not aPositionsOnly then renderObject.Rotation := b2Body.GetAngle * rad2deg; end; class procedure Box2D.ReverseSyncObjects(renderObject: TglrSprite; b2Body: Tb2Body); var p: TglrVec2f; begin p := Vec2f(renderObject.AbsoluteMatrix.Pos) * C_COEF; b2Body.SetTransform(ConvertGLToB2(p), renderObject.Rotation * deg2rad); // SyncObjects(b2Body, renderObject); end; class function Box2D.ConvertB2ToGL(aVec: TVector2): TglrVec2f; begin Result := Vec2f(aVec.x, aVec.y); end; class function Box2D.ConvertGLToB2(aVec: TglrVec2f): TVector2; begin Result.SetValue(aVec.x, aVec.y); end; class function Box2D.Box(b2World: Tb2World; const aSprite: TglrSprite; d, f, r: Double; mask, category: UInt16; group: SmallInt): Tb2Body; var BodyDef: Tb2BodyDef; ShapeDef: Tb2PolygonShape; FixtureDef: Tb2FixtureDef; begin FixtureDef := Tb2FixtureDef.Create; ShapeDef := Tb2PolygonShape.Create; BodyDef := Tb2BodyDef.Create; with BodyDef do begin bodyType := b2_dynamicBody; position := ConvertGLToB2(Vec2f(aSprite.Position) * C_COEF); angle := aSprite.Rotation * deg2rad; end; with ShapeDef do begin SetAsBox(aSprite.Width / 2 * C_COEF, aSprite.Height / 2 * C_COEF); end; with FixtureDef do begin shape := ShapeDef; density := d; friction := f; restitution := r; filter.maskBits := mask; filter.categoryBits := category; filter.groupIndex := group; end; Result := b2World.CreateBody(BodyDef); Result.CreateFixture(FixtureDef); Result.SetSleepingAllowed(False); end; {var aCenter: TdfVec2f; begin case aSprite.PivotPoint of ppTopLeft: ; ppTopRight: ; ppBottomLeft: ; ppBottomRight: ; ppCenter: aCenter := dfVec2f(0, 0); ppTopCenter: ; ppBottomCenter: ; ppCustom: ; end; Result := dfb2InitBox(b2World, aSprite.Position, dfVec2f(aSprite.Width * 0.5, aSprite.Height * 0.5), aSprite.Rotation, d, f, r, mask, category, group); end; } class function Box2D.Box(b2World: Tb2World; aPos, aSize: TglrVec2f; aRot: Single; d, f, r: Double; mask, category: UInt16; group: SmallInt): Tb2Body; var BodyDef: Tb2BodyDef; ShapeDef: Tb2PolygonShape; FixtureDef: Tb2FixtureDef; begin FixtureDef := Tb2FixtureDef.Create; ShapeDef := Tb2PolygonShape.Create; BodyDef := Tb2BodyDef.Create; with BodyDef do begin bodyType := b2_dynamicBody; position := ConvertGLToB2(aPos * C_COEF); angle := aRot * deg2rad; end; with ShapeDef do begin SetAsBox(aSize.x * 0.5 * C_COEF, aSize.y * 0.5 * C_COEF); end; with FixtureDef do begin shape := ShapeDef; density := d; friction := f; restitution := r; filter.maskBits := mask; filter.categoryBits := category; filter.groupIndex := group; end; Result := b2World.CreateBody(BodyDef); Result.CreateFixture(FixtureDef); Result.SetSleepingAllowed(False); end; class function Box2D.Circle(b2World: Tb2World; aRad: Double; aPos: TglrVec2f; d, f, r: Double; mask, category: UInt16; group: SmallInt): Tb2Body; var BodyDef: Tb2BodyDef; ShapeDef: Tb2CircleShape; FixtureDef: Tb2FixtureDef; begin FixtureDef := Tb2FixtureDef.Create; ShapeDef := Tb2CircleShape.Create; BodyDef := Tb2BodyDef.Create; with BodyDef do begin bodyType := b2_dynamicBody; position := ConvertGLToB2(aPos * C_COEF); end; with ShapeDef do begin m_radius := aRad * C_COEF; end; with FixtureDef do begin shape := ShapeDef; density := d; friction := f; restitution := r; filter.maskBits := mask; filter.categoryBits := category; filter.groupIndex := group; end; Result := b2World.CreateBody(BodyDef); Result.CreateFixture(FixtureDef); Result.SetSleepingAllowed(False); end; class function Box2D.Circle(b2World: Tb2World; const aSprite: TglrSprite; d, f, r: Double; mask, category: UInt16; group: SmallInt): Tb2Body; begin Result := Circle(b2World, aSprite.Width / 2, Vec2f(aSprite.Position), d, f, r, mask, Category, group); end; class function Box2D.BoxStatic(b2World: Tb2World; const aSprite: TglrSprite; d, f, r: Double; mask, category: UInt16; group: SmallInt): Tb2Body; begin Result := BoxStatic(b2World, Vec2f(aSprite.Position), Vec2f(aSprite.Width, aSprite.Height), aSprite.Rotation, d, f, r, mask, category, group); end; class function Box2D.BoxStatic(b2World: Tb2World; aPos, aSize: TglrVec2f; aRot: Single; d, f, r: Double; mask, category: UInt16; group: SmallInt): Tb2Body; overload; var BodyDef: Tb2BodyDef; ShapeDef: Tb2PolygonShape; FixtureDef: Tb2FixtureDef; begin FixtureDef := Tb2FixtureDef.Create; ShapeDef := Tb2PolygonShape.Create; BodyDef := Tb2BodyDef.Create; with BodyDef do begin bodyType := b2_staticBody; position := ConvertGLToB2(aPos * C_COEF); angle := aRot * deg2rad; end; with ShapeDef do begin SetAsBox(aSize.x * 0.5 * C_COEF, aSize.y * 0.5 * C_COEF); end; with FixtureDef do begin shape := ShapeDef; density := d; friction := f; restitution := r; filter.maskBits := mask; filter.categoryBits := category; filter.groupIndex := group; end; Result := b2World.CreateBody(BodyDef); Result.CreateFixture(FixtureDef); Result.SetSleepingAllowed(True); end; class function Box2D.ChainStatic(b2World: Tb2World; aPos: TglrVec2f; aVertices: array of TglrVec2f; d, f, r: Double; mask, category: UInt16; group: SmallInt): Tb2Body; var BodyDef: Tb2BodyDef; ShapeDef: Tb2ChainShape; FixtureDef: Tb2FixtureDef; Ar: TVectorArray; i: Integer; begin FixtureDef := Tb2FixtureDef.Create; //ShapeDef := Tb2ChainShape.Create; BodyDef := Tb2BodyDef.Create; with BodyDef do begin bodyType := b2_staticBody; position := ConvertGLToB2(aPos * C_COEF); angle := 0; end; SetLength(Ar, Length(aVertices)); for i := 0 to High(aVertices) do Ar[i] := ConvertGLToB2(aVertices[i] * C_COEF); ShapeDef := Tb2ChainShape.CreateChain(@Ar[0], Length(Ar)); with FixtureDef do begin shape := ShapeDef; density := d; friction := f; restitution := r; filter.maskBits := mask; filter.categoryBits := category; filter.groupIndex := group; end; Result := b2World.CreateBody(BodyDef); Result.CreateFixture(FixtureDef); Result.SetSleepingAllowed(True); end; class function Box2D.Polygon(b2World: Tb2World; aPos: TglrVec2f; aVertices: array of TglrVec2f; d, f, r: Double; mask, category: UInt16; group: SmallInt): Tb2Body; var BodyDef: Tb2BodyDef; ShapeDef: Tb2PolygonShape; FixtureDef: Tb2FixtureDef; Ar: TVectorArray; i: Integer; begin SetLength(Ar, Length(aVertices)); for i := 0 to High(aVertices) do Ar[i] := ConvertGLToB2(aVertices[i] * C_COEF); FixtureDef := Tb2FixtureDef.Create; ShapeDef := Tb2PolygonShape.Create; BodyDef := Tb2BodyDef.Create; with BodyDef do begin bodyType := b2_dynamicBody; position := ConvertGLToB2(aPos * C_COEF); //angle := aRot * deg2rad; end; with ShapeDef do begin ShapeDef.SetVertices(@Ar[0], Length(Ar)); // SetAsBox(aSize.x * 0.5 * C_COEF, aSize.y * 0.5 * C_COEF); end; with FixtureDef do begin shape := ShapeDef; density := d; friction := f; restitution := r; filter.maskBits := mask; filter.categoryBits := category; filter.groupIndex := group; end; Result := b2World.CreateBody(BodyDef); Result.CreateFixture(FixtureDef); Result.SetSleepingAllowed(False); end; class function Box2D.BoxSensor(b2World: Tb2World; aPos: TglrVec2f; aSize: TglrVec2f; aRot: Single; mask, cat: Word; IsStatic: Boolean): Tb2Body; var BodyDef: Tb2BodyDef; ShapeDef: Tb2PolygonShape; FixtureDef: Tb2FixtureDef; begin FixtureDef := Tb2FixtureDef.Create; ShapeDef := Tb2PolygonShape.Create; BodyDef := Tb2BodyDef.Create; with BodyDef do begin if IsStatic then bodyType := b2_staticBody else bodyType := b2_dynamicBody; position := ConvertGLToB2(aPos * C_COEF); angle := aRot * deg2rad; end; with ShapeDef do begin SetAsBox(aSize.x * 0.5 * C_COEF, aSize.y * 0.5 * C_COEF); end; with FixtureDef do begin shape := ShapeDef; isSensor := True; filter.maskBits := mask; filter.categoryBits := cat; end; Result := b2World.CreateBody(BodyDef); Result.CreateFixture(FixtureDef); Result.SetSleepingAllowed(False); end; class function Box2D.CircleSensor(b2World: Tb2World; aPos: TglrVec2f; aSize: Single; mask, cat: Word; IsStatic: Boolean): Tb2Body; var BodyDef: Tb2BodyDef; ShapeDef: Tb2CircleShape; FixtureDef: Tb2FixtureDef; begin FixtureDef := Tb2FixtureDef.Create; ShapeDef := Tb2CircleShape.Create; BodyDef := Tb2BodyDef.Create; with BodyDef do begin if IsStatic then bodyType := b2_staticBody else bodyType := b2_dynamicBody; position := ConvertGLToB2(aPos * C_COEF); end; with ShapeDef do begin m_radius := aSize * C_COEF; end; with FixtureDef do begin shape := ShapeDef; isSensor := True; filter.maskBits := mask; filter.categoryBits := cat; end; Result := b2World.CreateBody(BodyDef); Result.CreateFixture(FixtureDef); Result.SetSleepingAllowed(True); end; { Tglrb2ContactListener } procedure Tglrb2ContactListener.BeginContact(var contact: Tb2Contact); var i: Integer; begin inherited; for i := 0 to High(world.FOnBeginContact) do world.FOnBeginContact[i](contact); end; procedure Tglrb2ContactListener.EndContact(var contact: Tb2Contact); var i: Integer; begin inherited; for i := 0 to High(world.FOnEndContact) do world.FOnEndContact[i](contact); end; procedure Tglrb2ContactListener.PostSolve(var contact: Tb2Contact; const impulse: Tb2ContactImpulse); begin inherited; end; procedure Tglrb2ContactListener.PreSolve(var contact: Tb2Contact; const oldManifold: Tb2Manifold); begin inherited; end; end.
{ Routines that handle jump targets. * * Syntax processing routines need to primarily branch on three different * criteria: * * 1 - Furthest input stream point reached on error re-parse. * * 2 - Syntax matched template. * * 3 - Syntax did not match template. * * A parsing routine must immediately exit with FALSE and all SYN library state * left as-is on case 1. Whenever the input stream position could be advanced, * the end of re-parse must be checked. If true, execution must jump to the * label indicated by LABEL_ERR_P. This pointer is initialized to NIL when * the parsing routine is first created. It must be filled in on the first * attempt to use it. The parsing routine cleanup code in SST_R_SYN_DEFINE * will write the label and the error handling code follwing it when the * label exists. * * Code that writes a syntax parsing function should call SST_R_SYN_ERR_CHECK * immediately after any action that could advance the input stream parsing * position. SST_R_SYN_ERR_CHECK creates the error abort label if necessary, * and writes the conditional jump to that label on end of error re-parse * encountered. * * The jump targets mechanism implemented in this module is to handle jumping * depending on whether the input stream matched the expected syntax. This * always assumes case 1 has already been handled. Put another way, hitting * the error re-parse end is handled as an exception. Syntax matched yes/no * are normal run time cases, and is what the facilities in this module * support. * * At the level of a whole syntax parsing routine, the routine returns TRUE * when the input stream matched the syntax and FALSE if not. In the FALSE * case, the input stream position and syntax tree being built are restored to * their state on entry to the routine. * * Internally in a syntax parsing routine, there may be subordinate sections * that handle syntax matched yes/no in private ways to ultimately derive the * yes/no state for the whole section. Such sections may be nested. * * The jump targets mechanism is a way to keep track of what actions should be * taken for each yes/no case in each nested section. A jump targets data * structure, JUMP_TARGETS_T, keeps track of where to go for each syntax * matched yes/no case. The options for each case are fall thru, jump to * a specific label, or do whatever it says in another jump target for that * case. * * Code that writes syntax parsing functions would use the routines here in * the following ways: * * SST_R_SYN_JTARG_INIT (JTARG) * * Initializes the jump targets JTARG to fall thru for all cases. This * routine should only be called to initialize the top level jump targets. * This is therfore called once in SST_R_SYN_DEFINE when setting up for * writing a syntax parsing function. Subsequent code that writes the * syntax parsing function would generally not call this routine. * * SST_R_SYN_JTARG_SUB (JTARG, SUBTARG, MOD_YES, MOD_NO) * * Used to create jump targets for a subordinate section of code. * * SST_R_SYN_JTARG_GOTO (JTARG, FLAGS) * * Write the conditional GOTOs for the syntax matched yes/no cases listed * in FLAGS. * * SST_R_SYN_JTARG_HERE (JTARG) * * Writes labels, as needed, at the current position for cases indicated to * fall thru. This is how labels for jump locations are written into the * syntax parsing function. } module sst_r_syn_jtarg; define sst_r_syn_jtarg_init; define sst_r_syn_jtarg_sub; define sst_r_syn_jtarg_label; define sst_r_syn_jtarg_label_define; define sst_r_syn_jtarg_label_here; define sst_r_syn_jtarg_label_goto; define sst_r_syn_jtarg_sym; define sst_r_syn_jtarg_here; define sst_r_syn_jtarg_goto_targ; define sst_r_syn_jtarg_goto; %include 'sst_r_syn.ins.pas'; { ******************************************************************************** * * Subroutine SST_R_SYN_JTARG_INIT (JTARG) * * Initialize the jump targets JTARG. The target for each case is set to fall * thru. } procedure sst_r_syn_jtarg_init ( {initialize jump targets} out jtarg: jump_targets_t); {the set of jump targets to initialize} val_param; begin jtarg.yes.flags := [jflag_fall_k]; jtarg.yes.lab_p := nil; jtarg.no.flags := [jflag_fall_k]; jtarg.no.lab_p := nil; end; { ******************************************************************************** * * Local subroutine TARG_SUB (JTI, JTO, JSYM_P) * * Create individual jump target JTO from template JTI with modifier JSYM_P. } procedure targ_sub ( {create subordinate target for one case} in var jti: jump_target_t; {template target} out jto: jump_target_t; {output target} in jsym_p: sst_symbol_p_t); {label to jump to, or LAB_xxx_K special values} val_param; begin { * Handle "same" modifier case. } if jsym_p = lab_same_k then begin {modifier is "same" ?} jto.flags := jti.flags + [jflag_indir_k]; {make indirect to input target} jto.indir_p := addr(jti); return; end; { * Handle "fall thru" modifier case. } if jsym_p = lab_fall_k then begin {modifier is "fall thru" ?} jto.flags := [jflag_fall_k]; jto.lab_p := nil; return; end; { * Modifier is explicit label. } jto.flags := []; jto.lab_p := jsym_p; end; { ******************************************************************************** * * Subroutine SST_R_SYN_JTARG_SUB (JTARG, SUBTARG, LAB_YES_P, LAB_NO_P) * * Create subordinate jump targets in SUBTARG, using the existing jump targets * JTARG as a template. * * LAB_YES_P and LAB_NO_P point to labels to jump to for syntax matched yes and * no cases. Or, these can have the following special values: * * LAB_FALL_K - The jump target is to fall thru. No jump is required. * * LAB_SAME_K - The jump location in SUBTARG will be the same as in JTARG. * This creates an indirect reference in SUBTARG to JTARG. } procedure sst_r_syn_jtarg_sub ( {make new jump targets from old and modifiers} in var jtarg: jump_targets_t; {old jump targets} out subtarg: jump_targets_t; {resulting new jump targets} in lab_yes_p: sst_symbol_p_t; {label to jump to for YES case, or LAB_xxx_K} in lab_no_p: sst_symbol_p_t); {label to jump to for NO case, or LAB_xxx_K} val_param; begin targ_sub (jtarg.yes, subtarg.yes, lab_yes_p); targ_sub (jtarg.no, subtarg.no, lab_no_p); end; { ******************************************************************************** * * Subroutine SST_R_SYN_JTARG_LABEL (LAB_P) * * Create a new label and return LAB_P pointing to the symbol for that label. } procedure sst_r_syn_jtarg_label ( {create a label symbol} out lab_p: sst_symbol_p_t); {returned pointer to the label symbol} val_param; const max_msg_parms = 1; {max parameters we can pass to a message} var name: string_var32_t; {label name} token: string_var32_t; {scratch token for number conversion} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; stat: sys_err_t; begin name.max := sizeof(name.str); {init local var strings} token.max := sizeof(token.str); string_vstring (name, 'lab', 3); {set static part of label name} string_f_int (token, seq_label); {make sequence number string} seq_label := seq_label + 1; {update sequence number for next time} string_append (name, token); {make full label name} sst_symbol_new_name (name, lab_p, stat); {create the new symbol} sys_msg_parm_vstr (msg_parm[1], name); sys_error_abort (stat, 'sst_syn_read', 'symbol_label_create', msg_parm, 1); lab_p^.symtype := sst_symtype_label_k; {fill in new label symbol descriptor} lab_p^.label_opc_p := nil; {opcode defining label not created yet} end; { ******************************************************************************** * * Subroutine SST_R_SYN_JTARG_LABEL_DEFINE (LAB) * * Define the existing label LAB at the current position in the code being * written. } procedure sst_r_syn_jtarg_label_define ( {define existing label at current position} in var lab: sst_symbol_t); {label symbol} val_param; begin sst_opcode_new; {create label target opcode} sst_opc_p^.opcode := sst_opc_label_k; {opcode is a label} sst_opc_p^.label_sym_p := addr(lab); {point to the label symbol} lab.label_opc_p := sst_opc_p; {link label symbol to defining opcode} end; { ******************************************************************************** * * Subroutine SST_R_SYN_JTARG_LABEL_HERE (LAB_P) * * Create a new label and define it at the current position in the code being * written. LAB_P is returned pointing to the symbol for the new label. } procedure sst_r_syn_jtarg_label_here ( {create a label symbol at the current location} out lab_p: sst_symbol_p_t); {returned pointer to the label symbol} val_param; begin sst_r_syn_jtarg_label (lab_p); {create the new label} sst_r_syn_jtarg_label_define (lab_p^); {define it at the current position} end; { ******************************************************************************** * * Subroutine SST_R_SYN_JTARG_LABEL_GOTO (LAB) * * Jump to the label LAB. } procedure sst_r_syn_jtarg_label_goto ( {unconditionally jump to a label} in var lab: sst_symbol_t); {label to jump to} val_param; begin sst_opcode_new; {create new opcode} sst_opc_p^.opcode := sst_opc_goto_k; {this opcode is a GOTO} sst_opc_p^.goto_sym_p := addr(lab); {set pointer to label to go to} end; { ******************************************************************************** * * Subroutine SST_R_SYN_JTARG_SYM (JT, SYM_P) * * Return pointer to the label corresponding to jump target JT. A label is * implicitly created, if one doesn't already exist. } procedure sst_r_syn_jtarg_sym ( {get or make symbol for jump target label} in out jt: jump_target_t; {descriptor for this jump target} out sym_p: sst_symbol_p_t); {returned pointing to jump label symbol} val_param; var jt_p: jump_target_p_t; {pointer to base jump target descriptor} begin jt_p := addr(jt); {init base descriptor to first descriptor} while jflag_indir_k in jt_p^.flags do begin {this is an indirect descriptor ?} jt_p := jt_p^.indir_p; {resolve one level of indirection} end; {back to resolve next level of indirection} { * JT_P is pointing to the base jump target descriptor. } if jt_p^.lab_p <> nil then begin {a label symbol already exists here ?} sym_p := jt_p^.lab_p; {fetch label symbol pointer from jump desc} return; end; { * No label symbol exists for this jump target. Create one and pass back SYM_P * pointing to it. } sst_r_syn_jtarg_label (sym_p); {create the new label} jt_p^.lab_p := sym_p; {save symbol pointer in jump descriptor} end; { ******************************************************************************** * * Local subroutine TARG_HERE (JT) * * Write the label for the jump target JT in the current location, if the jump * target is fall thru, has a label, and is the base jump target. } procedure targ_here ( in jt: jump_target_t); {descriptor for jump target to process} val_param; begin if jflag_indir_k in jt.flags then return; {this is not a base jump target ?} if not (jflag_fall_k in jt.flags) then return; {not fall thru case ?} if jt.lab_p = nil then return; {no label used for this jump target ?} sst_r_syn_jtarg_label_define (jt.lab_p^); {define label at this location} end; { ******************************************************************************** * * Subroutine SST_R_SYN_JTARG_HERE (JTARG) * * Write labels here for jump targets in JTARG as appropriate. } procedure sst_r_syn_jtarg_here ( {write implicit labels created by jump targs} in jtarg: jump_targets_t); {jump targets descriptor now done with} val_param; begin targ_here (jtarg.yes); {write labels as needed for each case} targ_here (jtarg.no); end; { ******************************************************************************** * * Subroutine SST_R_SYN_JTARG_GOTO_TARG (JT) * * Unconditionally go to the location specified by the jump target JT. Nothing * is done is the jump target is set to fall thru. } procedure sst_r_syn_jtarg_goto_targ ( {unconditionally go as indicated by target} in out jt: jump_target_t); {jump target for the specific case} val_param; begin if {just fall thru, nothing to do ?} (jflag_fall_k in jt.flags) and {fall thru indicated ?} (not (jflag_indir_k in jt.flags)) {but not also indirect ?} then return; sst_opcode_new; {create GOTO opcode} sst_opc_p^.opcode := sst_opc_goto_k; sst_r_syn_jtarg_sym ( {get or make jump target symbol} jt, {jump target descriptor} sst_opc_p^.goto_sym_p); {returned pointer to label symbol} end; { ******************************************************************************** * * Subroutine SST_R_SYN_JTARG_GOTO (JTARG, FLAGS) * * Jump as specified by the jump targets JTARG. FLAGS indicates which cases to * write conditional code to go to. Cases not listed in FLAGS are ignored. * The local MATCH variable indicates the syntax matched yes/no condition. } procedure sst_r_syn_jtarg_goto ( {go to jump targets, as required} in out jtarg: jump_targets_t; {where to go for each case} in flags: jtarg_t); {which cases to write code for} val_param; var jump_yes, jump_no: boolean; {need to write conditional jumps for yes/no} begin jump_yes := {need to write cond jump for YES case ?} (jtarg_yes_k in flags) and {this jump target enabled ?} ( (not (jflag_fall_k in jtarg.yes.flags)) or {not fall thru ?} (jflag_indir_k in jtarg.yes.flags)); {indirect reference ?} jump_no := {need to write cond jump for NO case ?} (jtarg_no_k in flags) and {this jump target enabled ?} ( (not (jflag_fall_k in jtarg.no.flags)) or {not fall thru ?} (jflag_indir_k in jtarg.no.flags)); {indirect reference ?} if not (jump_yes or jump_no) then return; {nothing to do ?} { * Handle the special case of only jumping on the NO case. The conditional * expression will the NOT MATCH, with the jump performed on TRUE. } if jump_no and (not jump_yes) then begin {only jumping on NO case ?} sst_opcode_new; {create new opcode for IF} sst_opc_p^.opcode := sst_opc_if_k; sst_opc_p^.if_exp_p := match_not_exp_p; {NOT MATCH variable value} sst_opc_p^.if_false_p := nil; {there is no FALSE case code} sst_opcode_pos_push (sst_opc_p^.if_true_p); {set up for writing TRUE code} sst_opcode_new; {create GOTO opcode} sst_opc_p^.opcode := sst_opc_goto_k; sst_r_syn_jtarg_sym ( {get or make jump target symbol} jtarg.no, {jump target descriptor} sst_opc_p^.goto_sym_p); {returned pointer to label symbol} sst_opcode_pos_pop; {done writing TRUE case opcodes} return; end; { * Jumping on the YES case, and maybe also on the NO case. The conditional * expression will be MATCH. } sst_opcode_new; {create new opcode for IF} sst_opc_p^.opcode := sst_opc_if_k; sst_opc_p^.if_exp_p := match_exp_p; {MATCH variable value} sst_opc_p^.if_false_p := nil; {init to no FALSE case code} sst_opcode_pos_push (sst_opc_p^.if_true_p); {set up for writing TRUE code} sst_opcode_new; {create GOTO opcode} sst_opc_p^.opcode := sst_opc_goto_k; sst_r_syn_jtarg_sym ( {get or make jump target symbol} jtarg.yes, {jump target descriptor} sst_opc_p^.goto_sym_p); {returned pointer to label symbol} sst_opcode_pos_pop; {done writing TRUE case opcodes} if jump_no then begin {write jump for NO case ?} sst_opcode_pos_push (sst_opc_p^.if_false_p); {set up for writing FALSE code} sst_opcode_new; {create GOTO opcode} sst_opc_p^.opcode := sst_opc_goto_k; sst_r_syn_jtarg_sym ( {get or make jump target symbol} jtarg.no, {jump target descriptor} sst_opc_p^.goto_sym_p); {returned pointer to label symbol} sst_opcode_pos_pop; {done writing TRUE case opcodes} end; end;
unit formTestAction; interface uses SysUtils, Types, Classes, Variants, QTypes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QComCtrls, QExtCtrls; type TfrmTestAction = class(TForm) ScrollBox1: TScrollBox; Panel1: TPanel; edtSpeed: TSpinEdit; Label4: TLabel; imgAnimation: TImage; Timer: TTimer; procedure edtSpeedChanged(Sender: TObject; NewValue: Integer); procedure TimerTimer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } num_bmps: integer; current_frame: integer; bmps: array[0..1000] of TBitmap; end; var frmTestAction: TfrmTestAction; implementation {$R *.xfm} procedure TfrmTestAction.edtSpeedChanged(Sender: TObject; NewValue: Integer); begin Timer.Interval := (edtSpeed.Value*1000) div 60; end; procedure TfrmTestAction.TimerTimer(Sender: TObject); begin if not frmTestAction.Visible then exit; Inc(current_frame); if current_frame>=num_bmps then begin current_frame := -1; exit; end; if bmps[current_frame] <> nil then imgAnimation.Picture.Assign(bmps[current_frame]); end; procedure TfrmTestAction.FormCreate(Sender: TObject); var i: integer; begin num_bmps := 0; current_frame := -1; for i := 0 to 1000 do bmps[i] := nil; end; procedure TfrmTestAction.FormClose(Sender: TObject; var Action: TCloseAction); var i: integer; begin for i := 0 to num_bmps-1 do begin if bmps[i]<>nil then bmps[i].Destroy; bmps[i]:=nil; end; num_bmps:=0; current_frame:=-1; end; end.
unit EcconomyRelay; interface uses Persistent, Collection, Kernel, BackupInterfaces, Accounts; const MinRecessionFact = 0.25; MaxStimulusFact = 1.25; RecessionFactDec = 0.25/(24*365); RecessionFactInc = 0.25/(24*365); type TEcconomyRelay = class(TPersistent) public constructor Create; destructor Destroy; override; private fAreas : TCollection; public procedure Update; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; implementation uses ServiceBlock, ClassStorage, MathUtils; // TEcconomyRelay constructor TEcconomyRelay.Create; begin inherited; fAreas := TCollection.Create(0, rkUse); end; destructor TEcconomyRelay.Destroy; begin fAreas.Free; inherited; end; procedure TEcconomyRelay.Update; var count : integer; i : integer; Service : TMetaService; sum : TMoney; avg : TMoney; begin count := fAreas.Count; if count = 0 then begin count := TheClassStorage.ClassCount[tidClassFamily_Services]; for i := 0 to pred(count) do begin Service := TMetaService(TheClassStorage.ClassByIdx[tidClassFamily_Services, i]); fAreas.Insert(Service); end; end; if count > 0 then begin sum := 0; for i := 0 to pred(count) do begin Service := TMetaService(fAreas[i]); sum := sum + Service.SaleProfit; end; avg := sum/count; for i := 0 to pred(count) do begin Service := TMetaService(fAreas[i]); if Service.SaleProfit > avg then Service.RecFact := realmax(MinRecessionFact, Service.RecFact - RecessionFactDec) else if Service.SaleProfit < avg then Service.RecFact := realmin(MaxStimulusFact, Service.RecFact + RecessionFactInc); end; end; end; procedure TEcconomyRelay.LoadFromBackup(Reader : IBackupReader); begin // >> end; procedure TEcconomyRelay.StoreToBackup(Writer : IBackupWriter); begin // >> end; end.
unit system16a_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,m68000,main_engine,controls_engine,gfx_engine,rom_engine,pal_engine, ppi8255,sound_engine,ym_2151,fd1089,dialogs,mcs48,dac; function iniciar_system16a:boolean; implementation const //Shinobi shinobi_rom:array[0..3] of tipo_roms=( (n:'epr-12010.43';l:$10000;p:0;crc:$7df7f4a2),(n:'epr-12008.26';l:$10000;p:$1;crc:$f5ae64cd), (n:'epr-12011.42';l:$10000;p:$20000;crc:$9d46e707),(n:'epr-12009.25';l:$10000;p:$20001;crc:$7961d07e)); shinobi_sound:tipo_roms=(n:'epr-11267.12';l:$8000;p:0;crc:$dd50b745); shinobi_n7751:tipo_roms=(n:'7751.bin';l:$400;p:0;crc:$6a9534fc); shinobi_n7751_data:tipo_roms=(n:'epr-11268.1';l:$8000;p:0;crc:$6d7966da); shinobi_tiles:array[0..2] of tipo_roms=( (n:'epr-11264.95';l:$10000;p:0;crc:$46627e7d),(n:'epr-11265.94';l:$10000;p:$10000;crc:$87d0f321), (n:'epr-11266.93';l:$10000;p:$20000;crc:$efb4af87)); shinobi_sprites:array[0..7] of tipo_roms=( (n:'epr-11290.10';l:$10000;p:0;crc:$611f413a),(n:'epr-11294.11';l:$10000;p:$1;crc:$5eb00fc1), (n:'epr-11291.17';l:$10000;p:$20000;crc:$3c0797c0),(n:'epr-11295.18';l:$10000;p:$20001;crc:$25307ef8), (n:'epr-11292.23';l:$10000;p:$40000;crc:$c29ac34e),(n:'epr-11296.24';l:$10000;p:$40001;crc:$04a437f8), (n:'epr-11293.29';l:$10000;p:$60000;crc:$41f41063),(n:'epr-11297.30';l:$10000;p:$60001;crc:$b6e1fd72)); //Alex Kidd alexkid_rom:array[0..3] of tipo_roms=( (n:'epr-10447.43';l:$10000;p:0;crc:$29e87f71),(n:'epr-10445.26';l:$10000;p:$1;crc:$25ce5b6f), (n:'epr-10448.42';l:$10000;p:$20000;crc:$05baedb5),(n:'epr-10446.25';l:$10000;p:$20001;crc:$cd61d23c)); alexkid_sound:tipo_roms=(n:'epr-10434.12';l:$8000;p:0;crc:$77141cce); alexkid_tiles:array[0..2] of tipo_roms=( (n:'epr-10431.95';l:$8000;p:0;crc:$a7962c39),(n:'epr-10432.94';l:$8000;p:$8000;crc:$db8cd24e), (n:'epr-10433.93';l:$8000;p:$10000;crc:$e163c8c2)); alexkid_sprites:array[0..7] of tipo_roms=( (n:'epr-10437.10';l:$8000;p:0;crc:$522f7618),(n:'epr-10441.11';l:$8000;p:$1;crc:$74e3a35c), (n:'epr-10438.17';l:$8000;p:$10000;crc:$738a6362),(n:'epr-10442.18';l:$8000;p:$10001;crc:$86cb9c14), (n:'epr-10439.23';l:$8000;p:$20000;crc:$b391aca7),(n:'epr-10443.24';l:$8000;p:$20001;crc:$95d32635), (n:'epr-10440.29';l:$8000;p:$30000;crc:$23939508),(n:'epr-10444.30';l:$8000;p:$30001;crc:$82115823)); alexkid_n7751_data:array[0..1] of tipo_roms=( (n:'epr-10435.1';l:$8000;p:0;crc:$ad89f6e3),(n:'epr-10436.2';l:$8000;p:$8000;crc:$96c76613)); //Fantasy Zone fantzone_rom:array[0..5] of tipo_roms=( (n:'epr-7385a.43';l:$8000;p:0;crc:$4091af42),(n:'epr-7382a.26';l:$8000;p:$1;crc:$77d67bfd), (n:'epr-7386a.42';l:$8000;p:$10000;crc:$b0a67cd0),(n:'epr-7383a.25';l:$8000;p:$10001;crc:$5f79b2a9), (n:'epr-7387.41';l:$8000;p:$20000;crc:$0acd335d),(n:'epr-7384.24';l:$8000;p:$20001;crc:$fd909341)); fantzone_sound:tipo_roms=(n:'epr-7535a.12';l:$8000;p:0;crc:$bc1374fa); fantzone_tiles:array[0..2] of tipo_roms=( (n:'epr-7388.95';l:$8000;p:0;crc:$8eb02f6b),(n:'epr-7389.94';l:$8000;p:$8000;crc:$2f4f71b8), (n:'epr-7390.93';l:$8000;p:$10000;crc:$d90609c6)); fantzone_sprites:array[0..5] of tipo_roms=( (n:'epr-7392.10';l:$8000;p:0;crc:$5bb7c8b6),(n:'epr-7396.11';l:$8000;p:$1;crc:$74ae4b57), (n:'epr-7393.17';l:$8000;p:$10000;crc:$14fc7e82),(n:'epr-7397.18';l:$8000;p:$10001;crc:$e05a1e25), (n:'epr-7394.23';l:$8000;p:$20000;crc:$531ca13f),(n:'epr-7398.24';l:$8000;p:$20001;crc:$68807b49)); //Alien Syndrome alien_rom:array[0..5] of tipo_roms=( (n:'epr-10804.43';l:$8000;p:0;crc:$23f78b83),(n:'epr-10802.26';l:$8000;p:$1;crc:$996768bd), (n:'epr-10805.42';l:$8000;p:$10000;crc:$53d7fe50),(n:'epr-10803.25';l:$8000;p:$10001;crc:$0536dd33), (n:'epr-10732.41';l:$8000;p:$20000;crc:$c5712bfc),(n:'epr-10729.24';l:$8000;p:$20001;crc:$3e520e30)); alien_key:tipo_roms=(n:'317-0037.key';l:$2000;p:0;crc:$68bb7745); alien_sound:tipo_roms=(n:'epr-10705.12';l:$8000;p:0;crc:$777b749e); alien_tiles:array[0..2] of tipo_roms=( (n:'epr-10739.95';l:$10000;p:0;crc:$a29ec207),(n:'epr-10740.94';l:$10000;p:$10000;crc:$47f93015), (n:'epr-10741.93';l:$10000;p:$20000;crc:$4970739c)); alien_sprites:array[0..7] of tipo_roms=( (n:'epr-10709.10';l:$10000;p:0;crc:$addf0a90),(n:'epr-10713.11';l:$10000;p:$1;crc:$ececde3a), (n:'epr-10710.17';l:$10000;p:$20000;crc:$992369eb),(n:'epr-10714.18';l:$10000;p:$20001;crc:$91bf42fb), (n:'epr-10711.23';l:$10000;p:$40000;crc:$29166ef6),(n:'epr-10715.24';l:$10000;p:$40001;crc:$a7c57384), (n:'epr-10712.29';l:$10000;p:$60000;crc:$876ad019),(n:'epr-10716.30';l:$10000;p:$60001;crc:$40ba1d48)); alien_n7751_data:array[0..2] of tipo_roms=( (n:'epr-10706.1';l:$8000;p:0;crc:$aa114acc),(n:'epr-10707.2';l:$8000;p:$8000;crc:$800c1d82), (n:'epr-10708.4';l:$8000;p:$10000;crc:$5921ef52)); //WB3 wb3_rom:array[0..3] of tipo_roms=( (n:'epr-12120.43';l:$10000;p:0;crc:$cbd8c99b),(n:'epr-12118.26';l:$10000;p:$1;crc:$e9a3280c), (n:'epr-12121.42';l:$10000;p:$20000;crc:$5e44c0a9),(n:'epr-12119.25';l:$10000;p:$20001;crc:$01ed3ef9)); wb3_key:tipo_roms=(n:'317-0086.key';l:$2000;p:0;crc:$5b8e7076); wb3_sound:tipo_roms=(n:'epr-12089.12';l:$8000;p:0;crc:$8321eb0b); wb3_tiles:array[0..2] of tipo_roms=( (n:'epr-12086.95';l:$10000;p:0;crc:$45b949df),(n:'epr-12087.94';l:$10000;p:$10000;crc:$6f0396b7), (n:'epr-12088.83';l:$10000;p:$20000;crc:$ba8c0749)); wb3_sprites:array[0..7] of tipo_roms=( (n:'epr-12090.10';l:$10000;p:0;crc:$aeeecfca),(n:'epr-12094.11';l:$10000;p:$1;crc:$615e4927), (n:'epr-12091.17';l:$10000;p:$20000;crc:$8409a243),(n:'epr-12095.18';l:$10000;p:$20001;crc:$e774ec2c), (n:'epr-12092.23';l:$10000;p:$40000;crc:$5c2f0d90),(n:'epr-12096.24';l:$10000;p:$40001;crc:$0cd59d6e), (n:'epr-12093.29';l:$10000;p:$60000;crc:$4891e7bb),(n:'epr-12097.30';l:$10000;p:$60001;crc:$e645902c)); //Tetris tetris_rom:array[0..1] of tipo_roms=( (n:'xepr12201.rom';l:$8000;p:1;crc:$343c0670),(n:'xepr12200.rom';l:$8000;p:$0;crc:$0b694740)); tetris_key:tipo_roms=(n:'317-0093.key';l:$2000;p:0;crc:$e0064442); tetris_sound:tipo_roms=(n:'epr-12205.rom';l:$8000;p:0;crc:$6695dc99); tetris_tiles:array[0..2] of tipo_roms=( (n:'epr-12202.rom';l:$10000;p:0;crc:$2f7da741),(n:'epr-12203.rom';l:$10000;p:$10000;crc:$a6e58ec5), (n:'epr-12204.rom';l:$10000;p:$20000;crc:$0ae98e23)); tetris_sprites:array[0..1] of tipo_roms=( (n:'epr-12169.b1';l:$8000;p:0;crc:$dacc6165),(n:'epr-12170.b5';l:$8000;p:$1;crc:$87354e42)); //Dip system16a_dip_a:array [0..2] of def_dip=( (mask:$0f;name:'Coin A';number:16;dip:((dip_val:$7;dip_name:'4C/1C'),(dip_val:$8;dip_name:'3C/1C'),(dip_val:$9;dip_name:'2C/1C'),(dip_val:$5;dip_name:'2C/1C 5C/3C 6C/4C'),(dip_val:$4;dip_name:'2C/1C 4C/3C'),(dip_val:$f;dip_name:'1C/1C'),(dip_val:$3;dip_name:'1C/1C 5C/6C'),(dip_val:$2;dip_name:'1C/1C 4C/5C'),(dip_val:$1;dip_name:'1C/1C 2C/3C'),(dip_val:$6;dip_name:'2C/3C'),(dip_val:$e;dip_name:'1C/2C'),(dip_val:$d;dip_name:'1C/3C'),(dip_val:$c;dip_name:'1C/4C'),(dip_val:$b;dip_name:'1C/5C'),(dip_val:$a;dip_name:'1C/6C'),(dip_val:$0;dip_name:'Free Play (if Coin B too) or 1C/1C'))), (mask:$f0;name:'Coin B';number:16;dip:((dip_val:$70;dip_name:'4C/1C'),(dip_val:$80;dip_name:'3C/1C'),(dip_val:$90;dip_name:'2C/1C'),(dip_val:$50;dip_name:'2C/1C 5C/3C 6C/4C'),(dip_val:$40;dip_name:'2C/1C 4C/3C'),(dip_val:$f0;dip_name:'1C/1C'),(dip_val:$30;dip_name:'1C/1C 5C/6C'),(dip_val:$20;dip_name:'1C/1C 4C/5C'),(dip_val:$10;dip_name:'1C/1C 2C/3C'),(dip_val:$60;dip_name:'2C/3C'),(dip_val:$e0;dip_name:'1C/2C'),(dip_val:$d0;dip_name:'1C/3C'),(dip_val:$c0;dip_name:'1C/4C'),(dip_val:$b0;dip_name:'1C/5C'),(dip_val:$a0;dip_name:'1C/6C'),(dip_val:$00;dip_name:'Free Play (if Coin A too) or 1C/1C'))),()); shinobi_dip_b:array [0..6] of def_dip=( (mask:$1;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$1;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$2;name:'Demo Sounds';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Lives';number:4;dip:((dip_val:$8;dip_name:'2 Lives'),(dip_val:$c;dip_name:'3 Lives'),(dip_val:$4;dip_name:'5 Lives'),(dip_val:$0;dip_name:'Free Play'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Difficulty';number:4;dip:((dip_val:$20;dip_name:'Easy'),(dip_val:$30;dip_name:'Normal'),(dip_val:$10;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Enemy''s Bullet Speed';number:2;dip:((dip_val:$40;dip_name:'Slow'),(dip_val:$0;dip_name:'Fast'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Language';number:2;dip:((dip_val:$80;dip_name:'Japanese'),(dip_val:$0;dip_name:'English'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); alexkidd_dip_b:array [0..5] of def_dip=( (mask:$1;name:'Continue';number:2;dip:((dip_val:$1;dip_name:'Only before level 5'),(dip_val:$0;dip_name:'Unlimited'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$2;name:'Demo Sounds';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Lives';number:4;dip:((dip_val:$c;dip_name:'3 Lives'),(dip_val:$8;dip_name:'4 Lives'),(dip_val:$4;dip_name:'5 Lives'),(dip_val:$0;dip_name:'240'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Bonus Life';number:4;dip:((dip_val:$20;dip_name:'10000'),(dip_val:$30;dip_name:'20000'),(dip_val:$10;dip_name:'40000'),(dip_val:$0;dip_name:'None'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c0;name:'Time Adjust';number:4;dip:((dip_val:$80;dip_name:'70'),(dip_val:$c0;dip_name:'60'),(dip_val:$40;dip_name:'50'),(dip_val:$0;dip_name:'40'),(),(),(),(),(),(),(),(),(),(),(),())),()); fantzone_dip_b:array [0..5] of def_dip=( (mask:$1;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$1;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$2;name:'Demo Sounds';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Lives';number:4;dip:((dip_val:$8;dip_name:'2 Lives'),(dip_val:$c;dip_name:'3 Lives'),(dip_val:$4;dip_name:'4 Lives'),(dip_val:$0;dip_name:'240'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Extra Ship Cost';number:4;dip:((dip_val:$30;dip_name:'5000'),(dip_val:$20;dip_name:'10000'),(dip_val:$10;dip_name:'15000'),(dip_val:$0;dip_name:'20000'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c0;name:'Difficulty';number:4;dip:((dip_val:$80;dip_name:'Easy'),(dip_val:$c0;dip_name:'Normal'),(dip_val:$40;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),()); aliensynd_dip_b:array [0..4] of def_dip=( (mask:$2;name:'Demo Sounds';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Lives';number:4;dip:((dip_val:$8;dip_name:'2 Lives'),(dip_val:$c;dip_name:'3 Lives'),(dip_val:$4;dip_name:'4 Lives'),(dip_val:$0;dip_name:'Free Play'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Timer';number:4;dip:((dip_val:$0;dip_name:'120'),(dip_val:$10;dip_name:'130'),(dip_val:$20;dip_name:'140'),(dip_val:$30;dip_name:'150'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c0;name:'Difficulty';number:4;dip:((dip_val:$80;dip_name:'Easy'),(dip_val:$c0;dip_name:'Normal'),(dip_val:$40;dip_name:'Hard'),(dip_val:$0;dip_name:'Very Hard'),(),(),(),(),(),(),(),(),(),(),(),())),()); wb3_dip_b:array [0..5] of def_dip=( (mask:$2;name:'Demo Sounds';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Lives';number:4;dip:((dip_val:$0;dip_name:'2 Lives'),(dip_val:$c;dip_name:'3 Lives'),(dip_val:$8;dip_name:'4 Lives'),(dip_val:$8;dip_name:'5 Lives'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$10;name:'Bonus Life';number:2;dip:((dip_val:$10;dip_name:'50k/100k/180k/300k'),(dip_val:$0;dip_name:'50k/150k/300k'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Difficulty';number:2;dip:((dip_val:$20;dip_name:'Normal'),(dip_val:$0;dip_name:'Hard'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Test Mode';number:2;dip:((dip_val:$40;dip_name:'No'),(dip_val:$0;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); tetris_dip_b:array [0..2] of def_dip=( (mask:$2;name:'Demo Sounds';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Difficulty';number:4;dip:((dip_val:$20;dip_name:'Easy'),(dip_val:$30;dip_name:'Normal'),(dip_val:$10;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),()); CPU_SYNC=4; type tsystem16_info=record normal,shadow,hilight:array[0..31] of byte; banks:byte; screen:array[0..7] of byte; screen_enabled:boolean; tile_buffer:array[0..7,0..$7ff] of boolean; end; var rom,rom_data:array[0..$1ffff] of word; ram:array[0..$1fff] of word; tile_ram:array[0..$3fff] of word; char_ram:array[0..$7ff] of word; sprite_ram:array[0..$3ff] of word; sprite_rom:array[0..$3ffff] of word; sprite_bank:array[0..$f] of byte; n7751_data:array[0..$17fff]of byte; s16_info:tsystem16_info; n7751_numroms,sound_latch,n7751_command:byte; n7751_rom_address:dword; procedure draw_sprites(pri:byte); var sprpri:byte; f:integer; bottom,top:word; addr,bank,y,pix,data_7,pixels,color:word; x,xpos,pitch:integer; spritedata:dword; procedure system16a_draw_pixel(x,y,pix:word); var punt,punt2,temp1,temp2,temp3:word; begin //only draw if onscreen, not 0 or 15 if ((x<320) and ((pix and $f)<>0) and ((pix and $f)<>15)) then begin if (pix and $3f0)=$3f0 then begin //Shadow punt:=getpixel(x+ADD_SPRITE,y+ADD_SPRITE,7); punt2:=paleta[$1000]; temp1:=(((punt and $f800)+(punt2 and $f800)) shr 1) and $f800; temp2:=(((punt and $7e0)+(punt2 and $7e0)) shr 1) and $7e0; temp3:=(((punt and $1f)+(punt2 and $1f)) shr 1) and $1f; punt:=temp1 or temp2 or temp3; end else punt:=paleta[pix+$400]; //Normal putpixel(x+ADD_SPRITE,y+ADD_SPRITE,1,@punt,7); end; end; begin for f:=0 to $7f do begin sprpri:=(sprite_ram[(f*8)+4] and $ff) and $3; if sprpri<>pri then continue; addr:=sprite_ram[(f*8)+3]; sprite_ram[(f*8)+7]:=addr; bottom:=(sprite_ram[f*8] shr 8)+1; if bottom>$f0 then break; bank:=sprite_bank[(sprite_ram[(f*8)+4] shr 4) and $7]; top:=(sprite_ram[f*8] and $ff)+1; // if hidden, or top greater than/equal to bottom, or invalid bank if ((top>=bottom) or (bank=255)) then continue; xpos:=(sprite_ram[(f*8)+1] and $1ff)-$bd; pitch:=smallint(sprite_ram[(f*$8)+2]); color:=((sprite_ram[(f*8)+4] shr 8) and $3f) shl 4; // clamp to within the memory region size spritedata:=$8000*(bank mod s16_info.banks); // loop from top to bottom for y:=top to (bottom-1) do begin // advance a row addr:=addr+pitch; // skip drawing if not within the cliprect if (y<256) then begin // note that the System 16A sprites have a design flaw that allows the address // to carry into the flip flag, which is the topmost bit -- it is very important // to emulate this as the games compensate for it // non-flipped case if (addr and $8000)=0 then begin data_7:=addr; x:=xpos; while (x<512) do begin pixels:=sprite_rom[spritedata+(data_7 and $7fff)]; // draw four pixels pix:=(pixels shr 12) and $f; system16a_draw_pixel(x,y,pix or color); pix:=(pixels shr 8) and $f; system16a_draw_pixel(x+1,y,pix or color); pix:=(pixels shr 4) and $f; system16a_draw_pixel(x+2,y,pix or color); pix:=(pixels shr 0) and $f; system16a_draw_pixel(x+3,y,pix or color); x:=x+4; // stop if the last pixel in the group was 0xf if (pix=15) then begin sprite_ram[(f*8)+7]:=data_7; break; end else data_7:=data_7+1; end; end else begin // flipped case data_7:=addr; x:=xpos; while (x<512) do begin pixels:=sprite_rom[spritedata+(data_7 and $7fff)]; // draw four pixels pix:=(pixels shr 0) and $f; system16a_draw_pixel(x,y,pix or color); pix:=(pixels shr 4) and $f; system16a_draw_pixel(x+1,y,pix or color); pix:=(pixels shr 8) and $f; system16a_draw_pixel(x+2,y,pix or color); pix:=(pixels shr 12) and $f; system16a_draw_pixel(x+3,y,pix or color); x:=x+4; // stop if the last pixel in the group was 0xf if (pix=15) then begin sprite_ram[(f*8)+7]:=data_7; break; end else data_7:=data_7-1; end; end; end; end; end; end; procedure draw_tiles(num:byte;px,py:word;scr:byte;trans:boolean); var pos,f,nchar,color,data:word; x,y:word; begin pos:=s16_info.screen[num]*$800; for f:=$0 to $7ff do begin data:=tile_ram[pos+f]; color:=(data shr 5) and $7f; if (s16_info.tile_buffer[num,f] or buffer_color[color]) then begin x:=((f and $3f) shl 3)+px; y:=((f shr 6) shl 3)+py; nchar:=((data shr 1) and $1000) or (data and $fff); if trans then put_gfx_trans(x,y,nchar,color shl 3,scr,0) else put_gfx(x,y,nchar,color shl 3,scr,0); if (data and $1000)<>0 then put_gfx_trans(x,y,nchar,color shl 3,scr+1,0) else put_gfx_block_trans(x,y,scr+1,8,8); s16_info.tile_buffer[num,f]:=false; end; end; end; procedure update_video_system16a; var f,nchar,color,scroll_x1,scroll_x2,x,y,atrib:word; scroll_y1,scroll_y2:byte; begin if not(s16_info.screen_enabled) then begin fill_full_screen(7,$1fff); actualiza_trozo_final(0,0,320,224,7); exit; end; //Background draw_tiles(0,0,256,3,false); draw_tiles(1,512,256,3,false); draw_tiles(2,0,0,3,false); draw_tiles(3,512,0,3,false); scroll_x1:=char_ram[$7fd] and $1ff; scroll_x1:=($c8-scroll_x1) and $3ff; scroll_y1:=char_ram[$793] and $ff; //Foreground draw_tiles(4,0,256,5,true); draw_tiles(5,512,256,5,true); draw_tiles(6,0,0,5,true); draw_tiles(7,512,0,5,true); scroll_x2:=char_ram[$7fc] and $1ff; scroll_x2:=($c8-scroll_x2) and $3ff; scroll_y2:=char_ram[$792] and $ff; //text for f:=$0 to $6ff do begin atrib:=char_ram[f]; color:=(atrib shr 8) and $7; if (gfx[0].buffer[f] or buffer_color[color]) then begin x:=(f and $3f) shl 3; y:=(f shr 6) shl 3; nchar:=atrib and $ff; put_gfx_trans(x,y,nchar,color shl 3,1,0); if (atrib and $800)<>0 then put_gfx_trans(x,y,nchar,color shl 3,2,0) else put_gfx_block_trans(x,y,2,8,8); gfx[0].buffer[f]:=false; end; end; //Lo pongo todo con prioridades, falta scrollrow y scrollcol!! scroll_x_y(3,7,scroll_x1,scroll_y1); //0 draw_sprites(0); scroll_x_y(4,7,scroll_x1,scroll_y1); //1 draw_sprites(1); scroll_x_y(5,7,scroll_x2,scroll_y2); //2 draw_sprites(2); scroll_x_y(6,7,scroll_x2,scroll_y2); //2 actualiza_trozo(192,0,320,224,1,0,0,320,224,7); //4 draw_sprites(3); actualiza_trozo(192,0,320,224,2,0,0,320,224,7); //8 //Y lo pinto a la pantalla principal actualiza_trozo_final(0,0,320,224,7); fillchar(buffer_color,MAX_COLOR_BUFFER,0); end; procedure eventos_system16a; begin if event.arcade then begin //P1 if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $ffdf) else marcade.in1:=(marcade.in1 or $20); if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $ffef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $ff7f) else marcade.in1:=(marcade.in1 or $80); if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $ffbf) else marcade.in1:=(marcade.in1 or $40); if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $fffb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $fffd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.but2[0] then marcade.in1:=(marcade.in1 and $fffe) else marcade.in1:=(marcade.in1 or $1); //P2 if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $ffdf) else marcade.in2:=(marcade.in2 or $20); if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $ffef) else marcade.in2:=(marcade.in2 or $10); if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $ff7f) else marcade.in2:=(marcade.in2 or $80); if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $ffbf) else marcade.in2:=(marcade.in2 or $40); if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $fffb) else marcade.in2:=(marcade.in2 or $4); if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $fffd) else marcade.in2:=(marcade.in2 or $2); if arcade_input.but2[1] then marcade.in2:=(marcade.in2 and $fffe) else marcade.in2:=(marcade.in2 or $1); //Service if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $ffef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $ffdf) else marcade.in0:=(marcade.in0 or $20); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $fffe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $fffd) else marcade.in0:=(marcade.in0 or $2); end; end; procedure system16a_principal_adpcm; var frame_m,frame_s,frame_s_sub:single; f:word; h:byte; begin init_controls(false,false,false,true); frame_m:=m68000_0.tframes; frame_s:=z80_0.tframes; frame_s_sub:=mcs48_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to 261 do begin for h:=1 to CPU_SYNC do begin //main m68000_0.run(frame_m); frame_m:=frame_m+m68000_0.tframes-m68000_0.contador; //sound z80_0.run(frame_s); frame_s:=frame_s+z80_0.tframes-z80_0.contador; //sound sub cpu mcs48_0.run(frame_s_sub); frame_s_sub:=frame_s_sub+mcs48_0.tframes-mcs48_0.contador; end; if f=223 then begin m68000_0.irq[4]:=HOLD_LINE; update_video_system16a; end; end; eventos_system16a; video_sync; end; end; procedure system16a_principal; var frame_m,frame_s:single; f:word; h:byte; begin init_controls(false,false,false,true); frame_m:=m68000_0.tframes; frame_s:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to 261 do begin for h:=1 to CPU_SYNC do begin //main m68000_0.run(frame_m); frame_m:=frame_m+m68000_0.tframes-m68000_0.contador; //sound z80_0.run(frame_s); frame_s:=frame_s+z80_0.tframes-z80_0.contador; end; if f=223 then begin m68000_0.irq[4]:=HOLD_LINE; update_video_system16a; end; end; eventos_system16a; video_sync; end; end; function standar_s16_io_r(direccion:word):word; var res:word; begin case (direccion and $3000) of $0000:res:=pia8255_0.read((direccion shr 1) and 3); $1000:case (direccion and 7) of 0,1:res:=marcade.in0; //SERVICE 2,3:res:=marcade.in1; //P1 4,5:res:=$ff; //UNUSED 6,7:res:=marcade.in2; //P2 end; $2000:case (direccion and $3) of 0,1:res:=marcade.dswa; //DSW1 2,3:res:=marcade.dswb; //DSW2 end; else res:=$ffff; end; standar_s16_io_r:=res; end; function system16a_getword(direccion:dword):word; begin case direccion of 0..$3fffff:system16a_getword:=rom[(direccion and $3ffff) shr 1]; $400000..$7fffff:case (direccion and $7ffff) of $00000..$0ffff:system16a_getword:=tile_ram[(direccion and $7fff) shr 1]; $10000..$1ffff:system16a_getword:=char_ram[(direccion and $fff) shr 1]; $40000..$7ffff:system16a_getword:=sprite_ram[(direccion and $7ff) shr 1]; else system16a_getword:=$ffff; end; $800000..$bfffff:case (direccion and $fffff) of $40000..$7ffff:system16a_getword:=buffer_paleta[(direccion and $fff) shr 1]; else system16a_getword:=$ffff; end; $c00000..$ffffff:case (direccion and $7ffff) of $00000..$0ffff:system16a_getword:=tile_ram[(direccion and $7fff) shr 1]; $10000..$1ffff:system16a_getword:=char_ram[(direccion and $fff) shr 1]; $40000..$5ffff:system16a_getword:=standar_s16_io_r(direccion and $3fff); //misc_io $60000..$6ffff:system16a_getword:=$ffff; //watch dog $70000..$7ffff:system16a_getword:=ram[(direccion and $3fff) shr 1]; end; end; end; function system16a_getword_fd1089(direccion:dword):word; begin case direccion of 0..$3fffff:if m68000_0.opcode then system16a_getword_fd1089:=rom[(direccion and $3ffff) shr 1] else system16a_getword_fd1089:=rom_data[(direccion and $3ffff) shr 1]; else system16a_getword_fd1089:=system16a_getword(direccion); end; end; procedure test_screen_change(direccion:word); var tmp:byte; begin if direccion=$74e then begin //Background abajo 1-2 tmp:=(char_ram[$74e] shr 12) and $7; if tmp<>s16_info.screen[0] then begin s16_info.screen[0]:=tmp; fillchar(s16_info.tile_buffer[0,0],$800,1); end; tmp:=(char_ram[$74e] shr 8) and $7; if tmp<>s16_info.screen[1] then begin s16_info.screen[1]:=tmp; fillchar(s16_info.tile_buffer[1,0],$800,1); end; //Background arriba 1-2 tmp:=(char_ram[$74e] shr 4) and $7; if tmp<>s16_info.screen[2] then begin s16_info.screen[2]:=tmp; fillchar(s16_info.tile_buffer[2,0],$800,1); end; tmp:=char_ram[$74e] and $7; if tmp<>s16_info.screen[3] then begin s16_info.screen[3]:=tmp; fillchar(s16_info.tile_buffer[3,0],$800,1); end; end; if direccion=$74f then begin //Foreground abajo tmp:=(char_ram[$74f] shr 12) and $7; if tmp<>s16_info.screen[4] then begin s16_info.screen[4]:=tmp; fillchar(s16_info.tile_buffer[4,0],$800,1); end; tmp:=(char_ram[$74f] shr 8) and $7; if tmp<>s16_info.screen[5] then begin s16_info.screen[5]:=tmp; fillchar(s16_info.tile_buffer[5,0],$800,1); end; //Foreground arriba tmp:=(char_ram[$74f] shr 4) and $7; if tmp<>s16_info.screen[6] then begin s16_info.screen[6]:=tmp; fillchar(s16_info.tile_buffer[6,0],$800,1); end; tmp:=char_ram[$74f] and $7; if tmp<>s16_info.screen[7] then begin s16_info.screen[7]:=tmp; fillchar(s16_info.tile_buffer[7,0],$800,1); end; end; end; procedure change_pal(direccion:word); var val:word; color:tcolor; r,g,b:integer; begin // get the new value val:=buffer_paleta[direccion]; // byte 0 byte 1 // sBGR BBBB GGGG RRRR // x000 4321 4321 4321 r:=((val shr 12) and $01) or ((val shl 1) and $1e); g:=((val shr 13) and $01) or ((val shr 3) and $1e); b:=((val shr 14) and $01) or ((val shr 7) and $1e); //normal color.r:=s16_info.normal[r]; color.g:=s16_info.normal[g]; color.b:=s16_info.normal[b]; set_pal_color(color,direccion); //shadow color.r:=s16_info.shadow[r]; color.g:=s16_info.shadow[g]; color.b:=s16_info.shadow[b]; set_pal_color(color,direccion+$800); //hilight color.r:=s16_info.hilight[r]; color.g:=s16_info.hilight[g]; color.b:=s16_info.hilight[b]; set_pal_color(color,direccion+$1000); //Buffer buffer_color[(direccion shr 3) and $7f]:=true; end; procedure test_tile_buffer(direccion:word); var num_scr,f:byte; pos:word; begin num_scr:=direccion shr 11; pos:=direccion and $7ff; for f:=0 to 7 do if s16_info.screen[f]=num_scr then s16_info.tile_buffer[f,pos]:=true; end; procedure system16a_putword(direccion:dword;valor:word); begin case direccion of 0..$3ffff:; $400000..$7fffff:case (direccion and $7ffff) of $00000..$0ffff:if tile_ram[(direccion and $7fff) shr 1]<>valor then begin tile_ram[(direccion and $7fff) shr 1]:=valor; test_tile_buffer((direccion and $7fff) shr 1); end; $10000..$1ffff:if char_ram[(direccion and $fff) shr 1]<>valor then begin char_ram[(direccion and $fff) shr 1]:=valor; gfx[0].buffer[(direccion and $fff) shr 1]:=true; test_screen_change((direccion and $fff) shr 1); end; $40000..$7ffff:sprite_ram[(direccion and $7ff) shr 1]:=valor; end; $800000..$bfffff:case (direccion and $fffff) of $40000..$7ffff:if (buffer_paleta[(direccion and $fff) shr 1]<>valor) then begin buffer_paleta[(direccion and $fff) shr 1]:=valor; change_pal((direccion and $fff) shr 1); end; end; $c00000..$ffffff:case (direccion and $7ffff) of $00000..$0ffff:if tile_ram[(direccion and $7fff) shr 1]<>valor then begin tile_ram[(direccion and $7fff) shr 1]:=valor; test_tile_buffer((direccion and $7fff) shr 1); end; $10000..$1ffff:begin if char_ram[(direccion and $fff) shr 1]<>valor then begin char_ram[(direccion and $fff) shr 1]:=valor; gfx[0].buffer[(direccion and $fff) shr 1]:=true; end; test_screen_change((direccion and $fff) shr 1); end; $40000..$5ffff:if (direccion and $3000)=0 then pia8255_0.write((direccion shr 1) and $3,valor and $ff); $70000..$7ffff:begin ram[(direccion and $3fff) shr 1]:=valor; if ((direccion and $3fff) shr 1)=$38 then sound_latch:=valor; end; end; end; end; function system16a_snd_getbyte(direccion:word):byte; var res:byte; begin res:=$ff; case direccion of $0..$7fff,$f800..$ffff:res:=mem_snd[direccion]; $e800:begin pia8255_0.set_port(2,0); res:=sound_latch; end; end; system16a_snd_getbyte:=res; end; procedure system16a_snd_putbyte(direccion:word;valor:byte); begin if direccion>$f7ff then mem_snd[direccion]:=valor; end; function system16a_snd_inbyte(puerto:word):byte; var res:byte; begin res:=$ff; case (puerto and $ff) of $00..$3f:if (puerto and 1)<>0 then res:=ym2151_0.status; $c0..$ff:begin pia8255_0.set_port(2,0); res:=sound_latch; end; end; system16a_snd_inbyte:=res; end; procedure system16a_snd_outbyte(puerto:word;valor:byte); begin case (puerto and $ff) of $00..$3f:case (puerto and 1) of 0:ym2151_0.reg(valor); 1:ym2151_0.write(valor); end; $80..$bf:; end; end; procedure system16a_snd_outbyte_adpcm(puerto:word;valor:byte); begin case (puerto and $ff) of $00..$3f:case (puerto and 1) of 0:ym2151_0.reg(valor); 1:ym2151_0.write(valor); end; $80..$bf:begin n7751_rom_address:=n7751_rom_address and $3fff; n7751_rom_address:=n7751_rom_address or ((valor and 1) shl 14); if (((valor and $4)=0) and (n7751_numroms>=2)) then n7751_rom_address:=n7751_rom_address or $08000; if (((valor and $8)=0) and (n7751_numroms>=3)) then n7751_rom_address:=n7751_rom_address or $10000; if (((valor and $10)=0) and (n7751_numroms>=4)) then n7751_rom_address:=n7751_rom_address or $18000; n7751_command:=valor shr 5; end; end; end; procedure ppi8255_wporta(valor:byte); begin sound_latch:=valor; end; procedure ppi8255_wportb(valor:byte); begin s16_info.screen_enabled:=(valor and $10)<>0; end; procedure ppi8255_wportc(valor:byte); begin if (valor and $80)<>0 then z80_0.change_nmi(CLEAR_LINE) else z80_0.change_nmi(ASSERT_LINE); end; procedure system16a_sound_adpcm; begin ym2151_0.update; dac_0.update; end; procedure system16a_sound_update; begin ym2151_0.update; end; procedure ym2151_snd_port(valor:byte); begin if (valor and $1)<>0 then mcs48_0.change_reset(CLEAR_LINE) else mcs48_0.change_reset(ASSERT_LINE); if (valor and $2)<>0 then mcs48_0.change_irq(CLEAR_LINE) else mcs48_0.change_irq(ASSERT_LINE); end; //Sub sound cpu function system16a_sound_inport(puerto:word):byte; begin case puerto of MCS48_PORT_BUS:system16a_sound_inport:=n7751_data[n7751_rom_address]; MCS48_PORT_T1:system16a_sound_inport:=0; MCS48_PORT_P2:system16a_sound_inport:=$80 or ((n7751_command and $07) shl 4) or (mcs48_0.i8243.p2_r and $f); end; end; procedure system16a_sound_outport(puerto:word;valor:byte); begin case puerto of MCS48_PORT_P1:dac_0.data8_w(valor); MCS48_PORT_P2:mcs48_0.i8243.p2_w(valor and $f); MCS48_PORT_PROG:mcs48_0.i8243.prog_w(valor); end; end; procedure n7751_rom_offset_w(puerto:word;valor:byte); var mask,newdata:dword; begin // P4 - address lines 0-3 // P5 - address lines 4-7 // P6 - address lines 8-11 // P7 - address lines 12-13 mask:=($f shl (4*puerto)) and $3fff; newdata:=(valor shl (4*puerto)) and mask; n7751_rom_address:=(n7751_rom_address and not(mask)) or newdata; end; //Main procedure reset_system16a; var f:byte; begin m68000_0.reset; z80_0.reset; ym2151_0.reset; pia8255_0.reset; if ((main_vars.tipo_maquina=114) or (main_vars.tipo_maquina=115) or (main_vars.tipo_maquina=186)) then mcs48_0.reset; reset_audio; marcade.in0:=$ffff; marcade.in1:=$ffff; marcade.in2:=$ffff; for f:=0 to $f do sprite_bank[f]:=f; s16_info.screen_enabled:=true; fillchar(s16_info.tile_buffer,$4000,1); sound_latch:=0; n7751_rom_address:=0; end; function iniciar_system16a:boolean; var f:word; memoria_temp:array[0..$7ffff] of byte; fd1089_key:array[0..$1fff] of byte; weights:array[0..1,0..5] of single; i0,i1,i2,i3,i4:integer; const resistances_normal:array[0..5] of integer=(3900, 2000, 1000, 1000 div 2,1000 div 4, 0); resistances_sh:array[0..5] of integer=(3900, 2000, 1000, 1000 div 2, 1000 div 4, 470); procedure convert_chars(n:byte); const pt_x:array[0..7] of dword=(0, 1, 2, 3, 4, 5, 6, 7 ); pt_y:array[0..7] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8); begin init_gfx(0,8,8,n*$1000); gfx[0].trans[0]:=true; gfx_set_desc_data(3,0,8*8,n*$10000*8,n*$8000*8,0); convert_gfx(0,0,@memoria_temp[0],@pt_x[0],@pt_y[0],false,false); end; begin llamadas_maquina.reset:=reset_system16a; iniciar_system16a:=false; iniciar_audio(false); //text screen_init(1,512,256,true); screen_init(2,512,256,true); //Background screen_init(3,1024,512); screen_mod_scroll(3,1024,512,1023,512,256,511); screen_init(4,1024,512,true); screen_mod_scroll(4,1024,512,1023,512,256,511); //Foreground screen_init(5,1024,512,true); screen_mod_scroll(5,1024,512,1023,512,256,511); screen_init(6,1024,512,true); screen_mod_scroll(6,1024,512,1023,512,256,511); //Final screen_init(7,512,256,false,true); iniciar_video(320,224); //Main CPU m68000_0:=cpu_m68000.create(10000000,262*CPU_SYNC); //Sound CPU z80_0:=cpu_z80.create(4000000,262*CPU_SYNC); z80_0.change_ram_calls(system16a_snd_getbyte,system16a_snd_putbyte); //PPI 825 pia8255_0:=pia8255_chip.create; pia8255_0.change_ports(nil,nil,nil,ppi8255_wporta,ppi8255_wportb,ppi8255_wportc); if ((main_vars.tipo_maquina=114) or (main_vars.tipo_maquina=115) or (main_vars.tipo_maquina=186)) then begin z80_0.change_io_calls(system16a_snd_inbyte,system16a_snd_outbyte_adpcm); z80_0.init_sound(system16a_sound_adpcm); ym2151_0:=ym2151_chip.create(4000000); ym2151_0.change_port_func(ym2151_snd_port); //Creo el segundo chip de sonido mcs48_0:=cpu_mcs48.create(6000000,262*CPU_SYNC,N7751); mcs48_0.change_io_calls(system16a_sound_inport,system16a_sound_outport); mcs48_0.i8243.change_calls(nil,n7751_rom_offset_w); dac_0:=dac_chip.Create(1); end else begin z80_0.change_io_calls(system16a_snd_inbyte,system16a_snd_outbyte); z80_0.init_sound(system16a_sound_update); ym2151_0:=ym2151_chip.create(4000000); end; //DIP marcade.dswa:=$ff; marcade.dswa_val:=@system16a_dip_a; case main_vars.tipo_maquina of 114:begin //Shinobi llamadas_maquina.bucle_general:=system16a_principal_adpcm; n7751_numroms:=1; if not(roms_load(mcs48_0.get_rom_addr,shinobi_n7751)) then exit; if not(roms_load(@n7751_data,shinobi_n7751_data)) then exit; //Main CPU m68000_0.change_ram16_calls(system16a_getword,system16a_putword); //cargar roms if not(roms_load16w(@rom,shinobi_rom)) then exit; //cargar sonido if not(roms_load(@mem_snd,shinobi_sound)) then exit; //convertir tiles if not(roms_load(@memoria_temp,shinobi_tiles)) then exit; convert_chars(2); //Cargar ROM de los sprites y recolocarlos if not(roms_load16b(@memoria_temp,shinobi_sprites)) then exit; for f:=0 to 7 do begin copymemory(@sprite_rom[0],@memoria_temp[0],$10000); copymemory(@sprite_rom[$20000],@memoria_temp[$10000],$10000); copymemory(@sprite_rom[$8000],@memoria_temp[$20000],$10000); copymemory(@sprite_rom[$28000],@memoria_temp[$30000],$10000); copymemory(@sprite_rom[$10000],@memoria_temp[$40000],$10000); copymemory(@sprite_rom[$30000],@memoria_temp[$50000],$10000); copymemory(@sprite_rom[$18000],@memoria_temp[$60000],$10000); copymemory(@sprite_rom[$38000],@memoria_temp[$70000],$10000); end; s16_info.banks:=8; marcade.dswb:=$fc; marcade.dswb_val:=@shinobi_dip_b; end; 115:begin //Alex Kid llamadas_maquina.bucle_general:=system16a_principal_adpcm; n7751_numroms:=2; if not(roms_load(mcs48_0.get_rom_addr,shinobi_n7751)) then exit; if not(roms_load(@n7751_data,alexkid_n7751_data)) then exit; m68000_0.change_ram16_calls(system16a_getword,system16a_putword); //cargar roms if not(roms_load16w(@rom,alexkid_rom)) then exit; //cargar sonido if not(roms_load(@mem_snd,alexkid_sound)) then exit; //convertir tiles if not(roms_load(@memoria_temp,alexkid_tiles)) then exit; convert_chars(1); //Cargar ROM de los sprites if not(roms_load16b(@sprite_rom,alexkid_sprites)) then exit; s16_info.banks:=4; marcade.dswb:=$fc; marcade.dswb_val:=@alexkidd_dip_b; end; 116:begin //Fantasy Zone llamadas_maquina.bucle_general:=system16a_principal; m68000_0.change_ram16_calls(system16a_getword,system16a_putword); //cargar roms if not(roms_load16w(@rom,fantzone_rom)) then exit; //cargar sonido if not(roms_load(@mem_snd,fantzone_sound)) then exit; //convertir tiles if not(roms_load(@memoria_temp,fantzone_tiles)) then exit; convert_chars(1); //Cargar ROM de los sprites if not(roms_load16b(@sprite_rom,fantzone_sprites)) then exit; s16_info.banks:=4; marcade.dswb:=$fc; marcade.dswb_val:=@fantzone_dip_b; end; 186:begin //Alien Syndrome llamadas_maquina.bucle_general:=system16a_principal_adpcm; n7751_numroms:=3; if not(roms_load(mcs48_0.get_rom_addr,shinobi_n7751)) then exit; if not(roms_load(@n7751_data,alien_n7751_data)) then exit; m68000_0.change_ram16_calls(system16a_getword_fd1089,system16a_putword); //cargar roms if not(roms_load16w(@memoria_temp,alien_rom)) then exit; //Decode fd1089 if not(roms_load(@fd1089_key,alien_key)) then exit; fd1089_decrypt($40000,@memoria_temp,@rom,@rom_data,@fd1089_key,fd_typeB); //cargar sonido if not(roms_load(@mem_snd,alien_sound)) then exit; //convertir tiles if not(roms_load(@memoria_temp,alien_tiles)) then exit; convert_chars(2); //Cargar ROM de los sprites y recolocarlos if not(roms_load16b(@memoria_temp,alien_sprites)) then exit; for f:=0 to 7 do begin copymemory(@sprite_rom[0],@memoria_temp[0],$10000); copymemory(@sprite_rom[$20000],@memoria_temp[$10000],$10000); copymemory(@sprite_rom[$8000],@memoria_temp[$20000],$10000); copymemory(@sprite_rom[$28000],@memoria_temp[$30000],$10000); copymemory(@sprite_rom[$10000],@memoria_temp[$40000],$10000); copymemory(@sprite_rom[$30000],@memoria_temp[$50000],$10000); copymemory(@sprite_rom[$18000],@memoria_temp[$60000],$10000); copymemory(@sprite_rom[$38000],@memoria_temp[$70000],$10000); end; s16_info.banks:=8; marcade.dswb:=$fd; marcade.dswb_val:=@aliensynd_dip_b; end; 187:begin //WB3 llamadas_maquina.bucle_general:=system16a_principal; m68000_0.change_ram16_calls(system16a_getword_fd1089,system16a_putword); //cargar roms if not(roms_load16w(@memoria_temp,wb3_rom)) then exit; //Decode fd1089 if not(roms_load(@fd1089_key,wb3_key)) then exit; fd1089_decrypt($40000,@memoria_temp,@rom,@rom_data,@fd1089_key,fd_typeA); //cargar sonido if not(roms_load(@mem_snd,wb3_sound)) then exit; //convertir tiles if not(roms_load(@memoria_temp,wb3_tiles)) then exit; convert_chars(2); //Cargar ROM de los sprites y recolocarlos if not(roms_load16b(@memoria_temp,wb3_sprites)) then exit; for f:=0 to 7 do begin copymemory(@sprite_rom[0],@memoria_temp[0],$10000); copymemory(@sprite_rom[$20000],@memoria_temp[$10000],$10000); copymemory(@sprite_rom[$8000],@memoria_temp[$20000],$10000); copymemory(@sprite_rom[$28000],@memoria_temp[$30000],$10000); copymemory(@sprite_rom[$10000],@memoria_temp[$40000],$10000); copymemory(@sprite_rom[$30000],@memoria_temp[$50000],$10000); copymemory(@sprite_rom[$18000],@memoria_temp[$60000],$10000); copymemory(@sprite_rom[$38000],@memoria_temp[$70000],$10000); end; s16_info.banks:=8; marcade.dswb:=$7c; marcade.dswb_val:=@wb3_dip_b; end; 198:begin //Tetris llamadas_maquina.bucle_general:=system16a_principal; m68000_0.change_ram16_calls(system16a_getword,system16a_putword); //cargar roms if not(roms_load16w(@rom,tetris_rom)) then exit; //cargar sonido if not(roms_load(@mem_snd,tetris_sound)) then exit; //convertir tiles if not(roms_load(@memoria_temp,tetris_tiles)) then exit; convert_chars(2); //Cargar ROM de los sprites if not(roms_load16b(@sprite_rom,tetris_sprites)) then exit; s16_info.banks:=1; marcade.dswb:=$30; marcade.dswb_val:=@tetris_dip_b; end; end; //poner la paleta compute_resistor_weights(0,255,-1.0, 6,@resistances_normal[0],@weights[0],0,0, 0,nil,nil,0,0, 0,nil,nil,0,0); compute_resistor_weights(0,255,-1.0, 6,@resistances_sh[0],@weights[1],0,0, 0,nil,nil,0,0, 0,nil,nil,0,0); for f:=0 to 31 do begin i4:=(f shr 4) and 1; i3:=(f shr 3) and 1; i2:=(f shr 2) and 1; i1:=(f shr 1) and 1; i0:=(f shr 0) and 1; s16_info.normal[f]:=combine_6_weights(@weights[0],i0,i1,i2,i3,i4,0); s16_info.shadow[f]:=combine_6_weights(@weights[1],i0,i1,i2,i3,i4,0); s16_info.hilight[f]:=combine_6_weights(@weights[1],i0,i1,i2,i3,i4,1); end; //final reset_system16a; iniciar_system16a:=true; end; end.
unit uPenerimaanKas; interface uses uModel, uRekBank, uAR, System.Generics.Collections,System.SysUtils, uSupplier, uAccount; type TPenerimaanKas = class; TPenerimaanKasAR = class; TPenerimaanKasAPNew = class; TPenerimaanKasLain = class; TPenerimaanKasAR = class(TAppObjectItem) private FAR: TAR; FKeterangan: string; FNominal: Double; FPenerimaanKas: TPenerimaanKas; FUangBayar: Double; FUangSisa: Double; function GetUangSisa: Double; public function GetHeaderField: string; override; procedure SetHeaderProperty(AHeaderProperty : TAppObject); override; published property AR: TAR read FAR write FAR; property Keterangan: string read FKeterangan write FKeterangan; property Nominal: Double read FNominal write FNominal; property PenerimaanKas: TPenerimaanKas read FPenerimaanKas write FPenerimaanKas; property UangBayar: Double read FUangBayar write FUangBayar; property UangSisa: Double read GetUangSisa write FUangSisa; end; TPenerimaanKas = class(TAPPobject) private FCabang: TCabang; FJenisTransaksi: string; FKeterangan: string; FNoBukti: string; FNominal: Double; FPembeli: TSupplier; FPenerimaanKasARItems: TObjectlist<TPenerimaanKasAR>; FPetugas: string; FRekBank: TRekBank; FTglBukti: TDatetime; FPenerimaanKasAPNewItems: TObjectList<TPenerimaanKasAPNew>; FPenerimaanKasLainItems: TObjectList<TPenerimaanKasLain>; function GetPenerimaanKasARItems: TObjectlist<TPenerimaanKasAR>; function GetPenerimaanKasAPNewItems: TObjectList<TPenerimaanKasAPNew>; function GetPenerimaanKasLainItems: TObjectList<TPenerimaanKasLain>; public destructor Destroy; override; published property Cabang: TCabang read FCabang write FCabang; property JenisTransaksi: string read FJenisTransaksi write FJenisTransaksi; property Keterangan: string read FKeterangan write FKeterangan; property NoBukti: string read FNoBukti write FNoBukti; property Nominal: Double read FNominal write FNominal; property Pembeli: TSupplier read FPembeli write FPembeli; property PenerimaanKasARItems: TObjectlist<TPenerimaanKasAR> read GetPenerimaanKasARItems write FPenerimaanKasARItems; property Petugas: string read FPetugas write FPetugas; property RekBank: TRekBank read FRekBank write FRekBank; property TglBukti: TDatetime read FTglBukti write FTglBukti; property PenerimaanKasAPNewItems: TObjectList<TPenerimaanKasAPNew> read GetPenerimaanKasAPNewItems write FPenerimaanKasAPNewItems; property PenerimaanKasLainItems: TObjectList<TPenerimaanKasLain> read GetPenerimaanKasLainItems write FPenerimaanKasLainItems; end; TPenerimaanKasAPNew = class(TAppObjectItem) private FAccount: TAccount; FAP: TAP; FKeterangan: string; FNominal: Double; FPenerimaanKas: TPenerimaanKas; public function GetHeaderField: string; override; procedure SetHeaderProperty(AHeaderProperty : TAppObject); override; published property Account: TAccount read FAccount write FAccount; property AP: TAP read FAP write FAP; property Keterangan: string read FKeterangan write FKeterangan; property Nominal: Double read FNominal write FNominal; property PenerimaanKas: TPenerimaanKas read FPenerimaanKas write FPenerimaanKas; end; TPenerimaanKasLain = class(TAppObjectItem) private FAccount: TAccount; FKeterangan: string; FNominal: Double; FPenerimaanKas: TPenerimaanKas; public function GetHeaderField: string; override; procedure SetHeaderProperty(AHeaderProperty : TAppObject); override; published property Account: TAccount read FAccount write FAccount; property Keterangan: string read FKeterangan write FKeterangan; property Nominal: Double read FNominal write FNominal; property PenerimaanKas: TPenerimaanKas read FPenerimaanKas write FPenerimaanKas; end; implementation function TPenerimaanKasAR.GetHeaderField: string; begin Result := 'PenerimaanKas'; end; function TPenerimaanKasAR.GetUangSisa: Double; begin FUangSisa := FUangBayar - FNominal; Result := FUangSisa; end; procedure TPenerimaanKasAR.SetHeaderProperty(AHeaderProperty : TAppObject); begin Self.PenerimaanKas := TPenerimaanKas(AHeaderProperty); end; destructor TPenerimaanKas.Destroy; var I: Integer; begin inherited; FreeAndNil(FRekBank); FreeAndNil(FPembeli); FreeAndNil(FCabang); for I := 0 to PenerimaanKasARItems.Count - 1 do begin PenerimaanKasARItems[i].AR.Free; end; PenerimaanKasARItems.Free; end; function TPenerimaanKas.GetPenerimaanKasARItems: TObjectlist<TPenerimaanKasAR>; begin if FPenerimaanKasARItems = nil then FPenerimaanKasARItems := TObjectList<TPenerimaanKasAR>.Create(False); Result := FPenerimaanKasARItems; end; function TPenerimaanKas.GetPenerimaanKasAPNewItems: TObjectList<TPenerimaanKasAPNew>; begin if FPenerimaanKasAPNewItems = nil then FPenerimaanKasAPNewItems := TObjectList<TPenerimaanKasAPNew>.Create; Result := FPenerimaanKasAPNewItems; end; function TPenerimaanKas.GetPenerimaanKasLainItems: TObjectList<TPenerimaanKasLain>; begin if FPenerimaanKasLainItems = nil then FPenerimaanKasLainItems := TObjectList<TPenerimaanKasLain>.Create; Result := FPenerimaanKasLainItems; end; function TPenerimaanKasAPNew.GetHeaderField: string; begin Result := 'PenerimaanKas'; end; procedure TPenerimaanKasAPNew.SetHeaderProperty(AHeaderProperty : TAppObject); begin Self.PenerimaanKas := TPenerimaanKas(AHeaderProperty); end; function TPenerimaanKasLain.GetHeaderField: string; begin Result := 'PenerimaanKas'; end; procedure TPenerimaanKasLain.SetHeaderProperty(AHeaderProperty : TAppObject); begin Self.PenerimaanKas := TPenerimaanKas(AHeaderProperty); end; end.
unit mnSynHighlighterLua; {$mode objfpc}{$H+} {** * * This file is part of the "Mini Library" * * @url http://www.sourceforge.net/projects/minilib * @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html) * See the file COPYING.MLGPL, included in this distribution, * @author Zaher Dirkey *} interface uses Classes, SysUtils, SynEdit, SynEditTypes, SynEditHighlighter, SynHighlighterHashEntries, mnSynHighlighterMultiProc; type { TLuaProcessor } TLuaProcessor = class(TCommonSynProcessor) private protected function GetIdentChars: TSynIdentChars; override; function GetEndOfLineAttribute: TSynHighlighterAttributes; override; procedure Created; override; public procedure QuestionProc; procedure DirectiveProc; procedure DashProc; procedure BracketProc; procedure GreaterProc; procedure LowerProc; procedure Next; override; procedure Prepare; override; procedure MakeProcTable; override; end; { TmnSynLuaSyn } TmnSynLuaSyn = class(TSynMultiProcSyn) private protected function GetSampleSource: string; override; public class function GetLanguageName: string; override; public constructor Create(AOwner: TComponent); override; procedure InitProcessors; override; published end; const SYNS_LangLua = 'Lua'; SYNS_FilterLua = 'Lua Lang Files (*.lua)|*.lua'; cLuaSample = '-- defines a factorial function'#13#10+ 'function fact(n)'#13#10+ ' if n == 0 then'#13#10+ ' return 1'#13#10+ ' else'#13#10+ ' return n * fact(n-1)'#13#10+ ' end'#13#10+ 'end'#13#10; {$INCLUDE 'LuaKeywords.inc'} implementation uses mnUtils; procedure TLuaProcessor.GreaterProc; begin Parent.FTokenID := tkSymbol; Inc(Parent.Run); if Parent.FLine[Parent.Run] in ['=', '>'] then Inc(Parent.Run); end; procedure TLuaProcessor.LowerProc; begin Parent.FTokenID := tkSymbol; Inc(Parent.Run); case Parent.FLine[Parent.Run] of '=': Inc(Parent.Run); '<': begin Inc(Parent.Run); if Parent.FLine[Parent.Run] = '=' then Inc(Parent.Run); end; end; end; procedure TLuaProcessor.DashProc; begin Inc(Parent.Run); case Parent.FLine[Parent.Run] of '-': begin Inc(Parent.Run); if Parent.FLine[Parent.Run] = '*' then DocumentSLProc else if ScanMatch('TODO') then DocumentSLProc else if ScanMatch('[[') then begin if Parent.FLine[Parent.Run] = '*' then DocumentMLProc else CommentMLProc; end else CommentSLProc; end; else Parent.FTokenID := tkSymbol; end; end; procedure TLuaProcessor.BracketProc; begin Inc(Parent.Run); case Parent.FLine[Parent.Run] of '[': begin SetRange(rscSpecialString); Inc(Parent.Run); SpecialStringProc; end else Parent.FTokenID := tkSymbol; end; end; procedure TLuaProcessor.MakeProcTable; var I: Char; begin inherited; for I := #0 to #255 do case I of '?': ProcTable[I] := @QuestionProc; '''': ProcTable[I] := @StringSQProc; '"': ProcTable[I] := @StringDQProc; '[': ProcTable[I] := @BracketProc; '-': ProcTable[I] := @DashProc; '>': ProcTable[I] := @GreaterProc; '<': ProcTable[I] := @LowerProc; '0'..'9': ProcTable[I] := @NumberProc; 'A'..'Z', 'a'..'z', '_': ProcTable[I] := @IdentProc; end; end; procedure TLuaProcessor.QuestionProc; begin Inc(Parent.Run); case Parent.FLine[Parent.Run] of '>': begin Parent.Processors.Switch(Parent.Processors.MainProcessor); Inc(Parent.Run); Parent.FTokenID := tkProcessor; end else Parent.FTokenID := tkSymbol; end; end; procedure TLuaProcessor.DirectiveProc; begin Parent.FTokenID := tkProcessor; WordProc; end; procedure TLuaProcessor.Next; begin Parent.FTokenPos := Parent.Run; if (Parent.FLine[Parent.Run] in [#0, #10, #13]) then ProcTable[Parent.FLine[Parent.Run]] else case Range of rscComment: CommentMLProc; rscDocument: DocumentMLProc; rscStringSQ, rscStringDQ, rscStringBQ: StringProc; rscSpecialString: SpecialStringProc; else if ProcTable[Parent.FLine[Parent.Run]] = nil then UnknownProc else ProcTable[Parent.FLine[Parent.Run]]; end; end; procedure TLuaProcessor.Prepare; begin inherited; EnumerateKeywords(Ord(tkKeyword), sLuaKeywords, TSynValidStringChars, @DoAddKeyword); EnumerateKeywords(Ord(tkType), sLuaTypes, TSynValidStringChars, @DoAddKeyword); EnumerateKeywords(Ord(tkFunction), sLuaFunctions, TSynValidStringChars + ['.'], @DoAddKeyword); SetRange(rscUnknown); end; function TLuaProcessor.GetEndOfLineAttribute: TSynHighlighterAttributes; begin if (Range = rscDocument) or (LastRange = rscDocument) then Result := Parent.DocumentAttri else Result := inherited GetEndOfLineAttribute; end; procedure TLuaProcessor.Created; begin inherited Created; CloseComment := ']]'; CloseSpecialString := ']]'; end; function TLuaProcessor.GetIdentChars: TSynIdentChars; begin Result := TSynValidStringChars + ['.']; end; constructor TmnSynLuaSyn.Create(AOwner: TComponent); begin inherited Create(AOwner); FDefaultFilter := SYNS_FilterLua; end; procedure TmnSynLuaSyn.InitProcessors; begin inherited; Processors.Add(TLuaProcessor.Create(Self, 'Lua')); Processors.MainProcessor := 'Lua'; Processors.DefaultProcessor := 'Lua'; end; class function TmnSynLuaSyn.GetLanguageName: string; begin Result := 'Lua'; end; function TmnSynLuaSyn.GetSampleSource: string; begin Result := cLuaSample; end; end.
unit InputLine; interface uses BaseDevice, SysUtils, Graphics, Classes, Windows, MSScriptControl_TLB, Activex, ComObj, SyncObjs; type TDoubleArr = array of Double; TCurrentCalibration = (MultiplierOffset, Sheet, Script); TInputLine = class; IInputLineChangedCallback = interface procedure OnInputLineChanged(inputLine : TInputLine); end; TInputLine = class Constructor Create(device : IBaseRequestOnlyDevice; index : integer); function IsListening() : boolean; procedure SetListeningFlag(flag : boolean); procedure SetName(newName : string); function GetName() : string; procedure SetGraphColor(newColor : TColor); function GetGraphColor() : TColor; function GetIndeviceIndex() : integer; function GetGraphWidth() : integer; procedure SetGraphWidth(newWidth : integer); function GetOffset() : double; function GetMultiplier() : double; procedure SetOffsetAndMultiplier(newOffset, newMultiplier: double); function GetScriptText() : string; procedure SetScriptText(scriptText : string); function Calibrate(val : integer) : double; procedure SubscribeOnInputLineChanged(callback : IInputLineChangedCallback); procedure UnSubscribeOnInputLineChanged(callback : IInputLineChangedCallback); function GetMinInputVal : integer; function GetMaxInputVal : integer; procedure SetSheedData(corr : TDoubleArr); Destructor Destroy; override; private requestOnlyDevice : IBaseRequestOnlyDevice; inDeviceIndex : integer; name : string; graphColor : TColor; graphWidth : integer; inputLineChangedObservers : TList; offset : double; multiplier : double; listenersCount : integer; currentCalibration : TCurrentCalibration; scriptSection : TCriticalSection; scriptText : string; scriptMachine : TScriptControl; needRecompileScript : boolean; sheetData : TDoubleArr; procedure fireInputLineChanged; function CalibrateMultiplierOffset(val : integer) : double; function CalibrateSheet(val : integer) : double; function CalibrateScript(val : integer) : double; end; implementation { TInputLine } function TInputLine.Calibrate(val: integer): double; begin case self.currentCalibration of MultiplierOffset: Result := self.CalibrateMultiplierOffset(val); Sheet: Result := self.CalibrateSheet(val); Script: Result := self.CalibrateScript(val); else Result := 0; end; end; function TInputLine.CalibrateMultiplierOffset(val: integer): double; begin Result := val * self.multiplier + offset; end; function TInputLine.CalibrateScript(val: integer): double; begin if not Assigned(self.scriptMachine) then begin CoInitialize(nil); self.scriptMachine := TScriptControl.Create(nil); scriptMachine.Language := 'JScript'; end; scriptSection.Enter; if self.needRecompileScript then begin scriptMachine.AddCode('var Calibrate = function(inputData){'+#10+#13+scriptText+#10+#13+'}'); needRecompileScript := false; end; scriptSection.Leave; try Result := double(scriptMachine.Eval('Calibrate(' + FloatToStr(val) + ')')); except on Exception : EOleException do begin Result := 0; exit; end; end; end; function TInputLine.CalibrateSheet(val: integer): double; begin Result := sheetData[val]; end; constructor TInputLine.Create(device: IBaseRequestOnlyDevice; index: integer); begin offset := 0; multiplier := 1; listenersCount := 0; self.inDeviceIndex := index; self.requestOnlyDevice := device; name := 'Channel ' + IntToStr(index + 1); graphWidth := 1; inputLineChangedObservers := TList.Create; self.currentCalibration := MultiplierOffset; scriptText := 'return inputData'; self.scriptSection := TCriticalSection.Create; needRecompileScript := false; end; destructor TInputLine.Destroy; var i : integer; begin for i := 0 to self.inputLineChangedObservers.Count - 1 do begin (IInputLineChangedCallback(self.inputLineChangedObservers[i]))._Release; end; end; procedure TInputLine.fireInputLineChanged; var i : integer; begin for i := 0 to self.inputLineChangedObservers.Count - 1 do begin (IInputLineChangedCallback(self.inputLineChangedObservers[i])).OnInputLineChanged(self); end; end; function TInputLine.GetGraphColor: TColor; begin Result := self.graphColor; end; function TInputLine.GetGraphWidth: integer; begin Result := self.graphWidth; end; function TInputLine.GetIndeviceIndex: integer; begin Result := self.inDeviceIndex; end; function TInputLine.GetMaxInputVal: integer; begin Result := requestOnlyDevice.GetMaximumValInInputLine(self.inDeviceIndex); end; function TInputLine.GetMinInputVal: integer; begin Result := requestOnlyDevice.GetMinimumValInInputLine(self.inDeviceIndex); end; function TInputLine.GetMultiplier: double; begin Result := self.multiplier; end; function TInputLine.GetName: string; begin Result := name; end; function TInputLine.GetOffset: double; begin Result := self.offset; end; function TInputLine.GetScriptText: string; begin Result := self.scriptText; end; function TInputLine.IsListening: boolean; begin Result := self.listenersCount > 0; end; procedure TInputLine.SetGraphColor(newColor: TColor); begin graphColor := newColor; self.fireInputLineChanged; end; procedure TInputLine.SetGraphWidth(newWidth: integer); begin self.graphWidth := newWidth; self.fireInputLineChanged; end; procedure TInputLine.SetListeningFlag(flag: boolean); begin if (flag) then InterlockedIncrement(self.listenersCount) else InterlockedDecrement(self.listenersCount); end; procedure TInputLine.SetName(newName: string); begin name := newName; self.fireInputLineChanged; end; procedure TInputLine.SetOffsetAndMultiplier(newOffset, newMultiplier: double); begin self.offset := newOffset; self.multiplier := newMultiplier; self.currentCalibration := MultiplierOffset; end; procedure TInputLine.SetScriptText(scriptText: string); var testScriptMachine : TScriptControl; begin CoInitialize(nil); testScriptMachine := TScriptControl.Create(nil); try testScriptMachine.Language := 'JScript'; testScriptMachine.AddCode('var testFunc = function(inputData){'+#10+#13+scriptText+#10+#13+'}'); testScriptMachine.Eval('testFunc(1)'); except on Exception : EOleException do begin MessageBox(0, PAnsiChar(Exception.Message), 'Error in script', MB_OK or MB_ICONERROR); exit; end; end; scriptSection.Enter; self.scriptText := scriptText; needRecompileScript := true; self.currentCalibration := Script; scriptSection.Leave; end; procedure TInputLine.SetSheedData(corr: TDoubleArr); var rangeMin, rangeMax : integer; begin rangeMin := self.GetMinInputVal; rangeMax := self.GetMaxInputVal; if (Length(corr) = (rangeMax - rangeMin + 1)) then begin self.sheetData := corr; self.currentCalibration := Sheet; end; end; procedure TInputLine.SubscribeOnInputLineChanged( callback: IInputLineChangedCallback); begin callback._AddRef; self.inputLineChangedObservers.Add(Pointer(callback)); end; procedure TInputLine.UnSubscribeOnInputLineChanged( callback: IInputLineChangedCallback); var i : integer; var callbackInList : IInputLineChangedCallback; begin for i := 0 to inputLineChangedObservers.Count - 1 do begin callbackInList := IInputLineChangedCallback(inputLineChangedObservers[i]); if (callbackInList = callback) then begin inputLineChangedObservers.Delete(i); callback._Release; exit; end; end; end; end.
unit furqDecoders; interface procedure QS2Decode(aData: PByte; aDataSize: Longword; aBuffer: PByte); procedure QS1Decode(aData: PByte; aDataSize: Longword); procedure BFDecode(aData: Pointer; aDataSize: Longword; aBuffer: Pointer); function Crc32(X: PByte; N: Integer): Cardinal; implementation uses SysUtils; {$I bfshkeys.pas.inc} {$OVERFLOWCHECKS OFF} const cQS2key: string = '04 Корянов Виктор <victor2@nm.ru>, http://urq.ru/urq_dos'; function BF_F(xL: Longword): Longword; {$IFDEF VER170}inline;{$ENDIF} begin Result:= (((cBF_SBox[0, (xL shr 24) and $FF] + cBF_SBox[1, (xL shr 16) and $FF]) xor cBF_SBox[2, (xL shr 8) and $FF]) + cBF_SBox[3, xL and $FF]); end; procedure BFDoRound(var xL, xR: Longword; RNum: Integer); {$IFDEF VER170}inline;{$ENDIF} begin xL:= xL xor BF_F(xR) xor cBF_PBox[RNum]; end; procedure BlowfishDecryptECB(InData, OutData: Pointer); var xL, xR: Longword; begin Move(InData^, xL, 4); Move(Pointer(Integer(InData) + 4)^, xR, 4); xL:= xL xor cBF_PBox[17]; BFDoRound(xR, xL, 16); BFDoRound(xL, xR, 15); BFDoRound(xR, xL, 14); BFDoRound(xL, xR, 13); BFDoRound(xR, xL, 12); BFDoRound(xL, xR, 11); BFDoRound(xR, xL, 10); BFDoRound(xL, xR, 9); BFDoRound(xR, xL, 8); BFDoRound(xL, xR, 7); BFDoRound(xR, xL, 6); BFDoRound(xL, xR, 5); BFDoRound(xR, xL, 4); BFDoRound(xL, xR, 3); BFDoRound(xR, xL, 2); BFDoRound(xL, xR, 1); xR:= xR xor cBF_PBox[0]; Move(xR, OutData^, 4); Move(xL, Pointer(Integer(OutData) + 4)^, 4); end; procedure BFDecode(aData: Pointer; aDataSize: Longword; aBuffer: Pointer); var l_BlockNum: Integer; I: Integer; begin l_BlockNum := aDataSize div 8; if l_BlockNum = 0 then Exit; I := 0; repeat BlowfishDecryptECB(aData, aBuffer); Inc(Longword(aData), 8); Inc(Longword(aBuffer), 8); Inc(I); until I = l_BlockNum; end; {$R-} procedure QS2Decode(aData: PByte; aDataSize: Longword; aBuffer: PByte); var I: Integer; K: Integer; E: Byte; C: Byte; begin K := 1; E := 9; for I := 1 to aDataSize do begin C := aData^; C := (C - E - Byte(cQS2Key[K])); aBuffer^ := C; Inc(K); if K > Length(cQS2Key) then begin E := E + 1; K := 1; end; Inc(Longword(aData)); Inc(Longword(aBuffer)); end; end; const Crc32Table: array [0..255] of Longword = ( $00000000, $77073096, $EE0E612C, $990951BA, $076DC419, $706AF48F, $E963A535, $9E6495A3, $0EDB8832, $79DCB8A4, $E0D5E91E, $97D2D988, $09B64C2B, $7EB17CBD, $E7B82D07, $90BF1D91, $1DB71064, $6AB020F2, $F3B97148, $84BE41DE, $1ADAD47D, $6DDDE4EB, $F4D4B551, $83D385C7, $136C9856, $646BA8C0, $FD62F97A, $8A65C9EC, $14015C4F, $63066CD9, $FA0F3D63, $8D080DF5, $3B6E20C8, $4C69105E, $D56041E4, $A2677172, $3C03E4D1, $4B04D447, $D20D85FD, $A50AB56B, $35B5A8FA, $42B2986C, $DBBBC9D6, $ACBCF940, $32D86CE3, $45DF5C75, $DCD60DCF, $ABD13D59, $26D930AC, $51DE003A, $C8D75180, $BFD06116, $21B4F4B5, $56B3C423, $CFBA9599, $B8BDA50F, $2802B89E, $5F058808, $C60CD9B2, $B10BE924, $2F6F7C87, $58684C11, $C1611DAB, $B6662D3D, $76DC4190, $01DB7106, $98D220BC, $EFD5102A, $71B18589, $06B6B51F, $9FBFE4A5, $E8B8D433, $7807C9A2, $0F00F934, $9609A88E, $E10E9818, $7F6A0DBB, $086D3D2D, $91646C97, $E6635C01, $6B6B51F4, $1C6C6162, $856530D8, $F262004E, $6C0695ED, $1B01A57B, $8208F4C1, $F50FC457, $65B0D9C6, $12B7E950, $8BBEB8EA, $FCB9887C, $62DD1DDF, $15DA2D49, $8CD37CF3, $FBD44C65, $4DB26158, $3AB551CE, $A3BC0074, $D4BB30E2, $4ADFA541, $3DD895D7, $A4D1C46D, $D3D6F4FB, $4369E96A, $346ED9FC, $AD678846, $DA60B8D0, $44042D73, $33031DE5, $AA0A4C5F, $DD0D7CC9, $5005713C, $270241AA, $BE0B1010, $C90C2086, $5768B525, $206F85B3, $B966D409, $CE61E49F, $5EDEF90E, $29D9C998, $B0D09822, $C7D7A8B4, $59B33D17, $2EB40D81, $B7BD5C3B, $C0BA6CAD, $EDB88320, $9ABFB3B6, $03B6E20C, $74B1D29A, $EAD54739, $9DD277AF, $04DB2615, $73DC1683, $E3630B12, $94643B84, $0D6D6A3E, $7A6A5AA8, $E40ECF0B, $9309FF9D, $0A00AE27, $7D079EB1, $F00F9344, $8708A3D2, $1E01F268, $6906C2FE, $F762575D, $806567CB, $196C3671, $6E6B06E7, $FED41B76, $89D32BE0, $10DA7A5A, $67DD4ACC, $F9B9DF6F, $8EBEEFF9, $17B7BE43, $60B08ED5, $D6D6A3E8, $A1D1937E, $38D8C2C4, $4FDFF252, $D1BB67F1, $A6BC5767, $3FB506DD, $48B2364B, $D80D2BDA, $AF0A1B4C, $36034AF6, $41047A60, $DF60EFC3, $A867DF55, $316E8EEF, $4669BE79, $CB61B38C, $BC66831A, $256FD2A0, $5268E236, $CC0C7795, $BB0B4703, $220216B9, $5505262F, $C5BA3BBE, $B2BD0B28, $2BB45A92, $5CB36A04, $C2D7FFA7, $B5D0CF31, $2CD99E8B, $5BDEAE1D, $9B64C2B0, $EC63F226, $756AA39C, $026D930A, $9C0906A9, $EB0E363F, $72076785, $05005713, $95BF4A82, $E2B87A14, $7BB12BAE, $0CB61B38, $92D28E9B, $E5D5BE0D, $7CDCEFB7, $0BDBDF21, $86D3D2D4, $F1D4E242, $68DDB3F8, $1FDA836E, $81BE16CD, $F6B9265B, $6FB077E1, $18B74777, $88085AE6, $FF0F6A70, $66063BCA, $11010B5C, $8F659EFF, $F862AE69, $616BFFD3, $166CCF45, $A00AE278, $D70DD2EE, $4E048354, $3903B3C2, $A7672661, $D06016F7, $4969474D, $3E6E77DB, $AED16A4A, $D9D65ADC, $40DF0B66, $37D83BF0, $A9BCAE53, $DEBB9EC5, $47B2CF7F, $30B5FFE9, $BDBDF21C, $CABAC28A, $53B39330, $24B4A3A6, $BAD03605, $CDD70693, $54DE5729, $23D967BF, $B3667A2E, $C4614AB8, $5D681B02, $2A6F2B94, $B40BBE37, $C30C8EA1, $5A05DF1B, $2D02EF8D ); Crc32Start: Cardinal = $FFFFFFFF; function Crc32(X: PByte; N: Integer): Cardinal; var I: Integer; begin Result := Crc32Start; for I := 1 to N do // The CRC Bytes are located at the end of the information begin Result := (Result shr 8) xor Crc32Table[(Result xor X^) and $FF]; Inc(Longword(X)); end; Result := Result xor Crc32Start; end; procedure QS1Decode(aData: PByte; aDataSize: Longword); var I: Longword; begin for I := 1 to aDataSize do begin if aData^ >= 32 then aData^ := 31 - aData^; Inc(Longword(aData)); end; end; end.
//** Сцена умений персонажа. unit uSceneSkill; interface uses Types, Graphics, uScene, uImage, uSkillTree; type //** Сцена умений персонажа. TSceneSkill = class(TSceneFrame) private //** ID навыка под указателем мыши. function GetID: Integer; public //** Умения персонажа. Skill: TSkill; //** Позиция иконки навыка в древе. PRect: array [0..SkillCount] of TRect; //** Конструктор. constructor Create; //** Деструктор. destructor Destroy; override; //** Рендер сцены. procedure Draw(); override; //** Нажата клавиша мыши. function MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; override; //** Указатель на текущую сцену. function Enum(): TSceneEnum; override; //** Движение указателя мыши. function MouseMove(X, Y: Integer): Boolean; override; //** Щелчок мышью. function Click(Button: TMouseBtn): Boolean; override; end; var //** Сцена умений персонажа. SceneSkill: TSceneSkill; implementation uses SysUtils, uSaveLoad, uUtils, uColors, uBox, uVars, uScript; { TSceneSkill } function TSceneSkill.GetID: Integer; var I: ShortInt; begin Result := -1; for I := 0 to SkillCount - 1 do begin if IsMouseInRect(Skill.GetIconPos(I).X + 400, Skill.GetIconPos(I).Y, Skill.GetIconPos(I).X + 464, Skill.GetIconPos(I).Y + 64) then begin Result := I; Exit; end; end; end; function TSceneSkill.Click(Button: TMouseBtn): Boolean; begin Result := inherited Click(Button); case Button of mbLeft: if (GetID >= 0) then if Skill.Inc(GetID) then begin Run('Calculator.pas'); SceneManager.Draw(); end; end; end; constructor TSceneSkill.Create; begin inherited Create(spRight); Skill := TSkill.Create; end; destructor TSceneSkill.Destroy; begin FreeAndNil(Skill); inherited; end; procedure TSceneSkill.Draw; begin inherited; Back.Canvas.Font.Color := cBlackRare; Skill.RenderAsTree(Back.Canvas); if (GetID >= 0) then Hint.ShowSkill(Skill.GetIconPos(GetID).X, Skill.GetIconPos(GetID).Y, GetID, True, Origin, HintBack); Refresh; end; function TSceneSkill.Enum: TSceneEnum; begin Result := scSkill; end; function TSceneSkill.MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; begin Result := False; Self.Draw; SceneManager.Draw(); end; function TSceneSkill.MouseMove(X, Y: Integer): Boolean; begin Result := False; Self.Draw; SceneManager.Draw(); end; initialization finalization SceneSkill.Free; end.
unit UCalcWheel; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.FlexCel.Core, FlexCel.XlsAdapter, FMX.Edit, FMX.Objects, FMX.Platform, FMX.Layouts, FMX.ListBox, FMX.Ani; type TWheelForm = class(TForm) ToolBar1: TToolBar; btnCalc: TSpeedButton; lblEntry: TLabel; edEntry: TEdit; lblResult: TLabel; edResult: TEdit; Wheel: TImage; lblCurrent: TLabel; WheelPop: TPopup; WheelListBox: TListBox; ColorKeyAnimation1: TColorKeyAnimation; procedure btnCalcClick(Sender: TObject); procedure WheelClick(Sender: TObject); procedure FormCreate(Sender: TObject); private Workbook: TXlsFile; procedure WheelListItemBoxClick(Sender: TObject); procedure LoadConfig; procedure CreateConfig; function GetCell(const sheet: string; const r, c: integer): string; function ConfigFile: string; procedure LoadPopupItems; function DocFolder: string; procedure Calc; public { Public declarations } end; var WheelForm: TWheelForm; implementation uses IOUtils; {$R *.fmx} function TWheelForm.GetCell(const sheet: string; const r, c: integer): string; var ResultIndex: integer; begin Result := '*Error*'; ResultIndex := Workbook.GetSheetIndex(sheet, false); if (ResultIndex < 1) then begin exit; end; Workbook.ActiveSheet := ResultIndex; Result := Workbook.GetStringFromCell(r, c); end; function TWheelForm.ConfigFile: string; begin Result := TPath.GetLibraryPath + '/Preferences/config.txt'; end; function TWheelForm.DocFolder: string; begin Result := TPath.GetLibraryPath + '/'; end; procedure TWheelForm.LoadConfig; var sr: TStreamReader; fn: string; begin try if (TFile.Exists(ConfigFile)) then begin sr := TStreamReader.Create(ConfigFile); fn := sr.ReadLine; end else begin fn := DocFolder + 'default.xls'; end; if fn = '' then Workbook := TXlsFile.Create(1, true) else Workbook := TXlsFile.Create(fn, true); except on ex: Exception do begin Workbook := TXlsFile.Create(1, true); end; end; lblCurrent.Text := TPath.GetFileNameWithoutExtension(Workbook.ActiveFileName); lblEntry.Text := GetCell('Data', 1, 1); Calc; end; procedure TWheelForm.CreateConfig; var sw: TStreamWriter; begin sw := TStreamWriter.Create(ConfigFile); sw.WriteLine(Workbook.ActiveFileName); end; procedure TWheelForm.Calc; var DataIndex, ResultIndex: integer; begin DataIndex := Workbook.GetSheetIndex('Data', false); if (DataIndex < 1) then begin ShowMessage('Can''t find the sheet "Data"'); exit; end; Workbook.ActiveSheet := DataIndex; Workbook.SetCellFromString(1, 2, edEntry.Text); ResultIndex := Workbook.GetSheetIndex('Result', false); if (ResultIndex < 1) then begin ShowMessage('Can''t find the sheet "Result"'); exit; end; Workbook.Recalc; Workbook.ActiveSheet := ResultIndex; lblResult.Text := Workbook.GetStringFromCell(1,1); edResult.Text := Workbook.GetStringFromCell(1,2); end; procedure TWheelForm.btnCalcClick(Sender: TObject); begin Calc; end; procedure TWheelForm.FormCreate(Sender: TObject); begin LoadConfig; end; procedure TWheelForm.LoadPopupItems; var fn: string; files: TStringDynArray; li: TListBoxItem; begin WheelListBox.Items.Clear; files := TDirectory.GetFiles(DocFolder, '*.xls'); for fn in files do begin li := TListBoxItem.Create(WheelListBox); li.Text := TPath.GetFileNameWithoutExtension(fn); li.OnClick := WheelListItemBoxClick; WheelListBox.AddObject(li); end; end; procedure TWheelForm.WheelClick(Sender: TObject); begin LoadPopupItems; WheelPop.Popup; end; procedure TWheelForm.WheelListItemBoxClick(Sender: TObject); begin WheelPop.Visible := false; try Workbook.Open(DocFolder + (Sender as TListBoxItem).Text + '.xls'); except ShowMessage('Invalid file: ' + (Sender as TListBoxItem).Text); Workbook.NewFile(1); end; CreateConfig; LoadConfig; end; end.
unit mcCodeInsideSymbols; interface uses Classes, ToolsAPI; type TCodeInsightSymbolList = class(TInterfacedObject, IOTACodeInsightSymbolList) private FStrings: Tstrings; public procedure AfterConstruction;override; destructor Destroy; override; procedure AddSymbol(const aText: string); protected { Implementor should clear its symbol list } procedure Clear; { returns the count of the symbols in the list - may be modified by setting a filter - } function GetCount: Integer; { returns whether the symbol is able to be read from and written to } function GetSymbolIsReadWrite(I: Integer): Boolean; { returns whether the symbols is abstract. Viewer draws these in the 'need to implement' color } function GetSymbolIsAbstract(I: Integer): Boolean; { return the symbol flags for the item at index 'I'. I is the index in the filtered list } function GetViewerSymbolFlags(I: Integer): TOTAViewerSymbolFlags; { return the visibility flags for the item at index 'I'. I is the index in the filtered list } function GetViewerVisibilityFlags(I: Integer): TOTAViewerVisibilityFlags; { return the procedure flags for the item at index 'I'. I is the index in the filtered list } function GetProcDispatchFlags(I: Integer): TOTAProcDispatchFlags; { The list was requested to be sorted by 'Value' } procedure SetSortOrder(const Value: TOTASortOrder); { returns the sort order of the list } function GetSortOrder: TOTASortOrder; { given an identifier, return the index of the closest partial match } function FindIdent(const AnIdent: string): Integer; { given an identifier, find the 'Index' of an exact match in the list and return True. Otherwise return False } function FindSymIndex(const Ident: string; var Index: Integer): Boolean; { set the lists filter to 'FilterText'. It is up to the implementor to determine how to filter or if they even want to filter } procedure SetFilter(const FilterText: string); { return the symbol text for item 'Index'. i.e. Form1 } function GetSymbolText(Index: Integer): string; { return the symbol type text for item 'Index'. i.e. TForm1 } function GetSymbolTypeText(Index: Integer): string; { return the symbol class text for item 'Index'. i.e. 'var', 'function', 'type', etc } function GetSymbolClassText(I: Integer): string; property SymbolClassText[I: Integer]: string read GetSymbolClassText; property SymbolTypeText[I: Integer]: string read GetSymbolTypeText; property SymbolText[I: Integer]: string read GetSymbolText; property SymbolFlags[I: Integer]: TOTAViewerSymbolFlags read GetViewerSymbolFlags; property SymbolVisibility[I: Integer]: TOTAViewerVisibilityFlags read GetViewerVisibilityFlags; property SymbolIsAbstract[I: Integer]: Boolean read GetSymbolIsAbstract; property SymbolIsReadWrite[I: Integer]: Boolean read GetSymbolIsReadWrite; property FuncDispatchFlags[I: Integer]: TOTAProcDispatchFlags read GetProcDispatchFlags; property SortOrder: TOTASortOrder read GetSortOrder write SetSortOrder; property Count: Integer read GetCount; end; implementation { TCodeInsightSymbolList } procedure TCodeInsightSymbolList.AddSymbol(const aText: string); begin FStrings.Add(aText); end; procedure TCodeInsightSymbolList.AfterConstruction; begin inherited; FStrings := TStringList.Create; end; procedure TCodeInsightSymbolList.Clear; begin FStrings.Clear; end; destructor TCodeInsightSymbolList.Destroy; begin FStrings.Free; inherited; end; function TCodeInsightSymbolList.FindIdent(const AnIdent: string): Integer; begin Result := 0; end; function TCodeInsightSymbolList.FindSymIndex(const Ident: string; var Index: Integer): Boolean; begin Index := FStrings.IndexOf(Ident); Result := Index >= 0; end; function TCodeInsightSymbolList.GetCount: Integer; begin Result := FStrings.Count; end; function TCodeInsightSymbolList.GetProcDispatchFlags( I: Integer): TOTAProcDispatchFlags; begin Result := pdfNone; end; function TCodeInsightSymbolList.GetSortOrder: TOTASortOrder; begin Result := soAlpha; end; function TCodeInsightSymbolList.GetSymbolClassText(I: Integer): string; begin Result := 'My class'; end; function TCodeInsightSymbolList.GetSymbolIsAbstract(I: Integer): Boolean; begin Result := False; end; function TCodeInsightSymbolList.GetSymbolIsReadWrite(I: Integer): Boolean; begin Result := False; end; function TCodeInsightSymbolList.GetSymbolText(Index: Integer): string; begin Result := FStrings.Strings[Index]; end; function TCodeInsightSymbolList.GetSymbolTypeText(Index: Integer): string; begin Result := 'My type'; end; function TCodeInsightSymbolList.GetViewerSymbolFlags( I: Integer): TOTAViewerSymbolFlags; begin Result := vsfProcedure; end; function TCodeInsightSymbolList.GetViewerVisibilityFlags( I: Integer): TOTAViewerVisibilityFlags; begin Result := 0; end; procedure TCodeInsightSymbolList.SetFilter(const FilterText: string); begin // end; procedure TCodeInsightSymbolList.SetSortOrder(const Value: TOTASortOrder); begin // end; end.
unit Model.Generator; interface uses Model.Interfaces, Model.Generator.Params, Model.EntityGenerate, Model.ModelGenerate, Model.RoutersGenerate; type TModelGenerator = class(TInterfacedObject, iModelGenerator) private FParams : iModelGeneratorParams; public constructor Create; Destructor Destroy; override; class function New : iModelGenerator; function Params : iModelGeneratorParams; function EntityGenerate: iModelEntityGenerate; function ModelGenerate: iModelModelGenerate; function RoutersGenerate: iModelRoutersGenerate; end; implementation { TModelEntityGenerate } constructor TModelGenerator.Create; begin FParams := TModelGeneratorParams.New(Self); end; destructor TModelGenerator.Destroy; begin inherited; end; function TModelGenerator.EntityGenerate: iModelEntityGenerate; begin Result := TModelEntityGenerate.New(Self); end; function TModelGenerator.ModelGenerate: iModelModelGenerate; begin Result := TModelModelGenerate.New(Self); end; class function TModelGenerator.New: iModelGenerator; begin Result := Self.Create; end; function TModelGenerator.Params: iModelGeneratorParams; begin Result := FParams; end; function TModelGenerator.RoutersGenerate: iModelRoutersGenerate; begin Result := TModelRoutersGenerate.New(Self); end; end.
unit ddRowProperty; // Модуль: "w:\common\components\rtl\Garant\dd\ddRowProperty.pas" // Стереотип: "SimpleClass" // Элемент модели: "TddRowProperty" MUID: (518A10050368) {$Include w:\common\components\rtl\Garant\dd\ddDefine.inc} interface uses l3IntfUses , ddPropertyObject , ddBorder , ddTypes , k2Interfaces ; type TddRowProperty = class(TddPropertyObject) private f_Gaph: LongInt; f_Left: LongInt; f_Width: LongInt; f_AutoFit: Boolean; f_Border: TddBorder; f_IsLastRow: Boolean; f_RowIndex: LongInt; f_trwWidthB: LongInt; f_trftsWidthA: TddRTFWidthUnits; f_trftsWidthB: TddRTFWidthUnits; f_trwWidthA: LongInt; protected procedure pm_SetAutoFit(aValue: Boolean); function pm_GettrwWidthB: LongInt; procedure pm_SettrwWidthB(aValue: LongInt); procedure pm_SettrftsWidthA(aValue: TddRTFWidthUnits); procedure pm_SettrftsWidthB(aValue: TddRTFWidthUnits); function pm_GettrwWidthA: LongInt; procedure pm_SettrwWidthA(aValue: LongInt); procedure Cleanup; override; {* Функция очистки полей объекта. } public procedure MergeWith(P: TddPropertyObject); override; procedure InheriteFrom(P: TddPropertyObject); override; procedure Write2Generator(const Generator: Ik2TagGenerator); override; procedure Reset; override; function Diff(P: TddPropertyObject; aForReader: Boolean): TddPropertyObject; override; constructor Create; override; {* конструктор объекта. Возвращает объект, со счетчиком ссылок равным 1. } procedure Clear; override; procedure AssignFrom(anOther: TddPropertyObject); override; public property Gaph: LongInt read f_Gaph write f_Gaph; property Left: LongInt read f_Left write f_Left; property Width: LongInt read f_Width write f_Width; property AutoFit: Boolean read f_AutoFit write pm_SetAutoFit; property Border: TddBorder read f_Border; property IsLastRow: Boolean read f_IsLastRow write f_IsLastRow; property RowIndex: LongInt read f_RowIndex write f_RowIndex; property trwWidthB: LongInt read pm_GettrwWidthB write pm_SettrwWidthB; property trftsWidthA: TddRTFWidthUnits read f_trftsWidthA write pm_SettrftsWidthA; property trftsWidthB: TddRTFWidthUnits read f_trftsWidthB write pm_SettrftsWidthB; property trwWidthA: LongInt read pm_GettrwWidthA write pm_SettrwWidthA; end;//TddRowProperty implementation uses l3ImplUses , l3Base , ddCellProperty //#UC START# *518A10050368impl_uses* //#UC END# *518A10050368impl_uses* ; procedure TddRowProperty.pm_SetAutoFit(aValue: Boolean); //#UC START# *518A11380166_518A10050368set_var* //#UC END# *518A11380166_518A10050368set_var* begin //#UC START# *518A11380166_518A10050368set_impl* f_AutoFit := aValue; //#UC END# *518A11380166_518A10050368set_impl* end;//TddRowProperty.pm_SetAutoFit function TddRowProperty.pm_GettrwWidthB: LongInt; //#UC START# *5390359B0041_518A10050368get_var* //#UC END# *5390359B0041_518A10050368get_var* begin //#UC START# *5390359B0041_518A10050368get_impl* Result := f_trwWidthB; //#UC END# *5390359B0041_518A10050368get_impl* end;//TddRowProperty.pm_GettrwWidthB procedure TddRowProperty.pm_SettrwWidthB(aValue: LongInt); //#UC START# *5390359B0041_518A10050368set_var* //#UC END# *5390359B0041_518A10050368set_var* begin //#UC START# *5390359B0041_518A10050368set_impl* f_trwWidthB := aValue; //#UC END# *5390359B0041_518A10050368set_impl* end;//TddRowProperty.pm_SettrwWidthB procedure TddRowProperty.pm_SettrftsWidthA(aValue: TddRTFWidthUnits); //#UC START# *561618B20192_518A10050368set_var* //#UC END# *561618B20192_518A10050368set_var* begin //#UC START# *561618B20192_518A10050368set_impl* f_TrftsWidthA := aValue; //#UC END# *561618B20192_518A10050368set_impl* end;//TddRowProperty.pm_SettrftsWidthA procedure TddRowProperty.pm_SettrftsWidthB(aValue: TddRTFWidthUnits); //#UC START# *561618E6019B_518A10050368set_var* //#UC END# *561618E6019B_518A10050368set_var* begin //#UC START# *561618E6019B_518A10050368set_impl* f_TrftsWidthB := aValue; //#UC END# *561618E6019B_518A10050368set_impl* end;//TddRowProperty.pm_SettrftsWidthB function TddRowProperty.pm_GettrwWidthA: LongInt; //#UC START# *56161936018E_518A10050368get_var* //#UC END# *56161936018E_518A10050368get_var* begin //#UC START# *56161936018E_518A10050368get_impl* Result := f_TrwWidthA; //#UC END# *56161936018E_518A10050368get_impl* end;//TddRowProperty.pm_GettrwWidthA procedure TddRowProperty.pm_SettrwWidthA(aValue: LongInt); //#UC START# *56161936018E_518A10050368set_var* //#UC END# *56161936018E_518A10050368set_var* begin //#UC START# *56161936018E_518A10050368set_impl* f_TrwWidthA := aValue; //#UC END# *56161936018E_518A10050368set_impl* end;//TddRowProperty.pm_SettrwWidthA procedure TddRowProperty.MergeWith(P: TddPropertyObject); //#UC START# *525E369F0158_518A10050368_var* //#UC END# *525E369F0158_518A10050368_var* begin //#UC START# *525E369F0158_518A10050368_impl* Assert(False); //#UC END# *525E369F0158_518A10050368_impl* end;//TddRowProperty.MergeWith procedure TddRowProperty.InheriteFrom(P: TddPropertyObject); //#UC START# *525E37430345_518A10050368_var* //#UC END# *525E37430345_518A10050368_var* begin //#UC START# *525E37430345_518A10050368_impl* Assert(False); //#UC END# *525E37430345_518A10050368_impl* end;//TddRowProperty.InheriteFrom procedure TddRowProperty.Write2Generator(const Generator: Ik2TagGenerator); //#UC START# *525E377B007E_518A10050368_var* //#UC END# *525E377B007E_518A10050368_var* begin //#UC START# *525E377B007E_518A10050368_impl* Assert(False); //#UC END# *525E377B007E_518A10050368_impl* end;//TddRowProperty.Write2Generator procedure TddRowProperty.Reset; //#UC START# *525E478A0232_518A10050368_var* //#UC END# *525E478A0232_518A10050368_var* begin //#UC START# *525E478A0232_518A10050368_impl* Assert(False); //#UC END# *525E478A0232_518A10050368_impl* end;//TddRowProperty.Reset function TddRowProperty.Diff(P: TddPropertyObject; aForReader: Boolean): TddPropertyObject; //#UC START# *525E47E10065_518A10050368_var* //#UC END# *525E47E10065_518A10050368_var* begin //#UC START# *525E47E10065_518A10050368_impl* Assert(False); Result := nil; //#UC END# *525E47E10065_518A10050368_impl* end;//TddRowProperty.Diff constructor TddRowProperty.Create; {* конструктор объекта. Возвращает объект, со счетчиком ссылок равным 1. } //#UC START# *47914F960008_518A10050368_var* //#UC END# *47914F960008_518A10050368_var* begin //#UC START# *47914F960008_518A10050368_impl* inherited; f_RowIndex := -1; f_Gaph := ddDefaultPad; f_Left := -ddDefaultPad; f_Width := 0; f_IsLastRow := False; f_Border := TddBorder.Create; f_Border.isFramed := True; f_Border.BorderOwner := boRow; f_trwWidthB := 0; f_trwWidthA := 0; f_trftsWidthA := dd_wuNull; f_trftsWidthB := dd_wuNull; //#UC END# *47914F960008_518A10050368_impl* end;//TddRowProperty.Create procedure TddRowProperty.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_518A10050368_var* //#UC END# *479731C50290_518A10050368_var* begin //#UC START# *479731C50290_518A10050368_impl* f_IsLastRow := False; f_RowIndex := -1; l3Free(f_Border); f_trwWidthB := 0; f_trwWidthA := 0; f_trftsWidthA := dd_wuNull; f_trftsWidthB := dd_wuNull; inherited; //#UC END# *479731C50290_518A10050368_impl* end;//TddRowProperty.Cleanup procedure TddRowProperty.Clear; //#UC START# *518A13330058_518A10050368_var* //#UC END# *518A13330058_518A10050368_var* begin //#UC START# *518A13330058_518A10050368_impl* f_RowIndex := -1; f_IsLastRow := False; f_Border.Clear; Left := -ddDefaultPad; Gaph := ddDefaultPad; f_trwWidthB := 0; f_trwWidthA := 0; f_trftsWidthA := dd_wuNull; f_trftsWidthB := dd_wuNull; //#UC END# *518A13330058_518A10050368_impl* end;//TddRowProperty.Clear procedure TddRowProperty.AssignFrom(anOther: TddPropertyObject); //#UC START# *5301DFE6002C_518A10050368_var* //#UC END# *5301DFE6002C_518A10050368_var* begin //#UC START# *5301DFE6002C_518A10050368_impl* if (anOther is TddRowProperty) then begin Left := TddRowProperty(anOther).Left; Gaph := TddRowProperty(anOther).Gaph; trwWidthB := TddRowProperty(anOther).trwWidthB; trwWidthA := TddRowProperty(anOther).trwWidthA; trftsWidthA := TddRowProperty(anOther).trftsWidthA; trftsWidthB := TddRowProperty(anOther).trftsWidthB; RowIndex := TddRowProperty(anOther).RowIndex; IsLastRow := TddRowProperty(anOther).IsLastRow; f_Border.AssignFrom(TddRowProperty(anOther).Border); end // if (anOther is TddRowProperty) then else inherited AssignFrom(anOther); //#UC END# *5301DFE6002C_518A10050368_impl* end;//TddRowProperty.AssignFrom end.
unit uFormBasicRegister; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uFormBasic, System.ImageList, Vcl.ImgList, cxImageList, cxGraphics, System.Actions, Vcl.ActnList, Vcl.ExtCtrls, Vcl.StdCtrls, Data.DB, DBAccess, Uni, MemDS; type TfrmBasicRegister = class(TfrmBasic) ActionList: TActionList; cxImageList: TcxImageList; actNew: TAction; actSave: TAction; actRefresh: TAction; actUndo: TAction; btnNew: TButton; Bevel: TBevel; btnSave: TButton; btnUndo: TButton; btnRefreash: TButton; qyRegister: TUniQuery; dsRegister: TUniDataSource; procedure FormCreate(Sender: TObject); private FsTable: string; FnKey: Integer; procedure SetConnection; procedure New; function Save: boolean; procedure Undo; procedure Refreash; function TestRequiredFieldsFilled: boolean; function TestValidation: Boolean; virtual; public property Table: string read FsTable write FsTable; property Key: Integer read FnKey write FnKey; end; var frmBasicRegister: TfrmBasicRegister; implementation uses FCT.Connection, uFormMessage; {$R *.dfm} { TfrmBasicRegister } procedure TfrmBasicRegister.FormCreate(Sender: TObject); begin inherited; SetConnection; end; procedure TfrmBasicRegister.New; begin qyRegister.ReadOnly := False; qyRegister.Cancel; try qyRegister.Open; qyRegister.Append; except on E: exception do begin TfrmMessage.ShowError('Ocorreu um erro ao iniciar novo registro. Mensagem: ' + E.Message); Abort; end; end; end; procedure TfrmBasicRegister.Refreash; begin if not qyRegister.Active then Exit; end; function TfrmBasicRegister.Save: boolean; begin if not TestRequiredFieldsFilled then Exit; if not TestValidation then Exit; if qyRegister.State in dsEditModes then qyRegister.Post; try qyRegister.ApplyUpdates; except on E: Exception do Abort; end; end; procedure TfrmBasicRegister.SetConnection; var I: integer; begin for I := 0 to Self.ComponentCount - 1 do if (Self.Components[I]).ClassNameIs('TUniQuery') then (Self.Components[I] as TUniQuery).Connection := TFCTConnection.GetConnection; end; function TfrmBasicRegister.TestRequiredFieldsFilled: boolean; var nI: Integer; slRequiredFields: TStringList; begin slRequiredFields := TStringList.Create; try if qyRegister.State in dsEditModes then qyRegister.UpdateRecord; except on E: Exception do begin Abort; end; end; try for nI := 0 to qyRegister.FieldDefList.Count - 1 do begin if ((qyRegister.Fields[nI].Required) and (Trim(qyRegister.Fields[nI].AsString) = EmptyStr)) then slRequiredFields.Add(qyRegister.FieldByName(qyRegister.Fields[nI].FieldName).DisplayLabel); end; Result := (slRequiredFields.Count = 0); if (not Result) then TfrmMessage.ShowInformation('Por favor preencha o(s) campo(s) obrigatório(s) abaixo: ' + sLineBreak + sLineBreak + slRequiredFields.CommaText); finally FreeAndNil(slRequiredFields); end; end; function TfrmBasicRegister.TestValidation: Boolean; begin Result := True; end; procedure TfrmBasicRegister.Undo; begin qyRegister.Cancel; end; end.
unit Broadcast; interface uses Protocol, Kernel, WorkCenterBlock, Classes, Collection, BackupInterfaces, Surfaces, Accounts, StdFluids, Languages; const tidTownParameter_Broadcast = 'Broadcast'; tidEnvironmental_Broadcast = 'Broadcast'; type TMetaBroadcaster = class( TMetaWorkCenter ) public constructor Create( anId : string; aBroadcastId : string; aBroadcastCost : TMoney; aCapacities : array of TFluidValue; aSupplyAccount : TAccountId; aProdAccount : TAccountId; aSalaryAccount : TAccountId; aBlockClass : CBlock ); private fBroadcastId : string; fBroadcastCost : TMoney; public property BroadcastId : string read fBroadcastId; property BroadcastCost : TMoney read fBroadcastCost; end; TBroadcaster = class( TFinanciatedWorkCenter ) protected constructor Create( aMetaBlock : TMetaBlock; aFacility : TFacility ); override; public destructor Destroy; override; private fAdvertisement : TOutputData; private fAntennas : TLockableCollection; fHoursOnAir : byte; fBudget : TPercent; fCommercials : TPercent; published property HoursOnAir : byte read fHoursOnAir write fHoursOnAir; property Budget : TPercent read fBudget write fBudget; property Commercials : TPercent read fCommercials write fCommercials; public function Evaluate : TEvaluationResult; override; procedure Autoconnect( loaded : boolean ); override; function GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; override; function ConnectTo ( Block : TBlock; Symetrical : boolean ) : string; override; procedure DisconnectFrom( Block : TBlock; Symetrical : boolean ); override; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; private fViewers : TFluidValue; fPresence : TSurfaceValue; fCompetition : TSurfaceValue; fRating : single; fLastViewers : integer; end; TMetaAntenna = class( TMetaWorkCenter ) private fBroadcastId : string; fPower : integer; public property BroadcastId : string read fBroadcastId write fBroadcastId; property Power : integer read fPower write fPower; end; TPeopleIntegrators = array[TPeopleKind] of TSurfaceIntegrator; TAntenna = class( TFinanciatedWorkCenter ) public destructor Destroy; override; private fBroadcaster : TBroadcaster; fSignal : TSurfaceModifier; fSignalInt : TSurfaceIntegrator; fPeopleInt : TPeopleIntegrators; fQuality : single; fPeople : TFluidValue; public function Evaluate : TEvaluationResult; override; procedure Autoconnect( loaded : boolean ); override; function GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; override; function ConnectTo ( Block : TBlock; Symetrical : boolean ) : string; override; procedure DisconnectFrom( Block : TBlock; Symetrical : boolean ); override; private procedure LinkToBroadcaster( aBroadcaster : TBroadcaster ); protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; procedure RegisterBackup; implementation uses ClassStorage, MetaInstances, SysUtils, PyramidalModifier, Population, MathUtils, SimHints; const AvgAdTime = (1/(60*60))*45; // in seconds constructor TMetaBroadcaster.Create( anId : string; aBroadcastId : string; aBroadcastCost : TMoney; aCapacities : array of TFluidValue; aSupplyAccount : TAccountId; aProdAccount : TAccountId; aSalaryAccount : TAccountId; aBlockClass : CBlock ); var Sample : TBroadcaster; begin inherited Create( anId, aCapacities, aSupplyAccount, aProdAccount, aSalaryAccount, aBlockClass ); fBroadcastId := aBroadcastId; fBroadcastCost := aBroadcastCost; Sample := nil; MetaOutputs.Insert( TMetaOutput.Create( tidGate_Advertisement, FluidData(qIlimited, 100), TPullOutput, TMetaFluid(TheClassStorage.ClassById[tidClassFamily_Fluids, tidFluid_Advertisement]), 5, [mgoptCacheable, mgoptEditable], sizeof(Sample.fAdvertisement), Sample.Offset(Sample.fAdvertisement))); end; // TBroadcaster constructor TBroadcaster.Create( aMetaBlock : TMetaBlock; aFacility : TFacility ); begin inherited; fHoursOnAir := 12; fCommercials := 30; fBudget := 100; fAntennas := TLockableCollection.Create( 0, rkUse ); end; destructor TBroadcaster.Destroy; var i : integer; begin fAntennas.Lock; try for i := 0 to pred(fAntennas.Count) do TAntenna(fAntennas[i]).fBroadcaster := nil; finally fAntennas.Unlock; end; fAntennas.Free; inherited; end; function TBroadcaster.Evaluate : TEvaluationResult; var Quality : single; i : integer; WEffic : single; begin result := inherited Evaluate; // Broadcasters sell to anyone if fTradeLevel <> tlvAnyone then SetTradeLevel(tlvAnyone); if not Facility.CriticalTrouble and Facility.HasTechnology then begin if fCompetition > 0 then fRating := realmin(1, fPresence/fCompetition) else fRating := 1; WEffic := WorkForceEfficiency; fViewers := fViewers*fRating; //fAdvertisement.Q := 100*sqrt(WEffic)*(fHoursOnAir/24)*(fCommercials/100)*fViewers*dt/AvgAdTime; fAdvertisement.Q := (fHoursOnAir/24)*(fCommercials/100)*fViewers*dt/(10*AvgAdTime); Quality := sqrt(WEffic)*(1 - fCommercials/100)*(fBudget/100); fAdvertisement.K := round(100*Quality); with TMetaBroadcaster(MetaBlock) do BlockGenMoney( -BroadcastCost*(fBudget/100)*(fHoursOnAir/24)*dt, ProdAccount ); fAntennas.Lock; try for i := 0 to pred(fAntennas.Count) do TAntenna(fAntennas[i]).fQuality := realmax(0, Quality); finally fAntennas.Unlock; end; HireWorkForce( realmin(0.7, fHoursOnAir/24) ); end else begin fAdvertisement.Q := 0; fAdvertisement.K := 0; fLastViewers := 0; end; fLastViewers := round( fViewers ); fViewers := 0; fPresence := 0; fCompetition := 0; end; procedure TBroadcaster.Autoconnect( loaded : boolean ); begin inherited; fAntennas.Pack; //RDOSetTradeLevel( integer(tlvAnyone) ); >> end; function TBroadcaster.GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; function SalesRatio : single; begin if fAdvertisement.Q > 0 then result := 1 - fAdvertisement.Extra.Q/fAdvertisement.Q else result := 0 end; var k : TPeopleKind; begin result := inherited GetStatusText( kind, ToTycoon ); if not Facility.CriticalTrouble and (Facility.Trouble and facNeedsWorkForce = 0) then case kind of sttMain : result := result + SimHints.GetHintText( mtidTVMainOne.Values[ToTycoon.Language], [fLastViewers] ) + LineBreak + SimHints.GetHintText( mtidTVMainTwo.Values[ToTycoon.Language], [round(100*fRating)] ); sttSecondary : result := result + SimHints.GetHintText( mtidTVSec.Values[ToTycoon.Language], [fHoursOnAir, fCommercials, round(100*SalesRatio), fAntennas.Count] ); sttHint : if fAntennas.Count = 0 then result := result + SimHints.GetHintText( mtidTVWarning.Values[ToTycoon.Language], [0] ); end else if Facility.Trouble and facNeedsWorkForce <> 0 then case kind of sttMain : result := result + SimHints.GetHintText( mtidHiringWorkForce.Values[ToTycoon.Language], [round(100*WorkForceRatioAvg)] ); sttSecondary : with TMetaWorkCenter(MetaBlock) do for k := low(k) to high(k) do if Capacity[k] > 0 then if WorkersMax[k].Q > 0 then begin result := result + SimHints.GetHintText( mtidHiringWorkForceSec.Values[ToTycoon.Language], [ mtidWorkforceKindName[k].Values[ToTycoon.Language], round(Workers[k].Q), round(WorkersMax[k].Q) ] ); end; end; end; function TBroadcaster.ConnectTo( Block : TBlock; Symetrical : boolean ) : string; var report : string; begin result := inherited ConnectTo( Block, Symetrical ); if ObjectIs( TAntenna.ClassName, Block ) then begin if Block.Facility.Company.Owner = Facility.Company.Owner then if TAntenna(Block).fBroadcaster <> self then begin if TAntenna(Block).fBroadcaster <> nil then report := 'Antenna previously connected to ' + Block.Facility.Name + '.' + LineBreak + 'Now connected to ' + Facility.Name + '.' else report := 'Antenna successfully connected to ' + Facility.Name + '.'; TAntenna(Block).LinkToBroadcaster( self ); end else report := 'Antenna was already connected.' else report := 'You are not allowed to do that!'; if result <> '' then result := report + LineBreak + result else result := report; end; end; procedure TBroadcaster.DisconnectFrom( Block : TBlock; Symetrical : boolean ); begin inherited; end; procedure TBroadcaster.LoadFromBackup( Reader : IBackupReader ); begin inherited; Reader.ReadObject( 'Antennas', fAntennas, nil ); fHoursOnAir := Reader.ReadByte( 'HoursOnAir', 24 ); fBudget := Reader.ReadByte( 'Budget', 100 ); fCommercials := Reader.ReadByte( 'Commercials', 30 ); end; procedure TBroadcaster.StoreToBackup( Writer : IBackupWriter ); begin inherited; Writer.WriteObject( 'Antennas', fAntennas ); Writer.WriteByte( 'HoursOnAir', fHoursOnAir ); Writer.WriteByte( 'Budget', fBudget ); Writer.WriteByte( 'Commercials', fCommercials ); end; // TAntenna destructor TAntenna.Destroy; var kind : TPeopleKind; begin if fBroadcaster <> nil then fBroadcaster.fAntennas.Delete( self ); fSignal.Delete; for kind := low(kind) to high(kind) do fPeopleInt[kind].Delete; fSignalInt.Delete; inherited; end; function TAntenna.Evaluate : TEvaluationResult; var kind : TPeopleKind; begin result := inherited Evaluate; if (fBroadcaster <> nil) and fBroadcaster.Facility.Deleted then fBroadcaster := nil; if fBroadcaster <> nil then begin fBroadcaster.fPresence := fBroadcaster.fPresence + fSignal.Value; fBroadcaster.fCompetition := fBroadcaster.fCompetition + fSignalInt.Value; if not fBroadcaster.Facility.CriticalTrouble then fSignal.Value := fQuality*TMetaAntenna(MetaBlock).Power else fSignal.Value := 0; fPeople := 0; for kind := low(kind) to high(kind) do fPeople := fPeople + sqrt(sqrt(fQuality))*fPeopleInt[kind].Value; fBroadcaster.fViewers := fBroadcaster.fViewers + fPeople/5; end; end; procedure TAntenna.Autoconnect( loaded : boolean ); var kind : TPeopleKind; begin inherited; for kind := low(kind) to high(kind) do fPeopleInt[kind] := TSurfaceIntegrator.Create( PeopleKindPrefix[kind] + tidEnvironment_People, GetArea( TMetaAntenna(MetaBlock).Power, amdIncludeBlock )); fSignalInt := TSurfaceIntegrator.Create( TMetaAntenna(MetaBlock).BroadcastId, GetArea( TMetaAntenna(MetaBlock).Power, amdIncludeBlock )); fSignal := TPyramidalModifier.Create( TMetaAntenna(MetaBlock).BroadcastId, Point(xOrigin, yOrigin), 0, 1 ); fSignal.FixedArea := true; with TMetaAntenna(MetaBlock) do fSignal.Area := Rect( xOrigin - Power, yOrigin - Power, xOrigin + Power, yOrigin + Power ); end; function TAntenna.GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; begin result := inherited GetStatusText( kind, ToTycoon ); case kind of sttSecondary : begin result := result + //'Potential audience: ' + IntToStr(round(fPeople)) + '.'; SimHints.GetHintText( mtidAntenaAudience.Values[ToTycoon.Language], [round(fPeople)] ); if fBroadcaster <> nil then result := result + ' ' + //' Channel rating: ' + IntToStr(round(100*fBroadcaster.fRating)) + '%.'; SimHints.GetHintText( mtidAntenaRating.Values[ToTycoon.Language], [round(100*fBroadcaster.fRating)] ); end; sttHint : if fBroadcaster = nil then result := result + //'HINT: Use the "Connect" button in the settings panel to connect this antenna to a station.'; SimHints.GetHintText( mtidAntenaHint.Values[ToTycoon.Language], [0] ); end; end; function TAntenna.ConnectTo( Block : TBlock; Symetrical : boolean ) : string; begin result := inherited ConnectTo( Block, Symetrical ); end; procedure TAntenna.DisconnectFrom( Block : TBlock; Symetrical : boolean ); begin inherited; end; procedure TAntenna.LinkToBroadcaster( aBroadcaster : TBroadcaster ); begin if fBroadcaster <> nil then fBroadcaster.fAntennas.Delete( self ); fBroadcaster := aBroadcaster; fBroadcaster.fAntennas.Insert( self ); end; procedure TAntenna.LoadFromBackup( Reader : IBackupReader ); begin inherited; Reader.ReadObject( 'Broadcaster', fBroadcaster, nil ); end; procedure TAntenna.StoreToBackup( Writer : IBackupWriter ); begin inherited; Writer.WriteObjectRef( 'Broadcaster', fBroadcaster ); end; // RegisterBackup procedure RegisterBackup; begin RegisterClass( TBroadcaster ); RegisterClass( TAntenna ); end; end.
namespace Sugar.Test; interface uses Sugar, RemObjects.Elements.EUnit; type UrlTest = public class (Test) private Data: Url; public method Setup; override; method FromString; method Scheme; method Host; method Port; method Path; method QueryString; method UserInfo; method Fragment; method TestToString; end; implementation method UrlTest.Setup; begin Data := new Url("https://username:password@example.com:8080/users?user_id=42#phone"); end; method UrlTest.Scheme; begin Assert.AreEqual(Data.Scheme, "https"); Assert.AreEqual(new Url("ftp://1.1.1.1/").Scheme, "ftp"); end; method UrlTest.Host; begin Assert.AreEqual(Data.Host, "example.com"); Assert.AreEqual(new Url("ftp://1.1.1.1/").Host, "1.1.1.1"); end; method UrlTest.Port; begin Assert.AreEqual(Data.Port, 8080); Assert.AreEqual(new Url("ftp://1.1.1.1/").Port, -1); end; method UrlTest.Path; begin Assert.AreEqual(Data.Path, "/users"); Assert.AreEqual(new Url("ftp://1.1.1.1/").Path, "/"); Assert.AreEqual(new Url("http://1.1.1.1/?id=1").Path, "/"); Assert.AreEqual(new Url("http://1.1.1.1/page.html").Path, "/page.html"); end; method UrlTest.QueryString; begin Assert.AreEqual(Data.QueryString, "user_id=42"); Assert.IsNil(new Url("ftp://1.1.1.1/").QueryString); end; method UrlTest.Fragment; begin Assert.AreEqual(Data.Fragment, "phone"); Assert.IsNil(new Url("ftp://1.1.1.1/").Fragment); end; method UrlTest.FromString; begin Assert.AreEqual(new Url("http://example.com/").ToString, "http://example.com/"); Assert.Throws(->new Url(nil), "Nil"); Assert.Throws(->new Url(""), "Empty"); Assert.Throws(->new Url("1http://example.com"), "1http"); Assert.Throws(->new Url("http_ex://example.com"), "http_ex"); Assert.Throws(->new Url("http://%$444;"), "url"); end; method UrlTest.TestToString; begin Assert.AreEqual(Data.ToString, "https://username:password@example.com:8080/users?user_id=42#phone"); Assert.AreEqual(new Url("ftp://1.1.1.1/").ToString, "ftp://1.1.1.1/"); end; method UrlTest.UserInfo; begin Assert.AreEqual(Data.UserInfo, "username:password"); Assert.IsNil(new Url("ftp://1.1.1.1/").UserInfo); Assert.AreEqual(new Url("ftp://user@1.1.1.1/").UserInfo, "user"); end; end.
unit D_NameEd; { $Id: D_NameEd.pas,v 1.37 2012/07/30 09:11:33 dinishev Exp $ } {$Include l3Define.inc} interface uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons, StdCtrls, ExtCtrls, OvcBase, l3Types, l3Interfaces, evCustomMemoTextSource, evEditorWindow, evEditor, evMemo, BottomBtnDlg, TB97Ctls, evMultiSelectEditorWindow, evCustomEditor, evEditorWithOperations, evTextSource, afwControl, evCustomMemo, afwControlPrim, afwBaseControl, nevControl, evCustomEditorWindowPrim, evCustomEditorWindowModelPart, evCustomEditorModelPart, evCustomEditorWindow; type TNameEditDlg = class(TBottomBtnDlg) pnlName: TPanel; lblNameRus: TLabel; lblNameEng: TLabel; mNameRus: TevMemo; mNameEng: TevMemo; sbSpellChecker: TSpeedButton; procedure mEditorCharCountChangeRus(Sender: TObject); procedure mEditorCharCountChangeEng(Sender: TObject); procedure OKClick(Sender: TObject); procedure sbSpellCheckerClick(Sender: TObject); procedure pnlNameResize(Sender: TObject); procedure mNameTextSourceBruttoCharCountChange(Sender: TObject); procedure FormCreate(Sender: TObject); private fROnly : Boolean; fBiLingual : Boolean; protected procedure SetROnly(aValue : Boolean); virtual; procedure SetBiLingual(aValue : Boolean); virtual; procedure SetEditTextR(const Value : Tl3PCharLen); function GetEditTextR : Tl3PCharLen; procedure SetEditTextE(const Value : Tl3PCharLen); function GetEditTextE : Tl3PCharLen; public function Execute(aMaxTextLen : Integer = 0) : Boolean; property EditTextR : Tl3PCharLen read GetEditTextR write SetEditTextR; property EditTextE : Tl3PCharLen read GetEditTextE write SetEditTextE; property ROnly : Boolean read fROnly write SetROnly; property BiLingual : Boolean read fBiLingual write SetBiLingual; end; implementation {$R *.DFM} uses Dialogs, vtDialogs, SysUtils, StrShop, evTypes, D_Spell, Main, l3Base, l3String, evFacadTextSource, evFacadeUtils ; {$INCLUDE ProjectDefine.inc} function TNameEditDlg.Execute(aMaxTextLen : Integer = 0) : Boolean; begin sbSpellChecker.Enabled := False; //fMaxTextLen := aMaxTextLen; if aMaxTextLen <> 0 then begin mNameRus.NeedReplaceQuotes := False; mNameEng.NeedReplaceQuotes := False; evSetBruttoCharLimit(mNameRus.TextSource, aMaxTextLen + 2); evSetNettoCharCountEvent(mNameRus.TextSource, mEditorCharCountChangeRus); mEditorCharCountChangeRus(Self); evSetBruttoCharLimit(mNameEng.TextSource, aMaxTextLen + 2); evSetNettoCharCountEvent(mNameEng.TextSource, mEditorCharCountChangeEng); evSetTextParaLimit(mNameRus.TextSource, 1); evSetTextParaLimit(mNameEng.TextSource, 1); end; SetBiLingual(fBiLingual); Result := ShowModal = mrOk; end; procedure TNameEditDlg.SetEditTextR(const Value : Tl3PCharLen); begin mNameRus.Buffer := Value; {NameEditor.IsOpen := True;} end; function TNameEditDlg.GetEditTextR : Tl3PCharLen; begin Tl3WString(Result) := mNameRus.Buffer; end; resourcestring sidName = 'Название'; sidNameRus = 'Название на русском'; sidNameEng = 'Название на английском'; procedure TNameEditDlg.mEditorCharCountChangeRus(Sender: TObject); begin if BiLingual then lblNameRus.Caption := Format(sidNameRus+' '+scFmtCounter, [evGetNettoCharCount(mNameRus.TextSource), evGetBruttoCharLimit(mNameRus.TextSource) - 2]) else lblNameRus.Caption := Format(sidName+' '+scFmtCounter, [evGetNettoCharCount(mNameRus.TextSource), evGetBruttoCharLimit(mNameRus.TextSource) - 2]); end; procedure TNameEditDlg.mEditorCharCountChangeEng(Sender: TObject); begin lblNameEng.Caption := Format(sidNameEng+' '+scFmtCounter, [evGetNettoCharCount(mNameEng.TextSource), evGetBruttoCharLimit(mNameEng.TextSource) - 2]); end; procedure TNameEditDlg.OKClick(Sender: TObject); begin if (Trim(mNameRus.Text) = '') then begin ShowMessage(Format(sidCanNotBeEmpty, [sidNameRus])); ActiveControl := mNameRus; ModalResult := mrNone; end; end; procedure TNameEditDlg.sbSpellCheckerClick(Sender: TObject); var lCurEditor : TevMemo; begin if ActiveControl = mNameEng then lCurEditor := mNameEng else lCurEditor := mNameRus; TSpellCheckDlg.Execute(lCurEditor, MainForm.SpellDictionary); end; //procedure TNameEditDlg.mEditorTextSourceBruttoCharCountChange(Sender: TObject); //begin // sbSpellChecker.Enabled := True; //end; procedure TNameEditDlg.SetROnly(aValue : Boolean); begin fROnly := aValue; OK.Enabled := not aValue; mNameRus.ReadOnly := aValue; mNameEng.ReadOnly := aValue; end; procedure TNameEditDlg.SetBiLingual(aValue : Boolean); begin fBiLingual := aValue; If fBiLingual then begin mNameRus.Height := (pnlName.ClientHeight - TControl(mNameRus).Left) div 2 - TControl(mNameRus).Top; lblNameEng.Top := (pnlName.ClientHeight - TControl(mNameRus).Left) div 2 + lblNameRus.Top; lblNameEng.Visible := True; TControl(mNameEng).Top := (pnlName.ClientHeight - TControl(mNameRus).Left) div 2 + TControl(mNameRus).Top; mNameEng.Height := pnlName.ClientHeight - TControl(mNameEng).Top - TControl(mNameRus).Left; //mNameRus.Height; lblNameRus.Caption := sidNameRus; mNameEng.Visible := True; end else begin mNameRus.Height := pnlName.ClientHeight - TControl(mNameRus).Top - TControl(mNameRus).Left; lblNameEng.Visible := False; lblNameRus.Caption := sidName; mNameEng.Visible := False; end; end; procedure TNameEditDlg.pnlNameResize(Sender: TObject); begin inherited; SetBiLingual(fBiLingual); end; function TNameEditDlg.GetEditTextE: Tl3PCharLen; begin if fBiLingual then Tl3WString(Result) := mNameEng.Buffer else Result := l3PCharLen; end; procedure TNameEditDlg.SetEditTextE(const Value: Tl3PCharLen); begin mNameEng.Buffer := Value; end; procedure TNameEditDlg.mNameTextSourceBruttoCharCountChange(Sender: TObject); begin sbSpellChecker.Enabled := True; end; procedure TNameEditDlg.FormCreate(Sender: TObject); begin inherited; mNameRus.KeepAllFormatting := False; EvSetPlainTextFlag(mNameRus, False); mNameEng.KeepAllFormatting := False; EvSetPlainTextFlag(mNameEng, False); end; end.
unit AdvancedLinkLabel; {********************* TAdvancedLinkLabel v. 1.0, 2016, Стрелец Coder Open Source ********************** Компонент Delphi расширяющий функционал стандартного LinkLabel путём добавления обработки события OnClick по умолчанию. Обработчик по умолчанию автоматически находит тег гиперссылки (при его наличии) и открывает её. Работает только с главными страницами web сайтов расположенных на доменах второго уровня. Не предназначено для версий ниже XE2 ********************** Delphi component extends the functionality of the standard LinkLabel by add processing of the OnClick event by default. The default handler automatically finds the tag of a hyperlink (when available) and opens it. Only works with web sites located on the second level domains. Not intended for versions prior to XE2 } interface uses Winapi.Windows, System.SysUtils, System.RegularExpressions, System.Classes, Vcl.Controls, Vcl.ExtCtrls, ShellAPI; const TagPattern = '<a.+href=".+"(.+>|>).+</a>'; URLPattern = '(http|https)://\w+\.\w+/'; type TAdvancedLinkLabel = class(TLinkLabel) public constructor Create(AOwner: TComponent); override; procedure DefaultClick(Sender: TObject); end; procedure Register; implementation procedure Register; begin RegisterComponents('AdvancedLinkLabel', [TAdvancedLinkLabel]); end; { TStreletzCoderLinkLabel } procedure TAdvancedLinkLabel.DefaultClick(Sender: TObject); var TagRegExp, URLRegExp: TRegEx; TagMatch, URLMatch: TMatch; begin // Проверяем наличие тега гиперссылки TagRegExp := TRegEx.Create(TagPattern); if TagRegExp.IsMatch(Caption) then begin // Если тег гиперссылки есть, ищем URL TagMatch := TagRegExp.Match(Caption); URLRegExp := TagRegExp.Create(URLPattern); if URLRegExp.IsMatch(TagMatch.Value) then begin // Если URL найден, открываем ссылку URLMatch := URLRegExp.Match(TagMatch.Value); ShellExecute(self.Handle, 'open', PWideChar(URLMatch.Value), nil, nil, SW_RESTORE); end else exit; end else exit; end; constructor TAdvancedLinkLabel.Create(AOwner: TComponent); begin inherited Create(AOwner); self.OnClick := DefaultClick; end; end.
{$include lem_directives.inc} unit LemLemminiLoader; interface uses Classes, SysUtils, LemTerrain, LemInteractiveObject, LemSteel, LemLevel; type TLemminiLevelLoader = class(TLevelLoader) public // class procedure LoadLevel(aStream: TStream; aLevel: TLevel); override; end; implementation end. uses UMisc, UFastStrings; class procedure TLemminiLevelLoader.LoadLevel(aStream: TStream; aLevel: TLevel); var List: TStringList; N, V: string; i, H: Integer; T: TTerrain; O: TInteractiveObject; S: TSteel; // TDF: TTerrainDrawingFlags; // ODF: TObjectDrawingFlags; // get integer from lemmini ini file function GetInt(const aName: string): Integer; begin Result := StrToIntDef(List.Values[aName], -1); if Result = -1 then if aName = 'numToRecue' then Result := StrToIntDef(List.Values['numToRescue'], -1); //Log([aName, Result]); end; function CheckSuperLemming: Boolean; begin Result := Trim(UpperCase(List.Values['superlemming'])) = 'TRUE'; end; // get style function GetStyleNo: Integer; var i: Integer; aStyle: string; begin aStyle := List.Values['style']; raise exception.create('getstyle how are we going to do this'); //Result := Style.graphbyname(aStyle).GraphicSetId; end; procedure GetGraphicSet; var i: Integer; aStyle: string; begin aStyle := List.Values['style']; //if fStyle = nil then //fStyle := StyleMgr.StyleList[STYLE_LEMMINI]; raise exception.create('getgraphicset how are we going to do this'); //fGraph := fStyle.GraphicSetList.FindByName(aStyle); //fGraph.EnsureMetaData; end; begin with aLevel do begin List := TStringList.Create; BeginUpdate; try ClearLevel; List.NameValueSeparator := '='; List.LoadFromStream(aStream); {------------------------------------------------------------------------------- o First a little adjusting. TStringList is too dumb to recognize name/value pairs when spaces are involved. o Then delete all comments -------------------------------------------------------------------------------} for i := 0 to List.Count - 1 do begin V := List[i]; repeat if FastPos(V, ' =', Length(V), 2, 1) = 0 then if FastPos(V, '= ', Length(V), 2, 1) = 0 then Break; V := FastReplace(V, ' =', '='); V := FastReplace(V, '= ', '='); until False; H := Pos('#', V); if H >= 1 then begin // Log(['voor', V]); V := Copy(V, 1, H - 1); // Log(['na', V]); end; List[i] := V;//FastReplace(List[i], ' = ', '='); end; GetGraphicSet; with LevelInfo do begin ReleaseRate := GetInt('releaseRate'); LemmingsCount := GetInt('numLemmings'); RescueCount := GetInt('numToRecue'); TimeLimit := GetInt('timeLimit'); ClimberCount := GetInt('numClimbers'); FloaterCount := GetInt('numFloaters'); BomberCount := GetInt('numBombers'); BlockerCount := GetInt('numBlockers'); BuilderCount := GetInt('numBuilders'); BasherCount := GetInt('numBashers'); MinerCount := GetInt('numMiners'); DiggerCount := GetInt('numDiggers'); ScreenPosition := GetInt('xPos'); assert(false); GraphicSet := 123;//Graph.GraphicSetId; Superlemming := CheckSuperLemming; end; {------------------------------------------------------------------------------- Get the objects # Objects # id, xpos, ypos, paint mode (), upside down (0,1) # paint modes: 8=VIS_ON_TERRAIN, 4=NO_OVERWRITE, 0=FULL (only one value possible) object_0 = 6, 1664, 64, 4, 0 object_1 = 5, 1152, 288, 0, 0 -------------------------------------------------------------------------------} i := 0; repeat V := List.Values['object_' + i2s(i)]; if V = '' then Break; // paint modes: 8=VIS_ON_TERRAIN, 4=NO_OVERWRITE, 0=FULL (only one value possible) O := InteractiveObjects.Add; O.Identifier := StrToIntDef(SplitString(V, 0, ','), -1); O.Left := StrToIntDef(SplitString(V, 1, ','), -1); O.Top := StrToIntDef(SplitString(V, 2, ','), -1); ODF := []; H := StrToIntDef(SplitString(V, 3, ','), -1); if H = -1 then raise Exception.Create('Lemming ini file object drawingflag error'); if H and 8 <> 0 then Include(ODF, odfOnlyShowOnTerrain); if H and 4 <> 0 then Include(ODF, odfNoOverwrite); H := StrToIntDef(SplitString(V, 4, ','), -1); if H = -1 then raise Exception.Create('Lemming ini file upside down indicator error'); if H = 1 then Include(ODF, odfInvert); O.ObjectDrawingFlags := ODF; Inc(i); until False; {------------------------------------------------------------------------------- Get the terrain # Terrain # id, xpos, ypos, modifier # modifier: 8=NO_OVERWRITE, 4=UPSIDE_DOWN, 2=REMOVE (combining allowed, 0=FULL) terrain_0 = 7, 1360, 130, 0 terrain_1 = 7, 1420, 130, 0 -------------------------------------------------------------------------------} i := 0; repeat V := List.Values['terrain_' + i2s(i)]; if V = '' then Break; T := TerrainCollection.Add; T.TerrainId := StrToIntDef(SplitString(V, 0, ','), -1); T.TerrainX := StrToIntDef(SplitString(V, 1, ','), -1); T.TerrainY := StrToIntDef(SplitString(V, 2, ','), -1); H := StrToIntDef(SplitString(V, 3, ','), -1); if H = -1 then raise Exception.Create('Lemming ini file terrain drawingflag error (' + i2s(i) + ')'); // 8=NO_OVERWRITE, 4=UPSIDE_DOWN, 2=REMOVE TDF := []; if H and 8 <> 0 then Include(TDF, tdfNoOverwrite); if H and 4 <> 0 then Include(TDF, tdfInvert); if H and 2 <> 0 then Include(TDF, tdfErase); T.TerrainDrawingFlags := TDF; //Log(['terrain', i]); Inc(i); until False; {------------------------------------------------------------------------------- Get the steel #Steel # id, xpos, ypos, width, height steel_0 = 1328, 80, 48, 128 steel_1 = 1256, 80, 48, 128 -------------------------------------------------------------------------------} i := 0; repeat V := List.Values['steel_' + i2s(i)]; if V = '' then Break; S := SteelCollection.Add; S.SteelX := StrToIntDef(SplitString(V, 0, ','), -1); S.SteelY := StrToIntDef(SplitString(V, 1, ','), -1); S.SteelWidth := StrToIntDef(SplitString(V, 2, ','), -1); S.SteelHeight := StrToIntDef(SplitString(V, 3, ','), -1); Inc(i); until False; {------------------------------------------------------------------------------- Get the name #Name name = Worra load of old blocks! -------------------------------------------------------------------------------} LevelName := Trim(List.Values['name']); //if fResolution = LoRes then //AdjustResolution(0.5); CacheSizes; finally List.Free; EndUpdate; end; end; end; end.
unit main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, clDownLoader, clWinInet, clDC, clDCUtils, clMultiDC, clSingleDC, clProgressBar, clProgressBarDC, ExtCtrls, ComCtrls, clResourceState, DemoBaseFormUnit; type TDownLoaderTest = class(TclDemoBaseForm) btnDownLoad: TButton; edtURL: TEdit; edtFile: TEdit; Label1: TLabel; Label2: TLabel; clDownLoader1: TclDownLoader; memPreview: TMemo; Label3: TLabel; edtStatistic: TEdit; btnGetInfo: TButton; Label5: TLabel; Label4: TLabel; memErrors: TMemo; Label6: TLabel; edtUser: TEdit; edtPassword: TEdit; btnStop: TButton; memInfo: TMemo; Label7: TLabel; edtDirectory: TEdit; Label8: TLabel; Label9: TLabel; clProgressBar1: TclProgressBarDC; Label10: TLabel; edtThreadCount: TEdit; Label11: TLabel; edtBufferSize: TEdit; updBufferSize: TUpDown; updThreadCount: TUpDown; Label12: TLabel; Label13: TLabel; procedure btnDownLoadClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure btnGetInfoClick(Sender: TObject); procedure btnStopClick(Sender: TObject); procedure edtFileChange(Sender: TObject); procedure edtUserChange(Sender: TObject); procedure edtPasswordChange(Sender: TObject); procedure edtURLChange(Sender: TObject); procedure edtDirectoryChange(Sender: TObject); procedure clDownLoader1DataItemProceed(Sender: TObject; ResourceInfo: TclResourceInfo; AStateItem: TclResourceStateItem; CurrentData: PAnsiChar; CurrentDataSize: Integer); procedure clDownLoader1URLParsing(Sender: TObject; var URLComponents: URL_COMPONENTS); procedure clDownLoader1StatusChanged(Sender: TObject; Status: TclProcessStatus); procedure clDownLoader1Changed(Sender: TObject); procedure clDownLoader1GetResourceInfo(Sender: TObject; ResourceInfo: TclResourceInfo); procedure clDownLoader1DataTextProceed(Sender: TObject; Text: TStrings); procedure clDownLoader1Error(Sender: TObject; const Error: String; ErrorCode: Integer); procedure edtThreadCountChange(Sender: TObject); procedure edtBufferSizeChange(Sender: TObject); private FIsLoading: Boolean; end; var DownLoaderTest: TDownLoaderTest; implementation {$R *.DFM} procedure TDownLoaderTest.btnDownLoadClick(Sender: TObject); begin memInfo.Lines.Clear(); memErrors.Lines.Clear(); clDownLoader1.Start(True); end; procedure TDownLoaderTest.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := not clDownLoader1.IsBusy; end; procedure TDownLoaderTest.btnGetInfoClick(Sender: TObject); begin memInfo.Lines.Clear(); memErrors.Lines.Clear(); clDownLoader1.GetResourceInfo(True); end; procedure TDownLoaderTest.btnStopClick(Sender: TObject); begin clDownLoader1.Stop(); end; procedure TDownLoaderTest.edtFileChange(Sender: TObject); begin if FIsLoading then Exit; clDownLoader1.LocalFile := edtFile.Text; end; procedure TDownLoaderTest.edtUserChange(Sender: TObject); begin if FIsLoading then Exit; clDownLoader1.UserName := edtUser.Text; end; procedure TDownLoaderTest.edtPasswordChange(Sender: TObject); begin if FIsLoading then Exit; clDownLoader1.Password := edtPassword.Text; end; procedure TDownLoaderTest.edtURLChange(Sender: TObject); begin if FIsLoading then Exit; clDownLoader1.URL := edtURL.Text; end; procedure TDownLoaderTest.edtDirectoryChange(Sender: TObject); begin if FIsLoading then Exit; clDownLoader1.LocalFolder := edtDirectory.Text; end; procedure TDownLoaderTest.clDownLoader1DataItemProceed(Sender: TObject; ResourceInfo: TclResourceInfo; AStateItem: TclResourceStateItem; CurrentData: PAnsiChar; CurrentDataSize: Integer); var State: TclResourceStateList; begin State := AStateItem.ResourceState; edtStatistic.Text := Format('%.2n of %.2n Kb proceed, speed %.2n Kb/sec, elapsed %.2n min, remains %.2n min', [State.BytesProceed / 1024, State.ResourceSize / 1024, State.Speed / 1024, State.ElapsedTime / 60, State.RemainingTime / 60]); end; procedure TDownLoaderTest.clDownLoader1URLParsing(Sender: TObject; var URLComponents: URL_COMPONENTS); begin with URLComponents do begin memInfo.Lines.Add('Scheme: ' + lpszScheme); memInfo.Lines.Add('Host: ' + lpszHostName); memInfo.Lines.Add('User: ' + lpszUserName); memInfo.Lines.Add('Path: ' + lpszUrlPath); memInfo.Lines.Add('Extra: ' + lpszExtraInfo); end; end; procedure TDownLoaderTest.clDownLoader1StatusChanged(Sender: TObject; Status: TclProcessStatus); var s: String; begin case Status of psSuccess: MessageBox(0, 'Process completed successfully', 'Message', 0); psFailed: begin s := (Sender as TclDownLoader).Errors.Text; MessageBox(0, PChar(s), 'Error', 0); end; psTerminated: MessageBox(0, 'Process stopped', 'Message', 0); psErrors: MessageBox(0, 'Process completed with some warnings', 'Message', 0); end; end; procedure TDownLoaderTest.clDownLoader1Changed(Sender: TObject); begin if FIsLoading then Exit; FIsLoading := True; try edtURL.Text := clDownLoader1.URL; edtUser.Text := clDownLoader1.UserName; edtPassword.Text := clDownLoader1.Password; edtFile.Text := clDownLoader1.LocalFile; edtDirectory.Text := clDownLoader1.LocalFolder; updThreadCount.Position := clDownLoader1.ThreadCount; updBufferSize.Position := clDownLoader1.BatchSize; finally FIsLoading := False; end; end; procedure TDownLoaderTest.clDownLoader1GetResourceInfo(Sender: TObject; ResourceInfo: TclResourceInfo); var s: String; begin if (ResourceInfo <> nil) then begin s := 'Resource ' + ResourceInfo.Name + '; Size ' + IntToStr(ResourceInfo.Size) + '; Date ' + DateTimeToStr(ResourceInfo.Date) + '; Type ' + ResourceInfo.ContentType; if ResourceInfo.Compressed then begin s := s + '; Compressed'; end; end else begin s := 'There are no any info available.'; end; memInfo.Lines.Add(s); end; procedure TDownLoaderTest.clDownLoader1DataTextProceed(Sender: TObject; Text: TStrings); begin memPreview.Lines.Assign(Text); end; procedure TDownLoaderTest.clDownLoader1Error(Sender: TObject; const Error: String; ErrorCode: Integer); begin memErrors.Lines.Text := (Sender as TclDownLoader).Errors.Text; end; procedure TDownLoaderTest.edtThreadCountChange(Sender: TObject); begin if FIsLoading then Exit; clDownLoader1.ThreadCount := updThreadCount.Position; end; procedure TDownLoaderTest.edtBufferSizeChange(Sender: TObject); begin if FIsLoading then Exit; clDownLoader1.BatchSize := updBufferSize.Position; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clTcpServerTls; interface {$I clVer.inc} {$IFDEF DELPHI7} {$WARN UNSAFE_CODE OFF} {$WARN UNSAFE_TYPE OFF} {$WARN UNSAFE_CAST OFF} {$ENDIF} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, {$ELSE} System.Classes, System.SysUtils, {$ENDIF} clTcpServer, clCertificate, clSspiTls, clCertificateStore; type TclUserConnectionTls = class; TclVerifyClientEvent = procedure (Sender: TObject; AConnection: TclUserConnectionTls; ACertificate: TclCertificate; const AStatusText: string; AStatusCode: Integer; var AVerified: Boolean) of object; TclServerTlsMode = (stNone, stImplicit, stExplicitAllow, stExplicitRequire); TclUserConnectionTls = class(TclUserConnection) private FNeedStartTls: Boolean; function GetIsTls: Boolean; public constructor Create; property IsTls: Boolean read GetIsTls; end; TclTcpServerTls = class(TclTcpServer) private FUseTLS: TclServerTlsMode; FTLSFlags: TclTlsFlags; FRequireClientCertificate: Boolean; FOnGetCertificate: TclGetCertificateEvent; FOnVerifyClient: TclVerifyClientEvent; FCSP: string; procedure GetCertificate(Sender: TObject; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean); procedure VerifyClient(Sender: TObject; ACertificate: TclCertificate; const AStatusText: string; AStatusCode: Integer; var AVerified: Boolean); protected procedure ReadConnection(AConnection: TclUserConnection); override; procedure AssignNetworkStream(AConnection: TclUserConnection); override; procedure InternalStartTls(AConnection: TclUserConnectionTls); procedure DoGetCertificate(var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean); virtual; procedure DoVerifyClient(AConnection: TclUserConnectionTls; ACertificate: TclCertificate; const AStatusText: string; AStatusCode: Integer; var AVerified: Boolean); virtual; public constructor Create(AOwner: TComponent); override; procedure AssignTlsStream(AConnection: TclUserConnectionTls); procedure StartTls(AConnection: TclUserConnectionTls); published property UseTLS: TclServerTlsMode read FUseTLS write FUseTLS default stNone; property TLSFlags: TclTlsFlags read FTLSFlags write FTLSFlags default [tfUseTLS]; property CSP: string read FCSP write FCSP; property RequireClientCertificate: Boolean read FRequireClientCertificate write FRequireClientCertificate default False; property OnGetCertificate: TclGetCertificateEvent read FOnGetCertificate write FOnGetCertificate; property OnVerifyClient: TclVerifyClientEvent read FOnVerifyClient write FOnVerifyClient; end; implementation uses clSocket, clTlsSocket, clUtils{$IFDEF LOGGER}, clLogger{$ENDIF}; { TclTcpServerTls } procedure TclTcpServerTls.AssignNetworkStream(AConnection: TclUserConnection); begin if (UseTLS = stImplicit) then begin AssignTlsStream(TclUserConnectionTls(AConnection)); end else begin inherited AssignNetworkStream(AConnection); end; end; procedure TclTcpServerTls.AssignTlsStream(AConnection: TclUserConnectionTls); var stream: TclTlsNetworkStream; begin stream := TclTlsNetworkStream.Create(); AConnection.NetworkStream := stream; stream.OnGetCertificate := GetCertificate; stream.OnVerifyPeer := VerifyClient; stream.TLSFlags := TLSFlags; stream.CSP := CSP; stream.RequireClientCertificate := RequireClientCertificate; end; constructor TclTcpServerTls.Create(AOwner: TComponent); begin inherited Create(AOwner); FUseTLS := stNone; FTLSFlags := [tfUseTLS]; FRequireClientCertificate := False; end; procedure TclTcpServerTls.DoVerifyClient(AConnection: TclUserConnectionTls; ACertificate: TclCertificate; const AStatusText: string; AStatusCode: Integer; var AVerified: Boolean); begin if Assigned(OnVerifyClient) then begin OnVerifyClient(Self, AConnection, ACertificate, AStatusText, AStatusCode, AVerified); end; end; procedure TclTcpServerTls.DoGetCertificate(var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean); begin if Assigned(OnGetCertificate) then begin OnGetCertificate(Self, ACertificate, AExtraCerts, Handled); end; end; procedure TclTcpServerTls.GetCertificate(Sender: TObject; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean); begin DoGetCertificate(ACertificate, AExtraCerts, Handled); end; procedure TclTcpServerTls.StartTls(AConnection: TclUserConnectionTls); begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'StartTls');{$ENDIF} Assert(not AConnection.FNeedStartTls); AConnection.FNeedStartTls := True; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'StartTls'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'StartTls', E); raise; end; end;{$ENDIF} end; procedure TclTcpServerTls.InternalStartTls(AConnection: TclUserConnectionTls); begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, Format('(%d) InternalStartTls', [AConnection.Socket.Socket]));{$ENDIF} if AConnection.FNeedStartTls then begin AConnection.FNeedStartTls := False; {$IFDEF LOGGER}clPutLogMessage(Self, edInside, Format('(%d) InternalStartTls', [AConnection.Socket.Socket]));{$ENDIF} AssignTlsStream(AConnection); AConnection.OpenSession(); end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'InternalStartTls'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'InternalStartTls', E); raise; end; end;{$ENDIF} end; procedure TclTcpServerTls.ReadConnection(AConnection: TclUserConnection); begin InternalStartTls(TclUserConnectionTls(AConnection)); inherited ReadConnection(AConnection); end; procedure TclTcpServerTls.VerifyClient(Sender: TObject; ACertificate: TclCertificate; const AStatusText: string; AStatusCode: Integer; var AVerified: Boolean); var ns: TclNetworkStream; begin ns := TclNetworkStream(Sender); DoVerifyClient(TclUserConnectionTls(ns.Connection), ACertificate, AStatusText, AStatusCode, AVerified); end; { TclUserConnectionTls } constructor TclUserConnectionTls.Create; begin inherited Create(); FNeedStartTls := False; end; function TclUserConnectionTls.GetIsTls: Boolean; begin Result := (NetworkStream is TclTlsNetworkStream); end; end.
{ *************************************************************************** } { } { This file is part of the XPde project } { } { Copyright (c) 2002 Jose Leon Serna <ttm@xpde.com> } { } { 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; see the file COPYING. If not, write to } { the Free Software Foundation, Inc., 59 Temple Place - Suite 330, } { Boston, MA 02111-1307, USA. } { } { *************************************************************************** } unit uXPStyledFrame; interface uses SysUtils, Types, Classes, Variants, QTypes, QGraphics, QControls, QForms, XLib, QDialogs, QStdCtrls, QExtCtrls, Qt, uCommon, uGraphics, uWindowManager, uResample; type TStyledFrame = class; //A caption button TXPCaptionButton=class(TPanel) private { TODO : Add support for inactive states } FMask: TBitmap; FOver: TBitmap; FNormal: TBitmap; FPressed: TBitmap; FGlyph: string; procedure SetGlyph(const Value: string); public frame: TStyledFrame; procedure SetParent(const Value:TWidgetControl);override; procedure mouseenter(AControl:TControl);override; procedure mouseleave(AControl:TControl);override; procedure MouseDown(button: TMouseButton; Shift: TShiftState; X, Y: integer);override; procedure MouseUp(button: TMouseButton; Shift: TShiftState; X, Y: integer);override; procedure setup; constructor Create(AOwner:TComponent);override; destructor Destroy;override; property Glyph: string read FGlyph write SetGlyph; end; //A frame the can be styled TStyledFrame = class(TForm) topFrame: TPanel; bottomFrame: TPanel; middleFrame: TPanel; leftFrame: TPanel; rightFrame: TPanel; bottomFrameLeft: TPanel; bottomFrameRight: TPanel; clientArea: TPanel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure topFrameMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure topFrameMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure topFrameMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure rightFrameMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure rightFrameMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure rightFrameMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure leftFrameMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure bottomFrameMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure bottomFrameRightMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure bottomFrameLeftMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); private { Private declarations } { TODO : Organize all frame bitmaps in a common place, to save resources } //Masks to created rounded effect FLeftMask: TBitmap; FRightMask: TBitmap; FFullMask: TBitmap; //Bottom bitmap FBottom: TBitmap; FBottomLeft: TBitmap; FBottomRight: TBitmap; FBottomInactive: TBitmap; FBottomLeftInactive: TBitmap; FBottomRightInactive: TBitmap; //Caption bitmap parts FCaption: TBitmap; FCaptionLeft: TBitmap; FCaptionRight: TBitmap; //Left bitmap FLeft: TBitmap; FLeftInactive: TBitmap; //Left bitmap FRight: TBitmap; FRightInactive: TBitmap; FCaptionInactive: TBitmap; FCaptionLeftInactive: TBitmap; FCaptionRightInactive: TBitmap; //Caption buttons FCloseButton: TXPCaptionButton; FMaxButton: TXPCaptionButton; FMinButton: TXPCaptionButton; //A value for performance purposes lastWidth: integer; //Moving and resizing variables moving: boolean; resizing: boolean; ox: integer; oy: integer; //The window caption windowtitle: widestring; public { Public declarations } client:TWMClient; //All this must be changed { TODO : Optimize the way a window icon is retrieved and stored } imgIcon: TImage; mini_icon_a: TBitmap; mini_icon_i: TBitmap; mini_icon_s: TBitmap; icon_s: TBitmap; normalIcon: TBitmap; smallIcon: TBitmap; //Used to know the next dimensions of the frame in advance procedure ChangeBounds(ALeft, ATop, AWidth, AHeight: Integer); override; //Setup the frame procedure setup; //Returns the frame sizes (left, top, right, bottom) function getFrameBorderSizes:TRect; //Updates the window title (check it) procedure updateWindowTitle; { TODO : Make the window title a property of the frame } procedure setTitle(ATitle: widestring); function getTitle:widestring; { TODO : Make the client a property } procedure setClient(AClient:TWMClient); //Resizes all the bitmaps to fit the new dimensions procedure resizeBitmaps(AWidth,AHeight:integer); //Returns the control that is going to be the parent of the client function getHostControl:TWidgetControl; //Notifications procedure updateWindowState; procedure updateActiveState; procedure updateClientSize; procedure updateButtonsPosition(AWidth:integer); //Builds the icons for the window, must be optimized procedure setupIcons; //Event handlers procedure OnCloseButton(Sender:TObject); procedure OnMaximizeButton(Sender:TObject); procedure OnMinimizeButton(Sender:TObject); end; var StyledFrame: TStyledFrame; implementation {$R *.xfm} procedure TStyledFrame.FormCreate(Sender: TObject); var dir: string; begin normalIcon:=TBitmap.create; smallIcon:=TBitmap.create; //All this must change imgIcon:=TImage.create(nil); mini_icon_a:=TBitmap.create; mini_icon_a.width:=16; mini_icon_a.height:=16; mini_icon_i:=TBitmap.create; mini_icon_i.width:=16; mini_icon_i.height:=16; mini_icon_s:=TBitmap.create; mini_icon_s.width:=16; mini_icon_s.height:=16; icon_s:=TBitmap.create; icon_s.width:=32; icon_s.height:=32; { TODO : Use the constructor instead FormCreate } windowtitle:=''; //Setup masks used to allow non rect frames to be used FLeftMask:=TBitmap.create; FRightMask:=TBitmap.create; FFullMask:=TBitmap.create; dir:=getSystemInfo(XP_FRAME_DIR); FLeftMask.LoadFromFile(dir+'/frame_mask_left.bmp'); FRightMask.LoadFromFile(dir+'/frame_mask_right.bmp'); FFullMask.PixelFormat:=pf1bit; FFullMask.assign(FLeftMask); FFullMask.Width:=qforms.screen.width; FFullMask.height:=qforms.screen.height; //Some helper vars moving:=false; lastwidth:=-1; //Creates bitmaps needed for the frame FBottom:=TBitmap.create; FBottomLeft:=TBitmap.create; FBottomRight:=TBitmap.create; FBottomInactive:=TBitmap.create; FBottomLeftInactive:=TBitmap.create; FBottomRightInactive:=TBitmap.create; FCaption:=TBitmap.create; FCaptionLeft:=TBitmap.create; FCaptionRight:=TBitmap.create; FCaptionInactive:=TBitmap.create; FCaptionLeftInactive:=TBitmap.create; FCaptionRightInactive:=TBitmap.create; FLeft:=TBitmap.create; FLeftInactive:=TBitmap.create; FRight:=TBitmap.create; FRightInactive:=TBitmap.create; //Caption buttons FCloseButton:=TXPCaptionButton.create(nil); FCloseButton.frame:=self; FCloseButton.Glyph:='close'; FMaxButton:=TXPCaptionButton.create(nil); FMaxButton.frame:=self; FMaxButton.Glyph:='maximize'; FMinButton:=TXPCaptionButton.create(nil); FMinButton.frame:=self; FMinButton.Glyph:='minimize'; //Setup the frame setup; end; procedure TStyledFrame.setup; var dir: string; begin dir:=getSystemInfo(XP_FRAME_DIR); //Frames only yet support tiled left and and right frames FLeft.LoadFromFile(dir+'/frameleft_active.png'); FLeftInactive.LoadFromFile(dir+'/frameleft_inactive.png'); leftFrame.Bitmap.assign(FLeft); leftFrame.Width:=leftFrame.bitmap.width; FRight.LoadFromFile(dir+'/frameright_active.png'); FRightInactive.LoadFromFile(dir+'/frameright_inactive.png'); rightFrame.Bitmap.assign(FRight); rightFrame.Width:=rightFrame.bitmap.width; //Bottom frame is split in three parts, two corners and a central part that is stretched as needed FBottom.LoadFromFile(dir+'/framebottom_active.png'); FBottomInactive.LoadFromFile(dir+'/framebottom_inactive.png'); bottomFrame.bitmap.assign(FBottom); bottomFrame.height:=FBottom.height; FBottomLeft.LoadFromFile(dir+'/framebottom_left_active.png'); FBottomLeftInactive.LoadFromFile(dir+'/framebottom_left_inactive.png'); bottomFrameLeft.Bitmap.assign(FBottomLeft); bottomFrameLeft.Width:=bottomFrameLeft.bitmap.width; FBottomRight.LoadFromFile(dir+'/framebottom_right_active.png'); FBottomRightInactive.LoadFromFile(dir+'/framebottom_right_inactive.png'); bottomFrameRight.bitmap.assign(FBottomRight); bottomFrameRight.Width:=bottomFrameRight.bitmap.width; //Caption is also built from three parts FCaption.LoadFromFile(dir+'/captionbar_active.png'); FCaptionInactive.LoadFromFile(dir+'/captionbar_inactive.png'); topFrame.bitmap.assign(FCaption); topFrame.height:=FCaption.height; FCaptionLeft.LoadFromFile(dir+'/captionbar_left_active.png'); FCaptionLeftInactive.LoadFromFile(dir+'/captionbar_left_inactive.png'); FCaptionRight.LoadFromFile(dir+'/captionbar_right_active.png'); FCaptionRightInactive.LoadFromFile(dir+'/captionbar_right_inactive.png'); //Set buttons positions //Don't use anchors here because are a bit slower updateButtonsPosition(Width); FCloseButton.parent:=topFrame; FCloseButton.OnClick:=OnCloseButton; FMaxButton.parent:=topFrame; FMaxButton.OnClick:=OnMaximizeButton; FMinButton.parent:=topFrame; FMinButton.OnClick:=OnMinimizeButton; end; procedure TStyledFrame.FormDestroy(Sender: TObject); begin normalIcon.free; smallIcon.free; //Destroy all objects not needed imgIcon.free; mini_icon_a.free; mini_icon_i.free; mini_icon_s.free; icon_s.free; FLeftMask.free; FRightMask.free; FCloseButton.free; FMaxButton.free; FMinButton.free; FBottom.free; FBottomLeft.free; FBottomRight.free; FBottomLeftInactive.free; FBottomRightInactive.free; FCaption.free; FCaptionLeft.free; FCaptionRight.free; FLeft.free; FRight.free; FBottomInactive.free; FCaptionInactive.free; FCaptionLeftInactive.free; FCaptionRightInactive.free; FLeftInactive.free; FRightInactive.free; end; procedure TStyledFrame.resizeBitmaps(AWidth,AHeight:integer); var w: integer; t: integer; temp: TBitmap; atitle: string; k: integer; const caption_x=28; caption_y=7; style=[fsBold]; fsize=11; ix=8; iy=7; begin //Resize bitmaps to fit the new frame dimensions if (assigned(bottomFrameLeft)) then begin temp:=TBitmap.create; try if (AWidth<Constraints.MinWidth) then AWidth:=Constraints.MinWidth; w:=AWidth-bottomFrameLeft.width-bottomFrameRight.width; t:=AWidth-FCaptionLeft.width-FCaptionRight.width; if (lastWidth<>w) then begin //This is the bottom frame bottomFrame.Bitmap.width:=AWidth; if client.isactive then begin leftFrame.bitmap.assign(FLeft); rightFrame.bitmap.assign(FRight); bottomFrameLeft.Bitmap.Assign(FBottomLeft); bottomFrameRight.Bitmap.Assign(FBottomRight); bottomFrame.Bitmap.Canvas.StretchDraw(rect(bottomFrameLeft.width,0,bottomFrameLeft.width+w,bottomFrame.Height),FBottom); end else begin leftFrame.bitmap.assign(FLeftInactive); rightFrame.bitmap.assign(FRightInactive); bottomFrameLeft.Bitmap.Assign(FBottomLeftInactive); bottomFrameRight.Bitmap.Assign(FBottomRightInactive); bottomFrame.Bitmap.Canvas.StretchDraw(rect(bottomFrameLeft.width,0,bottomFrameLeft.width+w,bottomFrame.Height),FBottomInactive); end; //This is the top frame temp.assign(topFrame.bitmap); temp.width:=AWidth; if (client.isactive) then begin temp.canvas.draw(0,0,FCaptionLeft); temp.Canvas.StretchDraw(rect(FCaptionLeft.width,0,FCaptionLeft.width+t,topFrame.Height),FCaption); temp.canvas.draw(AWidth-FCaptionRight.width,0,FCaptionRight); end else begin temp.canvas.draw(0,0,FCaptionLeftInactive); temp.Canvas.StretchDraw(rect(FCaptionLeft.width,0,FCaptionLeft.width+t,topFrame.Height),FCaptionInactive); temp.canvas.draw(AWidth-FCaptionRight.width,0,FCaptionRightInactive); end; temp.Canvas.draw(ix,iy, smallIcon); temp.canvas.font.Size:=fsize; temp.canvas.font.Style:=style; atitle:=windowtitle; k:=0; while (canvas.TextWidth(atitle)>FMinButton.Left-caption_x-32) do begin atitle:=copy(windowtitle,1,length(windowtitle)-k)+'...'; if (atitle='...') then break; inc(k); end; temp.canvas.font.color:=clGray; temp.Canvas.TextOut(caption_x+1,caption_y+1,atitle); if (client.isactive) then temp.canvas.font.color:=clWhite else temp.canvas.font.color:=rgbtocolor(200,200,200); temp.Canvas.TextOut(caption_x,caption_y,atitle); topFrame.Bitmap.assign(temp); topFrame.refresh; lastwidth:=w; //This is the mask FFullMask.Canvas.draw(0,0,FLeftMask); FFullMask.Canvas.fillrect(Rect(FLeftMask.width,0, AWidth-FRightMask.width,FLeftMask.height)); FFullMask.Canvas.draw(AWidth-FRightMask.width,0,FRightMask); QWidget_setMask(self.handle,QBitmapH(FFullMask.handle)); end; finally temp.free; end; end; end; procedure TStyledFrame.ChangeBounds(ALeft, ATop, AWidth, AHeight: Integer); begin //The very first, resize bitmaps resizeBitmaps(AWidth,AHeight); inherited; //Then, reposition buttons updateButtonsPosition(AWidth); end; procedure TStyledFrame.topFrameMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin //Initiates moving { TODO : Dblclick must maximize window } if (not client.isactive) then client.activate; moving:=true; ox:=x; oy:=y; end; procedure TStyledFrame.topFrameMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin //Moves window if moving then begin //Why more? ;-) XSync(xpwindowmanager.display,1); QWidget_move(self.handle,left+(x-ox),top+(y-oy)); XSync(xpwindowmanager.display,0); end end; procedure TStyledFrame.topFrameMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin //Stops movement moving:=false; //Sends new coordinates to the client client.sendsyntheticConfigureNotify; end; { TXPCaptionButton } constructor TXPCaptionButton.Create(AOwner: TComponent); begin inherited; frame:=nil; FMask:=TBitmap.create; FNormal:=TBitmap.create; FOver:=TBitmap.create; FPressed:=TBitmap.create; setup; end; destructor TXPCaptionButton.Destroy; begin FMask.free; FNormal.free; FOver.free; FPressed.free; inherited; end; procedure TXPCaptionButton.MouseDown(button: TMouseButton; Shift: TShiftState; X, Y: integer); begin inherited; if (assigned(frame)) then begin if assigned(frame.client) then frame.client.activate; end; bitmap.Assign(FPressed); end; procedure TXPCaptionButton.mouseenter(AControl: TControl); begin inherited; bitmap.Assign(FOver); end; procedure TXPCaptionButton.mouseleave(AControl: TControl); begin inherited; bitmap.Assign(FNormal); end; procedure TXPCaptionButton.MouseUp(button: TMouseButton; Shift: TShiftState; X, Y: integer); begin inherited; if ptinrect(clientrect,point(x,y)) then bitmap.assign(FOver) else begin bitmap.Assign(FNormal); end; end; procedure TXPCaptionButton.SetGlyph(const Value: string); begin if (value<>FGlyph) then begin FGlyph := Value; setup; end; end; procedure TXPCaptionButton.SetParent(const Value: TWidgetControl); var dir: string; begin inherited; if (Parent<>nil) then begin dir:=getSystemInfo(XP_FRAME_DIR); FMask.LoadFromFile(dir+'/captionbutton_mask.bmp'); QWidget_setMask(self.handle, QBitmapH(FMask.handle)); end; end; procedure TXPCaptionButton.setup; var dir: string; glyph: TBitmap; gx,gy: integer; begin BevelOuter:=bvNone; dir:=getSystemInfo(XP_FRAME_DIR); FNormal.LoadFromFile(dir+'/captionbutton_normal.png'); FOver.LoadFromFile(dir+'/captionbutton_over.png'); FPressed.LoadFromFile(dir+'/captionbutton_press.png'); FNormal.transparent:=true; { TODO : Button sizes must be read from the themes or from bitmap dimensions } width:=19; height:=18; if (FGlyph<>'') then begin glyph:=TBitmap.create; try glyph.LoadFromFile(dir+'/'+FGlyph+'_active_normal.png'); glyph.Transparent:=true; gx:=(FNormal.width - glyph.width) div 2; gy:=((FNormal.height - glyph.height) div 2)+1; FNormal.Canvas.Draw(gx,gy,glyph); glyph.LoadFromFile(dir+'/'+FGlyph+'_active_over.png'); glyph.Transparent:=true; FOver.Canvas.Draw(gx,gy,glyph); glyph.LoadFromFile(dir+'/'+FGlyph+'_active_press.png'); glyph.Transparent:=true; FPressed.Canvas.Draw(gx,gy,glyph); finally glyph.free; end; end; bitmap.assign(FNormal); end; procedure TStyledFrame.rightFrameMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var size: TRect; begin //Resizes horizontally if resizing then begin size:=boundsrect; size.Right:=size.right+(x-ox); BoundsRect:=size; updateclientsize; end; end; procedure TStyledFrame.rightFrameMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (not client.isactive) then client.activate; ox:=x; oy:=y; resizing:=true; end; procedure TStyledFrame.rightFrameMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin resizing:=false; end; procedure TStyledFrame.leftFrameMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var size: TRect; begin //Resizes horizontally if resizing then begin size:=boundsrect; size.left:=size.left+(x-ox); BoundsRect:=size; updateclientsize; end; end; procedure TStyledFrame.bottomFrameMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var size: TRect; begin //Resizes vertically if resizing then begin size:=boundsrect; size.bottom:=size.bottom+(y-oy); BoundsRect:=size; updateclientsize; end; end; procedure TStyledFrame.bottomFrameRightMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var size: TRect; begin //Resizes NWSE if resizing then begin size:=boundsrect; size.right:=size.right+(x-ox); size.bottom:=size.bottom+(y-oy); BoundsRect:=size; updateclientsize; end; end; procedure TStyledFrame.bottomFrameLeftMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var size: TRect; begin //Resizes NESW if resizing then begin size:=boundsrect; size.left:=size.left+(x-ox); size.bottom:=size.bottom+(y-oy); BoundsRect:=size; updateclientsize; end; end; procedure TStyledFrame.setClient(AClient: TWMClient); begin client:=AClient; end; procedure TStyledFrame.setTitle(ATitle: widestring); begin windowtitle:=ATitle; updatewindowtitle; end; procedure TStyledFrame.updateWindowTitle; begin { TODO : Update window title } lastwidth:=-1; resizeBitmaps(Width,height); end; function TStyledFrame.getFrameBorderSizes: TRect; begin result.left:=leftFrame.width; result.top:=topFrame.height; result.right:=rightFrame.width; result.bottom:=bottomFrame.height; end; procedure TStyledFrame.setupIcons; var s: TBitmap; m: TBitmap; x,y: integer; source: TBitmap; image: QImageH; aimage: QImageH; begin s:=TBitmap.create; try s.assign(imgIcon.picture.bitmap); image := QImage_create; QPixmap_convertToImage(s.handle,image); aimage := QImage_create; QImage_smoothScale(image,aimage,32,32); QPixmap_convertFromImage(s.handle,aimage,0); normalIcon.canvas.brush.color:=rgbtocolor(255,0,255); normalIcon.Width:=32; normalIcon.height:=32; normalIcon.Canvas.Draw(0,0,s); normalIcon.transparent:=true; finally s.free; end; s:=TBitmap.create; try s.assign(imgIcon.picture.bitmap); image := QImage_create; QPixmap_convertToImage(s.handle,image); aimage := QImage_create; QImage_smoothScale(image,aimage,16,16); QPixmap_convertFromImage(s.handle,aimage,0); smallIcon.canvas.brush.color:=rgbtocolor(255,0,255); smallIcon.Width:=16; smallIcon.height:=16; smallIcon.Canvas.Draw(0,0,s); smallIcon.transparent:=true; finally s.free; end; (* { TODO : This must be completely changed } s:=TBitmap.create; try s.Canvas.Brush.Color:=$6b2408; s.canvas.pen.color:=$6b2408; s.width:=imgIcon.picture.bitmap.width; s.height:=imgIcon.picture.bitmap.height; s.Canvas.Draw(0,0,imgIcon.picture.bitmap); strecth(s,mini_icon_a,resampleFilters[1].filter,resamplefilters[1].width); finally s.free; end; s:=TBitmap.create; try s.Canvas.Brush.Color:=clGray; s.canvas.pen.color:=clGray; s.width:=imgIcon.picture.bitmap.width; s.height:=imgIcon.picture.bitmap.height; s.Canvas.Draw(0,0,imgIcon.picture.bitmap); strecth(s,mini_icon_i,resampleFilters[1].filter,resamplefilters[1].width); finally s.free; end; m:=TBitmap.create; try m.width:=16; m.height:=16; m.Canvas.Brush.Color:=clFuchsia; m.canvas.pen.color:=clFuchsia; m.Canvas.StretchDraw(rect(0,0,16,16),imgIcon.Picture.Bitmap); strecth(imgIcon.picture.bitmap,mini_icon_s,resampleFilters[1].filter,resamplefilters[1].width); for y:=0 to 15 do begin for x:=0 to 15 do begin if m.Canvas.Pixels[x,y]=clFuchsia then begin mini_icon_s.Canvas.Pixels[x,y]:=clFuchsia; end; end; end; finally m.free; end; m:=TBitmap.create; try m.width:=32; m.height:=32; m.Canvas.Brush.Color:=clFuchsia; m.canvas.pen.color:=clFuchsia; m.Canvas.StretchDraw(rect(0,0,32,32),imgIcon.Picture.Bitmap); strecth(imgIcon.picture.bitmap,icon_s,resampleFilters[1].filter,resamplefilters[1].width); for y:=0 to 31 do begin for x:=0 to 31 do begin if m.Canvas.Pixels[x,y]=clFuchsia then begin icon_s.Canvas.Pixels[x,y]:=clFuchsia; end; end; end; finally m.free; end; *) end; function TStyledFrame.getTitle: widestring; begin result:=windowtitle; end; procedure TStyledFrame.updateWindowState; begin if client.WindowState=wsMaximized then begin FMaxButton.Glyph:='restore'; end else begin FMaxButton.Glyph:='maximize'; end; end; function TStyledFrame.getHostControl: TWidgetControl; begin result:=clientArea; end; procedure TStyledFrame.updateActiveState; begin if assigned(client) then begin lastWidth:=-1; resizeBitmaps(width,height); end; end; procedure TStyledFrame.updateclientsize; begin if assigned(client) then begin client.beginresize; try XSync(xpwindowmanager.display,1); XResizeWindow(XPWindowManager.Display,client.getwindow,clientArea.width,clientArea.height); XSync(xpwindowmanager.display,0); finally client.endresize; end; end; end; procedure TStyledFrame.updateButtonsPosition(AWidth:integer); begin if assigned(FCloseButton) then begin if (AWidth<Constraints.MinWidth) then AWidth:=constraints.minwidth; FCloseButton.top:=((topFrame.Height - FCloseButton.Height) div 2)+2; FCloseButton.Left:=AWidth-FCloseButton.width-7; FMaxButton.Top:=FCloseButton.Top; FMaxButton.Left:=AWidth-FMaxButton.width-7-FCloseButton.width-4; FMinButton.Top:=FCloseButton.Top; FMinButton.Left:=AWidth-FMinButton.width-7-FCloseButton.width-4-FMaxButton.width-4; end; end; procedure TStyledFrame.OnCloseButton(Sender: TObject); begin if assigned(client) then client.close; end; procedure TStyledFrame.OnMaximizeButton(Sender: TObject); begin if assigned(client) then begin if client.windowstate<>wsMaximized then begin client.maximize; end else begin client.restore; end; end; end; procedure TStyledFrame.OnMinimizeButton(Sender: TObject); begin if assigned(client) then begin if client.windowstate<>wsMinimized then begin client.minimize; end else begin client.restore; end; end; end; initialization XPWindowManager.Frame:=TStyledFrame; end.
unit Unit2; interface type TStudent = class private FName:string; procedure SetName(const Value: string); public property Name:string read FName write SetName; //constructor Create;overload; constructor Create(FName:string);overload; end; implementation { TStudent } { constructor TStudent.Create; begin //调用父类的构造方法 inherited; end; } constructor TStudent.Create(FName: string); begin Self.Name:=FName; end; procedure TStudent.SetName(const Value: string); begin FName := Value; end; end.
unit main; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, lclintf, Grids, Menus, ComCtrls,form_F1,form_edit,queryresult; type { TForm1 } TForm1 = class(TForm) MainMenu1: TMainMenu; Memo2: TMemo; MenuItem1: TMenuItem; cmd_open: TMenuItem; cmd_save: TMenuItem; cmd_save_as: TMenuItem; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; StatusBar1: TStatusBar; StringGrid1: TStringGrid; sg2: TStringGrid; txt_answer: TEdit; lbl_set: TLabel; procedure cmd_saveClick(Sender: TObject); procedure cmd_save_asClick(Sender: TObject); procedure cmd_openClick(Sender: TObject); procedure txt_answerKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCreate(Sender: TObject); procedure lbl_setDblClick(Sender: TObject); procedure ProcessInputFile; procedure txt_answerKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState ); procedure Save(filename:string); procedure Open(filename:string); private { private declarations } public { public declarations } end; var Form1: TForm1; filename:string; datalist:Tstringlist; datalist_set:Tstringlist; datalist_get:Tstringlist; actual_dataset:integer; status:byte=$FF; good_cnt:integer=0; all_cnt:integer=0; implementation {$R *.lfm} { TForm1 } procedure TForm1.FormCreate(Sender: TObject); begin datalist:=Tstringlist.create; datalist_set:=Tstringlist.create; datalist_get:=Tstringlist.create; randomize; filename := Includetrailingpathdelimiter(Includetrailingpathdelimiter(extractfiledir(application.ExeName)) + 'WordLists') + 'default.wl'; opendialog1.initialdir := Includetrailingpathdelimiter(extractfiledir(application.ExeName)) + 'WordLists' ; Open(filename); end; procedure TForm1.txt_answerKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState ); var c,s:string; i,col,row:integer; begin if key = 13 then begin case status of 0,$FF: begin actual_dataset := Random(datalist_set.count); lbl_set.Caption := datalist_set[actual_dataset]; txt_answer.Font.Color:=clnavy; lbl_set.Font.Color:=clnavy; txt_answer.text :=''; status := 1; sg2.Cells[1,2]:= IntToStr(actual_dataset) ; end; 1: begin inc(all_cnt); if uppercase(trim(txt_answer.text)) = uppercase(datalist_get[actual_dataset]) then begin txt_answer.Font.Color:=clgreen; lbl_set.Font.Color:=clgreen; inc(good_cnt); end else begin lbl_set.Caption:= datalist_set[actual_dataset] + ' - ' + datalist_get[actual_dataset]; txt_answer.Font.Color:=clred; lbl_set.Font.Color:=clred; end; status := 0; sg2.Cells[1,1]:= IntToStr(good_cnt) + ' from ' + IntToStr(all_cnt); end; end end; if ssCtrl in shift then begin case key of 65: c :='Æ'; 67: c:= 'Ç'; 69: c:= 'Ë'; 73: c:= 'Ï'; 79: c:= 'Œ'; 89: c:= 'Ÿ'; end; txt_answer.text := txt_answer.text + c; txt_answer.SelStart:= length(txt_answer.text); txt_answer.Sellength:= 0; end; if ssAlt in shift then begin case key of 65: c:= 'æ'; 67: c:= 'ç'; 69: c:= 'ë'; 73: c:= 'ï'; 79: c:= 'œ'; 89: c:= 'ÿ'; end; txt_answer.text := txt_answer.text + c; txt_answer.SelStart:= length(txt_answer.text); txt_answer.Sellength:= 0; end; if key = 113 {F2 - EDIT} then begin if status <> $FF then begin frm_edit.KeyPreview := True; frm_edit.cmd_save_and_exit.Caption:= 'Save + Exit'; frm_edit.txt_edit_set.text := datalist_set[actual_dataset]; frm_edit.txt_edit_get.text := datalist_get[actual_dataset]; frm_edit.hint :=''; frm_edit.showmodal; if frm_edit.hint = '1' then begin datalist_set[actual_dataset] := frm_edit.txt_edit_set.text; datalist_get[actual_dataset] := frm_edit.txt_edit_get.text; Save(filename); frm_edit.hint:= ''; lbl_set.Caption := datalist_set[actual_dataset]; txt_answer.text := datalist_get[actual_dataset]; end; end; end; if key = 114 {F3 DELETE}then begin if status <> $FF then begin frm_edit.cmd_save_and_exit.Caption:= 'Delete this + Exit'; frm_edit.KeyPreview := True; frm_edit.txt_edit_set.text := datalist_set[actual_dataset]; frm_edit.txt_edit_get.text := datalist_get[actual_dataset]; frm_edit.hint :=''; frm_edit.showmodal; if frm_edit.hint = '1' then begin datalist_set.Delete(actual_dataset); datalist_get.Delete(actual_dataset); datalist.Delete(actual_dataset); Save(filename); frm_edit.hint:= ''; end; end; end; if key = 115 {F4 - ADD NEW } then begin if status <> $FF then begin frm_edit.KeyPreview := True; frm_edit.txt_edit_set.text := ''; frm_edit.txt_edit_get.text := ''; frm_edit.hint :=''; frm_edit.showmodal; if frm_edit.hint = '1' then begin datalist_set.add(frm_edit.txt_edit_set.text); datalist_get.add(frm_edit.txt_edit_get.text); Save(filename); frm_edit.hint:= ''; lbl_set.Caption := datalist_set[actual_dataset]; txt_answer.text := datalist_get[actual_dataset]; end; end; end; if key = 116 {F5 - OPEN Question IN BROWSER }then begin openurl('http://de.bab.la/woerterbuch/franzoesisch-deutsch/' + datalist_get[actual_dataset]); end; if key = 117 {F6 - OPEN Answer IN BROWSER }then begin openurl('http://de.bab.la/woerterbuch/deutsch-franzoesisch/' + datalist_set[actual_dataset]); end; if key = 118 {F7 - OPEN Question IN BROWSER }then begin openurl('http://de.bab.la/konjugieren/franzoesisch/' + datalist_get[actual_dataset]); end; if key = 119 {F8 - Search }then begin s:=inputbox('Search','for what:',datalist_set[actual_dataset]); frm_queryresult.StringGrid1.RowCount:=2; frm_queryresult.StringGrid1.cells[1,1] := ''; frm_queryresult.StringGrid1.cells[2,1] := ''; col:=1; row:=1; for i:= 0 to datalist_set.Count - 1 do begin if (pos(s,datalist_set[i]) <> 0) OR (pos(s,datalist_get[i]) <> 0) then begin if (frm_queryresult.StringGrid1.cells[1,frm_queryresult.StringGrid1.rowcount-1] = '') then begin frm_queryresult.StringGrid1.cells[0,frm_queryresult.StringGrid1.rowcount-1] := inttostr(i); frm_queryresult.StringGrid1.cells[1,frm_queryresult.StringGrid1.rowcount-1] := datalist_set[i]; frm_queryresult.StringGrid1.cells[2,frm_queryresult.StringGrid1.rowcount-1] := datalist_get[i]; end else begin frm_queryresult.StringGrid1.rowcount := frm_queryresult.StringGrid1.rowcount + 1; frm_queryresult.StringGrid1.cells[0,frm_queryresult.StringGrid1.rowcount-1] := inttostr(i); frm_queryresult.StringGrid1.cells[1,frm_queryresult.StringGrid1.rowcount-1] := datalist_set[i]; frm_queryresult.StringGrid1.cells[2,frm_queryresult.StringGrid1.rowcount-1] := datalist_get[i]; end; end; end; frm_queryresult.ShowModal; end; end; procedure TForm1.cmd_saveClick(Sender: TObject); begin if fileexists(statusbar1.Panels[0].text)=TRUE then begin Save(statusbar1.Panels[0].text); end; end; procedure TForm1.cmd_save_asClick(Sender: TObject); begin if savedialog1.Execute = TRUE then begin save(savedialog1.FileName); end; end; procedure TForm1.cmd_openClick(Sender: TObject); begin if opendialog1.Execute = TRUE then begin open(opendialog1.FileName); end; end; procedure TForm1.ProcessInputFile; var i:integer; s_set,s_get:string; p:byte; begin datalist_set.text := ''; datalist_get.text := ''; for i:= 0 to datalist.count - 1 do begin p:= pos('§',datalist[i]); s_set := datalist[i]; s_get := datalist[i]; if p <> 0 then begin delete(s_set,p,length(s_set)); s_set := trim(s_set); delete(s_get,1,p+1); s_get := trim(s_get); datalist_set.add(s_set); datalist_get.add(s_get); end; end; end; procedure TForm1.txt_answerKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if NOT((key > 36) AND (key < 41)) then begin txt_answer.SelStart:= length(txt_answer.text); txt_answer.Sellength:= 0; end; end; procedure TForm1.lbl_setDblClick(Sender: TObject); begin end; procedure TForm1.Save(filename:string); var i:integer; begin datalist.text := ''; for i:= 0 to datalist_set.count - 1 do begin datalist.Add(datalist_set[i] + ' § ' + datalist_get[i]); end; datalist.SaveToFile(filename); end; procedure TForm1.Open(filename:string); begin if fileexists(filename)=TRUE then begin datalist.LoadFromFile(filename); statusbar1.Panels[0].text := filename; end else begin showmessage('Couldn''t find file: '+ filename); end; ProcessInputFile; sg2.Cells[1,0] := IntToStr(datalist.Count); end; end.
unit k2AtomOperation; { Библиотека "K-2" } { Автор: Люлин А.В. © } { Модуль: k2AtomOperation - } { Начат: 18.10.2005 13:53 } { $Id: k2AtomOperation.pas,v 1.6 2012/07/12 18:33:21 lulin Exp $ } // $Log: k2AtomOperation.pas,v $ // Revision 1.6 2012/07/12 18:33:21 lulin // {RequestLink:237994598} // // Revision 1.5 2009/07/23 13:42:34 lulin // - переносим процессор операций туда куда надо. // // Revision 1.4 2009/07/22 17:16:40 lulin // - оптимизируем использование счётчика ссылок и преобразование к интерфейсам при установке атрибутов тегов. // // Revision 1.3 2009/07/06 13:32:12 lulin // - возвращаемся от интерфейсов к объектам. // // Revision 1.2 2008/02/12 12:53:20 lulin // - избавляемся от излишнего метода на базовом классе. // // Revision 1.1 2005/10/18 10:03:09 lulin // - реализация базовой Undo-записи перенесена в правильное место. // {$Include k2Define.inc } interface uses l3Types, k2Op, k2Interfaces ; type Tk2AtomOperation = class(Tk2Op) protected // property fields f_Atom : Long; f_Prop : Tk2CustomPropertyPrim; protected // property methods function pm_GetAtom: Ik2Tag; {-} protected // internal methods function SetParam(const anAtom : Ik2Tag; const aProp : Tk2CustomPropertyPrim): Tk2AtomOperation; {-} procedure Cleanup; override; {-} public // public methods procedure Clear; virtual; {-} public // public methods property Prop: Tk2CustomPropertyPrim read f_Prop; {-} property Atom: Ik2Tag read pm_GetAtom; {-} end;//Tk2AtomOperation implementation uses k2Base, k2BaseStruct ; // start class Tk2AtomOperation procedure Tk2AtomOperation.Cleanup; {override;} {-} begin Clear; inherited; end; procedure Tk2AtomOperation.Clear; {override;} {-} begin inherited; if (f_Atom <> 0) then FreeIntRef(Tk2TypePrim(f_Prop.ParentType), f_Atom); f_Prop := nil; end; function Tk2AtomOperation.pm_GetAtom: Ik2Tag; {-} begin if (f_Prop = nil) then Result := k2NullTag else Result := Tk2Type(f_Prop.ParentType).TagFromIntRef(f_Atom); end; function Tk2AtomOperation.SetParam(const anAtom : Ik2Tag; const aProp : Tk2CustomPropertyPrim): Tk2AtomOperation; {-} begin Clear; f_Prop := aProp; anAtom.SetIntRef(f_Atom); Result := Self; end; end.
{ CoreGraphics - CGLayer.h * Copyright (c) 2004 Apple Computer, Inc. * All rights reserved. } { Pascal Translation: Peter N Lewis, <peter@stairways.com.au>, August 2005 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit CGLayer; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,CFBase,CFDictionary,CGBase,CGGeometry,CGContext; {$ALIGN POWER} type CGLayerRef = ^SInt32; { an opaque 32-bit type } { Create a layer of size `size' relative to the context `context'. The * value of `size' is specified in default user space (base space) units. * If `size' is NULL, then the underlying size of `context' is used. The * parameter `auxiliaryInfo' should be NULL; it is reserved for future * expansion. } function CGLayerCreateWithContext( context: CGContextRef; size: CGSize; auxiliaryInfo: CFDictionaryRef ): CGLayerRef; external name '_CGLayerCreateWithContext'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Equivalent to `CFRetain(layer)', except it doesn't crash (as CFRetain * does) if `layer' is NULL. } function CGLayerRetain( layer: CGLayerRef ): CGLayerRef; external name '_CGLayerRetain'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Equivalent to `CFRelease(layer)', except it doesn't crash (as CFRelease * does) if `layer' is NULL. } procedure CGLayerRelease( layer: CGLayerRef ); external name '_CGLayerRelease'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Return the size of the layer `layer'. } function CGLayerGetSize( layer: CGLayerRef ): CGSize; external name '_CGLayerGetSize'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Return the context of `layer'. } function CGLayerGetContext( layer: CGLayerRef ): CGContextRef; external name '_CGLayerGetContext'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Draw the contents of `layer' into `rect' of `context'. The contents are * scaled, if necessary, to fit into `rect'; the rectangle `rect' is in * user space. } procedure CGContextDrawLayerInRect( context: CGContextRef; rect: CGRect; layer: CGLayerRef ); external name '_CGContextDrawLayerInRect'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Draw the contents of `layer' at `point' in `context'. This is * equivalent to calling "CGContextDrawLayerInRect" with a rectangle having * origin at `point' and size equal to the size of `layer'. } procedure CGContextDrawLayerAtPoint( context: CGContextRef; point: CGPoint; layer: CGLayerRef ); external name '_CGContextDrawLayerAtPoint'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Return the CFTypeID for CGLayerRefs. } function CGLayerGetTypeID: CFTypeID; external name '_CGLayerGetTypeID'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) end.
unit CustomerForma; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, DBGridEh, ToolCtrlsEh, Buttons, GridsEh, DBCtrlsEh, DBLookupEh, Mask, DBCtrls, ComCtrls, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet, AtrPages, Menus, FIBQuery, pFIBQuery, ToolWin, ActnList, System.Actions, PropFilerEh, PropStorageEh, DBGridEhGrouping, DBGridEhToolCtrls, DynVarsEh, MemTableDataEh, MemTableEh, EhLibVCL, DBAxisGridsEh, fmuCustomerBalance; type TCustomerForm = class(TForm) pnlForms: TPanel; pnlDATA: TPanel; trRead: TpFIBTransaction; trWrite: TpFIBTransaction; dsCustomer: TpFIBDataSet; mmCustomer: TMainMenu; mmiCustomer: TMenuItem; N2: TMenuItem; N3: TMenuItem; miDelete: TMenuItem; srcCustomer: TDataSource; Query: TpFIBQuery; spl1: TSplitter; Actions: TActionList; actPrint: TAction; actEdit: TAction; actFilterCustomer: TAction; actDouble: TAction; ToolBar1: TToolBar; ToolButton4: TToolButton; ToolButton3: TToolButton; ToolButton8: TToolButton; btnFilterCustomer: TToolButton; ToolButton1: TToolButton; actSave: TAction; ActCancel: TAction; ToolButton2: TToolButton; sprtr1: TToolButton; sprtr2: TToolButton; N5: TMenuItem; N6: TMenuItem; N7: TMenuItem; Splitter1: TSplitter; prpstrgh1: TPropStorageEh; dbgForms: TDBGridEh; srcPages: TDataSource; mtbPages: TMemTableEh; pnlTop: TPanel; pnlMain: TPanel; actCustNode: TAction; miCustNode: TMenuItem; actPrepay: TAction; miPrepay: TMenuItem; actTask: TAction; miTask: TMenuItem; miN1: TMenuItem; ActAddPayment: TAction; miActAddPayment: TMenuItem; actRequest: TAction; miRequest: TMenuItem; actRecAdd: TAction; miRecAdd: TMenuItem; actNPS: TAction; miNPS: TMenuItem; actResetpassword: TAction; miN2: TMenuItem; miResetpassword: TMenuItem; actCheckPassport: TAction; miCheckPassport: TMenuItem; actDelete: TAction; actOrderTP: TAction; miOrderTP: TMenuItem; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure actFilterCustomerExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure actSaveExecute(Sender: TObject); procedure ActCancelExecute(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure srcPagesDataChange(Sender: TObject; Field: TField); procedure FormShow(Sender: TObject); procedure actCustNodeExecute(Sender: TObject); procedure actPrepayExecute(Sender: TObject); procedure actTaskExecute(Sender: TObject); procedure ActAddPaymentExecute(Sender: TObject); procedure actRecAddExecute(Sender: TObject); procedure actNPSExecute(Sender: TObject); procedure actResetpasswordExecute(Sender: TObject); procedure actCheckPassportExecute(Sender: TObject); procedure actRequestExecute(Sender: TObject); procedure actDeleteExecute(Sender: TObject); procedure actOrderTPExecute(Sender: TObject); private FLastPage: TA4onPage; FInfoPage: TA4onPage; // FBalancePage: TA4onPage; FPageList: TA4onPages; FInEditState: Boolean; FCheckPassport: Boolean; procedure StartEdit(); procedure StopEdit(const Cancel: Boolean); procedure CreateCustomerPage(const Edit: Boolean = False); procedure ShowPage(const index: Integer); procedure UpdateCommands; procedure StartCommand(Sender: TObject); procedure UpdatePage(Sender: TObject); procedure SwitchIfoTab(const next: Boolean); procedure ValidatePassport; procedure InitSecurity; public constructor CreateA(AOwner: TComponent; aCustomer: Integer; const Edit: Boolean = False); destructor Destroy; override; end; procedure ShowCustomer(aCustomer: Integer; const Edit: Boolean = False); implementation {$R *.dfm} uses AtrCommon, AtrStrUtils, MAIN, DM, CF, PrjConst, OverbyteIcsWndControl, OverbyteIcsHttpProt, OverbyteIcsWSocket, OverbyteIcsUrl, fmuCustomerInfo, fmuCustomerSrv, fmuCustomerPayments, fmuCustomerSingleSrv, fmuCustomerKoef, fmuCustomerLetters, fmuCustomerRecourse, fmuCustomerRequests, fmuCustomerAttributes, fmuCustomerLan, fmuCustomerInternet, fmuCustomerCard, fmuCustomerDigit, fmuCustomerEdit, fmuCustomerBonus, fmuCustomerFiles, fmuCustomerMaterialsMove, fmuCustomerAppl, PaymentForma, RequestNewForma, RecourseForma, NPSAddForma, OrderTPForma, A4onTypeUnit, TextEditForma; procedure ShowCustomer(aCustomer: Integer; const Edit: Boolean = False); var i: Integer; finded: Integer; fCnt: Integer; begin finded := -1; fCnt := 0; for i := A4MainForm.MDIChildCount - 1 DownTo 0 Do if Assigned(A4MainForm.MDIChildren[i]) then if (A4MainForm.MDIChildren[i] is TCustomerForm) then begin Inc(fCnt); if (A4MainForm.MDIChildren[i].tag = aCustomer) then finded := i; end; if finded = -1 then begin if fCnt > 10 then begin if Application.MessageBox(PChar(rsManyCustomerForm), PChar(rsManyCustomerFormCaption), MB_YESNO + MB_ICONWARNING) = IDYES then begin for i := A4MainForm.MDIChildCount - 1 DownTo 0 Do if Assigned(A4MainForm.MDIChildren[i]) then if (A4MainForm.MDIChildren[i] is TCustomerForm) then A4MainForm.MDIChildren[i].Close; end; end; TCustomerForm.CreateA(Application, aCustomer, Edit); end else A4MainForm.MDIChildren[finded].Show; end; procedure TCustomerForm.ActAddPaymentExecute(Sender: TObject); var dt: TDate; sm: Currency; begin dt := NOW; sm := 0; ReceivePayment(dsCustomer['CUSTOMER_ID'], -1, -1, dt, sm); end; procedure TCustomerForm.ActCancelExecute(Sender: TObject); begin if actSave.Visible then begin StopEdit(true); dbgForms.SetFocus; end else begin Close; end; end; procedure TCustomerForm.actCheckPassportExecute(Sender: TObject); begin ValidatePassport; end; procedure TCustomerForm.actCustNodeExecute(Sender: TObject); begin if (dsCustomer.FieldByName('HOUSE_ID').IsNull) or (dsCustomer.FieldByName('FLAT_NO').IsNull) then Exit; A4MainForm.OpnenNodeByFlat(dsCustomer['HOUSE_ID'], dsCustomer['FLAT_NO']); end; procedure TCustomerForm.actDeleteExecute(Sender: TObject); var i: Integer; s: string; Save_Cursor: TCursor; begin if dmMain.InStrictMode then Exit; if (dsCustomer.RecordCount = 0) then Exit; If MessageDlg(rsDeleteCustomerWarning, mtConfirmation, [mbYes, mbNo], 0, mbNo) <> mrYes then Exit; s := ''; if not(dsCustomer.FieldByName('SURNAME').IsNull) then s := s + dsCustomer['SURNAME']; if not(dsCustomer.FieldByName('INITIALS').IsNull) then s := s + ' ' + dsCustomer['INITIALS']; s := s + rsACCOUNT + ' ' + dsCustomer['ACCOUNT_NO'] + '?'; If MessageDlg(Format(rsDeleteWithName, [s]), mtConfirmation, [mbNo, mbYes], 0) = mrNo then Exit; dsCustomer.Delete; Close; end; procedure TCustomerForm.actEditExecute(Sender: TObject); begin StartEdit; end; procedure TCustomerForm.actFilterCustomerExecute(Sender: TObject); var customers: string; begin if dsCustomer.State in [dsEdit, dsInsert] then Exit; customers := dsCustomer.FieldByName('CUSTOMER_ID').AsString; if (customers <> '') then ShowCustomers(7, customers); end; procedure TCustomerForm.actNPSExecute(Sender: TObject); begin if (dsCustomer.RecordCount = 0) or dsCustomer.FieldByName('CUSTOMER_ID').IsNull then Exit; if not(dmMain.AllowedAction(rght_Customer_full) or dmMain.AllowedAction(rght_Customer_NPS)) then Exit; AddNpsRating(dsCustomer['CUSTOMER_ID']); end; procedure TCustomerForm.actOrderTPExecute(Sender: TObject); var ci: TCustomerInfo; begin ci.CUSTOMER_ID := dsCustomer.FieldByName('CUSTOMER_ID').AsInteger; ci.cust_code := dsCustomer.FieldByName('cust_code').AsString; ci.Account_No := dsCustomer.FieldByName('Account_No').AsString; ci.CUST_STATE_DESCR := dsCustomer.FieldByName('CUST_STATE_DESCR').AsString; if (dmMain.GetSettingsValue('SHOW_AS_BALANCE') = '1') then ci.Debt_sum := -1 * dsCustomer.FieldByName('Debt_sum').AsCurrency else ci.Debt_sum := dsCustomer.FieldByName('Debt_sum').AsCurrency; ci.FIO := Trim(dsCustomer.FieldByName('Surname').AsString + ' ' + dsCustomer.FieldByName('Firstname').AsString + ' ' + dsCustomer.FieldByName('Midlename').AsString); ci.STREET_ID := dsCustomer.FieldByName('street_ID').AsInteger; ci.STREET := dsCustomer.FieldByName('STREET_SHORT').AsString + ' ' + dsCustomer.FieldByName('STREET_NAME').AsString; ci.HOUSE_ID := dsCustomer.FieldByName('HOUSE_ID').AsInteger; ci.HOUSE_no := dsCustomer.FieldByName('House_No').AsString; ci.FLAT_NO := dsCustomer.FieldByName('FLAT_No').AsString; ci.phone_no := dsCustomer.FieldByName('phone_no').AsString; ci.mobile := dsCustomer.FieldByName('MOBILE_PHONE').AsString; ci.notice := dsCustomer.FieldByName('notice').AsString; ci.Color := dsCustomer.FieldByName('HIS_COLOR').AsString; ci.isType := 0; ci.INN := dsCustomer.FieldByName('JUR_INN').AsString; ci.isJur := dsCustomer.FieldByName('Juridical').AsInteger; if ci.isJur = 1 then ci.FIO := Trim(dsCustomer.FieldByName('Firstname').AsString + ' ' + dsCustomer.FieldByName('Surname').AsString); CreateOrderTPForCustomer(-1, ci); end; procedure TCustomerForm.actPrepayExecute(Sender: TObject); var s: string; v: Extended; all: Boolean; Save_Cursor: TCursor; i: Integer; procedure AddPrepay(const psum: Extended; cid: Integer); begin with TpFIBQuery.Create(Self) do begin try Database := dmMain.dbTV; Transaction := dmMain.trWriteQ; sql.Text := 'execute procedure Set_Prepay(:Customer_Id, :Prepay_Sum)'; ParamByName('Prepay_Sum').value := psum; // v; ParamByName('Customer_Id').value := cid; // dsCustomers.FieldByName('customer_id').AsInteger; Transaction.StartTransaction; ExecQuery; Transaction.Commit; Close; finally Free; end; end; end; begin s := '0'; if InputQuery(rsPrepay, rsAmount, s) then begin if TryStrToFloat(s, v) then begin Save_Cursor := Screen.Cursor; Screen.Cursor := crHourGlass; AddPrepay(v, dsCustomer['customer_id']); Screen.Cursor := Save_Cursor; end; end; end; procedure TCustomerForm.actRecAddExecute(Sender: TObject); begin if (not dmMain.AllowedAction(rght_Recourses_add)) then Exit; if not dsCustomer.FieldByName('CUSTOMER_ID').IsNull then EditRecourse(dsCustomer.FieldByName('CUSTOMER_ID').AsInteger) end; procedure TCustomerForm.actRequestExecute(Sender: TObject); var aCustomer: Integer; begin if (not(dmMain.AllowedAction(rght_Request_Add) or dmMain.AllowedAction(rght_Request_Full))) then Exit; if (dsCustomer.RecordCount > 0) and (not dsCustomer.FieldByName('CUSTOMER_ID').IsNull) then aCustomer := dsCustomer['CUSTOMER_ID'] else aCustomer := -1; NewRequest(aCustomer); end; procedure TCustomerForm.actResetpasswordExecute(Sender: TObject); var pswd: String; begin // Сброс пароля if (dsCustomer.RecordCount = 0) or (dsCustomer.FieldByName('CUSTOMER_ID').IsNull) then Exit; if (not dmMain.AllowedAction(rght_Customer_PSWD)) then Exit; pswd := GenPassword(8); EditText(pswd, 'Новый пароль', Format('Абоненту %s будет установлен пароль', [dsCustomer['ACCOUNT_NO']])); with TpFIBQuery.Create(Self) do begin try Database := dmMain.dbTV; Transaction := dmMain.trWriteQ; sql.Text := 'UPDATE customer set Secret = :pswd where Customer_Id = :CID'; ParamByName('pswd').AsString := pswd; ParamByName('CID').AsInteger := dsCustomer['CUSTOMER_ID']; Transaction.StartTransaction; ExecQuery; Transaction.Commit; Close; finally Free; end; end; end; procedure TCustomerForm.actSaveExecute(Sender: TObject); begin if FInEditState then StopEdit(False); end; procedure TCustomerForm.actTaskExecute(Sender: TObject); begin if (dsCustomer.RecordCount = 0) or (dsCustomer.FieldByName('ACCOUNT_NO').IsNull) then Exit; A4MainForm.MakeTask('A', dsCustomer['ACCOUNT_NO'], nil); end; constructor TCustomerForm.CreateA(AOwner: TComponent; aCustomer: Integer; const Edit: Boolean = False); var CanEdit: Boolean; begin inherited Create(AOwner); FInEditState := Edit; dsCustomer.ParamByName('CUSTOMER_ID').AsInteger := aCustomer; dsCustomer.Open; tag := aCustomer; CanEdit := dmMain.AllowedAction(rght_Customer_add) or dmMain.AllowedAction(rght_Customer_edit) or (dmMain.AllowedAction(rght_Customer_full)); FPageList := TA4onPages.Create; if aCustomer <> -1 then begin Caption := 'А'; if not dsCustomer.FieldByName('ACCOUNT_NO').IsNull then Caption := Caption + ' ' + dsCustomer['ACCOUNT_NO']; if not dsCustomer.FieldByName('SURNAME').IsNull then Caption := Caption + ' ' + dsCustomer['SURNAME']; CreateCustomerPage(Edit and CanEdit); FPageList.Add(TapgCustomerSrv); FPageList.Add(TapgCustomerSingleSrv); FPageList.Add(TapgCustomerKoef); FPageList.Add(TapgCustomerPayments); FPageList.Add(TapgCustomerRequests); FPageList.Add(TapgCustomerAttributes); FPageList.Add(TapgCustomerDigit); FPageList.Add(TapgCustomerLan); FPageList.Add(TapgCustomerInternet); FPageList.Add(TapgCustomerLetters); FPageList.Add(TapgCustomerRecourse); FPageList.Add(TapgCustomerBonus); FPageList.Add(TapgCustomerFiles); FPageList.Add(TapgCustomerMaterialsMove); FPageList.Add(TapgCustomerAppl); FPageList.Add(TapgCustomerCard); FPageList.Add(TapgCustomerBalance); end; UpdateCommands; actEdit.Enabled := ((not Edit) and CanEdit); actSave.Enabled := (Edit and CanEdit); end; procedure TCustomerForm.UpdateCommands; var i: Integer; PageName: string; begin if mtbPages.Active then mtbPages.Close; mtbPages.Open; mtbPages.DisableControls; if Assigned(FPageList) then begin try for i := 0 to FPageList.Count - 1 do begin PageName := FPageList[i].PageClass.GetPageName; mtbPages.Append; mtbPages['id'] := i; mtbPages['name'] := PageName; mtbPages.Post; end; mtbPages.First; finally mtbPages.EnableControls; end; if FPageList.Count > 0 then begin ShowPage(0); end; end; end; procedure TCustomerForm.StartCommand(Sender: TObject); begin // end; procedure TCustomerForm.UpdatePage(Sender: TObject); begin // end; procedure TCustomerForm.ShowPage(const index: Integer); var Item: TA4onPageItem; Page: TA4onPage; begin if (Index < 0) or (Index >= FPageList.Count) then raise Exception.Create('Invalid page index'); Item := FPageList[Index]; if Item.Page = nil then begin Item.Page := Item.PageClass.CreatePage(Self, srcCustomer); Page := Item.Page; Page.InitForm; Page.OnUpdate := UpdatePage; Page.OnStart := StartCommand; Page.BorderStyle := bsNone; Page.Parent := pnlDATA; Page.Width := pnlDATA.ClientHeight; Page.Height := pnlDATA.ClientHeight; end else Page := Item.Page; if Page <> FLastPage then begin Page.Align := alClient; Page.Visible := true; Page.Width := pnlDATA.ClientWidth; Page.OpenData; if FLastPage <> nil then begin FLastPage.Visible := False; FLastPage.CloseData; end; FLastPage := Page; end; end; procedure TCustomerForm.srcPagesDataChange(Sender: TObject; Field: TField); begin if not mtbPages.FieldByName('ID').IsNull then ShowPage(mtbPages['ID']); end; procedure TCustomerForm.FormClose(Sender: TObject; var Action: TCloseAction); var i: Integer; begin if Assigned(FPageList) then begin for i := FPageList.Count - 1 downto 0 do begin if Assigned(FPageList[i].Page) then begin FPageList[i].Page.SaveState; FPageList[i].Page.CloseData; FPageList[i].Free; end; end; FPageList.Free; end; if Assigned(FInfoPage) then begin FInfoPage.CloseData; FInfoPage.Free; FInfoPage := nil; // FreeAndNil(FInfoPage); end; Action := caFree; end; destructor TCustomerForm.Destroy; begin inherited Destroy; end; procedure TCustomerForm.StartEdit(); begin actEdit.Enabled := False; FInEditState := true; CreateCustomerPage(true); end; procedure TCustomerForm.CreateCustomerPage(const Edit: Boolean = False); var CanEdit: Boolean; begin CanEdit := dmMain.AllowedAction(rght_Customer_add) or dmMain.AllowedAction(rght_Customer_edit) or (dmMain.AllowedAction(rght_Customer_full)); if Assigned(FInfoPage) then begin FInfoPage.CloseData; FInfoPage := nil; end; if not Edit then begin FInfoPage := TapgCustomerInfo.CreatePage(Self, srcCustomer); // (FInfoPage as TapgCustomerInfo).pnlInfo.Enabled := False; end else begin FInfoPage := TapgCustomerEdit.CreatePage(Self, srcCustomer); end; with FInfoPage do begin Parent := pnlMain; OnUpdate := UpdatePage; OnStart := StartCommand; BorderStyle := bsNone; Align := alClient; Visible := true; if Edit then FInfoPage.SetFocus; InitForm; OpenData; end; actEdit.Visible := not Edit; actSave.Enabled := CanEdit; actSave.Visible := Edit; ActCancel.Visible := Edit; sprtr1.Visible := Edit; sprtr2.Visible := Edit; end; procedure TCustomerForm.StopEdit(const Cancel: Boolean); var CanSave: Boolean; begin if not Cancel then begin if (not Assigned(FInfoPage)) then CanSave := true else begin CanSave := (FInfoPage.ValidateData); if not CanSave then begin CanSave := (Application.MessageBox(PWideChar(rsErrorQuestContinue), PWideChar(rsError), MB_OKCANCEL + MB_ICONQUESTION + MB_DEFBUTTON2) = IDOK); end; if (CanSave and (dsCustomer.State in [dsEdit, dsInsert])) then begin FInfoPage.SaveData; dsCustomer.Post; end; end; end else begin CanSave := true; if dsCustomer.State in [dsEdit, dsInsert] then dsCustomer.Cancel; end; if CanSave then begin actEdit.Enabled := true; FInEditState := False; // ActCancel.Enabled := False; actSave.Enabled := False; CreateCustomerPage(False); end; end; procedure TCustomerForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssAlt]) and ((Ord(Key) = VK_UP) or (Ord(Key) = VK_DOWN)) then begin SwitchIfoTab((Ord(Key) = VK_DOWN)); Key := 0; end else if FInEditState and (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then StopEdit(False); end; procedure TCustomerForm.FormKeyPress(Sender: TObject; var Key: Char); var go: Boolean; begin if (Ord(Key) = VK_RETURN) then begin go := true; if (ActiveControl is TDBLookupComboboxEh) then go := not(ActiveControl as TDBLookupComboboxEh).ListVisible else if (ActiveControl is TDBGridEh) then go := False else if (ActiveControl is TDBMemoEh) then go := False; if go then begin Key := #0; // eat enter key PostMessage(Self.Handle, WM_NEXTDLGCTL, 0, 0); end; end; end; procedure TCustomerForm.FormShow(Sender: TObject); var i: Integer; Font_size: Integer; Font_name: string; begin if TryStrToInt(dmMain.GetIniValue('FONT_SIZE'), i) then begin Font_size := i; Font_name := dmMain.GetIniValue('FONT_NAME'); for i := 0 to ComponentCount - 1 do begin if Components[i] is TDBGridEh then begin (Components[i] as TDBGridEh).Font.Name := Font_name; (Components[i] as TDBGridEh).Font.Size := Font_size; end; end; end; InitSecurity; end; procedure TCustomerForm.SwitchIfoTab(const next: Boolean); begin if (not mtbPages.FieldByName('ID').IsNull) then begin if next then begin if mtbPages.Eof then mtbPages.First else mtbPages.next; end else begin if mtbPages.BOF then mtbPages.Last else mtbPages.Prior; end; end; end; procedure TCustomerForm.ValidatePassport; var FHttpCli: TSslHttpCli; FSslContext: TSslContext; Datax: TStringStream; url: string; unp, ps, pn: string; answer: string; pValid: Integer; qry: TpFIBQuery; edtPERSONAL_N, edtPASSPORT_NUMBER: string; eFIRSTNAME: string; eSURNAME: string; eMIDLENAME: string; function HasInvalidChar(const s: string): Boolean; var i: Integer; begin i := 1; Result := False; while (i <= Length(s)) do begin if (not CharInSet(s[i], [' ', '0' .. '9', 'a' .. 'z', 'A' .. 'Z'])) then Result := true; Inc(i); end; end; procedure SplitNumber(const s: string; var ser: string; var num: string); var v: string; begin v := Trim(UpperCase(s)); ser := Copy(v, 1, 2); num := Trim(Copy(v, 3, 15)); end; function GetV(const FN: string): String; begin if (not dsCustomer.FieldByName(FN).IsNull) then Result := dsCustomer[FN] else Result := ''; end; begin if (not FCheckPassport) or (not dsCustomer.Active) or (dsCustomer.RecordCount = 0) then Exit; if (not dsCustomer.FieldByName('JURIDICAL').IsNull) and (dsCustomer['JURIDICAL'] = 1) then Exit; if (not dsCustomer.FieldByName('PASSPORT_VALID').IsNull) and (dsCustomer['PASSPORT_VALID'] = 1) then Exit; answer := ''; edtPERSONAL_N := GetV('PERSONAL_N'); eFIRSTNAME := GetV('FIRSTNAME'); eSURNAME := GetV('SURNAME'); eMIDLENAME := GetV('MIDLENAME'); edtPASSPORT_NUMBER := GetV('PASSPORT_NUMBER'); pValid := -1; if eSURNAME = '' then answer := 'Фамилия - ' + rsEmptyFieldError + #13#10; if eFIRSTNAME = '' then answer := answer + 'Имя - ' + rsEmptyFieldError + #13#10; if ((edtPERSONAL_N = '') or (HasInvalidChar(edtPERSONAL_N)) or (Length(edtPERSONAL_N) <> 14)) then answer := answer + 'Личный номер - ' + rsEmptyOrIncorrect + #13#10; if ((edtPASSPORT_NUMBER = '') or (HasInvalidChar(edtPASSPORT_NUMBER))) then answer := answer + 'Номер паспорта - ' + rsEmptyOrIncorrect + #13#10; if not answer.IsEmpty then begin ShowMessage(Trim(answer)); Exit; end; SplitNumber(edtPASSPORT_NUMBER, ps, pn); unp := dmMain.GetCompanyValue('UNN'); if unp = '' then unp := dmMain.GetCompanyValue('UNP'); url := Format('surname=%s&name=%s&lastname=%s', [UrlEncode(eSURNAME), UrlEncode(eFIRSTNAME), UrlEncode(eMIDLENAME)]) + Format('&ser=%s&num=%s&identif=%s', [UrlEncode(ps), UrlEncode(pn), UrlEncode(edtPERSONAL_N)]) + Format('&unp=%s&region=%s&district=%s&city=%s&street=%s&house=%s&housing=%s&room=%s', [UrlEncode(unp), UrlEncode(dmMain.GetCompanyValue('REGION')), UrlEncode(dmMain.GetCompanyValue('DISTRICT')), UrlEncode(dmMain.GetCompanyValue('CITY')), UrlEncode(dmMain.GetCompanyValue('STREET')), UrlEncode(dmMain.GetCompanyValue('HOUSE')), UrlEncode(dmMain.GetCompanyValue('HOUSING')), UrlEncode(dmMain.GetCompanyValue('ROOM'))]); FSslContext := TSslContext.Create(nil); FSslContext.Name := 'FSslContext'; FSslContext.SslDHParamLines.Clear; FSslContext.SslVerifyPeer := False; FHttpCli := TSslHttpCli.Create(nil); FHttpCli.Name := 'FHttpCli'; FHttpCli.Agent := 'a4on/1.0'; FHttpCli.ServerAuth := httpAuthBearer; FHttpCli.AuthBearerToken := dmMain.GetSettingsValue('KEY_MVD'); FHttpCli.ProxyAuth := httpAuthNone; FHttpCli.TimeOut := 30; FHttpCli.SslContext := FSslContext; FHttpCli.ResponseNoException := true; Datax := TStringStream.Create('', TEncoding.UTF8); FHttpCli.OnRequestDone := Nil; FHttpCli.RcvdStream := Datax; FHttpCli.url := rsCheckPassportURL + url; FHttpCli.Get; // sync if FHttpCli.StatusCode = 200 then begin answer := Datax.DataString; if answer.ToLower.Contains('выдан, действителен') then pValid := 1 else begin ShowMessage(answer); pValid := 0; end end else begin answer := rsError + ' ' + FHttpCli.StatusCode.ToString; ShowMessage(answer); end; FHttpCli.RcvdStream.Free; FHttpCli.RcvdStream := nil; FHttpCli.Free; FSslContext.Free; qry := TpFIBQuery.Create(Nil); try qry.Database := dmMain.dbTV; qry.Transaction := dmMain.trWriteQ; if pValid > -1 then begin qry.sql.Text := 'update customer c set c.Passport_Valid = :PV where c.Customer_Id = :CID'; qry.ParamByName('PV').value := pValid; qry.ParamByName('CID').value := dsCustomer['CUSTOMER_ID']; qry.Transaction.StartTransaction; qry.ExecQuery; qry.Transaction.Commit; end; if answer <> '' then begin qry.sql.Text := 'insert into Changelog (Log_Group, Object_Id, Value_Before, Value_After)'; qry.sql.Add(' values (:Log_Group, :Object_Id, :Value_Before, :Value_After)'); qry.ParamByName('Log_Group').value := 'PASSPORT_CHECK'; qry.ParamByName('Object_Id').value := dsCustomer['CUSTOMER_ID']; qry.ParamByName('Value_Before').value := Format('%s %s %s|%s%s|%s', [eSURNAME, eFIRSTNAME, eMIDLENAME, ps, pn, edtPERSONAL_N]); qry.ParamByName('Value_After').value := answer; qry.Transaction.StartTransaction; qry.ExecQuery; qry.Transaction.Commit; end; finally qry.Free; end; end; procedure TCustomerForm.InitSecurity; var FullAccess: Boolean; begin FullAccess := dmMain.AllowedAction(rght_Request_Full); FCheckPassport := (dmMain.GetSettingsValue('KEY_MVD') <> ''); actCheckPassport.Visible := FCheckPassport; actRequest.Visible := (FullAccess or dmMain.AllowedAction(rght_Request_Add)); actRecAdd.Visible := (FullAccess or dmMain.AllowedAction(rght_Recourses_add)); actNPS.Visible := (FullAccess or dmMain.AllowedAction(rght_Customer_NPS)); actResetpassword.Visible := (FullAccess or dmMain.AllowedAction(rght_Customer_PSWD)); ActAddPayment.Visible := (FullAccess or dmMain.AllowedAction(rght_Pays_add) or dmMain.AllowedAction(rght_Pays_AddToday)); actDelete.Enabled := (not dmMain.InStrictMode) and (dmMain.AllowedAction(rght_Customer_del) or FullAccess); actOrderTP.Visible := dmMain.AllowedAction(rght_OrdersTP_full) or dmMain.AllowedAction(rght_OrdersTP_add) or dmMain.AllowedAction(rght_OrdersTP_View); // actPrepay.Visible := (FullAccess or dmMain.AllowedAction(rght_Customer_NPS)); // actTask.Visible := (FullAccess or dmMain.AllowedAction(rght_Customer_NPS)); // actCheckPassport.Visible := (FullAccess or dmMain.AllowedAction(rght_Customer_NPS)); end; end.
unit format_edf; //support for EDF format ... http://www.edfplus.info/specs/edf.html interface uses eeg_type, sysutils,dialogs, DateUtils; function LoadEDF(lFilename: string; var lEEG: TEEG): boolean; function WriteEDF(lFilename: string; var lEEG: TEEG): boolean; implementation type TEEGHdr = packed record //Next: EDF header VERSION: array [1..8] of char; //8 ascii : version of this data format (0) : 5 since we read 3 bytes to determine file type ID: array [1..80] of char; //80 ascii : local patient identification (mind item 3 of the additional EDF+ specs) LOCALRECORD: array [1..80] of char; //80 ascii : local patient identification (mind item 3 of the additional EDF+ specs) STARTDATE: array [1..8] of char; //startdate of recording (dd.mm.yy) (mind item 2 of the additional EDF+ specs) STARTTIME: array [1..8] of char; //8 ascii : starttime of recording (hh.mm.ss) HDRBYTES: array [1..8] of char; //8 ascii : number of bytes in header record RESERVED: array [1..44] of char; //44 ascii : reserved RECORDS: array [1..8] of char; //8 ascii : number of data records (-1 if unknown, obey item 10 of the additional EDF+ specs) DURATIONSEC: array [1..8] of char; //8 ascii : duration of a data record, in seconds NS: array [1..4] of char; //4 ascii : number of signals (ns) in data record end; //TEEGHdr Header Structure TChanHdr = packed record //Next: Poly5 header Labl: array [1..16] of char; Transducer,Prefilter : array [1..80] of char; dimension,minimum,maximum,digminimum,digmaximum,samples : array [1..8] of char; Res : array [1..32] of char; end; procedure Str2Array(lIn: string; var lOut: array of char); var Len,i: integer; begin Len := length(lIn); if length(lOut) < Len then Len := length(lOut); if Len < 1 then exit; for i := 1 to Len do lOut[i-1] := lIn[i]; if Len < length(lOut) then for i := Len+1 to length(lOut) do lOut[i-1] := chr($20); end; procedure TDate2Hdr (lTime : TDateTime; var EEGHdr: TEEGHdr); //STARTDATE = dd.mm.yy :: STARTTIME = hh.mm.ss var lYY,lDD,lMo,lHH,lMi,lSS, lMs : Word; begin //Str2Array('12.34.56',EEGHdr.STARTTIME);//hh.mm.ss //Str2Array('12.12.99',EEGHdr.STARTDATE);//dd.mm.yy DecodeDateTime(lTime, lYY, lMo, lDD, lHH, lMi, lSS, lMs); if (lYY < 1985) or (lYY > 2084) then begin showmessage('This software is really obsolete.'); exit; end; if lYY > 1999 then lYY := lYY - 2000 else lYY := lYY - 1900; Str2Array(Format('%.*d', [2, lDD])+'.'+Format('%.*d', [2, lMo])+'.'+Format('%.*d', [2, lYY]), EEGHdr.STARTDATE); Str2Array(Format('%.*d', [2, lHH])+'.'+Format('%.*d', [2, lMi])+'.'+Format('%.*d', [2, lSS]), EEGHdr.STARTTIME); end; function SamplesPerRecord (NS,sampperchannel: integer): integer; const kRecBytes= 61440; //we want as few records as possible, so our time resolution will avoid rounding errors. //However.... // sampperchannel must be divisible by recordsize // record size should not exceed kRecBytes var i,s,bytes: integer; begin result := 1; s := 2; for i := 1 to 16 do begin bytes := s*2{16-bit ints}*NS; if bytes > kRecBytes then exit; if (sampperchannel mod s) = 0 then result := s else exit; s := s * 2; end; end; function WriteEDF(lFilename: string; var lEEG: TEEG): boolean; var EEGHdr: TEEGHdr; Hz: double; lsampperrec,Sig,NS,s,r,lsampperchannel,i,j,lnrec: integer; fp: file; ChanRA: array of TChanHdr; DataRA: array of smallint; begin decimalseparator := '.'; result := false; NS := NumChannels(lEEG); if NS < 1 then exit; //first maximum number of recordings for any channel lsampperchannel := NumSamples(lEEG,0); for Sig := 0 to (NS-1) do if NumSamples(lEEG,Sig) <> lsampperchannel then begin showmessage('Can only create EDF files where all channels have the same number of signals'); exit; end; lsampperrec := SamplesPerRecord (NS,lsampperchannel); lnrec := lsampperchannel div lsampperrec; Hz := lEEG.Channels[0].SampleRate; for Sig := 0 to (NS-1) do if lEEG.Channels[Sig].SampleRate <> Hz then begin showmessage('Can create EDF files where all channels have same sampling rate'); exit; end; FileMode := 2; //set to read/write AssignFile(fp, lFileName); Rewrite(fp, 1); FillChar(EEGHdr, SizeOf(TEEGHdr), $20); Str2Array('0',EEGHdr.VERSION); TDate2Hdr (lEEG.Time,EEGHdr) ; Str2Array(inttostr(NS),EEGHdr.NS); Str2Array('',EEGHdr.Reserved); //EDF+ support requires 'Str2Array('EDF+C',EEGHdr.Reserved); //'EDF+C' // and a new signal type : EDF Annotations Str2Array(floattostr(1/Hz* lsampperrec),EEGHdr.DURATIONSEC); Str2Array(inttostr(lnrec),EEGHdr.RECORDS); Str2Array(inttostr((NS+1)*256),EEGHdr.HDRBYTES); //main header is 256 bytes, +256 per channel BlockWrite(fp, EEGHdr, SizeOf(TEEGHdr)); SetLength( ChanRA, NS ); for Sig := 1 to NS do begin FillChar(ChanRA[Sig-1], SizeOf(TChanHdr), $20); Str2Array(lEEG.Channels[Sig-1].Info,ChanRA[Sig-1].Labl); Str2Array(lEEG.Channels[Sig-1].Info,ChanRA[Sig-1].Transducer); if lEEG.Channels[Sig-1].UnitType[1] = chr($B5) then Str2Array('uV',ChanRA[Sig-1].dimension) else Str2Array(lEEG.Channels[Sig-1].UnitType,ChanRA[Sig-1].dimension); Str2Array(inttostr(-32767),ChanRA[Sig-1].minimum); Str2Array(inttostr(32767),ChanRA[Sig-1].maximum); Str2Array(inttostr(-32767),ChanRA[Sig-1].digminimum); Str2Array(inttostr(32767),ChanRA[Sig-1].digmaximum); Str2Array(inttostr(lsampperrec),ChanRA[Sig-1].samples); Str2Array('',ChanRA[Sig-1].Res); end; for Sig := 1 to NS do BlockWrite(fp,ChanRA[Sig-1].Labl,SizeOf(ChanRA[Sig-1].Labl)); for Sig := 1 to NS do BlockWrite(fp,ChanRA[Sig-1].Transducer,SizeOf(ChanRA[Sig-1].Transducer)); for Sig := 1 to NS do BlockWrite(fp,ChanRA[Sig-1].dimension,SizeOf(ChanRA[Sig-1].dimension)); for Sig := 1 to NS do BlockWrite(fp,ChanRA[Sig-1].minimum,SizeOf(ChanRA[Sig-1].minimum)); for Sig := 1 to NS do BlockWrite(fp,ChanRA[Sig-1].maximum,SizeOf(ChanRA[Sig-1].maximum)); for Sig := 1 to NS do BlockWrite(fp,ChanRA[Sig-1].digminimum,SizeOf(ChanRA[Sig-1].digminimum)); for Sig := 1 to NS do BlockWrite(fp,ChanRA[Sig-1].digmaximum,SizeOf(ChanRA[Sig-1].digmaximum)); for Sig := 1 to NS do BlockWrite(fp,ChanRA[Sig-1].Prefilter,SizeOf(ChanRA[Sig-1].Prefilter)); for Sig := 1 to NS do BlockWrite(fp,ChanRA[Sig-1].samples,SizeOf(ChanRA[Sig-1].samples)); for Sig := 1 to NS do BlockWrite(fp,ChanRA[Sig-1].Res,SizeOf(ChanRA[Sig-1].Res)); SetLength( DataRA, lsampperchannel*NS ); i := 0; j := 0; for r := 1 to lnrec do begin for Sig := 0 to (NS-1) do begin for s := 0 to ( lsampperrec-1) do begin DataRA[i] := round(lEEG.Samples[Sig][j+s]); inc(i); end; //for each sample in record end;//for each channle; j := j + lsampperrec; end; //for each record BlockWrite(fp,DataRA[0],lsampperchannel*NS * sizeof(smallint)); CloseFile(fp); result := true; end; function ValidNumber(Ch1,Ch2: char; var lV: integer):boolean; begin result := false; if (not(Ch1 in ['0'..'9'])) or (not(Ch1 in ['0'..'9'])) then exit; lV := strtoint(Ch1+Ch2); end; function Time2TDate (EEGHdr: TEEGHdr): TDateTime; //STARTDATE = dd.mm.yy :: STARTTIME = hh.mm.ss var lYY,lDD,lMo,lHH,lMi,lSS : integer; begin result := now; if not(EEGHdr.STARTDATE[7] in ['0'..'9']) then showmessage('Your software is really obsolete.'); //'YY' means year >2084 if not ValidNumber(EEGHdr.STARTDATE[1],EEGHdr.STARTDATE[2],lDD) then exit; if not ValidNumber(EEGHdr.STARTDATE[4],EEGHdr.STARTDATE[5],lMo) then exit; if not ValidNumber(EEGHdr.STARTDATE[7],EEGHdr.STARTDATE[8],lYY) then exit; if not ValidNumber(EEGHdr.STARTTIME[1],EEGHdr.STARTTIME[2],lHH) then exit; if not ValidNumber(EEGHdr.STARTTIME[4],EEGHdr.STARTTIME[5],lMi) then exit; if not ValidNumber(EEGHdr.STARTTIME[7],EEGHdr.STARTTIME[8],lSS) then exit; if lYY >= 85 then lYY := lYY + 1900 else lYY := lYY + 2000; if not IsValidDateTime(lYY, lMo, lDD, lHH, lMi, lSS, 0) then exit; result := EncodeDateTime(lYY, lMo, lDD, lHH, lMi, lSS, 0); end; function LoadEDF(lFilename: string; var lEEG: TEEG): boolean; var fp: file; r,p,i,s,Sig,NS,Rec,sz,maxsamp: integer; samplesec: double; EEGHdr: TEEGHdr; Labl: array [1..16] of char; Transducer,Prefilter : array [1..80] of char; dimension,minimum,maximum,digminimum,digmaximum,samples : array [1..8] of char; Res : array [1..32] of char; SampRA: array of integer; DataRA: array of smallint; begin decimalseparator := '.'; result := false; FileMode := 0; //set to readonly AssignFile(fp, lFileName); Reset(fp, 1); if FileSize(fp) < sizeof(TEEGHdr) then raise Exception.Create('To small to be an EDF file :'+lFilename); seek(fp, 0); BlockRead(fp, EEGHdr, SizeOf(TEEGHdr)); lEEG.Time := Time2TDate(EEGHdr); //showmessage(FormatDateTime('yyyymmdd_hhnnss', (lEEG.Time))) ; samplesec := strtofloat(Trim(EEGHdr.DURATIONSEC)); NS := strtoint(Trim(EEGHdr.NS)); if NS < 1 then raise Exception.Create('EDF file has unexpected number of signals:'+inttostr(NS)); Rec := strtoint(Trim(EEGHdr.RECORDS)); if Rec < 1 then raise Exception.Create('EDF file has unexpected number of records:'+inttostr(Rec)); setlength(lEEG.Channels,NS); ClearEEGHdr ( lEEG); for Sig := 1 to NS do begin BlockRead(fp,Labl,SizeOf(Labl)); lEEG.Channels[Sig-1].Info := Trim(Labl); end; for Sig := 1 to NS do BlockRead(fp,Transducer,SizeOf(Transducer)); for Sig := 1 to NS do begin BlockRead(fp,dimension,SizeOf(dimension)); lEEG.Channels[Sig-1].UnitType := Trim(dimension); //showmessage(inttostr(Sig)+':'+inttostr(NS)+lEEG.Channels[Sig-1].UnitType ); if length(lEEG.Channels[Sig-1].UnitType) > 0 then if (lEEG.Channels[Sig-1].UnitType[1] = 'µ') or (lEEG.Channels[Sig-1].UnitType[1] = 'u') then lEEG.Channels[Sig-1].SignalLead := true else lEEG.Channels[Sig-1].SignalLead := false; end; for Sig := 1 to NS do BlockRead(fp,minimum,SizeOf(minimum)); for Sig := 1 to NS do BlockRead(fp,maximum,SizeOf(maximum)); for Sig := 1 to NS do BlockRead(fp,digminimum,SizeOf(digminimum)); for Sig := 1 to NS do BlockRead(fp,digmaximum,SizeOf(digmaximum)); for Sig := 1 to NS do BlockRead(fp,Prefilter,SizeOf(Prefilter)); SetLength( SampRA, NS ); for Sig := 1 to NS do begin BlockRead(fp,samples,SizeOf(samples)); SampRA[Sig-1] := strtoint(Trim(samples)); lEEG.Channels[Sig-1].SampleRate := SampRA[Sig-1]/SampleSec ; end; for Sig := 1 to NS do begin BlockRead(fp,Res,SizeOf(Res)); end; maxsamp := 0; for Sig := 0 to (NS-1) do if SampRA[Sig] > maxsamp then maxsamp := SampRA[Sig]; for Sig := 0 to (NS-1) do if SampRA[Sig] <> SampRA[0] then showmessage('This viewer may not show this EDF file correctly (annotations or variable sampling rate).'); i := 0; for Sig := 1 to NS do begin i := i + rec*SampRA[Sig-1]; end; if maxsamp < 1 then exit; sz := sizeof(TEEGHdr)+NS*sizeof(TChanHdr)+i*2; if sz > filesize(fp) then begin showmessage('EDF file smaller than described in header. Actual: '+inttostr(filesize(fp))+' expected: '+inttostr(sz) ); exit; end; setlength(lEEG.Samples,NS,maxsamp*rec); for r := 0 to maxsamp-1 do for Sig := 0 to (NS-1) do lEEG.Samples[Sig][r] := 0; setlength(DataRA,i); BlockRead(fp,DataRA[0],i * sizeof(smallint)); p := 0; for r := 1 to rec do begin for Sig := 0 to (NS-1) do begin if SampRA[Sig] > 0 then begin i := (r-1)* SampRA[Sig]; for s := 1 to SampRA[Sig] do begin lEEG.Samples[Sig][i] := DataRA[p]; inc(i); inc(p); end; //for each Samp end;//at least 1 sample t read end; //for each Sig end; // for each record CloseFile(fp); FileMode := 2; //set to readwrite result := true; end; //LoadFromEDFStream end.
{ GDAX/Coinbase-Pro client library Copyright (c) 2018 mr-highball 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. } unit gdax.api.time; interface uses Classes,gdax.api.types,gdax.api,gdax.api.consts; type { TGDAXTimeImpl } TGDAXTimeImpl = class(TGDAXRestApi,IGDAXTime) public const PROP_ISO = 'iso'; PROP_EPOCH = 'epoch'; strict private FISO: String; FEpoch: Extended; protected function GetEpoch: Extended; function GetISO: String; procedure SetEpoch(Const AValue: Extended); procedure SetISO(Const AValue: String); strict protected function DoGetSupportedOperations: TRestOperations; override; function GetHeadersForOperation(Const AOperation: TRestOperation; Const AHeaders: TStrings; out Error: String): Boolean; override; function GetEndpoint(Const AOperation: TRestOperation): String; override; function DoLoadFromJSON(Const AJSON: String; out Error: String): Boolean;override; public property ISO: String read GetISO write SetISO; property Epoch: Extended read GetEpoch write SetEpoch; end; implementation uses DateUtils, SysUtils, fpjson, jsonparser; { TGDAXTimeImpl } function TGDAXTimeImpl.DoGetSupportedOperations: TRestOperations; begin Result:=[roGet]; end; function TGDAXTimeImpl.GetHeadersForOperation(Const AOperation: TRestOperation; Const AHeaders: TStrings; out Error: String): Boolean; begin Result := False; try //to avoid circular dependency between authenticator and time, //we put the minimal headers here AHeaders.Add('%s=%s',['Content-Type','application/json']); AHeaders.Add('%s=%s',['User-Agent',USER_AGENT_MOZILLA]); Result := True; except on E:Exception do Error := E.Message; end; end; function TGDAXTimeImpl.DoLoadFromJSON(Const AJSON: String; out Error: String): Boolean; var LJSON : TJSONObject; begin Result := False; try LJSON := TJSONObject(GetJSON(AJSON)); if not Assigned(LJSON) then raise Exception.Create(E_BADJSON); try if not Assigned(LJSON) then begin Error := E_BADJSON; Exit; end; if LJSON.Find(PROP_ISO) = nil then begin Error := E_BADJSON; Exit; end; FISO := LJSON.Get(PROP_ISO); if LJSON.Find(PROP_EPOCH) = nil then begin Error := E_BADJSON; Exit; end; FEpoch := LJSON.Get(PROP_EPOCH); Result := True; finally LJSON.Free; end; except on E: Exception do Error := E.Message; end; end; function TGDAXTimeImpl.GetEndpoint(Const AOperation: TRestOperation): String; begin Result := GDAX_END_API_TIME; end; function TGDAXTimeImpl.GetEpoch: Extended; begin Result := FEpoch; end; function TGDAXTimeImpl.GetISO: String; begin Result := FISO; end; procedure TGDAXTimeImpl.SetEpoch(Const AValue: Extended); begin FEpoch := AValue; end; procedure TGDAXTimeImpl.SetISO(Const AValue: String); begin FISO := AValue; end; end.
unit GX_IdeSearchPathFavorites; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, GX_BaseForm, StdCtrls, ComCtrls; type Tf_SarchPathFavorites = class(TfmBaseForm) l_Favorites: TLabel; b_Close: TButton; lv_Favorites: TListView; b_Add: TButton; b_Edit: TButton; b_Delete: TButton; procedure b_AddClick(Sender: TObject); procedure b_EditClick(Sender: TObject); procedure b_DeleteClick(Sender: TObject); procedure lv_FavoritesDblClick(Sender: TObject); private procedure SetData(_Favorites: TStrings); procedure GetData(_Favorites: TStrings); procedure EditCurrent; public class procedure Execute(_Owner: TComponent; var _Favorites: TStringList); constructor Create(_Owner: TComponent); override; end; implementation uses GX_dzSelectDirectoryFix, GX_IdeSearchPathFavoriteEdit, GX_dzVclUtils; {$R *.dfm} { Tf_SarchPathFavorites } class procedure Tf_SarchPathFavorites.Execute(_Owner: TComponent; var _Favorites: TStringList); var frm: Tf_SarchPathFavorites; begin frm := Tf_SarchPathFavorites.Create(_Owner); try frm.SetData(_Favorites); frm.ShowModal; frm.GetData(_Favorites); finally FreeAndNil(frm); end; end; constructor Tf_SarchPathFavorites.Create(_Owner: TComponent); begin inherited; TControl_SetMinConstraints(Self); end; procedure Tf_SarchPathFavorites.b_AddClick(Sender: TObject); var li: TListItem; FavName: string; FavPath: string; begin FavName := 'New Entry'; FavPath := ''; if not Tf_IdeSearchPathFavoriteEdit.Execute(Self, FavName, FavPath) then Exit; li := lv_Favorites.Items.Add; li.Caption := FavName; li.SubItems.Add(FavPath); end; procedure Tf_SarchPathFavorites.b_DeleteClick(Sender: TObject); var li: TListItem; begin li := lv_Favorites.Selected; if not Assigned(li) then Exit; if MessageDlg('Delete this entry?', mtConfirmation, [mbYes, mbCancel], 0) <> mrYes then Exit; lv_Favorites.DeleteSelected; end; procedure Tf_SarchPathFavorites.b_EditClick(Sender: TObject); begin EditCurrent; end; procedure Tf_SarchPathFavorites.EditCurrent; var li: TListItem; FavName: string; FavPath: string; begin li := lv_Favorites.Selected; if not Assigned(li) then Exit; FavName := li.Caption; FavPath := li.SubItems[0]; if not Tf_IdeSearchPathFavoriteEdit.Execute(Self, FavName, FavPath) then Exit; li.Caption := FavName; li.SubItems[0] := FavPath; end; procedure Tf_SarchPathFavorites.GetData(_Favorites: TStrings); var i: Integer; FavName: string; FavValue: string; li: TListItem; begin for i := 0 to lv_Favorites.Items.Count - 1 do begin li := lv_Favorites.Items[i]; FavName := li.Caption; FavValue := li.SubItems[0]; _Favorites.Values[FavName] := FavValue; end; end; procedure Tf_SarchPathFavorites.lv_FavoritesDblClick(Sender: TObject); begin EditCurrent; end; procedure Tf_SarchPathFavorites.SetData(_Favorites: TStrings); var i: Integer; FavName: string; FavValue: string; li: TListItem; begin for i := 0 to _Favorites.Count - 1 do begin FavName := _Favorites.Names[i]; FavValue := _Favorites.Values[FavName]; li := lv_Favorites.Items.Add; li.Caption := FavName; li.SubItems.Add(FavValue); end; end; end.
unit enet_host; (** @file host.c @brief ENet host management functions freepascal 1.3.12 *) {$GOTO ON} interface uses enet_consts; procedure enet_host_bandwidth_limit (host : pENetHost;incomingBandwidth : enet_uint32; outgoingBandwidth : enet_uint32); procedure enet_host_bandwidth_throttle (host : pENetHost); procedure enet_host_broadcast (host : pENetHost; channelID : enet_uint8; packet : pENetPacket); function enet_host_connect (host : pENetHost; address : pENetAddress; channelCount : enet_size_t; data : enet_uint32):pENetPeer; function enet_host_create (address : pENetAddress;peerCount, channelLimit : enet_size_t; incomingBandwidth : enet_uint32;outgoingBandwidth : enet_uint32):pENetHost; procedure enet_host_destroy (host : pENetHost); implementation uses enet_peer, enet_packet, enet_list, enet_socket, enet_callbacks {$ifdef WINDOWS} , mmsystem {$endif} ; (** @defgroup host ENet host functions @{ *) (** Creates a host for communicating to peers. @param address the address at which other peers may connect to this host. If NULL, then no peers may connect to the host. @param peerCount the maximum number of peers that should be allocated for the host. @param channelLimit the maximum number of channels allowed; if 0, then this is equivalent to ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT @param incomingBandwidth downstream bandwidth of the host in bytes/second; if 0, ENet will assume unlimited bandwidth. @param outgoingBandwidth upstream bandwidth of the host in bytes/second; if 0, ENet will assume unlimited bandwidth. @returns the host on success and NULL on failure @remarks ENet will strategically drop packets on specific sides of a connection between hosts to ensure the host's bandwidth is not overwhelmed. The bandwidth parameters also determine the window size of a connection which limits the amount of reliable packets that may be in transit at any given time. *) function enet_host_create (address : pENetAddress;peerCount, channelLimit : enet_size_t; incomingBandwidth : enet_uint32;outgoingBandwidth : enet_uint32):pENetHost; var host : pENetHost; currentPeer : pENetPeer; begin if (peerCount > ENET_PROTOCOL_MAXIMUM_PEER_ID) then begin result := nil; exit; end; host := pENetHost(enet_malloc (sizeof (ENetHost))); if host = nil then begin result := nil; exit; end; fillchar(host^,SizeOf(ENetHost) ,0); host ^. peers := pENetPeer( enet_malloc (peerCount * sizeof (ENetPeer)) ); if host ^. peers = nil then begin enet_free(host); result:=nil; exit; end; fillchar (host ^. peers^, peerCount * sizeof (ENetPeer), 0); host ^. socket := enet_socket_create (ENET_SOCKET_TYPE_DATAGRAM); if (host ^. socket = ENET_SOCKET_NULL) or ((address <> nil) and (enet_socket_bind (host ^. socket, address) < 0)) then begin if (host ^. socket <> ENET_SOCKET_NULL) then enet_socket_destroy (host ^. socket); enet_free (host ^. peers); enet_free (host); result := nil; exit; end; enet_socket_set_option (host ^. socket, ENET_SOCKOPT_NONBLOCK, 1); enet_socket_set_option (host ^. socket, ENET_SOCKOPT_BROADCAST, 1); enet_socket_set_option (host ^. socket, ENET_SOCKOPT_RCVBUF, ENET_HOST_RECEIVE_BUFFER_SIZE); enet_socket_set_option (host ^. socket, ENET_SOCKOPT_SNDBUF, ENET_HOST_SEND_BUFFER_SIZE); if ((address <> nil) and (enet_socket_get_address (host ^. socket, @host ^. address) < 0)) then host ^. address := address^; if ((channelLimit=0) or (channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)) then channelLimit := ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT else if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT) then channelLimit := ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT; host ^. randomSeed := enet_uint32(host); host ^. randomSeed := host ^. randomSeed + enet_host_random_seed (); host ^. randomSeed := (host ^. randomSeed shl 16) or (host ^. randomSeed shr 16); host ^. channelLimit := channelLimit; host ^. incomingBandwidth := incomingBandwidth; host ^. outgoingBandwidth := outgoingBandwidth; host ^. bandwidthThrottleEpoch := 0; host ^. recalculateBandwidthLimits := 0; host ^. mtu := ENET_HOST_DEFAULT_MTU; host ^. peerCount := peerCount; host ^. commandCount := 0; host ^. bufferCount := 0; host ^. checksumfunc := nil; host ^. receivedAddress.host := ENET_HOST_ANY; host ^. receivedAddress.port := 0; host ^. receivedData := nil; host ^. receivedDataLength := 0; host ^. totalSentData := 0; host ^. totalSentPackets := 0; host ^. totalReceivedData := 0; host ^. totalReceivedPackets := 0; host ^. connectedPeers := 0; host ^. bandwidthLimitedPeers := 0; host ^. duplicatePeers := ENET_PROTOCOL_MAXIMUM_PEER_ID; host ^. maximumPacketSize := ENET_HOST_DEFAULT_MAXIMUM_PACKET_SIZE; host ^. maximumWaitingData := ENET_HOST_DEFAULT_MAXIMUM_WAITING_DATA; host ^. compressor.context := nil; host ^. compressor.compress := nil; host ^. compressor.decompress := nil; host ^. compressor.destroy := nil; host ^. interceptfunc := nil; enet_list_clear ( @ host ^. dispatchQueue); currentPeer := host ^. peers; while PChar(currentPeer)< PChar(@ pENetPeerArray(host ^. peers)^[host ^. peerCount] ) do begin currentPeer ^. host := host; currentPeer ^. incomingPeerID := (PChar(currentPeer)- PChar(host ^. peers)) div sizeof(ENetPeer); currentPeer ^. outgoingSessionID := $0FF; currentPeer ^. incomingSessionID := $0FF; currentPeer ^. data := nil; enet_list_clear (@currentPeer ^. acknowledgements); enet_list_clear (@currentPeer ^. sentReliableCommands); enet_list_clear (@currentPeer ^. sentUnreliableCommands); enet_list_clear (@currentPeer ^. outgoingReliableCommands); enet_list_clear (@currentPeer ^. outgoingUnreliableCommands); enet_list_clear (@currentPeer ^. dispatchedCommands); enet_peer_reset (currentPeer); inc(currentPeer); end; result := host; end; (** Destroys the host and all resources associated with it. @param host pointer to the host to destroy *) procedure enet_host_destroy (host : pENetHost); var currentPeer : pENetPeer; begin if host=nil then exit; enet_socket_destroy (host ^. socket); currentPeer := host ^. peers; while PChar(currentPeer) < PChar(@ pENetPeerArray(host ^. peers)^[host ^. peerCount]) do begin enet_peer_reset (currentPeer); inc(currentPeer); end; if ((host ^. compressor.context <> nil) and (@host ^. compressor.destroy<>nil)) then host ^. compressor.destroy(host ^. compressor.context); enet_free (host ^. peers); enet_free (host); end; (** Initiates a connection to a foreign host. @param host host seeking the connection @param address destination for the connection @param channelCount number of channels to allocate @param data user data supplied to the receiving host @returns a peer representing the foreign host on success, NULL on failure @remarks The peer returned will have not completed the connection until enet_host_service() notifies of an ENET_EVENT_TYPE_CONNECT event for the peer. *) function enet_host_connect (host : pENetHost; address : pENetAddress; channelCount : enet_size_t; data : enet_uint32):pENetPeer; var currentPeer : pENetPeer; channel : pENetChannel; command : ENetProtocol; begin if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT) then channelCount := ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT else if (channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT) then channelCount := ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT; currentPeer := host ^. peers; while PChar(currentPeer) < PChar(@ pENetPeerArray(host ^. peers)^[host ^. peerCount]) do begin if (currentPeer ^. state = ENET_PEER_STATE_DISCONNECTED) then break; inc(currentPeer); end; if PChar(currentPeer) >= PChar(@ pENetPeerArray(host ^. peers)^[host ^. peerCount]) then begin result := nil; exit; end; currentPeer ^. channels := pENetChannel( enet_malloc (channelCount * sizeof (ENetChannel)) ); if (currentPeer ^. channels = nil) then begin result:=nil; exit; end; currentPeer ^. channelCount := channelCount; currentPeer ^. state := ENET_PEER_STATE_CONNECTING; currentPeer ^. address := address^; Inc(host); currentPeer ^. connectID := host ^. randomSeed; if (host ^. outgoingBandwidth = 0) then currentPeer ^. windowSize := ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE else currentPeer ^. windowSize := (host ^. outgoingBandwidth div ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE; if (currentPeer ^. windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE) then currentPeer ^. windowSize := ENET_PROTOCOL_MINIMUM_WINDOW_SIZE else if (currentPeer ^. windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE) then currentPeer ^. windowSize := ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE; channel := currentPeer ^. channels; while PChar(channel) < PChar(@ pENetChannelArray(currentPeer ^. channels)^[channelCount]) do begin channel ^. outgoingReliableSequenceNumber := 0; channel ^. outgoingUnreliableSequenceNumber := 0; channel ^. incomingReliableSequenceNumber := 0; channel ^. incomingUnreliableSequenceNumber := 0; enet_list_clear (@ channel ^. incomingReliableCommands); enet_list_clear (@ channel ^. incomingUnreliableCommands); channel ^. usedReliableWindows := 0; fillchar(channel ^. reliableWindows, sizeof (channel ^. reliableWindows), 0); inc(channel); end; command.header.command := ENET_PROTOCOL_COMMAND_CONNECT or ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE; command.header.channelID := $FF; command.connect.outgoingPeerID := ENET_HOST_TO_NET_16 (currentPeer ^. incomingPeerID); command.connect.incomingSessionID := currentPeer ^. incomingSessionID; command.connect.outgoingSessionID := currentPeer ^. outgoingSessionID; command.connect.mtu := ENET_HOST_TO_NET_32 (currentPeer ^. mtu); command.connect.windowSize := ENET_HOST_TO_NET_32 (currentPeer ^. windowSize); command.connect.channelCount := ENET_HOST_TO_NET_32 (channelCount); command.connect.incomingBandwidth := ENET_HOST_TO_NET_32 (host ^. incomingBandwidth); command.connect.outgoingBandwidth := ENET_HOST_TO_NET_32 (host ^. outgoingBandwidth); command.connect.packetThrottleInterval := ENET_HOST_TO_NET_32 (currentPeer ^. packetThrottleInterval); command.connect.packetThrottleAcceleration := ENET_HOST_TO_NET_32 (currentPeer ^. packetThrottleAcceleration); command.connect.packetThrottleDeceleration := ENET_HOST_TO_NET_32 (currentPeer ^. packetThrottleDeceleration); command.connect.connectID := currentPeer ^. connectID; command.connect.data := ENET_HOST_TO_NET_32 (data); enet_peer_queue_outgoing_command (currentPeer, @ command, nil, 0, 0); result := currentPeer; end; (** Queues a packet to be sent to all peers associated with the host. @param host host on which to broadcast the packet @param channelID channel on which to broadcast @param packet packet to broadcast *) procedure enet_host_broadcast (host : pENetHost; channelID : enet_uint8; packet : pENetPacket); var currentPeer : pENetPeer; label continuework; begin currentPeer := host ^. peers; while PChar(currentPeer) < PChar(@ pENetPeerArray(host ^. peers)^[host ^. peerCount]) do begin if (currentPeer ^. state <> ENET_PEER_STATE_CONNECTED) then goto continuework; enet_peer_send (currentPeer, channelID, packet); continuework: inc(currentPeer); end; if (packet ^. referenceCount = 0) then enet_packet_destroy (packet); end; (** Sets the packet compressor the host should use to compress and decompress packets. @param host host to enable or disable compression for @param compressor callbacks for for the packet compressor; if NULL, then compression is disabled *) procedure enet_host_compress (host:pENetHost; compressor:pENetCompressor); begin if ((host ^. compressor.context <> nil) and (@ host ^. compressor.destroy<>nil)) then host ^.compressor.destroy(host ^.compressor.context); if (compressor <> nil) then host ^. compressor := compressor^ else host ^. compressor.context := nil; end; (** Limits the maximum allowed channels of future incoming connections. @param host host to limit @param channelLimit the maximum number of channels allowed; if 0, then this is equivalent to ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT *) procedure enet_host_channel_limit (host : pENetHost; channelLimit: enet_size_t); begin if ((channelLimit=0) or (channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)) then channelLimit := ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT else if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT) then channelLimit := ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT; host ^. channelLimit := channelLimit; end; (** Adjusts the bandwidth limits of a host. @param host host to adjust @param incomingBandwidth new incoming bandwidth @param outgoingBandwidth new outgoing bandwidth @remarks the incoming and outgoing bandwidth parameters are identical in function to those specified in enet_host_create(). *) procedure enet_host_bandwidth_limit (host : pENetHost;incomingBandwidth : enet_uint32; outgoingBandwidth : enet_uint32); begin host ^. incomingBandwidth := incomingBandwidth; host ^. outgoingBandwidth := outgoingBandwidth; host ^. recalculateBandwidthLimits := 1; end; procedure enet_host_bandwidth_throttle (host : pENetHost); var timeCurrent, elapsedTime, peersTotal, dataTotal, peersRemaining, bandwidth, throttle, bandwidthLimit : enet_uint32; needsAdjustment : integer; peer : pENetPeer; command : ENetProtocol; peerBandwidth : enet_uint32; label continuework1, continuework2, continuework3, continuework4, continuework5; begin timeCurrent := enet_time_get (); elapsedTime := timeCurrent - host ^. bandwidthThrottleEpoch; peersRemaining := enet_uint32( host ^. connectedPeers); dataTotal := enet_uint32(not 0); bandwidth := enet_uint32(not 0); throttle := 0; bandwidthLimit := 0; if host ^. bandwidthLimitedPeers > 0 then needsAdjustment:=1 else needsAdjustment:=0; if (elapsedTime < ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL) then exit; host ^. bandwidthThrottleEpoch := timeCurrent; if (peersRemaining = 0) then exit; if (host ^. outgoingBandwidth <> 0) then begin dataTotal := 0; bandwidth := (host ^. outgoingBandwidth * elapsedTime) div 1000; peer := host ^. peers; while pchar(peer) < pchar(@ pENetPeerArray(host ^. peers)^[host ^. peerCount]) do begin if ((peer ^. state <> ENET_PEER_STATE_CONNECTED) and (peer ^. state <> ENET_PEER_STATE_DISCONNECT_LATER)) then goto continuework1; Inc(dataTotal, peer ^. outgoingDataTotal); continuework1: Inc(peer); end; end; while (peersRemaining > 0) and (needsAdjustment <> 0) do begin needsAdjustment := 0; if (dataTotal <= bandwidth) then throttle := ENET_PEER_PACKET_THROTTLE_SCALE else throttle := (bandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) div dataTotal; peer := host ^. peers; while PChar(peer) < PChar(@ pENetPeerArray(host ^. peers)^[host ^. peerCount]) do begin if ((peer ^. state <> ENET_PEER_STATE_CONNECTED) and (peer ^. state <> ENET_PEER_STATE_DISCONNECT_LATER)) or (peer ^. incomingBandwidth = 0) or (peer ^. outgoingBandwidthThrottleEpoch = timeCurrent) then goto continuework2; peerBandwidth := (peer ^. incomingBandwidth * elapsedTime) div 1000; if ((throttle * peer ^. outgoingDataTotal) div ENET_PEER_PACKET_THROTTLE_SCALE <= peerBandwidth) then goto continuework2; peer ^. packetThrottleLimit := (peerBandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) div peer ^. outgoingDataTotal; if (peer ^. packetThrottleLimit = 0) then peer ^. packetThrottleLimit := 1; if (peer ^. packetThrottle > peer ^. packetThrottleLimit) then peer ^. packetThrottle := peer ^. packetThrottleLimit; peer ^. outgoingBandwidthThrottleEpoch := timeCurrent; peer ^. incomingDataTotal := 0; peer ^. outgoingDataTotal := 0; needsAdjustment := 1; dec(peersRemaining); dec(bandwidth, peerBandwidth); dec(dataTotal,peerBandwidth); continuework2: inc(peer); end; end; if (peersRemaining > 0) then begin if (dataTotal <= bandwidth) then throttle := ENET_PEER_PACKET_THROTTLE_SCALE else throttle := (bandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) div dataTotal; peer := host ^. peers; while PChar(peer) < PChar(@ pENetPeerArray(host ^. peers)^[host ^. peerCount]) do begin if ((peer ^. state <> ENET_PEER_STATE_CONNECTED) and (peer ^. state <> ENET_PEER_STATE_DISCONNECT_LATER)) or (peer ^. outgoingBandwidthThrottleEpoch = timeCurrent) then goto continuework3; peer ^. packetThrottleLimit := throttle; if (peer ^. packetThrottle > peer ^. packetThrottleLimit) then peer ^. packetThrottle := peer ^. packetThrottleLimit; peer ^. incomingDataTotal := 0; peer ^. outgoingDataTotal := 0; continuework3: Inc(peer); end; end; if host ^. recalculateBandwidthLimits<>0 then begin host ^. recalculateBandwidthLimits := 0; peersRemaining := enet_uint32(host ^. connectedPeers); bandwidth := host ^. incomingBandwidth; needsAdjustment := 1; if (bandwidth = 0) then bandwidthLimit := 0 else while (peersRemaining > 0) and (needsAdjustment <> 0) do begin needsAdjustment := 0; bandwidthLimit := bandwidth div peersRemaining; peer := host ^. peers; while PChar(peer) < PChar(@ pENetPeerArray(host ^. peers)^[host ^. peerCount]) do begin if ((peer ^. state <> ENET_PEER_STATE_CONNECTED) and (peer ^. state <> ENET_PEER_STATE_DISCONNECT_LATER)) or (peer ^. incomingBandwidthThrottleEpoch = timeCurrent) then goto continuework4; if (peer ^. outgoingBandwidth > 0) and (peer ^. outgoingBandwidth >= bandwidthLimit) then goto continuework4; peer ^. incomingBandwidthThrottleEpoch := timeCurrent; needsAdjustment := 1; dec(peersRemaining); dec(bandwidth,peer ^. outgoingBandwidth); continuework4: inc(peer); end; end; peer := host ^. peers; while PChar(peer) < PChar(@ pENetPeerArray(host ^. peers)^[host ^. peerCount]) do begin if (peer ^. state <> ENET_PEER_STATE_CONNECTED) and (peer ^. state <> ENET_PEER_STATE_DISCONNECT_LATER) then goto continuework5; command.header.command := ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT or ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE; command.header.channelID := $FF; command.bandwidthLimit.outgoingBandwidth := ENET_HOST_TO_NET_32 (host ^. outgoingBandwidth); if (peer ^. incomingBandwidthThrottleEpoch = timeCurrent) then command.bandwidthLimit.incomingBandwidth := ENET_HOST_TO_NET_32 (peer ^. outgoingBandwidth) else command.bandwidthLimit.incomingBandwidth := ENET_HOST_TO_NET_32 (bandwidthLimit); enet_peer_queue_outgoing_command (peer, @ command, nil, 0, 0); continuework5: inc(peer); end; end; end; (** @} *) end.
unit MainFrm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) ePath: TEdit; Button1: TButton; mTags: TMemo; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); private procedure LoadIniFile(path : string); private fTabs : TStringList; end; var Form1: TForm1; implementation uses IniFiles; {$R *.DFM} procedure TForm1.LoadIniFile(path : string); var iniFile : TIniFile; tabs, i : integer; aux : string; begin iniFile := TIniFile.Create(path); try tabs := iniFile.ReadInteger('InspectorInfo', 'TabCount', 0); for i := 0 to pred(tabs) do begin aux := iniFile.ReadString('InspectorInfo', 'TabName' + IntToStr(i), ''); fTabs.Add(aux); end; finally iniFile.Free; end; end; procedure TForm1.Button1Click(Sender: TObject); var SrcRec : TSearchRec; path : string; found : boolean; begin mTags.Clear; path := ePath.Text; found := FindFirst(path + '\*.ini', faArchive, SrcRec) = 0; while found do begin LoadIniFile(path + '\' + SrcRec.Name); found := FindNext(SrcRec) = 0; end; mTags.Lines := fTabs; end; procedure TForm1.FormCreate(Sender: TObject); begin fTabs := TStringList.Create; fTabs.Sorted := true; fTabs.Duplicates := dupIgnore; end; end.
unit kwStringSplit; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwStringSplit.pas" // Начат: 21.12.2011 20:39 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Scripting::ScriptEngine::StringProcessing::TkwStringSplit // // Разделяет строку на две по заданному разделителю. // // Пример: // {code} // 'ABC:DEF' ':' string:Split // {code} // Получаем на стеке: // 'ABC' ':DEF' // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses l3Interfaces, tfwScriptingInterfaces ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\tfwDualStrWord.imp.pas} TkwStringSplit = class(_tfwDualStrWord_) {* Разделяет строку на две по заданному разделителю. Пример: [code] 'ABC:DEF' ':' string:Split [code] Получаем на стеке: 'ABC' ':DEF' } protected // realized methods procedure DoStrings(const aCtx: TtfwContext; const aStr1: Il3CString; const aStr2: Il3CString); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwStringSplit {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses SysUtils, l3String, l3Base, tfwAutoregisteredDiction, tfwScriptEngine ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwStringSplit; {$Include ..\ScriptEngine\tfwDualStrWord.imp.pas} // start class TkwStringSplit procedure TkwStringSplit.DoStrings(const aCtx: TtfwContext; const aStr1: Il3CString; const aStr2: Il3CString); //#UC START# *4DD0D021034C_4EF20B8800E7_var* var l_P : Il3CString; l_S : Il3CString; l_Len : Integer; //#UC END# *4DD0D021034C_4EF20B8800E7_var* begin //#UC START# *4DD0D021034C_4EF20B8800E7_impl* l_Len := l3Len(aStr2); if (l_Len = 1) then l3Split(aStr1, l3Char(aStr2, 0), l_P, l_S) else l3Split(aStr1, aStr2, l_P, l_S); aCtx.rEngine.PushString(l_P); aCtx.rEngine.PushString(l_S); //#UC END# *4DD0D021034C_4EF20B8800E7_impl* end;//TkwStringSplit.DoStrings class function TkwStringSplit.GetWordNameForRegister: AnsiString; //#UC START# *4DB0614603C8_4EF20B8800E7_var* //#UC END# *4DB0614603C8_4EF20B8800E7_var* begin //#UC START# *4DB0614603C8_4EF20B8800E7_impl* Result := 'string:Split'; //#UC END# *4DB0614603C8_4EF20B8800E7_impl* end;//TkwStringSplit.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\tfwDualStrWord.imp.pas} {$IfEnd} //not NoScripts end.
unit DB_Quote_Instant; interface uses BaseDataSet, define_stock_quotes_instant, QuickList_QuoteInstant; type TDBQuoteInstant = class(TBaseDataSetAccess) protected fInstantQuoteList: TQuoteInstantList; function GetRecordCount: Integer; override; function GetRecordItem(AIndex: integer): Pointer; override; function GetItem(AIndex: integer): PRT_InstantQuote; overload; function GetItem(ACode: string): PRT_InstantQuote; overload; public constructor Create(ADBType: integer); reintroduce; destructor Destroy; override; class function DataTypeDefine: integer; override; procedure Sort; override; procedure Clear; override; function AddInstantQuote(ADataSrc: integer; AStockPackCode: integer): PRT_InstantQuote; function CheckOutInstantQuote(ADataSrc: integer; AStockPackCode: integer): PRT_InstantQuote; function FindRecordByKey(AKey: Integer): Pointer; override; function InstantQuoteByIndex(AIndex: integer): PRT_InstantQuote; property Items[AIndex: integer]: PRT_InstantQuote read GetItem; property Item[ACode: string]: PRT_InstantQuote read GetItem; end; implementation uses define_dealstore_file, QuickSortList; constructor TDBQuoteInstant.Create(ADBType: integer); begin inherited Create(ADBType, 0); fInstantQuoteList := TQuoteInstantList.Create; fInstantQuoteList.Duplicates := QuickSortList.lstDupIgnore; end; destructor TDBQuoteInstant.Destroy; begin Clear; fInstantQuoteList.Free; inherited; end; class function TDBQuoteInstant.DataTypeDefine: integer; begin Result := DataType_InstantData; end; function TDBQuoteInstant.GetRecordItem(AIndex: integer): Pointer; begin Result := Pointer(fInstantQuoteList.InstantQuote[AIndex]); end; function TDBQuoteInstant.GetItem(AIndex: integer): PRT_InstantQuote; begin Result := GetRecordItem(AIndex); end; function TDBQuoteInstant.GetItem(ACode: string): PRT_InstantQuote; begin Result := nil; end; function TDBQuoteInstant.GetRecordCount: integer; begin Result := fInstantQuoteList.Count; end; procedure TDBQuoteInstant.Sort; begin fInstantQuoteList.Sort; end; procedure TDBQuoteInstant.Clear; var i: integer; tmpInstantQuote: PRT_InstantQuote; begin for i := fInstantQuoteList.Count - 1 downto 0 do begin tmpInstantQuote := fInstantQuoteList.InstantQuote[i]; FreeMem(tmpInstantQuote); end; fInstantQuoteList.Clear; end; function TDBQuoteInstant.AddInstantQuote(ADataSrc: integer; AStockPackCode: integer): PRT_InstantQuote; begin Result := System.New(PRT_InstantQuote); FillChar(Result^, SizeOf(TRT_InstantQuote), 0); if nil <> Result then begin fInstantQuoteList.AddInstantQuote(AStockPackCode, Result); end; end; function TDBQuoteInstant.FindRecordByKey(AKey: Integer): Pointer; var tmpIndex: integer; begin Result := nil; tmpIndex := fInstantQuoteList.IndexOf(AKey); if 0 <= tmpIndex then Result := fInstantQuoteList.InstantQuote[tmpIndex]; end; function TDBQuoteInstant.InstantQuoteByIndex(AIndex: integer): PRT_InstantQuote; begin Result := GetRecordItem(AIndex); end; function TDBQuoteInstant.CheckOutInstantQuote(ADataSrc: integer; AStockPackCode: integer): PRT_InstantQuote; begin Result := nil; //FindInstantQuoteByCode(AMarketCode + AStockCode); if nil = Result then begin Result := AddInstantQuote(ADataSrc, AStockPackCode); end; end; end.
program TestReadString; uses SysUtils; Function ReadString(prompt : String):String; begin Write(prompt); ReadLn(result); end; function ReadDouble(prompt: String): Double; var temp: String; begin temp := ReadString(prompt); while not TryStrToFloat(temp, result) do begin WriteLn('Please enter a real number '); temp := ReadString(prompt); end; end; Function ReadInt(prompt : String):Integer; var temp : String; age : Integer; begin //temp := ReadString(prompt); while not TryStrToInt(ReadString(prompt),age) do begin WriteLn('Please enter a whole number :'); ReadLn(temp); end; result := age; end; function ReadIntegerRange(prompt : String ; min, max : Integer):Integer; begin result := ReadInt(prompt); While (result < min) or (result > max) do begin WriteLn('Please enter a value between ',min,' and ', max); result:= ReadInt(prompt); end; end; procedure Main(); var name : String; age : Integer; aDouble : Double; begin name := ReadString('EnterYourName :'); age := ReadIntegerRange('Enter your age :',1,50); aDouble := ReadDouble('Enter a real number'); WriteLn('Hi ',name, ' you are ',age,' you are this smart : ',aDouble:4:2); end; begin Main(); end.
// ************************************************************************************************** // // Unit uMisc // unit for the Delphi Preview Handler https://github.com/RRUZ/delphi-preview-handler // // The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); // you may not use this file except in compliance with the License. You may obtain a copy of the // License at http://www.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either express or implied. See the License for the specific language governing rights // and limitations under the License. // // The Original Code is uMisc.pas. // // The Initial Developer of the Original Code is Rodrigo Ruz V. // Portions created by Rodrigo Ruz V. are Copyright (C) 2011-2023 Rodrigo Ruz V. // All Rights Reserved. // // ************************************************************************************************* unit uMisc; interface uses SynEdit, SynEditHighlighter, uDelphiVersions, uDelphiIDEHighlight; function GetDllPath: String; function GetTempDirectory: string; function GetSpecialFolder(const CSIDL: integer): string; function GetFileVersion(const FileName: string): string; function GetModuleLocation: string; procedure RefreshSynEdit(FCurrentTheme: TIDETheme; SynEdit: SynEdit.TSynEdit); procedure SetSynAttr(FCurrentTheme: TIDETheme; Element: TIDEHighlightElements; SynAttr: TSynHighlighterAttributes; DelphiVersion: TDelphiVersions); procedure RefreshSynPasHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynCobolHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynCppHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynCSharpHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynCSSHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynDfmHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynEiffelHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynFortranHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynHTMLHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynIniHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynInnoHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynJavaHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynJScriptHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynPerlHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynPhpHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynPythonHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynRubyHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynSqlHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynUnixHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynXmlHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynAsmHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynVBHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshSynVbScriptHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); procedure RefreshBatSynHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var gbSearchBackwards: boolean; gbSearchCaseSensitive: boolean; gbSearchFromCaret: boolean; gbSearchSelectionOnly: boolean; gbSearchTextAtCaret: boolean; gbSearchWholeWords: boolean; gbSearchRegex: boolean; gsSearchText: string; gsSearchTextHistory: string; gsReplaceText: string; gsReplaceTextHistory: string; resourcestring STextNotFound = 'Text not found'; implementation uses ComObj, System.SysUtils, WinApi.Windows, WinApi.ShlObj, Vcl.Forms, Vcl.Graphics, Vcl.GraphUtil, SynHighlighterPas, SynHighlighterXML, SynHighlighterCpp, SynHighlighterAsm, SynHighlighterFortran, SynHighlighterEiffel, SynHighlighterPython, SynHighlighterPerl, SynHighlighterDfm, SynHighlighterBat, SynHighlighterVBScript, SynHighlighterPHP, SynHighlighterJScript, SynHighlighterHtml, SynHighlighterCSS, SynHighlighterCS, SynHighlighterCobol, SynHighlighterVB, SynHighlighterM3, SynHighlighterJava, SynHighlighterSml, SynHighlighterIni, SynHighlighterInno, SynHighlighterSQL, SynHighlighterUNIXShellScript, SynHighlighterRuby; procedure RefreshSynPasHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynPasSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Assembler, AsmAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Character, CharAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Preprocessor, DirectiveAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Float, FloatAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Hex, HexAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); end; end; procedure RefreshSynCobolHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynCobolSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, AreaAIdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Preprocessor, PreprocessorAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, BooleanAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, SequenceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, IndicatorAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, TagAreaAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.EnabledBreak, DebugLinesAttri, DelphiVer); end; end; procedure RefreshSynCppHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynCppSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Assembler, AsmAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Character, CharAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Preprocessor, DirecAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Float, FloatAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Hex, HexAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Preprocessor, InvalidAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, OctalAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); end; end; procedure RefreshSynCSharpHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynCSSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Assembler, AsmAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Preprocessor, DirecAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ErrorLine, InvalidAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); end; end; procedure RefreshSynCSSHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynCssSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, PropertyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, ColorAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.PlainText, TextAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, ValueAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, UndefPropertyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, ImportantPropertyAttri, DelphiVer); end; end; procedure RefreshSynDfmHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynDfmSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); end; end; procedure RefreshSynEiffelHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynEiffelSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, BasicTypesAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, LaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, OperatorAndSymbolsAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, PredefinedAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, ResultValueAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); end; end; procedure RefreshSynFortranHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynFortranSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); end; end; procedure RefreshSynHTMLHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynHTMLSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, AndAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.PlainText, TextAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, UndefKeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, ValueAttri, DelphiVer); end; end; procedure RefreshSynIniHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynIniSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, TextAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, SectionAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); end; end; procedure RefreshSynInnoHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynInnoSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, ConstantAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ErrorLine, InvalidAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, ParameterAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, SectionAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); end; end; procedure RefreshSynJavaHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynJavaSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, DocumentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.IllegalChar, InvalidAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); end; end; procedure RefreshSynJScriptHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynJScriptSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, NonReservedKeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, EventAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); end; end; procedure RefreshSynPerlHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynPerlSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ErrorLine, InvalidAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, OperatorAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Preprocessor, PragmaAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, VariableAttri, DelphiVer); end; end; procedure RefreshSynPhpHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynPHPSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, VariableAttri, DelphiVer); end; end; procedure RefreshSynPythonHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynPythonSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, NonKeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, SystemAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Hex, OctalAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Hex, HexAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Float, FloatAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Preprocessor, DocStringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ErrorLine, ErrorAttri, DelphiVer); end; end; procedure RefreshSynRubyHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynRubySyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, SecondKeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); end; end; procedure RefreshSynSqlHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynSQLSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Preprocessor, ConditionalCommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, DataTypeAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, DefaultPackageAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, DelimitedIdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ErrorLine, ExceptionAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, FunctionAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, PLSQLAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, SQLPlusAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, TableNameAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, VariableAttri, DelphiVer); end; end; procedure RefreshSynUnixHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynUNIXShellScriptSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, SecondKeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, VarAttri, DelphiVer); end; end; procedure RefreshSynVBHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynVBSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); end; end; procedure RefreshSynVbScriptHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynVBScriptSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); end; end; procedure RefreshSynXmlHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynXMLSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.AttributeNames, AttributeAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.AttributeValues, AttributeValueAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CDATAAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Preprocessor, DocTypeAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, ElementAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, EntityRefAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, NamespaceAttributeAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, NamespaceAttributeValueAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Preprocessor, ProcessingInstructionAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, SymbolAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Character, TextAttri, DelphiVer); end; end; procedure RefreshBatSynHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynBatSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, VariableAttri, DelphiVer); end; end; procedure RefreshSynAsmHighlighter(FCurrentTheme: TIDETheme; SynEdit: TSynEdit); var DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; RefreshSynEdit(FCurrentTheme, SynEdit); with TSynAsmSyn(SynEdit.Highlighter) do begin SetSynAttr(FCurrentTheme, TIDEHighlightElements.Comment, CommentAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Identifier, IdentifierAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.ReservedWord, KeyAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Number, NumberAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Whitespace, SpaceAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.String, StringAttri, DelphiVer); SetSynAttr(FCurrentTheme, TIDEHighlightElements.Symbol, SymbolAttri, DelphiVer); end; end; procedure SetSynAttr(FCurrentTheme: TIDETheme; Element: TIDEHighlightElements; SynAttr: TSynHighlighterAttributes; DelphiVersion: TDelphiVersions); begin SynAttr.Background := GetDelphiVersionMappedColor(StringToColor(FCurrentTheme[Element].BackgroundColorNew), DelphiVersion); SynAttr.Foreground := GetDelphiVersionMappedColor(StringToColor(FCurrentTheme[Element].ForegroundColorNew), DelphiVersion); SynAttr.Style := []; if FCurrentTheme[Element].Bold then SynAttr.Style := SynAttr.Style + [fsBold]; if FCurrentTheme[Element].Italic then SynAttr.Style := SynAttr.Style + [fsItalic]; if FCurrentTheme[Element].Underline then SynAttr.Style := SynAttr.Style + [fsUnderline]; end; procedure RefreshSynEdit(FCurrentTheme: TIDETheme; SynEdit: SynEdit.TSynEdit); var Element: TIDEHighlightElements; DelphiVer: TDelphiVersions; begin DelphiVer := DelphiXE; Element := TIDEHighlightElements.RightMargin; SynEdit.RightEdgeColor := GetDelphiVersionMappedColor(StringToColor(FCurrentTheme[Element].ForegroundColorNew), DelphiVer); Element := TIDEHighlightElements.MarkedBlock; SynEdit.SelectedColor.Foreground := GetDelphiVersionMappedColor(StringToColor(FCurrentTheme[Element].ForegroundColorNew), DelphiVer); SynEdit.SelectedColor.Background := GetDelphiVersionMappedColor(StringToColor(FCurrentTheme[Element].BackgroundColorNew), DelphiVer); Element := TIDEHighlightElements.LineNumber; SynEdit.Gutter.Color := StringToColor(FCurrentTheme[Element].BackgroundColorNew); SynEdit.Gutter.Font.Color := GetDelphiVersionMappedColor(StringToColor(FCurrentTheme[Element].ForegroundColorNew), DelphiVer); Element := TIDEHighlightElements.PlainText; SynEdit.Gutter.BorderColor := GetHighLightColor(StringToColor(FCurrentTheme[Element].BackgroundColorNew)); Element := TIDEHighlightElements.LineHighlight; SynEdit.ActiveLineColor := GetDelphiVersionMappedColor(StringToColor(FCurrentTheme[Element].BackgroundColorNew), DelphiVer); end; function GetDllPath: String; var Path: array [0 .. MAX_PATH - 1] of Char; begin SetString(Result, Path, GetModuleFileName(HInstance, Path, SizeOf(Path))); end; function GetTempDirectory: string; var lpBuffer: array [0 .. MAX_PATH] of Char; begin GetTempPath(MAX_PATH, @lpBuffer); Result := StrPas(lpBuffer); end; function GetWindowsDirectory: string; var lpBuffer: array [0 .. MAX_PATH] of Char; begin WinApi.Windows.GetWindowsDirectory(@lpBuffer, MAX_PATH); Result := StrPas(lpBuffer); end; function GetSpecialFolder(const CSIDL: integer): string; var lpszPath: PWideChar; begin lpszPath := StrAlloc(MAX_PATH); try ZeroMemory(lpszPath, MAX_PATH); if SHGetSpecialFolderPath(0, lpszPath, CSIDL, False) then Result := lpszPath else Result := ''; finally StrDispose(lpszPath); end; end; function GetFileVersion(const FileName: string): string; var FSO: OleVariant; begin FSO := CreateOleObject('Scripting.FileSystemObject'); Result := FSO.GetFileVersion(FileName); end; function GetModuleLocation: string; begin SetLength(Result, MAX_PATH); GetModuleFileName(HInstance, PChar(Result), MAX_PATH); Result:=PChar(Result); end; end.
unit a2unit; { This unit contains an implementation of the collection ADT using binary search trees. It gets the type definitions and basic tree operations from another unit called BinTrADT. Other than that, the forward declarations and main types are exactly the same as the collection ADT for assignment 1. Your job is to write the missing functions and procedures. You must write: Size(C), Insert(C,V), and Join(C1, C2). Make sure that both delete and join preserve the correct ordering of the Binary Search Tree. Also be sure not to use direct pointer references. Call the operations from the Binary Tree ADT instead. } interface uses BinTrADT; (********************* TYPE DEFINITIONS *********************) type (*Since we are using the BinaryTree ADT, all we have to do here is relate the main types for collections to the main types for binary trees. *) collection_element = TreeElement; collection = BinaryTree; { The forward declarations are exactly the same as before. Only the implementations have changed } procedure Create(var C:collection); procedure Destroy(var C:collection); function Size(C: collection): integer; function Is_Empty(C:collection): boolean; procedure Insert(var C:collection; V:collection_element); procedure Delete (var C:collection; V: collection_element); procedure Join(var C1: collection; var C2: collection); procedure Print(C: collection); function MemCheck: boolean; procedure IdentifyMyself ; implementation {********************** Memory Management Stuff *********************} {Note that since all the memory management is done by BinTrADT, we just have to call the MemCheck_BT function here} Function MemCheck; begin MemCheck := MemCheck_BT end; (********************** COLLECTION IMPLEMENTATIONS ***********************) (* Create(C) preconditions: C is undefined postconditions: C is the empty collection with storage allocated as needed. *) procedure Create(var C:collection); begin Create_Empty_BT(C); end; (* Destroy(C) preconditions: C is a defined collection postconditions: C' is undefined. All dynamically allocated memory is disposed*) procedure Destroy(var C:collection); begin Destroy_BT(C); end; (* Is_Empty(C) preconditions: C is a defined collection. postconditions: returns true if C is empty, false otherwise. *) function Is_Empty(C:collection): boolean; begin Is_Empty := Is_Empty_BT(C); end; { Size(C) preconditions: C is a defined collection. postconditions: returns the number of elements in C. } function Size(C: collection): integer; var L_size, R_size: integer ; BEGIN { Base case: if C is empty, then the number of elements in C is 0. } if ( Is_empty(C) ) then Size := 0 else { General case: Size will be the size of the left subtree, plus the size of the right subtree, plus 1 -- for the non-empty root node. Sizes of the left and right subtrees are obtained from the recursive call of Size on the left and right children. } BEGIN L_size := Size(LeftChild_BT(C)) ; R_size := Size(RightChild_BT(C)) ; Size := L_size + R_size + 1 END END; { fxn Size } { Insert(C, V) preconditions: C is a defined collection, V is a collection element. postconditions: C has value V added. Storage is allocated as needed. If V already occurs in C an additional copy is added. NOTE: You may do this recursively or iteratively (in a loop). NOTE: The collection should be able to hold multiple copies of a single element. This is easy to do. Just pick a side where the duplicates will go. So your binary search tree will be one of two types: either leftchild/rightchild are < and >= the root or they are <= and > the root. } procedure Insert(var C:collection; V:collection_element); { add_node(K, E, D) preconditions: K is a defined collection with an empty child on the side indicated by D. E is a collection_element. D is a direction (left or right). postconditions: a new node is allocated with value E, and attached to K as the D child. } procedure add_node(var K: collection; E: collection_element; D: direction) ; var T: collection ; BEGIN Create_Singleton_BT(T) ; { allocate the new node } Set_Root_Value_BT(T, E) ; { set the value to E } Attach_BT(T, K, D) ; { attach the node to K at D } END; { proc add_node } { Insert_rec(C, V) preconditions: C is a non-empty collection, V is a collection element. postconditions: a new collection_element with value V is added to C in the proper position to preserve the 'binary tree' property of C. } procedure Insert_rec(var C: collection; V: collection_element) ; var leftC, rightC: collection; BEGIN { Go left if V is <= the root value. This choice is optional, and means that duplicate values will go to the left of the matching value's node. } if ( V <= Get_Root_Value_BT(C) ) then BEGIN leftC := LeftChild_BT(C) ; { if the left child is empty, attach the new node there } if ( Is_Empty(leftC) ) then add_node(C, V, Left) else { otherwise, call Insert_rec on the existing left child to find the proper insert position } Insert_rec(leftC, V) END { if } else { if V is greater than the root value, the search will proceed to the right } BEGIN rightC := RightChild_BT(C) ; { if the right child is empty, attach the new node there } if ( Is_Empty(RightChild_BT(C)) ) then add_node(C, V, Right) else { otherwise, call Insert_rec again on the existing right child to find the insert position } Insert_rec(rightC, V) END { else } END; { proc Insert_rec } BEGIN if ( Is_Empty(C) ) then { if C is empty, create a new node for C and set the value to V } BEGIN Create_Singleton_BT(C) ; Set_Root_Value_BT(C, V) ; END { if } else { otherwise, call Insert_rec to compare the root value of C with V, and either insert V as left or right child, or proceed recursively through C searching for the proper position to insert V } Insert_rec(C, V) ; END; { fxn Insert } { Delete(C,V) preconditions: C is a defined collection, V is a collection element postconditions: C has the value V removed. If V occurs more than once, only one occurrence is removed. If V does not occur in C, no change is made. } procedure Delete (var C:collection; V: collection_element); var RTree, LTree, Largest, LargestLeftChild, LargestParent: BinaryTree; begin if not Is_Empty(C) then begin {First look for V in the root} if Get_Root_value_BT(C) = V then begin {Found. Delete it.} if Is_Empty(LeftChild_BT(C)) then begin {There is no left child, so just make the right child the new tree} RTree := RightChild_BT(C); prune_BT(RTree); Destroy_Singleton_BT(C); C := RTree; end else begin {There is a left child, so find the largest element in it and replace the root node with this element} LTree := LeftChild_BT(C); {First prune off the left and right trees} Prune_BT(LTree); RTree := RightChild_BT(C); Prune_BT(RTree); Destroy_Singleton_BT(C); {Now destroy the original root node} Largest := LTree; {Now search for the largest node in the left tree} While not Is_Empty_BT(RightChild_BT(Largest)) do Largest := RightChild_BT(Largest); LargestParent:= Parent_BT(Largest); {Get the parent of the largest node} if Is_Empty_BT(LargestParent) then begin {If there is no parent, then just move } attach_BT(Rtree, Largest, Right); {the entire subtree to the root position } C := Largest end else begin {If there is a parent...} LargestLeftChild:= LeftChild_BT(Largest); {get the left subtree of the largest} Prune_BT(Largest); {prune the largest} Prune_BT(LargestLeftChild); {prune the left subtree of the largest} Attach_BT(LargestLeftChild,LargestParent,Right);{move up the left subtree} Attach_BT(LTree,Largest,Left); {Make the largest the new root by } Attach_BT(RTree,Largest,Right); {attaching the appropriate subtrees } C := Largest end end end else begin {Root element was not V. We have to keep searching.} if Get_Root_Value_BT(C) > V then begin {Search left} LTree := LeftChild_BT(C); if not IS_Empty_BT(LTree) then begin {If no left tree, stop} Prune_BT(LTree); Delete(LTree, V); Attach_BT(LTree, C, Left) end end else begin {Search Right} RTree := RightChild_BT(C); if not Is_Empty_BT(RTree) then begin {If no right tree, stop} Prune_BT(RTree); Delete(RTree,V); Attach_BT(RTree, C, Right); end end end end end; (* Join(C1,C2) preconditions: C1 and C2 are two different defined collections. postconditions: C1 is the union of the two collections (i.e. it contains all the elements originally in C1 and C2). C2 is undefined. *) procedure Join(var C1, C2: collection); { Join_rec(C1, C2) preconditions: C1 and C2 are two different defined collections. postconditions: C1 has new collection_elements added, which copy all the values of C2, such that C1 preserves its 'binary tree' property. C2 is unchanged. } procedure Join_rec(var C1, C2: Collection) ; var leftC, rightC: collection ; BEGIN { if C2 is empty, do nothing. } if ( not Is_Empty(C2) ) then { other wise, will do a postorder traversal of C2 to copy all its values to C1 } BEGIN { recursive call of the procedure to join the left child of C2 to C1 } leftC := LeftChild_BT(C2) ; Join_rec(C1, leftC) ; { recursive call of the procedure to join the right child of C2 to C1 } rightC := RightChild_BT(C2) ; Join_rec(C1, rightC) ; { insert the root value of C2 into C1 } Insert(C1, Get_Root_Value_BT(C2)) ; END END; BEGIN { if C1 is empty, then all that is needed is to point C1 to C2 to obtain the new 'joined' C1. This will work if C2 is empty or not. Then a new node is created for C2 so that the destroy procedure can later be called to undefine C2. } if ( Is_Empty(C1) ) then BEGIN C1 := C2 ; Create_Singleton_BT(C2) END { however, if C1 is not empty but C2 is, then all that is needed is to undefine C2, and this can only be done by assigning it a new node first. } else if ( Is_Empty(C2) ) then Create_Singleton_BT(C2) else { when both C1 and C2 are non-empty, the Join_rec procedure is called to copy all the values in C2 as new collection_elements in C1. } Join_rec(C1, C2) ; { finally, the existing C2 -- either a new singleton or the non-empty C2 whose values were copied into C1 -- is destroyed to undefine it } Destroy(C2) END; (* Print(C1) preconditions: C1 is a defined collection. postconditions: The elements in C1 are printed to the screen in any order. If C1 is empty, the message "EMPTY COLLECTION" is printed to the screen. NOTE: The print could be done in any order, but to help you out, it prints in alphabetical order using an InOrder traversal. It also makes use of a nested subprocedure (Print_Rec). This subprocedure is hidden from all other parts of the program.*) procedure Print(C: Collection); (* Linear time O(n) *) procedure Print_Rec(C: Collection); begin if not Is_Empty(C) then begin Print_Rec(LeftChild_BT(C)); Writeln(Get_Root_Value_BT(C)); Print_Rec(RightChild_BT(C)) end end; begin if Is_Empty(C) then writeln('Empty Collection') else Print_Rec(C) end; procedure IdentifyMyself; begin writeln; writeln('***** Student Name: Mark Sattolo'); writeln('***** Student Number: 428500'); writeln('***** Professor Name: Sam Scott'); writeln('***** Course Number: CSI-2114D'); writeln('***** T.A. Name: Adam Murray'); writeln('***** Tutorial Number: D-1'); writeln; end; { proc IdentifyMyself } (******************** INITIALIZATION CODE **********************) (* Note that we have nothing to initialize this time, since memory management is being done by the Binary Tree ADT.*) end.
unit WrapDelphiTest; { Unit Tests for the WrapDelphi module Demo 31 also includes extensive unit testing of WrapDelphi } interface uses DUnitX.TestFramework, PythonEngine, WrapDelphi; type TFruit = (Apple, Banana, Orange); TFruits = set of TFruit; {$M+} ITestInterface = interface(IInterface) ['{AD50ADF2-2691-47CA-80AB-07AF1EDA8C89}'] procedure SetString(const S: string); function GetString: string; end; {$M-} TSubRecord = record DoubleField: double; end; TTestRecord = record StringField: string; SubRecord: TSubRecord; procedure SetStringField(S: string); end; TTestRttiAccess = class private FFruit: TFruit; FFruits: TFruits; public FruitField :TFruit; FruitsField: TFruits; StringField: string; DoubleField: double; ObjectField: TObject; RecordField: TTestRecord; InterfaceField: ITestInterface; procedure BuyFruits(AFruits: TFruits); property Fruit: TFruit read FFruit write FFruit; property Fruits: TFruits read FFruits write FFruits; end; TTestInterfaceImpl = class(TInterfacedObject, ITestInterface) private FString: string; procedure SetString(const S: string); function GetString: string; end; [TestFixture] TTestWrapDelphi = class(TObject) private PythonEngine: TPythonEngine; DelphiModule: TPythonModule; PyDelphiWrapper: TPyDelphiWrapper; Rtti_Var: Variant; TestRttiAccess: TTestRttiAccess; Rec: TTestRecord; Rtti_Rec: Variant; FTestInterface: ITestInterface; Rtti_Interface: Variant; public [SetupFixture] procedure SetupFixture; [TearDownFixture] procedure TearDownFixture; [Test] procedure TestEnumProperty; [Test] procedure TestSetProperty; [Test] procedure TestDoubleField; [Test] procedure TestEnumField; [Test] procedure TestSetField; [Test] procedure TestStringField; [Test] procedure TestSetProps; [Test] procedure TestObjectField; [Test] procedure TestMethodCall; [Test] procedure TestRecord; [Test] procedure TestRecordField; [Test] procedure TestInterface; [Test] procedure TestInterfaceField; end; implementation Uses System.SysUtils, System.Variants, System.Classes, System.Rtti, VarPyth, WrapDelphiClasses; { TTestRTTIAccess } procedure TTestRttiAccess.BuyFruits(AFruits: TFruits); begin Fruits := AFruits; end; { TTestVarPyth } procedure TTestWrapDelphi.SetupFixture; var Py : PPyObject; begin PythonEngine := TPythonEngine.Create(nil); PythonEngine.Name := 'PythonEngine'; PythonEngine.AutoLoad := False; PythonEngine.FatalAbort := True; PythonEngine.FatalMsgDlg := True; PythonEngine.UseLastKnownVersion := True; PythonEngine.AutoFinalize := True; PythonEngine.InitThreads := True; PythonEngine.PyFlags := [pfInteractive]; DelphiModule := TPythonModule.Create(nil); DelphiModule.Name := 'DelphiModule'; DelphiModule.Engine := PythonEngine; DelphiModule.ModuleName := 'delphi'; PyDelphiWrapper := TPyDelphiWrapper.Create(nil); PyDelphiWrapper.Name := 'PyDelphiWrapper'; PyDelphiWrapper.Engine := PythonEngine; PyDelphiWrapper.Module := DelphiModule; PythonEngine.LoadDll; // Then wrap the an instance our TTestRTTIAccess // It will allow us to to test access to public fields and methods as well // public (as well as published) properties. // This time we would like the object to be destroyed when the PyObject // is destroyed, so we need to set its Owned property to True; TestRttiAccess := TTestRTTIAccess.Create; TestRttiAccess.InterfaceField := TTestInterfaceImpl.Create; Py := PyDelphiWrapper.Wrap(TestRttiAccess, TObjectOwnership.soReference); DelphiModule.SetVar('rtti_var', Py); PythonEngine.Py_DecRef(Py); Py := PyDelphiWrapper.WrapRecord(@Rec, TRttiContext.Create.GetType(TypeInfo(TTestRecord)) as TRttiStructuredType); DelphiModule.SetVar('rtti_rec', Py); PythonEngine.Py_DecRef(Py); FTestInterface := TTestInterfaceImpl.Create; Py := PyDelphiWrapper.WrapInterface(TValue.From(FTestInterface)); DelphiModule.SetVar('rtti_interface', Py); PythonEngine.Py_DecRef(Py); PythonEngine.ExecString('from delphi import rtti_var, rtti_rec, rtti_interface'); Rtti_Var := MainModule.rtti_var; Rtti_Rec := MainModule.rtti_rec; Rtti_Interface := MainModule.rtti_interface; end; procedure TTestWrapDelphi.TearDownFixture; begin VarClear(Rtti_Var); VarClear(Rtti_Rec); VarClear(Rtti_Interface); PythonEngine.Free; PyDelphiWrapper.Free; DelphiModule.Free; TestRttiAccess.Free; end; procedure TTestWrapDelphi.TestDoubleField; begin TestRttiAccess.DoubleField := 3.14; Assert.AreEqual(double(Rtti_Var.DoubleField), double(3.14)); Rtti_Var.DoubleField := 1.23; Assert.AreEqual(double(TestRttiAccess.DoubleField), double(1.23)); end; procedure TTestWrapDelphi.TestEnumField; begin TestRttiAccess.FruitField := Apple; Assert.IsTrue(RTTI_var.FruitField = 'Apple'); Rtti_Var.FruitField := 'Banana'; Assert.IsTrue(TestRttiAccess.FruitField = Banana); end; procedure TTestWrapDelphi.TestEnumProperty; // Enumeration values are converted to/from strings begin TestRttiAccess.Fruit := Apple; Assert.IsTrue(RTTI_var.Fruit = 'Apple'); Rtti_Var.Fruit := 'Banana'; Assert.IsTrue(TestRttiAccess.Fruit = Banana); end; procedure TTestWrapDelphi.TestInterface; begin Rtti_Interface.SetString('Test'); Assert.IsTrue(Rtti_Interface.GetString() = 'Test'); end; procedure TTestWrapDelphi.TestInterfaceField; begin Rtti_Interface.SetString('New Value'); Assert.IsTrue(Rtti_Interface.GetString() = 'New Value'); Rtti_Var.InterfaceField.SetString('Old Value'); Assert.IsTrue(Rtti_Var.InterfaceField.GetString() = 'Old Value'); // Assign interface Rtti_Var.InterfaceField := Rtti_Interface; Assert.IsTrue(Rtti_Var.InterfaceField.GetString() = 'New Value'); Rtti_Var.InterfaceField := None; Assert.IsTrue(VarIsNone(Rtti_Var.InterfaceField)); end; procedure TTestWrapDelphi.TestMethodCall; begin TestRttiAccess.Fruits := []; Assert.AreEqual(string(Rtti_Var.Fruits), '[]'); Rtti_Var.BuyFruits(VarPythonCreate(['Apple', 'Banana'], stList)); Assert.AreEqual(string(Rtti_Var.Fruits), '[''Apple'', ''Banana'']'); end; procedure TTestWrapDelphi.TestObjectField; { Demonstrating and testing: Subclassing Delphi components in Python Creating Delphi objects in Python Assigning objects to object fields } Var Script: AnsiString; myComp: Variant; begin Script := 'from delphi import Component' + sLineBreak + 'class MyComponent(Component):' + SLineBreak + ' def __init__(self, Owner):' + SLineBreak + ' self._x = None' + SLineBreak + '' + SLineBreak + ' @property' + SLineBreak + ' def x(self):' + SLineBreak + ' return self._x' + SLineBreak + '' + SLineBreak + ' @x.setter' + SLineBreak + ' def x(self, value):' + SLineBreak + ' self._x = value' + SLineBreak + '' + SLineBreak + 'myComp = MyComponent(None)'; ; PythonEngine.ExecString(Script); myComp := MainModule.myComp; // accessing inherited property Assert.IsTrue(myComp.Name = ''); myComp.Name := 'NoName'; Assert.IsTrue(myComp.Name = 'NoName'); // accessing subclass property myComp.x := 3.14; Assert.IsTrue(myComp.x = 3.14); // Setting an object field rtti_var.ObjectField := myComp; Assert.IsTrue(rtti_var.ObjectField.Name = 'NoName'); Assert.AreEqual(TComponent(TestRttiAccess.ObjectField).Name, 'NoName'); rtti_var.ObjectField := None; Assert.IsTrue(rtti_var.ObjectField = None); end; procedure TTestWrapDelphi.TestRecord; begin Rtti_rec.StringField := 'abcd'; Assert.IsTrue(rtti_rec.StringField = 'abcd'); Rtti_rec.SetStringField('1234'); Assert.IsTrue(rtti_rec.StringField = '1234'); Assert.AreEqual(Rec.StringField, '1234'); Rtti_rec.SubRecord.DoubleField := 3.14; Assert.IsTrue(rtti_rec.SubRecord.DoubleField = 3.14); Assert.AreEqual(Rec.SubRecord.DoubleField, 3.14); end; procedure TTestWrapDelphi.TestRecordField; Var RecValue: Variant; begin RecValue := rtti_var.RecordField; RecValue.StringField := 'abc'; rtti_var.RecordField := RecValue; Assert.IsTrue(rtti_var.RecordField.StringField = 'abc'); end; procedure TTestWrapDelphi.TestSetField; // Sets are converted to/from list of strings begin TestRttiAccess.FruitsField := []; Assert.AreEqual(string(Rtti_Var.FruitsField), '[]'); Rtti_Var.FruitsField := VarPythonCreate(['Apple', 'Banana'], stList); Assert.AreEqual(string(Rtti_Var.FruitsField), '[''Apple'', ''Banana'']'); Assert.IsTrue(TestRttiAccess.FruitsField = [Apple, Banana]); end; procedure TTestWrapDelphi.TestSetProperty; begin TestRttiAccess.Fruits := []; Assert.AreEqual(string(Rtti_Var.Fruits), '[]'); Rtti_Var.Fruits := VarPythonCreate(['Apple', 'Banana'], stList); Assert.AreEqual(string(Rtti_Var.Fruits), '[''Apple'', ''Banana'']'); Assert.IsTrue(TestRttiAccess.Fruits = [Apple, Banana]); end; procedure TTestWrapDelphi.TestSetProps; begin rtti_var.SetProps(StringField := 'abc', DoubleField := 1.234); Assert.AreEqual(TestRttiAccess.StringField, 'abc'); Assert.AreEqual(TestRttiAccess.DoubleField, 1.234); end; procedure TTestWrapDelphi.TestStringField; begin TestRttiAccess.StringField := 'Hi'; Assert.AreEqual(string(Rtti_Var.StringField), 'Hi'); Rtti_Var.StringField := 'P4D'; Assert.AreEqual(TestRttiAccess.StringField, 'P4D'); end; { TTestRecord } procedure TTestRecord.SetStringField(S: string); begin Self.StringField := S; end; { TTestInterfaceImpl } function TTestInterfaceImpl.GetString: string; begin Result := FString; end; procedure TTestInterfaceImpl.SetString(const S: string); begin FString := S; end; initialization TDUnitX.RegisterTestFixture(TTestWrapDelphi); ReportMemoryLeaksOnShutdown := True; end.
unit MyServer; {$mode objfpc}{$H+} interface uses IdHTTPServer, IdCustomHTTPServer, IdContext, IdSocketHandle, IdGlobal, IdSSL, IdSSLOpenSSL, IdSSLOpenSSLHeaders, SysUtils, EventLog; type { THTTPServer } THTTPServer = class (TIdHTTPServer) public procedure InitComponent; override; procedure OnGet(AContext: TIdContext;ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure ServerException(AContext: TIdContext; AException: Exception); procedure OpenSSLGetPassword(var Password: String); procedure OpenSSLStatusInfo(const AMsg: String); end; var Log: TEventLog = nil; OpenSSL: TIdServerIOHandlerSSLOpenSSL = nil; implementation { THTTPServer } procedure THTTPServer.InitComponent; var Binding: TIdSocketHandle; begin {$IFDEF USE_ICONV} IdGlobal.GIdIconvUseTransliteration := True; {$ENDIF} inherited; //InitComponent; Log := TEventLog.Create(nil); Log.LogType := ltFile; Log.FileName := 'server.log'; OpenSSL:=TIdServerIOHandlerSSLOpenSSL.Create; with OpenSSL do begin SSLOptions.SSLVersions := [sslvTLSv1_2]; OnGetPassword := @OpenSSLGetPassword; OnStatusInfo := @OpenSSLStatusInfo; end; Bindings.Clear; Binding := Bindings.Add; Binding.IP := '127.0.0.1'; Binding.Port := 443; Binding.IPVersion := Id_IPv4; with OpenSSL.SSLOptions do begin CertFile := 'DEMO_Server.crt.pem'; KeyFile := 'DEMO_Server.key.pem'; RootCertFile := 'DEMO_RootCA.crt.pem'; CipherList := 'TLSv1.2:!NULL'; end; OnCommandGet := @OnGet; OnException := @ServerException; IOHandler := OpenSSL; Log.Info('Server Started on IP '+Binding.IP+' Port '+Binding.Port.ToString); end; procedure THTTPServer.OnGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); begin AResponseInfo.ContentText := 'Hello world!'; end; procedure THTTPServer.ServerException(AContext: TIdContext; AException: Exception); begin Log.Warning('EXCEPTION: ' + AException.Message); end; procedure THTTPServer.OpenSSLGetPassword(var Password: String); begin Password := 'demo'; end; procedure THTTPServer.OpenSSLStatusInfo(const AMsg: String); begin Log.Debug('SSL STATUS: ' + aMsg); end; FINALIZATION if Assigned(OpenSSL) then OpenSSL.Free; if Assigned(Log) then Log.Free; end.
unit uDebug; {$mode objfpc}{$H+} interface uses Classes, SysUtils, db; type ILogger = interface procedure Log(const S:string);overload; procedure Log(const S:string; const Fmt:array of const);overload; procedure LogException(E:Exception); Procedure ExceptionHandler(Sender : TObject; E : Exception); procedure LogDatasetFieldNames(const DatasetName:string; D:TDataset); end; function GlobalLogger:ILogger; implementation uses uConfig, functions_file, Forms; var Logger:ILogger; type { TLogger } TLogger = class(TInterfacedObject, ILogger) private //F:TFileStream; F:TextFile; ExceptionCaught:boolean; public constructor Create; destructor Destroy;override; procedure Log(const S:string);overload; procedure Log(const S:string; const Fmt:array of const);overload; procedure LogException(E:Exception); Procedure ExceptionHandler(Sender : TObject; E : Exception); procedure LogDatasetFieldNames(const DatasetName:string; D:TDataset); end; { TLogger } constructor TLogger.Create; begin inherited; ExceptionCaught:=false; //F:=TFileStream.Create( GlobalConfig.DebugLogFile, fmCreate or fmOpenWrite ); AssignFile(F, GlobalConfig.DebugLogFile); Rewrite(F); end; destructor TLogger.Destroy; var D, DLog:String; begin //F.Free; CloseFile(F); if ExceptionCaught then try //сохраняем в отдельной папке логов D:=GlobalConfig.DebugLogDirectory; fb_CreateDirectoryStructure( D ); DLog:=Format('%s/log-%s.log', [D, FormatDateTime('dd-mm-yyyy-hh-mm-ss', Now)]); //DLog:=Format('%s/log.log', [D]); fb_CopyFile(GlobalConfig.DebugLogFile, DLog, false, false); except end; inherited Destroy; end; procedure TLogger.Log(const S: string); var Buf:string; begin //Buf:=S + #13#10; //F.Write( PChar(@Buf[1])^, Length(Buf) ); WriteLn(F, S); Flush(F); end; procedure TLogger.Log(const S: string; const Fmt: array of const); begin Log( Format(S, Fmt) ); end; procedure TLogger.LogException(E: Exception); begin ExceptionCaught:=true; Log('***Исключение***: ' + E.Message); Log('***Исключение*** стек: '); DumpExceptionBackTrace(F); Flush(F); end; procedure TLogger.ExceptionHandler(Sender: TObject; E: Exception); begin LogException(E); //Halt(1); Application.Terminate; end; procedure TLogger.LogDatasetFieldNames(const DatasetName:string; D: TDataset); var S:String; n:Integer; begin S:=DatasetName + ':'; for n:=0 to D.FieldCount-1 do S:=S + Format(' %s(%s)', [D.Fields.Fields[n].FieldName, UpperCase(D.Fields.Fields[n].FieldName)]); Log(S); end; //============================================================================== function GlobalLogger:ILogger; begin if Logger = nil then begin Logger:=TLogger.Create; end; Result:=Logger; end; finalization Logger:=nil; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.36 2/1/05 12:37:48 AM RLebeau Removed IdCommandHandlersEnabledDefault variable, no longer used. Rev 1.35 1/3/05 4:43:20 PM RLebeau Changed use of AnsiSameText() to use TextIsSame() instead Rev 1.34 12/17/04 12:54:04 PM RLebeau Updated TIdCommandHandler.Check() to not match misspelled commands when a CmdDelimiter is specified. Rev 1.33 12/10/04 1:48:04 PM RLebeau Bug fix for TIdCommandHandler.DoCommand() Rev 1.32 10/26/2004 8:42:58 PM JPMugaas Should be more portable with new references to TIdStrings and TIdStringList. Rev 1.31 6/17/2004 2:19:50 AM JPMugaas Problem with unparsed parameters. The initial deliniator between the command and reply was being added to Unparsed Params leading some strange results and command failures. Rev 1.30 6/6/2004 11:44:34 AM JPMugaas Removed a temporary workaround for a Telnet Sequences issue in the TIdFTPServer. That workaround is no longer needed as we fixed the issue another way. Rev 1.29 5/16/04 5:20:22 PM RLebeau Removed local variable from TIdCommandHandler constructor, no longer used Rev 1.28 2004.03.03 3:19:52 PM czhower sorted Rev 1.27 3/3/2004 4:59:40 AM JPMugaas Updated for new properties. Rev 1.26 3/2/2004 8:10:36 AM JPMugaas HelpHide renamed to HelpVisable. Rev 1.25 3/2/2004 6:37:36 AM JPMugaas Updated with properties for more comprehensive help systems. Rev 1.24 2004.03.01 7:13:40 PM czhower Comaptibilty fix. Rev 1.23 2004.03.01 5:12:26 PM czhower -Bug fix for shutdown of servers when connections still existed (AV) -Implicit HELP support in CMDserver -Several command handler bugs -Additional command handler functionality. Rev 1.22 2004.02.29 9:49:06 PM czhower Bug fix, and now responses are also write buffered. Rev 1.21 2004.02.03 4:17:10 PM czhower For unit name changes. Rev 1.20 1/29/04 10:00:40 PM RLebeau Added setter methods to various TIdReply properties Rev 1.19 2003.12.31 7:31:58 PM czhower AnsiSameText --> TextIsSame Rev 1.18 10/19/2003 11:36:52 AM DSiders Added localization comments where setting response codes. Rev 1.17 2003.10.18 9:33:26 PM czhower Boatload of bug fixes to command handlers. Rev 1.16 2003.10.18 8:07:12 PM czhower Fixed bug with defaults. Rev 1.15 2003.10.18 8:03:58 PM czhower Defaults for codes Rev 1.14 10/5/2003 03:06:18 AM JPMugaas Should compile. Rev 1.13 8/9/2003 3:52:44 PM BGooijen TIdCommandHandlers can now create any TIdCommandHandler descendant. this makes it possible to override TIdCommandHandler.check and check for the command a different way ( binary commands, protocols where the string doesn't start with the command ) Rev 1.12 8/2/2003 2:22:54 PM SPerry Fixed OnCommandHandlersException problem Rev 1.11 8/2/2003 1:43:08 PM SPerry Modifications to get command handlers to work Rev 1.9 7/30/2003 10:18:30 PM SPerry Fixed AV when creating commandhandler (again) -- for some reason the bug fixed in Rev. 1.7 was still there. Rev 1.8 7/30/2003 8:31:58 PM SPerry Fixed AV with LFReplyClass. Rev 1.4 7/9/2003 10:55:26 PM BGooijen Restored all features Rev 1.3 7/9/2003 04:36:10 PM JPMugaas You now can override the TIdReply with your own type. This should illiminate some warnings about some serious issues. TIdReply is ONLY a base class with virtual methods. Rev 1.2 7/9/2003 01:43:22 PM JPMugaas Should now compile. Rev 1.1 7/9/2003 2:56:44 PM SPerry Added OnException event Rev 1.0 7/6/2003 4:47:38 PM SPerry Units that use Command handlers } unit IdCommandHandlers; { Original author: Chad Z. Hower Separate Unit : Sergio Perry } interface {$I IdCompilerDefines.inc} //Put FPC into Delphi mode uses Classes, IdBaseComponent, IdComponent, IdReply, IdGlobal, IdContext, IdReplyRFC; const IdEnabledDefault = True; // DO NOT change this default (ParseParams). Many servers rely on this IdParseParamsDefault = True; IdHelpVisibleDef = True; type TIdCommandHandlers = class; TIdCommandHandler = class; TIdCommand = class; { Events } TIdCommandEvent = procedure(ASender: TIdCommand) of object; TIdAfterCommandHandlerEvent = procedure(ASender: TIdCommandHandlers; AContext: TIdContext) of object; TIdBeforeCommandHandlerEvent = procedure(ASender: TIdCommandHandlers; var AData: string; AContext: TIdContext) of object; TIdCommandHandlersExceptionEvent = procedure(ACommand: String; AContext: TIdContext) of object; { TIdCommandHandler } TIdCommandHandler = class(TCollectionItem) protected FCmdDelimiter: Char; FCommand: string; FData: TObject; FDescription: TStrings; FDisconnect: boolean; FEnabled: boolean; FExceptionReply: TIdReply; FHelpSuperScript : String; //may be something like * or + which should appear in help FHelpVisible : Boolean; FName: string; FNormalReply: TIdReply; FOnCommand: TIdCommandEvent; FParamDelimiter: Char; FParseParams: Boolean; FReplyClass : TIdReplyClass; FResponse: TStrings; FTag: integer; // function GetDisplayName: string; override; procedure SetDescription(AValue: TStrings); procedure SetExceptionReply(AValue: TIdReply); procedure SetNormalReply(AValue: TIdReply); procedure SetResponse(AValue: TStrings); public function Check(const AData: string; AContext: TIdContext): boolean; virtual; procedure DoCommand(const AData: string; AContext: TIdContext; AUnparsedParams: string); virtual; procedure DoParseParams(AUnparsedParams: string; AParams: TStrings); virtual; constructor Create(ACollection: TCollection); override; destructor Destroy; override; // function GetNamePath: string; override; function NameIs(const ACommand: string): Boolean; // property Data: TObject read FData write FData; published property CmdDelimiter: Char read FCmdDelimiter write FCmdDelimiter; property Command: string read FCommand write FCommand; property Description: TStrings read FDescription write SetDescription; property Disconnect: boolean read FDisconnect write FDisconnect; property Enabled: boolean read FEnabled write FEnabled default IdEnabledDefault; property ExceptionReply: TIdReply read FExceptionReply write SetExceptionReply; property Name: string read FName write FName; property NormalReply: TIdReply read FNormalReply write SetNormalReply; property ParamDelimiter: Char read FParamDelimiter write FParamDelimiter; property ParseParams: Boolean read FParseParams write FParseParams; property Response: TStrings read FResponse write SetResponse; property Tag: Integer read FTag write FTag; // property HelpSuperScript : String read FHelpSuperScript write FHelpSuperScript; //may be something like * or + which should appear in help property HelpVisible : Boolean read FHelpVisible write FHelpVisible default IdHelpVisibleDef; property OnCommand: TIdCommandEvent read FOnCommand write FOnCommand; end; TIdCommandHandlerClass = class of TIdCommandHandler; { TIdCommandHandlers } TIdCommandHandlers = class(TOwnedCollection) protected FBase: TIdComponent; FExceptionReply: TIdReply; FOnAfterCommandHandler: TIdAfterCommandHandlerEvent; FOnBeforeCommandHandler: TIdBeforeCommandHandlerEvent; FOnCommandHandlersException: TIdCommandHandlersExceptionEvent; FParseParamsDef: Boolean; FPerformReplies: Boolean; FReplyClass: TIdReplyClass; FReplyTexts: TIdReplies; // procedure DoAfterCommandHandler(AContext: TIdContext); procedure DoBeforeCommandHandler(AContext: TIdContext; var VLine: string); procedure DoOnCommandHandlersException(const ACommand: String; AContext: TIdContext); function GetItem(AIndex: Integer): TIdCommandHandler; // This is used instead of the OwnedBy property directly calling GetOwner because // D5 dies with internal errors and crashes // function GetOwnedBy: TIdPersistent; procedure SetItem(AIndex: Integer; const AValue: TIdCommandHandler); public function Add: TIdCommandHandler; constructor Create( ABase: TIdComponent; AReplyClass: TIdReplyClass; AReplyTexts: TIdReplies; AExceptionReply: TIdReply = nil; ACommandHandlerClass: TIdCommandHandlerClass = nil ); reintroduce; function HandleCommand(AContext: TIdContext; var VCommand: string): Boolean; virtual; // property Base: TIdComponent read FBase; property Items[AIndex: Integer]: TIdCommandHandler read GetItem write SetItem; // OwnedBy is used so as not to conflict with Owner in D6 //property OwnedBy: TIdPersistent read GetOwnedBy; property ParseParamsDefault: Boolean read FParseParamsDef write FParseParamsDef; property PerformReplies: Boolean read FPerformReplies write FPerformReplies; property ReplyClass: TIdReplyClass read FReplyClass; property ReplyTexts: TIdReplies read FReplyTexts; // property OnAfterCommandHandler: TIdAfterCommandHandlerEvent read FOnAfterCommandHandler write FOnAfterCommandHandler; // Occurs in the context of the peer thread property OnBeforeCommandHandler: TIdBeforeCommandHandlerEvent read FOnBeforeCommandHandler write FOnBeforeCommandHandler; property OnCommandHandlersException: TIdCommandHandlersExceptionEvent read FOnCommandHandlersException write FOnCommandHandlersException; end; { TIdCommand } TIdCommand = class(TObject) protected FCommandHandler: TIdCommandHandler; FDisconnect: Boolean; FParams: TStrings; FPerformReply: Boolean; FRawLine: string; FReply: TIdReply; FResponse: TStrings; FContext: TIdContext; FUnparsedParams: string; FSendEmptyResponse: Boolean; // procedure DoCommand; virtual; procedure SetReply(AValue: TIdReply); procedure SetResponse(AValue: TStrings); public constructor Create(AOwner: TIdCommandHandler); virtual; destructor Destroy; override; procedure SendReply; // property CommandHandler: TIdCommandHandler read FCommandHandler; property Disconnect: Boolean read FDisconnect write FDisconnect; property PerformReply: Boolean read FPerformReply write FPerformReply; property Params: TStrings read FParams; property RawLine: string read FRawLine; property Reply: TIdReply read FReply write SetReply; property Response: TStrings read FResponse write SetResponse; property Context: TIdContext read FContext; property UnparsedParams: string read FUnparsedParams; property SendEmptyResponse: Boolean read FSendEmptyResponse write FSendEmptyResponse; end;//TIdCommand implementation uses SysUtils; { TIdCommandHandlers } constructor TIdCommandHandlers.Create( ABase: TIdComponent; AReplyClass: TIdReplyClass; AReplyTexts: TIdReplies; AExceptionReply: TIdReply = nil; ACommandHandlerClass: TIdCommandHandlerClass = nil ); begin if ACommandHandlerClass = nil then begin ACommandHandlerClass := TIdCommandHandler; end; inherited Create(ABase, ACommandHandlerClass); FBase := ABase; FExceptionReply := AExceptionReply; FParseParamsDef := IdParseParamsDefault; FPerformReplies := True; // RLebeau: default to legacy behavior FReplyClass := AReplyClass; FReplyTexts := AReplyTexts; end; function TIdCommandHandlers.Add: TIdCommandHandler; begin Result := TIdCommandHandler(inherited Add); end; function TIdCommandHandlers.HandleCommand(AContext: TIdContext; var VCommand: string): Boolean; var i, j: Integer; begin j := Count - 1; Result := False; DoBeforeCommandHandler(AContext, VCommand); try i := 0; while i <= j do begin if Items[i].Enabled then begin Result := Items[i].Check(VCommand, AContext); if Result then begin Break; end; end; Inc(i); end; finally DoAfterCommandHandler(AContext); end; end; procedure TIdCommandHandlers.DoAfterCommandHandler(AContext: TIdContext); begin if Assigned(OnAfterCommandHandler) then begin OnAfterCommandHandler(Self, AContext); end; end; procedure TIdCommandHandlers.DoBeforeCommandHandler(AContext: TIdContext; var VLine: string); begin if Assigned(OnBeforeCommandHandler) then begin OnBeforeCommandHandler(Self, VLine, AContext); end; end; procedure TIdCommandHandlers.DoOnCommandHandlersException(const ACommand: String; AContext: TIdContext); begin if Assigned(FOnCommandHandlersException) then begin OnCommandHandlersException(ACommand, AContext); end; end; function TIdCommandHandlers.GetItem(AIndex: Integer): TIdCommandHandler; begin Result := TIdCommandHandler(inherited Items[AIndex]); end; { function TIdCommandHandlers.GetOwnedBy: TIdPersistent; begin Result := GetOwner; end; } procedure TIdCommandHandlers.SetItem(AIndex: Integer; const AValue: TIdCommandHandler); begin inherited SetItem(AIndex, AValue); end; { TIdCommandHandler } procedure TIdCommandHandler.DoCommand( const AData: string; AContext: TIdContext; AUnparsedParams: string ); var LCommand: TIdCommand; begin LCommand := TIdCommand.Create(Self); with LCommand do try FRawLine := AData; FContext := AContext; FUnparsedParams := AUnparsedParams; if ParseParams then begin DoParseParams(AUnparsedParams, Params); end; // RLebeau 2/21/08: for the IRC protocol, RFC 2812 section 2.4 says that // clients are not allowed to issue numeric replies for server-issued // commands. Added the PerformReplies property so TIdIRC can specify // that behavior. if Self.Collection is TIdCommandHandlers then begin PerformReply := TIdCommandHandlers(Self.Collection).PerformReplies; end; try if (Reply.Code = '') and (Self.NormalReply.Code <> '') then begin Reply.Assign(Self.NormalReply); end; //if code<>'' before DoCommand, then it breaks exception handling Assert(Reply.Code <> ''); DoCommand; if Reply.Code = '' then begin Reply.Assign(Self.NormalReply); end; // UpdateText here in case user wants to add to it. SendReply also gets it in case // a different reply is sent (ie exception, etc), or the user changes the code in the event Reply.UpdateText; except on E: Exception do begin // If there is an unhandled exception, we override all replies // If nothing specified to override with, we throw the exception again. // If the user wants a custom value on exception other, its their responsibility // to catch it before it reaches us Reply.Clear; if PerformReply then begin // Try from command handler first if ExceptionReply.Code <> '' then begin Reply.Assign(ExceptionReply); // If still no go, from server // Can be nil though. Typically only servers pass it in end else if (Collection is TIdCommandHandlers) and (TIdCommandHandlers(Collection).FExceptionReply <> nil) then begin Reply.Assign(TIdCommandHandlers(Collection).FExceptionReply); end; if Reply.Code <> '' then begin //done this way in case an exception message has more than one line. //otherwise you could get something like this: // // 550 System Error. Code: 2 // The system cannot find the file specified // //and the second line would throw off some clients. Reply.Text.Text := E.Message; //Reply.Text.Add(E.Message); SendReply; end else begin raise; end; end else begin raise; end; end else begin raise; end; end; if PerformReply then begin SendReply; end; if (Response.Count > 0) or SendEmptyResponse then begin AContext.Connection.WriteRFCStrings(Response); end else if Self.Response.Count > 0 then begin AContext.Connection.WriteRFCStrings(Self.Response); end; finally try if Disconnect then begin AContext.Connection.Disconnect; end; finally Free; end; end; end; procedure TIdCommandHandler.DoParseParams(AUnparsedParams: string; AParams: TStrings); // AUnparsedParams is not preparsed and is completely left up to the command handler. This will // allow for future expansion such as multiple delimiters etc, and allow the logic to properly // remain in each of the command handler implementations. In the future there may be a base type // and multiple descendants begin AParams.Clear; if FParamDelimiter = #32 then begin SplitColumnsNoTrim(AUnparsedParams, AParams, #32); end else begin SplitColumns(AUnparsedParams, AParams, FParamDelimiter); end; end; function TIdCommandHandler.Check(const AData: string; AContext: TIdContext): boolean; // AData is not preparsed and is completely left up to the command handler. This will allow for // future expansion such as wild cards etc, and allow the logic to properly remain in each of the // command handler implementations. In the future there may be a base type and multiple descendants var LUnparsedParams: string; begin LUnparsedParams := ''; Result := TextIsSame(AData, Command); // Command by itself if not Result then begin if CmdDelimiter <> #0 then begin Result := TextStartsWith(AData, Command + CmdDelimiter); LUnparsedParams := Copy(AData, Length(Command) + 2, MaxInt); end else begin // Dont strip any part of the params out.. - just remove the command purely on length and // no delim Result := TextStartsWith(AData, Command); LUnparsedParams := Copy(AData, Length(Command) + 1, MaxInt); end; end; if Result then begin DoCommand(AData, AContext, LUnparsedParams); end; end; constructor TIdCommandHandler.Create(ACollection: TCollection); begin inherited Create(ACollection); FReplyClass := TIdCommandHandlers(ACollection).ReplyClass; if FReplyClass = nil then begin FReplyClass := TIdReplyRFC; end; FCmdDelimiter := #32; FEnabled := IdEnabledDefault; FName := ClassName + IntToStr(ID); FParamDelimiter := #32; FParseParams := TIdCommandHandlers(ACollection).ParseParamsDefault; FResponse := TStringList.Create; FDescription := TStringList.Create; FNormalReply := FReplyClass.CreateWithReplyTexts(nil, TIdCommandHandlers(ACollection).ReplyTexts); if FNormalReply is TIdReplyRFC then begin FNormalReply.Code := '200'; {do not localize} end; FHelpVisible := IdHelpVisibleDef; // Dont initialize, pulls from CmdTCPServer for defaults FExceptionReply := FReplyClass.CreateWithReplyTexts(nil, TIdCommandHandlers(ACollection).ReplyTexts); end; destructor TIdCommandHandler.Destroy; begin FreeAndNil(FResponse); FreeAndNil(FNormalReply); FreeAndNil(FDescription); FreeAndNil(FExceptionReply); inherited Destroy; end; function TIdCommandHandler.GetDisplayName: string; begin if Command = '' then begin Result := Name; end else begin Result := Command; end; end; { function TIdCommandHandler.GetNamePath: string; begin if Collection <> nil then begin // OwnedBy is used because D4/D5 dont expose Owner on TOwnedCollection but D6 does Result := TIdCommandHandlers(Collection).OwnedBy.GetNamePath + '.' + Name; end else begin Result := inherited GetNamePath; end; end; } function TIdCommandHandler.NameIs(const ACommand: string): Boolean; begin Result := TextIsSame(ACommand, FName); end; procedure TIdCommandHandler.SetExceptionReply(AValue: TIdReply); begin FExceptionReply.Assign(AValue); end; procedure TIdCommandHandler.SetNormalReply(AValue: TIdReply); begin FNormalReply.Assign(AValue); end; procedure TIdCommandHandler.SetResponse(AValue: TStrings); begin FResponse.Assign(AValue); end; procedure TIdCommandHandler.SetDescription(AValue: TStrings); begin FDescription.Assign(AValue); end; { TIdCommand } constructor TIdCommand.Create(AOwner: TIdCommandHandler); begin inherited Create; FParams := TStringList.Create; FReply := AOwner.FReplyClass.CreateWithReplyTexts(nil, TIdCommandHandlers(AOwner.Collection).ReplyTexts); FResponse := TStringList.Create; FCommandHandler := AOwner; FDisconnect := AOwner.Disconnect; end; destructor TIdCommand.Destroy; begin FreeAndNil(FReply); FreeAndNil(FResponse); FreeAndNil(FParams); inherited Destroy; end; procedure TIdCommand.DoCommand; begin if Assigned(CommandHandler.OnCommand) then begin CommandHandler.OnCommand(Self); end; end; procedure TIdCommand.SendReply; begin PerformReply := False; Reply.UpdateText; Context.Connection.IOHandler.Write(Reply.FormattedReply); end; procedure TIdCommand.SetReply(AValue: TIdReply); begin FReply.Assign(AValue); end; procedure TIdCommand.SetResponse(AValue: TStrings); begin FResponse.Assign(AValue); end; end.
// *************************************************************************** // // Delphi MVC Framework // // Copyright (c) 2010-2020 Daniele Teti and the DMVCFramework Team // // https://github.com/danieleteti/delphimvcframework // // *************************************************************************** // // 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 MyObjectU; interface uses JsonDataObjects, System.Generics.Collections, Data.DB, FireDAC.Comp.Client; type TMyObject = class private function GetCustomersDataset: TFDMemTable; public function Subtract(Value1, Value2: Integer): Integer; function ReverseString(const aString: string; const aUpperCase: Boolean): string; function GetCustomers(FilterString: string): TDataset; end; implementation uses System.SysUtils, System.StrUtils; function TMyObject.GetCustomers(FilterString: string): TDataset; var lMT: TFDMemTable; begin lMT := GetCustomersDataset; try if not FilterString.IsEmpty then begin lMT.Filter := FilterString; lMT.Filtered := True; end; lMT.First; Result := lMT; except lMT.Free; raise; end; end; function TMyObject.GetCustomersDataset: TFDMemTable; var lMT: TFDMemTable; begin lMT := TFDMemTable.Create(nil); try lMT.FieldDefs.Clear; lMT.FieldDefs.Add('Code', ftInteger); lMT.FieldDefs.Add('Name', ftString, 20); lMT.Active := True; lMT.AppendRecord([1, 'Ford']); lMT.AppendRecord([2, 'Ferrari']); lMT.AppendRecord([3, 'Lotus']); lMT.AppendRecord([4, 'FCA']); lMT.AppendRecord([5, 'Hyundai']); lMT.AppendRecord([6, 'De Tomaso']); lMT.AppendRecord([7, 'Dodge']); lMT.AppendRecord([8, 'Tesla']); lMT.AppendRecord([9, 'Kia']); lMT.AppendRecord([10, 'Tata']); lMT.AppendRecord([11, 'Volkswagen']); lMT.AppendRecord([12, 'Audi']); lMT.AppendRecord([13, 'Skoda']); lMT.First; Result := lMT; except lMT.Free; raise; end; end; function TMyObject.ReverseString(const aString: string; const aUpperCase: Boolean): string; begin Result := System.StrUtils.ReverseString(aString); if aUpperCase then Result := Result.ToUpper; end; function TMyObject.Subtract(Value1, Value2: Integer): Integer; begin Result := Value1 - Value2; end; end.
unit UGridUtility; interface uses System.SysUtils, System.Generics.Collections, System.Types, System.UITypes, System.Classes, System.Variants, UModel, System.StrUtils, UMyStringGrid, Model_Instruction; Type TGridUtility = class class procedure InsertRow(strigrid: TMyStringGrid; StartRow: Integer; Description, strQty, strAmount, strPrice, strDiscount, Code, Saved, Special: string; taxrate: string; subindex: Integer); class procedure InsertInstructionRow(strigrid: TMyStringGrid; StartRow: Integer; InstructionList: TList<TInstructionLink>; ShowPriceRow: Integer); class procedure GridDataToItems(Grid: TMyStringGrid; theOrder: TOrder); class procedure ItemsDataToGrid(Grid: TMyStringGrid; theOrder: TOrder); class procedure RemoveRows(strgrid: TMyStringGrid; StartRow, RemoveRows: Integer); class function IsInstruction(desc: string): boolean; class function IsSpilit(itemcode: string): boolean; class procedure ChangeDescription(Grid: TMyStringGrid; Menu: TMenu<TMenuItem>; Instruction: TInstruction<TMenuInstructionLink>); end; const colID = 0; colDesc = 1; colQty = 2; colPrice = 3; colAmount = 4; colDiscount = 5; colCode = 6; colSaved = 7; colSpecial = 8; colgst = 9; colPrint = 10; colOrigQty = 11; colSubDescription = 12; colCondition = 13; // var RowCells : Array of string; implementation class procedure TGridUtility.InsertInstructionRow(strigrid: TMyStringGrid; StartRow: Integer; InstructionList: TList<TInstructionLink>; ShowPriceRow: Integer); var i, colindex: Integer; ConditionString, S: String; OriginalCount: Integer; begin OriginalCount := strigrid.RowCount; strigrid.RowCount := strigrid.RowCount + InstructionList.Count; for i := strigrid.RowCount downto StartRow do begin for colindex := 1 to strigrid.ColumnCount - 1 do begin strigrid.cells[colindex, i] := strigrid.cells[colindex, i - 1]; end; end; for i := 0 to strigrid.RowCount - 1 do begin strigrid.cells[colID, i] := (i + 1).toString(); end; for i := 0 to InstructionList.Count - 1 do begin case InstructionList.Items[i].Condition of 0: ConditionString := ''; 1: ConditionString := ' [*] '; 2: ConditionString := ' [A] '; 3: ConditionString := ' [C] '; 4: ConditionString := ' [M] '; 5: ConditionString := ' [L] '; end; strigrid.cells[colDesc, StartRow + i] := ConditionString + InstructionList.Items[i].MenuItemDescription1; strigrid.cells[colQty, StartRow + i] := FloatToStr(InstructionList.Items[i].Qty); if InstructionList.Items[i].MaximunCharge = False then begin Str(InstructionList.Items[i].Price: 9: 2, S); strigrid.cells[colPrice, StartRow + i] := S end else strigrid.cells[colPrice, StartRow + i] := '0.00'; if (InstructionList.Items[i].MaximunCharge = True) and (ShowPriceRow = i) then begin Str(InstructionList.Items[i].Qty * InstructionList.Items[i].Price : 9: 2, S); strigrid.cells[colAmount, StartRow + i] := S; end else begin strigrid.cells[colAmount, StartRow + i] := ''; end; if (InstructionList.Items[i].MaximunCharge = False) and (InstructionList.Items[i].Qty * InstructionList.Items[i].Price <> 0) then begin Str(InstructionList.Items[i].Qty * InstructionList.Items[i].Price : 9: 2, S); strigrid.cells[colAmount, StartRow + i] := S; end; if InstructionList.Items[i].Qty * InstructionList.Items[i].Price = 0 then strigrid.cells[colAmount, StartRow + i] := ''; strigrid.cells[colDiscount, StartRow + i] := '0.00'; strigrid.cells[colCode, StartRow + i] := InstructionList.Items[i] .InstructionCode; strigrid.cells[colSaved, StartRow + i] := ''; strigrid.cells[colSpecial, StartRow + i] := ''; strigrid.cells[colgst, StartRow + i] := FloatToStr(InstructionList.Items[i].taxrate); strigrid.cells[colPrint, StartRow + i] := 'True'; strigrid.cells[colOrigQty, StartRow + i] := '0'; strigrid.cells[colSubDescription, StartRow + i] := ''; strigrid.cells[colCondition, StartRow + i] := IntToStr(InstructionList.Items[i].Condition); end; end; class procedure TGridUtility.InsertRow(strigrid: TMyStringGrid; StartRow: Integer; Description, strQty, strAmount, strPrice, strDiscount, Code, Saved, Special: string; taxrate: string; subindex: Integer); var colindex, i: Integer; begin strigrid.RowCount := strigrid.RowCount + 1; // j := StartRow; for i := strigrid.RowCount downto StartRow do begin for colindex := 1 to strigrid.ColumnCount - 1 do begin strigrid.cells[colindex, i] := strigrid.cells[colindex, i - 1]; end; end; for i := 0 to strigrid.RowCount - 1 do begin strigrid.cells[colID, i] := (i + 1).toString(); end; strigrid.cells[colDesc, StartRow] := Description; strigrid.cells[colQty, StartRow] := strQty; strigrid.cells[colPrice, StartRow] := strAmount; strigrid.cells[colAmount, StartRow] := strPrice; strigrid.cells[colDiscount, StartRow] := strDiscount; strigrid.cells[colCode, StartRow] := Code; strigrid.cells[colSaved, StartRow] := Saved; strigrid.cells[colSpecial, StartRow] := Special; strigrid.cells[colgst, StartRow] := taxrate; strigrid.cells[colPrint, StartRow] := 'True'; strigrid.cells[colOrigQty, StartRow] := '0'; strigrid.cells[colSubDescription, StartRow] := IntToStr(subindex); strigrid.Selected := StartRow; end; class procedure TGridUtility.ChangeDescription(Grid: TMyStringGrid; Menu: TMenu<TMenuItem>; Instruction: TInstruction<TMenuInstructionLink>); var i, subidx: Integer; item: TMenuItem; // sub: TSubDescription; begin // sub := TSubDescription.Create; for i := 0 to Grid.RowCount - 1 do if (not IsSpilit(Grid.cells[colCode, i])) then if (Grid.cells[colSpecial, i] <> 'Y') then if IsInstruction(Grid.cells[1, i]) then if Instruction.GetInstructionLinkByCode(Grid.cells[6, i]) = nil then Grid.cells[1, i] := ' [*] ' + Menu.GetItemByCode (Grid.cells[colCode, i]).Description(Menu.DescIdx) else Grid.cells[1, i] := ' [*] ' + Instruction.GetInstructionLinkByCode (Grid.cells[6, i]).Description(Menu.DescIdx) else begin item := Menu.GetItemByCode(Grid.cells[colCode, i]); if item <> nil then begin Grid.cells[colDesc, i] := item.Description(Menu.DescIdx); if item.PriceList.Count > 1 then begin subidx := StrToInt(Grid.cells[colSubDescription, i]); Grid.cells[colDesc, i] := Grid.cells[colDesc, i] + ' / ' + item.PriceList[subidx].Key; end; end; end; end; class procedure TGridUtility.GridDataToItems(Grid: TMyStringGrid; theOrder: TOrder); var i, index: Integer; item: TOrderItem; m: Integer; n: string; t: double; S: string; temp: string; tempb: boolean; Isspecial: boolean; begin theOrder.orderitemlist.clear; index := 0; for i := 0 to Grid.RowCount - 1 do begin Isspecial := (Grid.cells[colSpecial, i] = 'Y') and (Grid.cells[colQty, i] = ''); if Isspecial then begin temp := Grid.cells[colDesc, i]; if Length(temp) > 255 then temp := LeftStr(temp, 255); theOrder.orderitemlist[index - 1].SpecialOrder := temp; end else begin item := TOrderItem.Create; if not Isspecial then item.IDNo := index + 1; if (Grid.cells[2, i] <> '') and not IsSpilit(Grid.cells[colCode, i]) then begin item.Qty := strToFloat(Grid.cells[2, i]); end else item.Qty := 0; // price if (Grid.cells[3, i] <> '') and (not IsSpilit(Grid.cells[colCode, i])) then begin item.Price := strToFloat(Grid.cells[3, i]); if (Grid.cells[4, i] = '') then item.OriginalPrice := 0 else begin if (strToFloat(Grid.cells[4, i]) <> 0) and (strToFloat(Grid.cells[3, i]) = 0) then item.Price := strToFloat(Grid.cells[4, i]); item.OriginalPrice := item.Price; end; end else begin item.Price := 0; end; if LeftStr(Grid.cells[5, i], 1) = '$' then begin m := Length(Grid.cells[5, i]) - 1; n := RightStr(Grid.cells[5, i], m); t := strToFloat(n); item.Discount := t end else begin if RightStr(Grid.cells[5, i], 1) = '%' then begin m := Length(Grid.cells[5, i]) - 1; n := LeftStr(Grid.cells[5, i], m); t := strToFloat(n); item.Discount := t end else if (Grid.cells[5, i] <> '') and not IsSpilit(Grid.cells[colCode, i]) then item.Discount := strToFloat(Grid.cells[5, i]) else item.Discount := 0; end; if theOrder.OpName <> '' then item.OrderOperator := theOrder.OpName; if Grid.cells[colgst, i] <> '' then begin temp := Grid.cells[colgst, i]; Str(strToFloat(temp): 4: 2, S); end; // Condition Column if Grid.cells[colgst, i] <> '' then item.taxrate := strToFloat(S) else item.taxrate := strToFloat('0.00'); item.itemcode := Grid.cells[colCode, i]; item.VoidFlag := Grid.cells[colSaved, i] = 'Void'; if IsInstruction(Grid.cells[colDesc, i]) then item.Condition := 1 else item.Condition := 0; if Grid.cells[colPrint, i] = 'False' then item.PrintFlag := True else item.PrintFlag := False; tempb := item.PrintFlag; if Grid.cells[colOrigQty, i] <> '' then item.OriginalQty := strToFloat(Grid.cells[colOrigQty, i]) else item.OriginalQty := 0; if Grid.cells[colSubDescription, i] <> '' then item.PriceSelect := strToFloat(Grid.cells[colSubDescription, i]) else item.PriceSelect := 0; if Grid.cells[colCondition, i] <> '' then item.Condition := StrToInt(Grid.cells[colCondition, i]); theOrder.orderitemlist.Add(item); index := index + 1; end; end; end; class procedure TGridUtility.ItemsDataToGrid(Grid: TMyStringGrid; theOrder: TOrder); var i: Integer; S: string; temp: string; begin Grid.RowCount := 0; for i := 0 to theOrder.orderitemlist.Count - 1 do begin Grid.RowCount := Grid.RowCount + 1; Grid.cells[0, Grid.RowCount - 1] := IntToStr(Grid.RowCount); Grid.cells[colCode, Grid.RowCount - 1] := theOrder.orderitemlist.Items [i].itemcode; if IsSpilit(theOrder.orderitemlist.Items[i].itemcode) then begin Grid.cells[colDesc, Grid.RowCount - 1] := '------------------------------------------------------------------------------------------------------------'; Grid.cells[colQty, Grid.RowCount - 1] := '----------------------------------------------------------------------------------------------'; Grid.cells[colPrice, Grid.RowCount - 1] := '--------------------------------------'; Grid.cells[colAmount, Grid.RowCount - 1] := '----------------------------------------'; Grid.cells[7, Grid.RowCount - 1] := 'True'; Grid.RowCount := Grid.RowCount + 1; Grid.RowCount := Grid.RowCount - 1; end else begin if theOrder.orderitemlist.Items[i].SubDescription = '' then begin temp := theOrder.orderitemlist.Items[i].Description; Grid.cells[colDesc, Grid.RowCount - 1] := theOrder.orderitemlist.Items [i].Description; end else Grid.cells[colDesc, Grid.RowCount - 1] := theOrder.orderitemlist.Items [i].Description + ' / ' + theOrder.orderitemlist.Items[i] .SubDescription; Grid.cells[2, Grid.RowCount - 1] := FloatToStr(theOrder.orderitemlist.Items[i].Qty); Str(theOrder.orderitemlist.Items[i].Price: 8: 2, S); Grid.cells[3, Grid.RowCount - 1] := S; Str(theOrder.orderitemlist.Items[i].Qty * theOrder.orderitemlist.Items[i] .Price: 8: 2, S); Grid.cells[4, Grid.RowCount - 1] := S; Grid.cells[5, Grid.RowCount - 1] := FloatToStr(theOrder.orderitemlist.Items[i].Discount); if theOrder.orderitemlist.Items[i].VoidFlag then // Change void flag Grid.cells[7, Grid.RowCount - 1] := 'Void' // the item alredy get voided else Grid.cells[7, Grid.RowCount - 1] := 'True'; // saved item, can be voided Grid.cells[colgst, Grid.RowCount - 1] := FloatToStr(theOrder.orderitemlist.Items[i].taxrate); // taxrate Grid.cells[colSpecial, Grid.RowCount - 1] := ''; Grid.cells[colPrint, Grid.RowCount - 1] := 'False'; Grid.cells[colOrigQty, Grid.RowCount - 1] := FloatToStr(theOrder.orderitemlist.Items[i].Qty); Grid.cells[colSubDescription, Grid.RowCount - 1] := FloatToStr(theOrder.orderitemlist.Items[i].PriceSelect); Grid.cells[colCondition, Grid.RowCount - 1] := IntToStr(theOrder.orderitemlist.Items[i].Condition); // not saved, can be voided if Length(theOrder.orderitemlist.Items[i].SpecialOrder) >= 1 then // Special Order begin Grid.RowCount := Grid.RowCount + 1; Grid.cells[0, Grid.RowCount - 1] := IntToStr(Grid.RowCount); Grid.cells[colQty, Grid.RowCount - 1] := ''; Grid.cells[colAmount, Grid.RowCount - 1] := ''; Grid.cells[colPrice, Grid.RowCount - 1] := ''; Grid.cells[colDiscount, Grid.RowCount - 1] := ''; Grid.cells[colCode, Grid.RowCount - 1] := ''; Grid.cells[colDesc, Grid.RowCount - 1] := theOrder.orderitemlist.Items [i].SpecialOrder; Grid.cells[colSpecial, Grid.RowCount - 1] := 'Y'; Grid.cells[colSaved, Grid.RowCount - 1] := 'True'; Grid.cells[colgst, Grid.RowCount - 1] := FloatToStr(theOrder.orderitemlist.Items[i].taxrate); Grid.cells[colOrigQty, Grid.RowCount - 1] := ''; Grid.cells[colPrint, Grid.RowCount - 1] := 'False'; Grid.cells[colSubDescription, Grid.RowCount - 1] := ''; end; end; end; end; class procedure TGridUtility.RemoveRows(strgrid: TMyStringGrid; StartRow, RemoveRows: Integer); var colindex, i, j: Integer; begin if (strgrid.RowCount < 1) or ((StartRow + RemoveRows) > (strgrid.RowCount)) then exit; j := StartRow; for i := StartRow + RemoveRows to strgrid.RowCount - 1 do begin for colindex := 1 to strgrid.ColumnCount - 1 do strgrid.cells[colindex, j] := strgrid.cells[colindex, j + RemoveRows]; Inc(j); end; for i := strgrid.RowCount - RemoveRows to strgrid.RowCount - 1 do for colindex := 0 to strgrid.ColumnCount - 1 do strgrid.cells[colindex, i] := ''; strgrid.RowCount := strgrid.RowCount - RemoveRows; end; class function TGridUtility.IsInstruction(desc: string): boolean; var Description: string; temp: boolean; begin Description := desc; temp := (Description.IndexOf('*') >= 0); result := (Description.IndexOf('[*]') > 0); end; class function TGridUtility.IsSpilit(itemcode: string): boolean; begin result := (itemcode = '----'); end; end.
unit Eagle.Alfred.ProjectCommand; interface uses Classes, SysUtils, Eagle.ConsoleIO, Eagle.Alfred.DprojParser, Eagle.Alfred.Command; type TProjectCommand = class(TInterfacedObject, ICommand) private FAppPath: string; FDprojParser: TDprojParser; FConsoleIO: IConsoleIO; procedure GetSubDirs(const sRootDir: string; slt: TStrings); function AddDirSeparator(const dir: string): string; public constructor Create(const AppPath: string; ConsoleIO: IConsoleIO; DprojParser: TDprojParser); destructor Destroy; override; procedure Execute; procedure Help; end; implementation { TProjectCommand } function TProjectCommand.AddDirSeparator(const dir: string): string; var h:string; begin Result:= dir; h := dir; if h[Length(h)] <> '\' then h := h + '\'; Result:=h; end; constructor TProjectCommand.Create(const AppPath: string; ConsoleIO: IConsoleIO; DprojParser: TDprojParser); begin FAppPath := AppPath; FConsoleIO := ConsoleIO; FDprojParser := DprojParser; end; destructor TProjectCommand.Destroy; begin inherited; end; procedure TProjectCommand.Execute; var list: TStringList; begin list := TStringList.Create; try GetSubDirs('src', list); list.SaveToFile('search_library.txt'); finally list.Free; end; end; procedure TProjectCommand.GetSubDirs(const sRootDir: string; slt: TStrings); var srSearch: TSearchRec; sSearchPath: string; sltSub: TStrings; i: Integer; begin sltSub := TStringList.Create; slt.BeginUpdate; try sSearchPath := AddDirSeparator(sRootDir); if FindFirst(sSearchPath + '*', faDirectory, srSearch) = 0 then repeat if ((srSearch.Attr and faDirectory) = faDirectory) and (srSearch.Name <> '.') and (srSearch.Name <> '..') then begin slt.Add(sSearchPath + srSearch.Name); sltSub.Add(sSearchPath + srSearch.Name); end; until (FindNext(srSearch) <> 0); FindClose(srSearch); for i := 0 to sltSub.Count - 1 do GetSubDirs(sltSub.Strings[i], slt); finally slt.EndUpdate; FreeAndNil(sltSub); end; end; procedure TProjectCommand.Help; begin end; end.
unit define_ctp_deal; interface uses ThostFtdcTraderApiDataType; const //申万 tcp://180.168.212.51:41205 Port_Ctp_Deal = 41205; Ip_Ctp_Deal_SW_1 = '180.168.212.51'; Ip_Ctp_Deal_SW_2 = '180.168.212.52'; Ip_Ctp_Deal_SW_3 = '180.168.212.53'; Ip_Ctp_Deal_SW_4 = '180.168.212.54'; Ip_Ctp_Deal_SW_5 = '180.168.212.55'; type TDealDirection = (directionNone, directionBuy, directionSale); TDealOffsetMode = ( modeNone, modeOpen, // 开仓 modeCloseOut, // 平仓 modeCloseNow // 平今 ); TPriceMode = (priceLimit, priceNow); PDeal = ^TDeal; PDealOrderRequest = ^TDealOrderRequest; PDealOrderResponse = ^TDealOrderResponse; PDealCancelRequest = ^TDealCancelRequest; PDealCancelResponse = ^TDealCancelResponse; PDealResponse = ^TDealResponse; // 下单 TDealOrderRequest = record CloseDeal : PDeal; InstrumentID : AnsiString; // 合约 IF1508 Direction : TDealDirection; Mode : TDealOffsetMode; PriceMode : TPriceMode; Price : double; Num : Integer; OrderNo : AnsiString; // exchangeId for cancel RequestId : Integer; end; // 下单反馈 TDealOrderResponse = record // BrokerOrderSeq : Integer; // ExchangeID : AnsiString; // OrderSysID : AnsiString; end; // 撤单 TDealCancelRequest = record RequestId : Integer; end; TDealCancelResponse = record end; // 成交 TDealResponse = record Price : double; Num : Integer; end; TDealStatus = ( deal_Invalid, deal_Unknown, deal_Open, // 等待 成交 或取消 deal_Cancel, // 已经取消 deal_Deal, // 已经成交 deal_DealClose // 已经开仓并且已经平仓 ); TDeal = record Status : TDealStatus; // ---------------------------------- OrderRequest : TDealOrderRequest; // ---------------------------------- // 报单返回 ExchangeID : AnsiString; OrderSysID : AnsiString; BrokerOrderSeq : Integer; OrderResponse : PDealOrderResponse; // ---------------------------------- // 成交返回 Deal : PDealResponse; // ---------------------------------- // 两个方向 要不撤单 要不成交 CancelRequest : PDealCancelRequest; CancelResponse : PDealCancelResponse; end; TDealConsoleData = record Index: Integer; DealArray: array[0..300 - 1] of TDeal; //OrgData: TDealOrgDataConsole; LastRequestDeal: PDeal; end; PTradingAccount = ^TTradingAccount; TTradingAccount = record RecordTime: TDateTime; Data: ThostFtdcTradingAccountField; end; PInvestorPosition = ^TInvestorPosition; TInvestorPosition = record RecordTime: TDateTime; InstrumentId: AnsiString; Data: ThostFtdcInvestorPositionField; end; PInputOrder = ^TInputOrder; TInputOrder = record RecordTime: TDateTime; Data: ThostFtdcInputOrderField; end; PInputOrderAction = ^TInputOrderAction; TInputOrderAction = record RecordTime: TDateTime; Data: ThostFtdcInputOrderActionField; end; POrder = ^TOrder; TOrder = record MsgSrc: Integer; RecordTime: TDateTime; Data: ThostFtdcOrderField; end; PTrade = ^TTrade; TTrade = record MsgSrc: Integer; RecordTime: TDateTime; Data: ThostFtdcTradeField; end; PInstrument = ^TInstrument; TInstrument = record RecordTime: TDateTime; Data: ThostFtdcInstrumentField; end; TInputOrderCache = record Count: integer; InputOrderArray: array[0..1 * 1024 - 1] of PInputOrder; end; TInputOrderActionCache = record Count: integer; InputOrderActionArray: array[0..1 * 1024 - 1] of PInputOrderAction; end; TOrderCache = record Count: integer; OrderArray: array[0..1 * 1024 - 1] of POrder; end; TTradeCache = record Count: integer; TradeArray: array[0..1 * 1024 - 1] of PTrade; end; TInvestorPositionCache = record Count: integer; InvestorPositionArray: array[0..7] of PInvestorPosition; end; implementation end.
unit Streams; interface uses Generics; type PStream = ^TStream; TStream = object(TGeneric) constructor Create; destructor Destroy; virtual; procedure Reset; virtual; procedure WriteBlock(var Buf; ASize: Word); virtual; procedure ReadBlock(var Buf; ASize: Word); virtual; function Size: Longint; virtual; function EOS: Boolean; virtual; function BOS: Boolean; virtual; procedure Seek(APos: Longint); virtual; function Pos: Longint; virtual; function ErrorCode: Word; virtual; end; PFileStream = ^TFileStream; TFileStream = object(TStream) private F: File; Error: Word; public constructor Create(AFileName: string); destructor Destroy; virtual; procedure Reset; virtual; procedure WriteBlock(var Buf; ASize: Word); virtual; procedure ReadBlock(var Buf; ASize: Word); virtual; function Size: Longint; virtual; function EOS: Boolean; virtual; function BOS: Boolean; virtual; procedure Seek(APos: Longint); virtual; function Pos: Longint; virtual; function ErrorCode: Word; virtual; end; implementation constructor TStream.Create; begin Inherited Create; end; destructor TStream.Destroy; begin inherited Destroy; end; procedure TStream.Reset; begin end; procedure TStream.WriteBlock(var Buf; ASize: Word); begin end; procedure TStream.ReadBlock(var Buf; ASize: Word); begin FillChar(Buf, ASize, #0); end; function TStream.Size: Longint; begin Size := 0; end; function TStream.EOS: Boolean; begin EOS := True; end; function TStream.BOS: Boolean; begin BOS := True; end; procedure TStream.Seek(APos: Longint); begin end; function TStream.Pos: Longint; begin Pos := 0; end; function TStream.ErrorCode: Word; begin ErrorCode := 0; end; constructor TFileStream.Create(AFileName: string); begin inherited Create; {$I-} System.Assign(F, AFileName); System.Reset(F,1); if (System.IOResult <> 0) then begin System.Rewrite(F,1); Error := System.IOResult; end else Error := 0; end; destructor TFileStream.Destroy; begin System.Close(F); inherited Destroy; end; procedure TFileStream.Reset; begin if (Error = 0) then begin Close(F); Erase(F); Rewrite(F,1); Error := IOResult; end; end; procedure TFileStream.WriteBlock(var Buf; ASize: Word); begin if (Error = 0) then begin System.BlockWrite(F, Buf, ASize); Error := System.IOResult; end; end; procedure TFileStream.ReadBlock(var Buf; ASize: Word); begin if (Error = 0) then begin System.BlockRead(F, Buf, ASize); Error := System.IOResult; end; end; function TFileStream.Size: Longint; begin Size := System.FileSize(F); Error := System.IOResult; end; function TFileStream.EOS: Boolean; begin EOS := System.EOF(F); Error := System.IOResult; end; function TFileStream.BOS: Boolean; begin BOS := (System.FilePos(F) = 0); Error := System.IOResult; end; procedure TFileStream.Seek(APos: Longint); begin if (Error = 0) then begin System.Seek(F, APos); Error := System.IOResult; end; end; function TFileStream.Pos: Longint; begin Pos := System.FilePos(F); Error := System.IOResult; end; function TFileStream.ErrorCode: Word; begin ErrorCode := Error; end; end.
unit D_DocAddr; { $Id: D_DocAddr.pas,v 1.7 2016/06/16 05:38:44 lukyanets Exp $ } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, BottomBtnDlg, StdCtrls, vtSpin, Buttons, ExtCtrls, daTypes, ActnList, tb97GraphicControl, TB97Ctls, vtSpeedButton; type TDocAddrDlg = class(TBottomBtnDlg) lblDocID: TLabel; lblSubID: TLabel; edtDocID: TvtSpinEdit; edtSubID: TvtSpinEdit; ActionList1: TActionList; acPaste: TAction; btnPasteAddr: TSpeedButton; procedure OKClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure acPasteExecute(Sender: TObject); private function IsNemesisAddrInClipboard: Boolean; function PasteNemesisAddr : boolean; protected procedure WMActivateApp(var Message: TMessage); message WM_ACTIVATEAPP; public function Execute(Var aAddrRec : TdaGlobalCoordinateRec) : boolean; reintroduce; //property DocID : Integer read GetDocID write SetDocID; //property SubID : Integer read GetDocID write SetDocID; end; //function RequestDocAddr(var aValue : Integer; AOwner: TComponent; // aCaption : String = ''; aLabel : String = '') : Boolean; implementation uses Clipbrd, Main; {$R *.DFM} var gSaveDocID : integer; function TDocAddrDlg.Execute(Var aAddrRec : TdaGlobalCoordinateRec) : boolean; begin with aAddrRec do begin //if not PasteNemesisAddr then //begin edtDocID.AsInteger := Doc; edtSubID.AsInteger := Sub; If edtDocID.AsInteger = 0 then edtDocID.AsInteger := gSaveDocID; //end; Result := ShowModal = mrOK; If Result then begin Doc := edtDocID.AsInteger; Sub := edtSubID.AsInteger; gSaveDocID := Doc; end; end; end; function TDocAddrDlg.IsNemesisAddrInClipboard: Boolean; var l_Clip: string; I: Integer; l_DotCount: Integer; begin Result := False; l_Clip := Clipboard.AsText; if l_Clip <> '' then begin l_DotCount := 0; for I := 1 to Length(l_Clip) do case l_Clip[I] of '0'..'9': ; '.' : Inc(l_DotCount); else Exit; end; Result := (l_DotCount = 1); end; end; (* function RequestIntegerValue(var aValue : Integer; AOwner: TComponent; aCaption : String = ''; aLabel : String = '') : Boolean; begin With TIntegerEditDlg.Create(AOwner) do try Caption := aCaption; LabelText := aLabel; Value := aValue; Result := Execute; If Result then aValue := Value; finally Free; end; end; *) procedure TDocAddrDlg.OKClick(Sender: TObject); begin If edtDocID.AsInteger <= 0 then begin ModalResult := mrNone; ActiveControl := edtDocID; end; end; function TDocAddrDlg.PasteNemesisAddr : boolean; var l_Clip: string; l_DotPos: Integer; begin Result := IsNemesisAddrInClipboard; if Result then begin l_Clip := Clipboard.AsText; l_DotPos := Pos('.', l_Clip); edtDocID.Text := System.Copy(l_Clip, 1, l_DotPos-1); edtSubID.Text := System.Copy(l_Clip, l_DotPos+1, MaxInt); end; end; procedure TDocAddrDlg.FormActivate(Sender: TObject); begin //btnPasteAddr.Enabled := IsNemesisAddrInClipboard; end; procedure TDocAddrDlg.WMActivateApp(var Message: TMessage); begin inherited; //btnPasteAddr.Enabled := IsNemesisAddrInClipboard; end; procedure TDocAddrDlg.acPasteExecute(Sender: TObject); begin // если не можем вставить как адрес, вставим как есть if not PasteNemesisAddr then Paste; end; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} unit ColnProp; interface uses Windows, Classes, Forms, Controls, SysUtils, {$ifdef VCL_6_USED} DesignIntf, DesignEditors, DesignWindows, DsnConst, {$else} DsgnIntf, {$endif} ColnEdit, ElStatBar, ElSideBar; type TElStatusBarEditor = class(TComponentEditor) public procedure ExecuteVerb(Index: integer); override; function GetVerb(Index: integer): string; override; function GetVerbCount: integer; override; end; TElSideBarEditor = class(TComponentEditor) public procedure ExecuteVerb(Index: integer); override; function GetVerb(Index: integer): string; override; function GetVerbCount: integer; override; end; implementation procedure TElStatusBarEditor.ExecuteVerb(Index: integer); begin if Index = 0 then begin ShowCollectionEditor(Self.Designer, Component, (Component as TElStatusBar).Panels, 'Panels'); end; end; function TElStatusBarEditor.GetVerb(Index: integer): string; begin if Index = 0 then result := 'Status Panels ...'; end; function TElStatusBarEditor.GetVerbCount: integer; begin result := 1; end; procedure TElSideBarEditor.ExecuteVerb(Index: integer); begin if Index = 0 then begin ShowCollectionEditor(Self.Designer, Component, (Component as TElSideBar).Sections, 'Sections'); end; end; function TElSideBarEditor.GetVerb(Index: integer): string; begin if Index = 0 then result := 'Sidebar Sections ...' end; function TElSideBarEditor.GetVerbCount: integer; begin result := 1; end; end.
unit Controller.Customer; interface uses MVCFramework, MVCFramework.Commons, MVCFramework.Serializer.Commons, MVCFramework.ActiveRecord, FireDAC.Comp.Client, FireDAC.Phys.SQLite, MVCFramework.SQLGenerators.Sqlite, System.Generics.Collections, Model.Customer, System.JSON; type [MVCPath('/api')] TCustomerController = class(TMVCController) private FDConn : TFDConnection; protected procedure OnBeforeAction(Context: TWebContext; const AActionName: string; var Handled: Boolean); override; procedure OnAfterAction(Context: TWebContext; const AActionName: string); override; public [MVCPath('/customers')] [MVCHTTPMethod([httpGET])] procedure GetCustomers; [MVCPath('/customers/($id)')] [MVCHTTPMethod([httpGET])] procedure GetCustomer(id: Integer); [MVCPath('/customers')] [MVCHTTPMethod([httpPOST])] procedure CreateCustomer; [MVCPath('/customers/($id)')] [MVCHTTPMethod([httpPUT])] procedure UpdateCustomer(id: Integer); [MVCPath('/customers/($id)')] [MVCHTTPMethod([httpDELETE])] procedure DeleteCustomer(id: Integer); constructor Create; override; destructor Destroy; override; end; implementation uses System.SysUtils, MVCFramework.Logger, System.StrUtils; procedure TCustomerController.OnAfterAction(Context: TWebContext; const AActionName: string); begin { Executed after each action } inherited; end; procedure TCustomerController.OnBeforeAction(Context: TWebContext; const AActionName: string; var Handled: Boolean); begin { Executed before each action if handled is true (or an exception is raised) the actual action will not be called } inherited; end; //Sample CRUD Actions for a "Customer" entity procedure TCustomerController.GetCustomers; var lCustomers : TObjectList<TCustomer>; begin lCustomers := TMVCActiveRecord.SelectRQL<TCustomer>('', 20); Render<TCustomer>(lCustomers); end; procedure TCustomerController.GetCustomer(id: Integer); var lCustomer : TCustomer; begin lCustomer := TMVCActiveRecord.GetByPK<TCustomer>(id); Render(lCustomer); end; constructor TCustomerController.Create; begin inherited; FDConn := TFDConnection.Create(nil); FDConn.Params.Clear; FDConn.Params.Database := '../../../data/activerecorddb.db'; FDConn.DriverName := 'SQLite'; FDConn.Connected := True; ActiveRecordConnectionsRegistry.AddDefaultConnection(FDConn); end; procedure TCustomerController.CreateCustomer; var lCustomer : TCustomer; begin lCustomer := Context.Request.BodyAs<TCustomer>; lCustomer.Insert; Render(lCustomer); end; procedure TCustomerController.UpdateCustomer(id: Integer); var lCustomer : TCustomer; begin lCustomer := Context.Request.BodyAs<TCustomer>; lCustomer.id := id; lCustomer.Update; Render(lCustomer); end; procedure TCustomerController.DeleteCustomer(id: Integer); var lCustomer : TCustomer; begin lCustomer := TMVCActiveRecord.GetByPK<TCustomer>(id); lCustomer.Delete; Render(TJSONObject.Create(TJSONPair.Create('result', 'register successefully deleted'))); end; destructor TCustomerController.Destroy; begin ActiveRecordConnectionsRegistry.RemoveDefaultConnection; inherited; end; end.
unit uConfiguracao; interface type TTipoIntegracao = (tsToledo, tsFilizola, tsOutros); type TConfiguracao = class private FTipoIntegracao: TTipoIntegracao; FLocalArquivo: String; public property LocalArquivo: String read FLocalArquivo write FLocalArquivo; procedure TipoIntegracaoToString(pTipo: String); overload; procedure TipoIntegracao(pTipo: TTipoIntegracao); overload; function TipoIntegracaoToString: String; overload; function TipoIntegracao: TTipoIntegracao; overload; constructor Create; destructor Destroy; override; class function New: TConfiguracao; end; implementation { TConfiguracao } uses StrUtils, System.SysUtils; constructor TConfiguracao.Create; begin end; destructor TConfiguracao.Destroy; begin inherited; end; class function TConfiguracao.New: TConfiguracao; begin Result := TConfiguracao.Create; end; procedure TConfiguracao.TipoIntegracao(pTipo: TTipoIntegracao); begin FTipoIntegracao := pTipo; end; function TConfiguracao.TipoIntegracao: TTipoIntegracao; begin Result := FTipoIntegracao; end; procedure TConfiguracao.TipoIntegracaoToString(pTipo: String); begin case AnsiIndexStr(UpperCase(pTipo), ['T', 'F','O']) of 0 : FTipoIntegracao := tsToledo; 1 : FTipoIntegracao := tsFilizola; 2 : FTipoIntegracao := tsOutros; end; end; function TConfiguracao.TipoIntegracaoToString: String; begin case FTipoIntegracao of tsToledo : Result := 'T'; tsFilizola : Result := 'F'; tsOutros : Result := 'O'; end; end; end.
unit tmsUXlsRangeRecords; {$INCLUDE ..\FLXCOMPILER.INC} interface uses tmsUXlsBaseRecords, tmsUXlsBaseRecordLists, tmsUXlsOtherRecords, tmsXlsMessages, Classes, SysUtils, tmsUFlxMessages, Math, tmsUOle2Impl; type TExcelRange= packed record R1, R2, C1, C2: word; end; PExcelRange= ^TExcelRange; TRangeValuesList= class(TList) //Items are TExcelRange private FOtherDataLen :word; MaxRangesPerRecord: integer; procedure CopyIntersectRange(const R, Rx: PExcelRange; const NewFirstRow, NewLastRow, DestRow, aCount: integer; var MinR1, MaxR2: Word); function NextInRange(const Range: TXlsCellRange; const k: integer): integer; protected procedure Notify(Ptr: Pointer; Action: TListNotification); override; public constructor Create(const aMaxRangesPerRecord: integer; const aOtherDataLen: word); procedure Load(const aRecord: TBaseRecord; const aPos: integer); //these methods are to split the record repeating it procedure SaveToStreamR(const DataStream: TOle2File; const Line: integer); procedure SaveRangeToStreamR(const DataStream: TOle2File; const Line: integer; const aCount: integer; const Range: TXlsCellRange); function TotalSizeR(const aCount: integer): int64; function RepeatCountR(const aCount: integer): integer; function RecordSizeR(const Line: integer; const aCount:integer): integer; function CountRangeRecords(const Range: TXlsCellRange): integer; procedure CopyFrom( const RVL: TRangeValuesList); procedure ArrangeInsertRowsAndCols(const aRowPos, aRowCount, aColPos, aColCount:integer); //Formats are copied if the range intersects with the original. (Merged cells need all the range to be inside the original) procedure CopyRowsInclusive(const FirstRow, LastRow, DestRow, aCount: integer; var MinR1, MaxR2: Word; const UseCols: boolean); procedure CopyRowsExclusive(const FirstRow, LastRow, DestRow, aCount: integer; const UseCols: boolean); procedure DeleteRows(const aRow, aCount: integer; const Allow1Cell: boolean; const UseCols: boolean); procedure PreAddNewRange(var R1,C1,R2,C2: integer); procedure AddNewRange(const FirstRow, FirstCol, LastRow, LastCol: integer); end; TRangeEntry = class private protected RangeValuesList: TRangeValuesList; function DoCopyTo: TRangeEntry; virtual; public constructor Create; virtual; destructor Destroy; override; function CopyTo: TRangeEntry; procedure LoadFromStream(const DataStream: TOle2File; var RecordHeader: TRecordHeader; const First: TRangeRecord);virtual;abstract; procedure SaveToStream(const DataStream: TOle2File);virtual;abstract; procedure SaveRangeToStream(const DataStream: TOle2File; const CellRange: TXlsCellRange);virtual;abstract; function TotalSize: int64;virtual; abstract; function TotalRangeSize(const CellRange: TXlsCellRange): int64;virtual; abstract; procedure ArrangeInsertRowsAndCols(const aRowPos, aRowCount, aColPos, aColCount:integer; const SheetInfo: TSheetInfo);virtual; procedure InsertAndCopyRowsOrCols(const FirstRow, LastRow, DestRow, aCount: integer; const SheetInfo: TSheetInfo; const UseCols: boolean); virtual; procedure DeleteRowsOrCols(const aRow, aCount: word; const SheetInfo: TSheetInfo; const UseCols: boolean);virtual; end; //Merged cells can't be continued. We have to write independent records. TMergedCells = class (TRangeEntry) private public constructor Create; override; procedure Clear; procedure LoadFromStream(const DataStream: TOle2File; var RecordHeader: TRecordHeader; const First: TRangeRecord); override; procedure SaveToStream(const DataStream: TOle2File); override; procedure SaveRangeToStream(const DataStream: TOle2File; const CellRange: TXlsCellRange);override; function TotalSize: int64; override; function TotalRangeSize(const CellRange: TXlsCellRange): int64;override; procedure InsertAndCopyRowsOrCols(const FirstRow, LastRow, DestRow, aCount: integer; const SheetInfo: TSheetInfo; const UseCols: boolean); override; procedure DeleteRowsOrCols(const aRow, aCount: word; const SheetInfo: TSheetInfo; const UseCols: boolean);override; function CheckCell(const aRow, aCol: integer; var CellBounds: TXlsCellRange): boolean; function MergedCount: integer; function MergedCell(const i: integer): TXlsCellRange; procedure PreMerge(var R1,C1,R2,C2: integer); procedure MergeCells(const FirstRow, FirstCol, LastRow, LastCol: integer); procedure UnMergeCells(const FirstRow, FirstCol, LastRow, LastCol: integer); end; ClassOfTRangeEntry = class of TRangeEntry; implementation { TRangeValuesList } procedure TRangeValuesList.CopyFrom( const RVL: TRangeValuesList); var i: integer; R: PExcelRange; begin for i:=0 to RVL.Count-1 do begin New(R); try R^:=PExcelRange(RVL[i])^; Add(R); except FreeAndNil(R); raise; end; //except end; end; constructor TRangeValuesList.Create(const aMaxRangesPerRecord: integer; const aOtherDataLen: word); begin inherited Create; MaxRangesPerRecord := aMaxRangesPerRecord; FOtherDataLen:= aOtherDataLen; end; procedure TRangeValuesList.ArrangeInsertRowsAndCols(const aRowPos, aRowCount, aColPos, aColCount: integer); var i:integer; begin for i:=Count -1 downto 0 do begin if PExcelRange(Items[i]).R1>= aRowPos then IncMaxMin( PExcelRange(Items[i]).R1, aRowCount, Max_Rows, aRowPos); if PExcelRange(Items[i]).R2>= aRowPos then IncMaxMin( PExcelRange(Items[i]).R2, aRowCount, Max_Rows, PExcelRange(Items[i]).R1); if PExcelRange(Items[i]).C1>= aColPos then IncMaxMin( PExcelRange(Items[i]).C1, aColCount, Max_Columns, aColPos); if PExcelRange(Items[i]).C2>= aColPos then IncMaxMin( PExcelRange(Items[i]).C2, aColCount, Max_Columns, PExcelRange(Items[i]).C1); end; end; procedure TRangeValuesList.CopyIntersectRange(const R, Rx: PExcelRange; const NewFirstRow, NewLastRow, DestRow, aCount: integer; var MinR1, MaxR2: Word); var NewRange, NewRangex: PExcelRange; k, Lc: integer; begin Lc:=(NewLastRow-NewFirstRow+1)* aCount; if (Rx.R1<=NewFirstRow) and (Rx.R2>=NewLastRow) then // Just copy one big range begin New(NewRange); try NewRangex:=PExcelRange(PAddress(NewRange)+(PAddress(Rx)-PAddress(R))); NewRange^:=R^; NewRangex.R1:=DestRow; NewRangex.R2:=DestRow+Lc-1; Add(NewRange); if NewRangex.R1< MinR1 then MinR1:=NewRangex.R1; if NewRangex.R2> MaxR2 then MaxR2:=NewRangex.R2; except Dispose(NewRange); raise; end; //Except end else // We have to copy one small range for each aCount begin for k:=0 to aCount -1 do begin New(NewRange); try NewRangex:=PExcelRange(PAddress(NewRange)+(PAddress(Rx)-PAddress(R))); NewRange^:=R^; NewRangex.R1:=DestRow+(NewLastRow-NewFirstRow+1)*k; if Rx.R1>NewFirstRow then inc(NewRangex.R1, Rx.R1-NewFirstRow); NewRangex.R2:=DestRow+(NewLastRow-NewFirstRow+1)*(k+1)-1; if Rx.R2<NewLastRow then dec(NewRangex.R2, NewLastRow-Rx.R2); Add(NewRange); if NewRangex.R1< MinR1 then MinR1:=NewRangex.R1; if NewRangex.R2> MaxR2 then MaxR2:=NewRangex.R2; except Dispose(NewRange); raise; end; //Except end; end; end; procedure TRangeValuesList.CopyRowsInclusive(const FirstRow, LastRow, DestRow, aCount: integer; var MinR1, MaxR2: word; const UseCols: boolean); var i, Lc:integer; R, Rx: PExcelRange; NewFirstRow, NewLastRow: integer; begin Lc:=(LastRow-FirstRow+1)* aCount; if FirstRow<DestRow then NewFirstRow:=FirstRow else NewFirstRow:=FirstRow+ Lc; if LastRow<DestRow then NewLastRow:=LastRow else NewLastRow:=LastRow+Lc; for i:=0 to Count-1 do begin R:=PExcelRange(Items[i]); if UseCols then Rx:=PExcelRange(PAddress(R)+2*SizeOf(Word)) else Rx:=R; //when using cols, we fool the record so R1 really means C1. We can't use C1 there. if (Rx.R1<= NewLastRow) and (Rx.R2>= NewFirstRow) then begin //First Case, Block copied is above the original if (FirstRow>=DestRow) then if (Rx.R1<DestRow + Lc) then //nothing, range is automatically expanded else if (Rx.R1=DestRow + Lc) and( Rx.R2 >=NewLastRow) then //expand the range to include inserted rows begin Dec(Rx.R1, Lc); if Rx.R1< MinR1 then MinR1:=Rx.R1; end else CopyIntersectRange(R, Rx, NewFirstRow, NewLastRow, DestRow, aCount, MinR1, MaxR2) //We have to Copy the intersecting range, and clip the results //Second Case, Block copied is below the original else if (Rx.R2>DestRow-1) then //nothing, range is automatically expanded else if (Rx.R2=DestRow -1) and (Rx.R1<=NewFirstRow) then //expand the range to include inserted rows begin Inc(Rx.R2, Lc); if Rx.R2> MaxR2 then MaxR2:=Rx.R2; end else CopyIntersectRange(R, Rx, NewFirstRow, NewLastRow, DestRow, aCount, MinR1, MaxR2); //We have to Copy the intersecting range, and clip the results end; end; end; procedure TRangeValuesList.CopyRowsExclusive(const FirstRow, LastRow, DestRow, aCount: integer; const UseCols: boolean); var i, k, Lc:integer; R, Rx, NewRange, NewRangex: PExcelRange; NewFirstRow, NewLastRow, z: integer; xMaxRows: integer; begin Lc:=(LastRow-FirstRow+1)* aCount; if FirstRow<DestRow then NewFirstRow:=FirstRow else NewFirstRow:=FirstRow+ Lc; if LastRow<DestRow then NewLastRow:=LastRow else NewLastRow:=LastRow+Lc; if UseCols then xMaxRows:=Max_Columns else xMaxRows:=Max_Rows; for i:=0 to Count-1 do begin R:=PExcelRange(Items[i]); if UseCols then Rx:=PExcelRange(PAddress(R)+2*SizeOf(Word)) else Rx:=R; //when using cols, we fool the record so R1 really means C1. We can't use C1 there. if (Rx.R1>= NewFirstRow) and (Rx.R2<= NewLastRow) then for k:=0 to aCount-1 do begin New(NewRange); try NewRangex:=PExcelRange(PAddress(NewRange)+(PAddress(Rx)-PAddress(R))); NewRange^:=R^; if (FirstRow>=DestRow) then z:=k+1 else z:=-k; IncMax(NewRangex.R1, DestRow - FirstRow -(LastRow-FirstRow+1)*z, xMaxRows); IncMax(NewRangex.R2, DestRow - FirstRow -(LastRow-FirstRow+1)*z, xMaxRows); Add(NewRange); except Dispose(NewRange); raise; end; //Except end; end; end; procedure TRangeValuesList.DeleteRows(const aRow, aCount: integer; const Allow1Cell: boolean; const UseCols: boolean); var i:integer; R:PExcelRange; ColsEqual: boolean; begin for i:=Count-1 downto 0 do begin if UseCols then R:=PExcelRange(PAddress(Items[i])+2*SizeOf(Word)) else R:=PExcelRange(Items[i]); //when using cols, we fool the record so R1 really means C1. We can't use C1 there. if UseCols then ColsEqual:=PExcelRange(Items[i]).R1=PExcelRange(Items[i]).R2 else ColsEqual:=(R.C1=R.C2); if (R.R1>= aRow) and ((R.R2< aRow+aCount) or (not Allow1Cell and (R.R2=aRow+aCount) and ColsEqual)) then Delete(i); end; end; type //Just to avoid including windows.pas on d5 TRect1 = packed record Left, Top, Right, Bottom: Longint; end; procedure TRangeValuesList.PreAddNewRange(var R1,C1,R2,C2: integer); var i: integer; OutRect: TRect1; R: PExcelRange; begin //Check ranges are valid if (R1<0) or (R2<R1) or (R2>Max_Rows) or (C1<0) or (C2<C1) or (C2>Max_Columns) then exit; if (R1=R2)and(C1=C2) then exit; for i:=Count-1 downto 0 do begin R:=PExcelRange(Items[i]); OutRect.Left:=Max(R.C1, C1); OutRect.Top:=Max(R.R1, R1); OutRect.Right:=Min(R.C2, C2); OutRect.Bottom:=Min(R.R2, R2); if (OutRect.Left<=OutRect.Right)and(OutRect.Top<=OutRect.Bottom) then //found begin R1:=Min(R.R1, R1); R2:=Max(R.R2, R2); C1:=Min(R.C1, C1); C2:=Max(R.C2, C2); Delete(i); end; end; end; //We always have to call PreAddNewRange to verify it doesn't exist procedure TRangeValuesList.AddNewRange(const FirstRow, FirstCol, LastRow, LastCol: integer); var NewRange: PExcelRange; begin //Check ranges are valid if (FirstRow<0) or (LastRow<FirstRow) or (LastRow>Max_Rows) or (FirstCol<0) or (LastCol<FirstCol) or (LastCol>Max_Columns) then exit; if (FirstRow=LastRow)and(FirstCol=LastCol) then exit; New(NewRange); try NewRange.R1:=FirstRow; NewRange.R2:=LastRow; NewRange.C1:=FirstCol; NewRange.C2:=LastCol; add(NewRange); except Dispose(NewRange); raise; end; //Except end; procedure TRangeValuesList.Load(const aRecord: TBaseRecord; const aPos: integer); var i: integer; n: word; MyPos: integer; MyRecord: TBaseRecord; ExcelRange: PExcelRange; begin MyPos:= aPos; MyRecord:= aRecord; ReadMem(MyRecord, MyPos, SizeOf(n), @n); for i:=0 to n-1 do begin New(ExcelRange); try ReadMem(MyRecord, MyPos, SizeOf(TExcelRange), ExcelRange); Add(ExcelRange); ExcelRange:=nil; finally Dispose(ExcelRange); end; //finally end; end; procedure TRangeValuesList.Notify(Ptr: Pointer; Action: TListNotification); begin if Action = lnDeleted then Dispose(PExcelRange(Ptr)); inherited Notify(Ptr, Action); end; //------------ methods with "R" at the end add new records and don't use continue ---------------// function TRangeValuesList.RepeatCountR(const aCount: integer): integer; const Rl = SizeOf(TExcelRange); var OneRecCount: integer; begin OneRecCount := MaxRangesPerRecord; if aCount>0 then Result:= (aCount-1) div OneRecCount +1 else Result:=1; end; procedure TRangeValuesList.SaveToStreamR(const DataStream: TOle2File; const Line: integer); const Rl = SizeOf(TExcelRange); var OneRecCount, i: integer; myCount: word; begin OneRecCount := MaxRangesPerRecord ; if (Line+1)*OneRecCount >Count then MyCount:=Count-Line*OneRecCount else MyCount:=OneRecCount; DataStream.WriteMem(MyCount, SizeOf(MyCount)); for i:=Line*OneRecCount to Line*OneRecCount+myCount-1 do DataStream.WriteMem(PExcelRange(Items[i])^, Rl); end; function TRangeValuesList.NextInRange(const Range: TXlsCellRange; const k: integer): integer; var i: integer; begin Result:=-1; for i:=k+1 to Count-1 do if (Range.Top<= PExcelRange(Items[i]).R1 ) and (Range.Bottom>= PExcelRange(Items[i]).R2 ) and (Range.Left<= PExcelRange(Items[i]).C1 ) and (Range.Right>= PExcelRange(Items[i]).C2 ) then begin Result:=i; exit; end; end; procedure TRangeValuesList.SaveRangeToStreamR(const DataStream: TOle2File; const Line: integer; const aCount: integer; const Range: TXlsCellRange); const Rl = SizeOf(TExcelRange); var OneRecCount, i, k: integer; myCount: word; begin OneRecCount := MaxRangesPerRecord ; if (Line+1)*OneRecCount >aCount then MyCount:=aCount-Line*OneRecCount else MyCount:=OneRecCount; DataStream.WriteMem(MyCount, SizeOf(MyCount)); k:=NextInRange(Range, -1); for i:=Line*OneRecCount to Line*OneRecCount+myCount-1 do begin DataStream.WriteMem(PExcelRange(Items[k])^, Rl); k:=NextInRange(Range, k); end; end; function TRangeValuesList.TotalSizeR(const aCount:integer): int64; const Rl = SizeOf(TExcelRange); begin Result := (SizeOf(TRecordHeader)+ 2+ FOtherDataLen)* RepeatCountR(aCount) //Base data + Rl*aCount; // Registers end; function TRangeValuesList.RecordSizeR(const Line: integer; const aCount:integer): integer; const Rl = SizeOf(TExcelRange); var OneRecCount, MyCount: integer; begin OneRecCount := MaxRangesPerRecord; if (Line+1)*OneRecCount >aCount then MyCount:=aCount-Line*OneRecCount else MyCount:=OneRecCount; Result:= 2+ FOtherDataLen+MyCount*Rl; end; function TRangeValuesList.CountRangeRecords(const Range: TXlsCellRange): integer; var i: integer; begin Result:=0; for i:=0 to Count-1 do if (Range.Top<= PExcelRange(Items[i]).R1 ) and (Range.Bottom>= PExcelRange(Items[i]).R2 ) and (Range.Left<= PExcelRange(Items[i]).C1 ) and (Range.Right>= PExcelRange(Items[i]).C2 ) then Inc(Result); end; { TRangeEntry } function TRangeEntry.CopyTo: TRangeEntry; begin if Self=nil then Result:= nil //for this to work, this cant be a virtual method else Result:=DoCopyTo; end; constructor TRangeEntry.Create; begin inherited; end; destructor TRangeEntry.Destroy; begin FreeAndNil(RangeValuesList); inherited; end; function TRangeEntry.DoCopyTo: TRangeEntry; begin Result:= ClassOfTRangeEntry(ClassType).Create; Result.RangeValuesList.CopyFrom(RangeValuesList); end; procedure TRangeEntry.DeleteRowsOrCols(const aRow, aCount: word; const SheetInfo: TSheetInfo; const UseCols: boolean); begin if UseCols then ArrangeInsertRowsAndCols(0, 0, aRow, -aCount, SheetInfo) else ArrangeInsertRowsAndCols(aRow, -aCount, 0, 0, SheetInfo); end; procedure TRangeEntry.InsertAndCopyRowsOrCols(const FirstRow, LastRow, DestRow, aCount: integer; const SheetInfo: TSheetInfo; const UseCols: boolean); begin if UseCols then ArrangeInsertRowsAndCols(0,0,DestRow, (LastRow-FirstRow+1)* aCount, SheetInfo) else ArrangeInsertRowsAndCols(DestRow, (LastRow-FirstRow+1)* aCount,0,0, SheetInfo); end; procedure TRangeEntry.ArrangeInsertRowsAndCols(const aRowPos, aRowCount, aColPos, aColCount:integer; const SheetInfo: TSheetInfo); begin RangeValuesList.ArrangeInsertRowsAndCols(aRowPos, aRowCount, aColPos, aColCount); end; { TMergedCells } function TMergedCells.CheckCell(const aRow, aCol: integer; var CellBounds: TXlsCellRange): boolean; var i: integer; begin Result:=false; for i:=0 to RangeValuesList.Count-1 do if (PExcelRange(RangeValuesList[i]).R1<=aRow) and (PExcelRange(RangeValuesList[i]).R2>=aRow) and (PExcelRange(RangeValuesList[i]).C1<=aCol) and (PExcelRange(RangeValuesList[i]).C2>=aCol) then begin CellBounds.Left:= PExcelRange(RangeValuesList[i]).C1; CellBounds.Top:= PExcelRange(RangeValuesList[i]).R1; CellBounds.Right:= PExcelRange(RangeValuesList[i]).C2; CellBounds.Bottom:= PExcelRange(RangeValuesList[i]).R2; Result:=true; exit; end; end; procedure TMergedCells.Clear; begin if RangeValuesList<>nil then RangeValuesList.Clear; end; constructor TMergedCells.Create; begin inherited; RangeValuesList:= TRangeValuesList.Create(513, 0); end; procedure TMergedCells.DeleteRowsOrCols(const aRow, aCount: word; const SheetInfo: TSheetInfo; const UseCols: boolean); begin RangeValuesList.DeleteRows(aRow, aCount, false, UseCols); inherited; end; procedure TMergedCells.InsertAndCopyRowsOrCols(const FirstRow, LastRow, DestRow, aCount: integer; const SheetInfo: TSheetInfo; const UseCols: boolean); begin inherited; RangeValuesList.CopyRowsExclusive(FirstRow, LastRow, DestRow, aCount, UseCols); end; procedure TMergedCells.LoadFromStream(const DataStream: TOle2File; var RecordHeader: TRecordHeader; const First: TRangeRecord); var aPos: integer; begin Clear; aPos:=0; RangeValuesList.Load(First, aPos); First.Free; end; procedure TMergedCells.UnMergeCells(const FirstRow, FirstCol, LastRow, LastCol: integer); var i: integer; begin for i:=RangeValuesList.Count-1 downto 0 do if (PExcelRange(RangeValuesList[i]).R1=FirstRow) and (PExcelRange(RangeValuesList[i]).R2=LastRow) and (PExcelRange(RangeValuesList[i]).C1=FirstCol) and (PExcelRange(RangeValuesList[i]).C2=LastCol) then begin RangeValuesList.Delete(i); end; end; //Always call premergecell first... procedure TMergedCells.MergeCells(const FirstRow, FirstCol, LastRow, LastCol: integer); begin RangeValuesList.AddNewRange(FirstRow, FirstCol, LastRow, LastCol); end; procedure TMergedCells.PreMerge(var R1, C1, R2, C2: integer); begin RangeValuesList.PreAddNewRange(R1, C1, R2, C2); end; procedure TMergedCells.SaveRangeToStream(const DataStream: TOle2File; const CellRange: TXlsCellRange); var RecordHeader: TRecordHeader; i: integer; Rc: integer; begin Rc:=RangeValuesList.CountRangeRecords(CellRange); if Rc=0 then exit; //don't save empty MergedCells RecordHeader.Id:= xlr_CELLMERGING; for i:=0 to RangeValuesList.RepeatCountR(Rc)-1 do begin RecordHeader.Size:=RangeValuesList.RecordSizeR(i,Rc); DataStream.WriteMem(RecordHeader, SizeOf(RecordHeader)); RangeValuesList.SaveRangeToStreamR(DataStream, i, Rc, CellRange); end; end; procedure TMergedCells.SaveToStream(const DataStream: TOle2File); var RecordHeader: TRecordHeader; i: integer; begin if RangeValuesList.Count=0 then exit; //don't save empty MergedCells RecordHeader.Id:= xlr_CELLMERGING; for i:=0 to RangeValuesList.RepeatCountR(RangeValuesList.Count)-1 do begin RecordHeader.Size:=RangeValuesList.RecordSizeR(i, RangeValuesList.Count); DataStream.WriteMem(RecordHeader, SizeOf(RecordHeader)); RangeValuesList.SaveToStreamR(DataStream, i); end; end; function TMergedCells.TotalRangeSize(const CellRange: TXlsCellRange): int64; begin if RangeValuesList.Count=0 then Result:=0 else Result:= RangeValuesList.TotalSizeR(RangeValuesList.CountRangeRecords(CellRange)) ; end; function TMergedCells.TotalSize: int64; begin if RangeValuesList.Count=0 then TotalSize:=0 else TotalSize:= RangeValuesList.TotalSizeR(RangeValuesList.Count); end; function TMergedCells.MergedCount: integer; begin Result:=RangeValuesList.Count; end; function TMergedCells.MergedCell(const i: integer): TXlsCellRange; begin Result.Left:=PExcelRange(RangeValuesList[i]).C1; Result.Top:=PExcelRange(RangeValuesList[i]).R1; Result.Right:=PExcelRange(RangeValuesList[i]).C2; Result.Bottom:=PExcelRange(RangeValuesList[i]).R2; end; end.
{ rxlogin unit Copyright (C) 2005-2010 Lagunov Aleksey alexs@yandex.ru and Lazarus team original conception from rx library for Delphi (c) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit rxlogin; {$I RX.INC} interface uses LResources, LCLType, LCLIntf, SysUtils, LMessages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons; type TUpdateCaption = (ucNoChange, ucAppTitle, ucFormCaption); TRxLoginOption = (rloCustomSelect, rloMoreBtn, rloHelpBtn); TRxLoginOptions = set of TRxLoginOption; TRxLoginStorageParam = (rlsUserName, rlsTop, rlsLeft, rlsDetailStatus, rlsDetailItem); TRxLoginStorageParams = set of TRxLoginStorageParam; TRxLoginEvent = procedure(Sender: TObject; const UserName, Password: string; var AllowLogin: Boolean) of object; TCheckUnlockEvent = function(const Password: string): Boolean of object; TUnlockAppEvent = procedure(Sender: TObject; const UserName, Password: string; var AllowUnlock: Boolean) of object; TRxLoginForm = class; { TRxCustomLogin } TRxCustomLogin = class(TComponent) private FActive: Boolean; FAttemptNumber: Integer; FDetailItem: integer; FDetailItems: TStrings; FLoggedUser: string; FMaxPasswordLen: Integer; FAllowEmpty: Boolean; FLoginOptions: TRxLoginOptions; FShowDetails: boolean; FStorageParams: TRxLoginStorageParams; FUpdateCaption: TUpdateCaption; FIniFileName: string; FUseRegistry: Boolean; FLocked: Boolean; FUnlockDlgShowing: Boolean; FSaveOnRestore: TNotifyEvent; FAfterLogin: TNotifyEvent; FBeforeLogin: TNotifyEvent; FOnUnlock: TCheckUnlockEvent; FOnUnlockApp: TUnlockAppEvent; FOnIconDblClick: TNotifyEvent; function GetIniFileName: string; procedure SetDetailItems(const AValue: TStrings); procedure SetLoginOptions(const AValue: TRxLoginOptions); procedure SetShowDetails(const AValue: boolean); function UnlockHook(var Message: TLMessage): Boolean; protected function CheckUnlock(const UserName, Password: string): Boolean; dynamic; function CreateLoginForm(UnlockMode: Boolean): TRxLoginForm; virtual; procedure DoAfterLogin; dynamic; procedure DoBeforeLogin; dynamic; procedure DoIconDblCLick(Sender: TObject); dynamic; function DoLogin(var UserName: string): Boolean; virtual; abstract; function DoUnlockDialog: Boolean; virtual; procedure SetLoggedUser(const Value: string); procedure DoUpdateCaption; procedure UnlockOkClick(Sender: TObject); property Active: Boolean read FActive write FActive default True; property AllowEmptyPassword: Boolean read FAllowEmpty write FAllowEmpty default True; property AttemptNumber: Integer read FAttemptNumber write FAttemptNumber default 3; property IniFileName: string read GetIniFileName write FIniFileName; property MaxPasswordLen: Integer read FMaxPasswordLen write FMaxPasswordLen default 0; property UpdateCaption: TUpdateCaption read FUpdateCaption write FUpdateCaption default ucNoChange; property UseRegistry: Boolean read FUseRegistry write FUseRegistry default False; property ShowDetails: boolean read FShowDetails write SetShowDetails; property StorageParams:TRxLoginStorageParams read FStorageParams write FStorageParams default [rlsUserName]; property DetailItems:TStrings read FDetailItems write SetDetailItems; property DetailItem:integer read FDetailItem write FDetailItem; property LoginOptions:TRxLoginOptions read FLoginOptions write SetLoginOptions default [rloCustomSelect, rloMoreBtn, rloHelpBtn]; property AfterLogin: TNotifyEvent read FAfterLogin write FAfterLogin; property BeforeLogin: TNotifyEvent read FBeforeLogin write FBeforeLogin; property OnUnlock: TCheckUnlockEvent read FOnUnlock write FOnUnlock; { obsolete } property OnUnlockApp: TUnlockAppEvent read FOnUnlockApp write FOnUnlockApp; property OnIconDblClick: TNotifyEvent read FOnIconDblClick write FOnIconDblClick; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Login: Boolean; virtual; procedure TerminateApplication; procedure Lock; property LoggedUser: string read FLoggedUser; end; { TRxLoginDialog } TRxLoginDialog = class(TRxCustomLogin) private FOnCheckUser: TRxLoginEvent; FUserName:string; FFormTop:integer; FFormLeft:integer; procedure OkButtonClick(Sender: TObject); procedure WriteParams; procedure LoadParams; protected function DoCheckUser(const UserName, Password: string): Boolean; dynamic; function DoLogin(var UserName: string): Boolean; override; procedure Loaded; override; published property Active; property AttemptNumber; property IniFileName; property DetailItems; property DetailItem; property MaxPasswordLen; property UpdateCaption; property UseRegistry; property ShowDetails; property LoginOptions; property StorageParams; property OnCheckUser: TRxLoginEvent read FOnCheckUser write FOnCheckUser; property AfterLogin; property BeforeLogin; property OnUnlockApp; property OnIconDblClick; end; { TRxLoginForm } TRxLoginForm = class(TForm) AppIcon: TImage; btnHelp: TBitBtn; btnMore: TBitBtn; btnCancel: TBitBtn; KeyImage: TImage; HintLabel: TLabel; btnOK: TBitBtn; UserNameLabel: TLabel; PasswordLabel: TLabel; UserNameEdit: TEdit; PasswordEdit: TEdit; AppTitleLabel: TLabel; DataBaseLabel: TLabel; CustomCombo: TComboBox; procedure btnMoreClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure FormShow(Sender: TObject); private FSelectDatabase: Boolean; FUnlockMode: Boolean; FAttempt: Integer; FOnFormShow: TNotifyEvent; FOnOkClick: TNotifyEvent; function GetShowDetailParams: boolean; procedure SetLoginOptions(const AValue: TRxLoginOptions); procedure SetShowDetailParams(const AValue: boolean); public { Public declarations } AttemptNumber: Integer; property Attempt: Integer read FAttempt; property SelectDatabase: Boolean read FSelectDatabase write FSelectDatabase; property OnFormShow: TNotifyEvent read FOnFormShow write FOnFormShow; property OnOkClick: TNotifyEvent read FOnOkClick write FOnOkClick; property ShowDetailParams:boolean read GetShowDetailParams write SetShowDetailParams; property LoginOptions:TRxLoginOptions write SetLoginOptions; end; function CreateLoginDialog(UnlockMode, ASelectDatabase: Boolean; FormShowEvent, OkClickEvent: TNotifyEvent): TRxLoginForm; implementation uses Registry, IniFiles, RxAppUtils, RxDConst, VclUtils, RxConst; const keyLoginSection = 'Login Dialog'; keyLastLoginUserName = 'Last Logged User'; keyLastLoginFormTop = 'Last Logged Form Top'; keyLastLoginFormLeft = 'Last Logged Form Left'; keyLastLoginFormDetailStatus = 'Last Logged Detail Status'; keyLastLoginFormDetailSelected = 'Last Logged Selected Detail'; function CreateLoginDialog(UnlockMode, ASelectDatabase: Boolean; FormShowEvent, OkClickEvent: TNotifyEvent): TRxLoginForm; begin Result := TRxLoginForm.Create(Application); with Result do begin FSelectDatabase := ASelectDatabase; FUnlockMode := UnlockMode; if FUnlockMode then begin FormStyle := fsNormal; FSelectDatabase := False; end else begin FormStyle := fsStayOnTop; end; OnFormShow := FormShowEvent; OnOkClick := OkClickEvent; end; end; { TRxCustomLogin } constructor TRxCustomLogin.Create(AOwner: TComponent); begin inherited Create(AOwner); FDetailItems:=TStringList.Create; FActive := True; FAttemptNumber := 3; FAllowEmpty := True; FUseRegistry := False; FStorageParams:=[rlsUserName]; FLoginOptions:=[rloCustomSelect, rloMoreBtn, rloHelpBtn]; end; destructor TRxCustomLogin.Destroy; begin if FLocked then begin // Application.UnhookMainWindow(UnlockHook); FLocked := False; end; FreeAndNil(FDetailItems); inherited Destroy; end; function TRxCustomLogin.GetIniFileName: string; begin Result := FIniFileName; if (Result = '') and not (csDesigning in ComponentState) then begin if UseRegistry then Result := GetDefaultIniRegKey else Result := GetDefaultIniName; end; end; procedure TRxCustomLogin.SetDetailItems(const AValue: TStrings); begin if Assigned(AValue) then FDetailItems.Assign(AValue); end; procedure TRxCustomLogin.SetLoginOptions(const AValue: TRxLoginOptions); begin if FLoginOptions=AValue then exit; FLoginOptions:=AValue; end; procedure TRxCustomLogin.SetShowDetails(const AValue: boolean); begin if FShowDetails=AValue then exit; FShowDetails:=AValue; end; procedure TRxCustomLogin.SetLoggedUser(const Value: string); begin FLoggedUser := Value; end; procedure TRxCustomLogin.DoAfterLogin; begin if Assigned(FAfterLogin) then FAfterLogin(Self); end; procedure TRxCustomLogin.DoBeforeLogin; begin if Assigned(FBeforeLogin) then FBeforeLogin(Self); end; procedure TRxCustomLogin.DoIconDblCLick(Sender: TObject); begin if Assigned(FOnIconDblClick) then FOnIconDblClick(Self); end; procedure TRxCustomLogin.DoUpdateCaption; var F: TForm; begin F := Application.MainForm; if (F = nil) and (Owner is TForm) then F := Owner as TForm; if (F <> nil) and (LoggedUser <> '') then case UpdateCaption of ucAppTitle: F.Caption := Format('%s (%s)', [Application.Title, LoggedUser]); ucFormCaption: begin F.Caption := Format('%s (%s)', [F.Caption, LoggedUser]); UpdateCaption := ucNoChange; end; end; end; function TRxCustomLogin.Login: Boolean; var LoginName: string; begin LoginName := EmptyStr; DoBeforeLogin; Result := DoLogin(LoginName); if Result then begin SetLoggedUser(LoginName); DoUpdateCaption; DoAfterLogin; end; end; procedure TRxCustomLogin.Lock; begin // FSaveOnRestore := Application.OnRestore; Application.Minimize; // Application.HookMainWindow(UnlockHook); FLocked := True; end; procedure TRxCustomLogin.TerminateApplication; begin with Application do begin ShowMainForm := False; { if Application.Handle <> 0 then ShowOwnedPopups(Handle, False);} Terminate; end; CallTerminateProcs; Halt(10); end; procedure TRxCustomLogin.UnlockOkClick(Sender: TObject); var Ok: Boolean; begin with TRxLoginForm(Sender) do begin Ok := False; try Ok := CheckUnlock(UserNameEdit.Text, PasswordEdit.Text); except Application.HandleException(Self); end; if Ok then ModalResult := mrOk else ModalResult := mrCancel; end; end; function TRxCustomLogin.CheckUnlock(const UserName, Password: string): Boolean; begin Result := True; if Assigned(FOnUnlockApp) then FOnUnlockApp(Self, UserName, Password, Result) else if Assigned(FOnUnlock) then Result := FOnUnlock(Password); end; function TRxCustomLogin.CreateLoginForm(UnlockMode: Boolean): TRxLoginForm; begin Result := TRxLoginForm.Create(Application); with Result do begin FUnlockMode := UnlockMode; if FUnlockMode then begin FormStyle := fsNormal; FSelectDatabase := False; end else FormStyle := fsStayOnTop; if Assigned(Self.FOnIconDblClick) then begin with AppIcon do begin OnDblClick := @DoIconDblClick; Cursor := crHand; end; with KeyImage do begin OnDblClick := @DoIconDblClick; Cursor := crHand; end; end; PasswordEdit.MaxLength := FMaxPasswordLen; AttemptNumber := Self.AttemptNumber; end; end; function TRxCustomLogin.DoUnlockDialog: Boolean; begin with CreateLoginForm(True) do try OnFormShow := nil; OnOkClick := @UnlockOkClick; with UserNameEdit do begin Text := LoggedUser; ReadOnly := True; Font.Color := clGrayText; end; Result := ShowModal = mrOk; finally Free; end; end; function TRxCustomLogin.UnlockHook(var Message: TLMessage): Boolean; function DoUnlock: Boolean; var Popup: HWnd; begin (* with Application do if IsWindowVisible(Application.Handle) and IsWindowEnabled(Handle) then {$IFDEF WIN32} SetForegroundWindow(Handle); {$ELSE} BringWindowToTop(Handle); {$ENDIF} if FUnlockDlgShowing then begin Popup := GetLastActivePopup(Application.Handle); if (Popup <> 0) and IsWindowVisible(Popup) and (WindowClassName(Popup) = TRxLoginForm.ClassName) then begin {$IFDEF WIN32} SetForegroundWindow(Popup); {$ELSE} BringWindowToTop(Popup); {$ENDIF} end; //*) Result := False; (* Exit; end; FUnlockDlgShowing := True; try Result := DoUnlockDialog; finally FUnlockDlgShowing := False; end; if Result then begin Application.UnhookMainWindow(UnlockHook); FLocked := False; end;*) end; begin Result := False; if not FLocked then Exit; with Message do begin case Msg of { LM_QUERYOPEN: begin UnlockHook := not DoUnlock; end;} LM_SHOWWINDOW: if Bool(WParam) then begin UnlockHook := not DoUnlock; end; LM_SYSCOMMAND: if (WParam and $FFF0 = SC_RESTORE) { or (WParam and $FFF0 = SC_ZOOM) }then begin UnlockHook := not DoUnlock; end; end; end; end; { TRxLoginDialog } procedure TRxLoginDialog.Loaded; var FLoading: Boolean; begin FLoading := csLoading in ComponentState; inherited Loaded; if not (csDesigning in ComponentState) and FLoading then begin if Active and not Login then TerminateApplication; end; end; procedure TRxLoginDialog.OkButtonClick(Sender: TObject); var SC: Boolean; begin with TRxLoginForm(Sender) do begin {$IFDEF WIN32} SC := GetCurrentThreadID = MainThreadID; {$ELSE} SC := True; {$ENDIF} try if SC then Screen.Cursor := crHourGlass; try if DoCheckUser(UserNameEdit.Text, PasswordEdit.Text) then ModalResult := mrOk else ModalResult := mrNone; finally if SC then Screen.Cursor := crDefault; end; except Application.HandleException(Self); end; end; end; function TRxLoginDialog.DoCheckUser(const UserName, Password: string): Boolean; begin Result := True; if Assigned(FOnCheckUser) then FOnCheckUser(Self, UserName, Password, Result); end; procedure TRxLoginDialog.WriteParams; var Ini: TObject; begin try if UseRegistry then Ini := TRegIniFile.Create(IniFileName) else Ini := TIniFile.Create(IniFileName); try if rlsUserName in FStorageParams then IniWriteString(Ini, keyLoginSection, keyLastLoginUserName, FUserName); if rlsTop in FStorageParams then IniWriteInteger(Ini, keyLoginSection, keyLastLoginFormTop, FFormTop); if rlsLeft in FStorageParams then IniWriteInteger(Ini, keyLoginSection, keyLastLoginFormLeft, FFormLeft); if rlsDetailStatus in FStorageParams then IniWriteInteger(Ini, keyLoginSection, keyLastLoginFormDetailStatus, ord(FShowDetails)); if rlsDetailItem in FStorageParams then IniWriteInteger(Ini, keyLoginSection, keyLastLoginFormDetailSelected, FDetailItem); finally Ini.Free; end; except end; end; procedure TRxLoginDialog.LoadParams; var Ini: TObject; begin try if UseRegistry then begin Ini := TRegIniFile.Create(IniFileName); TRegIniFile(Ini).Access := KEY_READ; end else Ini := TIniFile.Create(IniFileName); try if rlsUserName in FStorageParams then FUserName:=IniReadString(Ini, keyLoginSection, keyLastLoginUserName, FUserName); if rlsTop in FStorageParams then FFormTop:=IniReadInteger(Ini, keyLoginSection, keyLastLoginFormTop, FFormTop); if rlsLeft in FStorageParams then FFormLeft:=IniReadInteger(Ini, keyLoginSection, keyLastLoginFormLeft, FFormLeft); if rlsDetailStatus in FStorageParams then FShowDetails:=IniReadInteger(Ini, keyLoginSection, keyLastLoginFormDetailStatus, ord(FShowDetails))=1; if rlsDetailItem in FStorageParams then FDetailItem:=IniReadInteger(Ini, keyLoginSection, keyLastLoginFormDetailSelected, FDetailItem); finally Ini.Free; end; except end; end; function TRxLoginDialog.DoLogin(var UserName: string): Boolean; var LoginForm:TRxLoginForm; begin try LoginForm:=CreateLoginForm(False); try FUserName:=UserName; LoginForm.OnOkClick := @Self.OkButtonClick; LoadParams; LoginForm.LoginOptions:=FLoginOptions; if rlsUserName in StorageParams then LoginForm.UserNameEdit.Text := FUserName; if rlsTop in StorageParams then LoginForm.Top:=FFormTop; if rlsLeft in StorageParams then LoginForm.Left:=FFormLeft; if rloCustomSelect in LoginOptions then begin LoginForm.CustomCombo.Items.Assign(DetailItems); if (FDetailItem>=0) and (FDetailItem<DetailItems.Count) then LoginForm.CustomCombo.ItemIndex:=FDetailItem; end; LoginForm.ShowDetailParams:=ShowDetails; Result := (LoginForm.ShowModal = mrOk); if Result then begin if rlsTop in StorageParams then FFormTop:=LoginForm.Top; if rlsLeft in StorageParams then FFormLeft:=LoginForm.Left; if rloCustomSelect in LoginOptions then FDetailItem:=LoginForm.CustomCombo.ItemIndex; ShowDetails:=LoginForm.ShowDetailParams; UserName := LoginForm.UserNameEdit.Text; FUserName:=UserName; WriteParams; end; finally LoginForm.Free; end; except Application.HandleException(Self); Result := False; end; end; { TRxLoginForm } procedure TRxLoginForm.FormCreate(Sender: TObject); begin Icon.Assign(Application.Icon); // if Icon.Empty then Icon.Handle := LoadIcon(0, IDI_APPLICATION); AppIcon.Picture.Assign(Icon); AppTitleLabel.Caption := Format(SAppTitleLabel, [Application.Title]); PasswordLabel.Caption := SPasswordLabel; UserNameLabel.Caption := SUserNameLabel; end; procedure TRxLoginForm.btnMoreClick(Sender: TObject); begin ShowDetailParams:=not ShowDetailParams; end; procedure TRxLoginForm.btnOKClick(Sender: TObject); begin Inc(FAttempt); if Assigned(FOnOkClick) then FOnOkClick(Self) else ModalResult := mrOk; if (ModalResult <> mrOk) and (FAttempt >= AttemptNumber) then ModalResult := mrCancel; end; procedure TRxLoginForm.FormShow(Sender: TObject); var I: Integer; S: string; begin if FSelectDatabase then begin ClientHeight := CustomCombo.Top + PasswordEdit.Top - UserNameEdit.Top; S := SDatabaseName; I := Pos(':', S); if I = 0 then I := Length(S); DataBaseLabel.Caption := '&' + Copy(S, 1, I); end else begin DataBaseLabel.Visible := False; CustomCombo.Visible := False; btnMore.Visible := False; end; SetShowDetailParams(ShowDetailParams); if not FUnlockMode then begin HintLabel.Caption := SHintLabel; Caption := SRegistration; end else begin HintLabel.Caption := SUnlockHint; Caption := SUnlockCaption; end; if (UserNameEdit.Text = EmptyStr) and not FUnlockMode then ActiveControl := UserNameEdit else ActiveControl := PasswordEdit; if Assigned(FOnFormShow) then FOnFormShow(Self); FAttempt := 0; end; procedure TRxLoginForm.SetShowDetailParams(const AValue: boolean); begin DataBaseLabel.Visible:=AValue; CustomCombo.Visible:=AValue; if AValue then begin btnMore.Caption:=SMore2; btnCancel.AnchorSideTop.Control:=CustomCombo; Height := CustomCombo.Top + CustomCombo.Height + btnCancel.Height + 12; end else begin btnMore.Caption:=SMore1; btnCancel.AnchorSideTop.Control:=PasswordEdit; Height := PasswordEdit.Top + PasswordEdit.Height + btnCancel.Height + 12; end; end; function TRxLoginForm.GetShowDetailParams: boolean; begin Result:=CustomCombo.Visible; end; procedure TRxLoginForm.SetLoginOptions(const AValue: TRxLoginOptions); begin btnHelp.Visible:=rloHelpBtn in AValue; if not btnHelp.Visible then begin btnCancel.AnchorSideLeft.Side:=asrBottom; btnCancel.AnchorSideLeft.Control:=Self; end; btnMore.Visible:=rloMoreBtn in AValue; FSelectDatabase:=rloCustomSelect in AValue; end; initialization {$I rxlogin.lrs} end.
program FiboSum; { Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. } var fibo, next, tmp, sum : longint; { simple integer type can't handle values this big } begin fibo := 0; next := 1; sum := 0; while (next < 4000000) do begin tmp := fibo + next; fibo := next; next := tmp; write(fibo, #9); if (fibo mod 2 = 0) then sum := sum + fibo; end; writeln; write('The sum of the EVEN members of the Fibonacci sequence '); writeln('up to 4 million is:'); writeln(sum); readln; end.
unit uClassDef; interface uses Variants, Classes; type TRangeElementList=class; //Class to hold the information of individual Range Element TRangeElement=class(TObject) private FId:Integer; FDescription:string; FSizeDescription:string; FColorDescription:string; FQuantity:Integer; function CalcTotalPlannedQuantity(const ARangeElement:TRangeElement; var TotalQuantity:Integer):Integer; protected public SubElements:TRangeElementList; function HasSubElements():Boolean; function GetTotalPlannedQuantity():Integer; constructor Create;overload; constructor Create(const aId: Integer);overload; constructor Create(const aId:Integer; aQuantity:Integer);overload; destructor Destroy;override; published property Id:Integer read FId write FId; property Description:string read FDescription write FDescription; property SizeDescription:string read FSizeDescription write FSizeDescription; property ColorDescription:string read FColorDescription write FColorDescription; property Quantity:Integer read FQuantity write FQuantity; end; //Class to hold the information of List of Range Elements TRangeElementList=class(TList) private protected function Get(Index:Integer):TRangeElement; function GetById(aId:Integer):TRangeElement; public property Items[Index:Integer]:TRangeElement read Get; default; property ItemById[Id:Integer]:TRangeElement read GetById; function Add(ARangeElement:TRangeElement):Integer; procedure Insert(Index:Integer; ARangeElement:TRangeElement); constructor Create;overload; destructor Destroy;override; published end; //Class to hold the information of individual Range TRange=class(TObject) private FId:Integer; FDescription:string; protected public Elements:TRangeElementList; function HasElements():Boolean; function GetTotalPlannedQuantity():Integer;overload; function GetTotalPlannedQuantity(ARangeElement:TRangeElement):Integer;overload; constructor Create;overload; constructor Create(aID:Integer; aDescription:string);overload; destructor Destroy;override; published property Id:Integer read FId write FId; property Description:string read FDescription write FDescription; end; //Class to hold the information of List of Ranges TRangeList=class(TList) private protected function Get(Index:Integer):TRange; function GetById(aId:Integer):TRange; public property Items[Index:Integer]:TRange read Get; default; property ItemById[Id:Integer]:TRange read GetById; function Add(ARange:TRange):Integer; procedure Insert(Index:Integer; ARange:TRange); constructor Create;overload; destructor Destroy;override; published end; implementation uses MaskUtils, SysUtils; { TRangeElement } constructor TRangeElement.Create; begin Create(0); end; constructor TRangeElement.Create(const aId: Integer); begin Create(aId, 0); end; constructor TRangeElement.Create(const aId: Integer; aQuantity: Integer); begin FId := aId; FQuantity := aQuantity; SubElements := TRangeElementList.Create(); end; destructor TRangeElement.Destroy; var I:Integer; begin //SubElements are Pointer to Elements. //No need to destroy Sub Elements. //we need destroy only Elemetns no Sub Elements inherited; end; function TRangeElement.CalcTotalPlannedQuantity(const ARangeElement: TRangeElement; var TotalQuantity:Integer): Integer; var I:Integer; begin TotalQuantity := TotalQuantity + ARangeElement.Quantity; for I:=0 to ARangeElement.SubElements.Count-1 do begin CalcTotalPlannedQuantity(ARangeElement.SubElements[I], TotalQuantity) end; end; function TRangeElement.GetTotalPlannedQuantity: Integer; var TotalQuantity:Integer; begin TotalQuantity:=0; CalcTotalPlannedQuantity(Self, TotalQuantity); Result := TotalQuantity; end; function TRangeElement.HasSubElements: Boolean; begin Result := (SubElements.Count>0); end; { TRangeElementList } constructor TRangeElementList.Create; begin // end; function TRangeElementList.Add(ARangeElement: TRangeElement): Integer; begin Result := inherited Add(ARangeElement); end; destructor TRangeElementList.Destroy; begin // inherited; end; function TRangeElementList.Get(Index: Integer): TRangeElement; begin Result := TRangeElement(inherited Get(Index)); end; procedure TRangeElementList.Insert(Index: Integer; ARangeElement: TRangeElement); begin inherited Insert(Index, ARangeElement); end; function TRangeElementList.GetById(aId: Integer): TRangeElement; var I:Integer; begin Result := nil; for I:=0 to Self.Count-1 do begin if (Self[I].Id = aId) then begin Result := Self[I]; Break; end; end; end; { TRange } constructor TRange.Create; begin Create(0,''); end; constructor TRange.Create(aID: Integer; aDescription: string); begin FId := aID; FDescription := aDescription; Elements := TRangeElementList.Create(); end; destructor TRange.Destroy; var I:Integer; begin for I:=Elements.Count-1 downto 0 do begin Elements[I].Free; end; inherited; end; function TRange.GetTotalPlannedQuantity: Integer; var I:Integer; begin Result := 0; for I:=0 to Elements.Count -1 do begin Result := Result + Elements[I].GetTotalPlannedQuantity(); end; end; function TRange.GetTotalPlannedQuantity(ARangeElement: TRangeElement): Integer; begin Result := ARangeElement.GetTotalPlannedQuantity(); end; function TRange.HasElements: Boolean; begin Result := (Elements.Count>0); end; { TRangeList } constructor TRangeList.Create; begin // end; destructor TRangeList.Destroy; begin // inherited; end; function TRangeList.Get(Index: Integer): TRange; begin Result := TRange(inherited Get(Index)); end; function TRangeList.Add(ARange: TRange): Integer; begin Result := inherited Add(ARange); end; procedure TRangeList.Insert(Index: Integer; ARange: TRange); begin inherited Insert(Index, ARange); end; function TRangeList.GetById(aId: Integer): TRange; var I:Integer; begin Result := nil; for I:=0 to Self.Count -1 do begin if (Self[I].Id = aId) then begin Result := Self[I]; Break; end; end; end; end.
program COMPERR4 ( OUTPUT ) ; //*********************************** //$A+ //*********************************** var SNEU : STRING ( 70 ) ; function BLANKS_LEVEL ( X : INTEGER ; ZONE : CHAR ) : STRING ; //********************************************************** // generate blanks depending on level // x = computed nesting level // zone = zone a or b // if x > 1 and zone a, additional indentation needed //********************************************************** var N : STRING ( 80 ) ; begin (* BLANKS_LEVEL *) N := '' ; while X > 2 do begin N := N || ' ' ; X := X - 1 end (* while *) ; if X > 1 then if ZONE = 'A' then N := N || ' ' ; BLANKS_LEVEL := N end (* BLANKS_LEVEL *) ; function S1 ( const S : STRING ) : STRING ; begin (* S1 *) S1 := S end (* S1 *) ; function S2 ( const S : STRING ) : STRING ; begin (* S2 *) S2 := TRIM ( S ) end (* S2 *) ; begin (* HAUPTPROGRAMM *) //******************************************************* // testen left mit leerem string ... scheint zu klappen //******************************************************* SNEU := LEFT ( ' ' , 4 ) ; WRITELN ( 'res = <' , SNEU , '>' ) ; SNEU := LEFT ( '' , 4 ) ; WRITELN ( 'res = <' , SNEU , '>' ) ; //******************************************************************** // bei den folgenden Ausgaben sollte immer irgendein Name rauskommen //******************************************************************** WRITELN ( 's1 = ' , S1 ( 'Bernd ' ) ) ; WRITELN ( 's2 = ' , S2 ( 'Oppolzer' ) ) ; //******************************************************************** // bei den folgenden Ausgaben sollte immer irgendein Name rauskommen //******************************************************************** WRITELN ( 'Karst-Oppolzer sollte rauskommen' ) ; SNEU := BLANKS_LEVEL ( 3 , 'A' ) ; WRITELN ( 'res = <' , SNEU , '>' ) ; SNEU := S2 ( 'Karst-Oppolzer' ) ; WRITELN ( 'res = <' , SNEU , '>' ) ; SNEU := BLANKS_LEVEL ( 3 , 'A' ) || S2 ( 'Karst-Oppolzer' ) ; WRITELN ( 'res = <' , SNEU , '>' ) ; //******************************************************************** // hier klappt's //******************************************************************** WRITELN ( 'hier klappt''s' ) ; SNEU := BLANKS_LEVEL ( 3 , 'A' ) ; SNEU := SNEU || S2 ( 'Karst-Oppolzer' ) ; WRITELN ( 'res = <' , SNEU , '>' ) ; //******************************************************************** // hier wieder nicht //******************************************************************** WRITELN ( 'hier wieder nicht' ) ; SNEU := BLANKS_LEVEL ( 3 , 'A' ) || TRIM ( 'Karst-Oppolzer' ) ; WRITELN ( 'res = <' , SNEU , '>' ) ; //******************************************************************** // hier klappt's wieder //******************************************************************** WRITELN ( 'hier klappt''s wieder' ) ; SNEU := BLANKS_LEVEL ( 3 , 'A' ) ; SNEU := SNEU || TRIM ( 'Karst-Oppolzer' ) ; WRITELN ( 'res = <' , SNEU , '>' ) ; end (* HAUPTPROGRAMM *) .
// SAX for Pascal Helper Classes, Simple API for XML Interfaces in Pascal. // Ver 1.1 July 4, 2003 // http://xml.defined.net/SAX (this will change!) // Based on http://www.saxproject.org/ // No warranty; no copyright -- use this as you will. unit SAXHelpers; interface uses Classes, SysUtils, SAX, SAXExt; type // Helper Classes TAttributesImpl = class; TDefaultHandler = class; TLocatorImpl = class; TNamespaceContext = class; TNamespaceSupport = class; TXMLFilterImpl = class; TXMLReaderImpl = class; // Extension Helper Classes TAttributes2Impl = class; TDefaultHandler2 = class; TLocator2Impl = class; // Error Helper Classes TSAXError = class; TSAXParseError = class; TSAXNotRecognizedError = class; TSAXNotSupportedError = class; TSAXIllegalStateError = class; TSAXIllegalArgumentError = class; // Default implementation of the Attributes interface. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p>This class provides a default implementation of the SAX2 // <a href="../SAX/IAttributes.html">IAttributes</a> interface, with the // addition of manipulators so that the list can be modified or // reused.</p> // // <p>There are two typical uses of this class:</p> // // <ol> // <li>to take a persistent snapshot of an Attributes object // in a <a href="../SAX/IContentHandler.html#startElement">startElement</a> event; or</li> // <li>to construct or modify an IAttributes object in a SAX2 driver or filter.</li> // </ol> // // <p>This class replaces the now-deprecated SAX1 AttributeListImpl // class; in addition to supporting the updated Attributes // interface rather than the deprecated <a href="../SAX/IAttributeList.html">IAttributeList</a> // interface, it also includes a much more efficient // implementation using a single array rather than a set of Vectors.</p> // // @since SAX 2.0 TAttributesImpl = class(TInterfacedObject, IAttributes) private Flength : Integer; Fdata : array of SAXString; // Ensure the internal array's capacity. // // @param n The minimum number of attributes that the array must // be able to hold. procedure ensureCapacity(n : Integer); // Report a bad array index in a manipulator. // // @param index The index to report. // @exception Exception Always. procedure badIndex(index : Integer); protected // Return the number of attributes in the list. // // @return The number of attributes in the list. // @see <a href="../SAX/IAttributes.html#getLength">IAttributes.getLength</a> function getLength() : Integer; // Return an attribute's Namespace URI. // // @param index The attribute's index (zero-based). // @return The Namespace URI, the empty string if none is // available or if the index is out of range. // @see <a href="../SAX/IAttributes.html#getURI">IAttributes.getURI</a> function getURI(index : Integer) : SAXString; // Return an attribute's local name. // // @param index The attribute's index (zero-based). // @return The attribute's local name, the empty string if // none is available or if the index if out of range. // @see <a href="../SAX/IAttributes.html#getLocalName">IAttributes.getLocalName</a> function getLocalName(index : Integer) : SAXString; // Return an attribute's qualified (prefixed) name. // // @param index The attribute's index (zero-based). // @return The attribute's qualified name, the empty string if // none is available or if the index is out of bounds. // @see <a href="../SAX/IAttributes.html#getQName">IAttributes.getQName</a> function getQName(index : Integer) : SAXString; // Return an attribute's type by index. // // @param index The attribute's index (zero-based). // @return The attribute's type, 'CDATA' if the type is unknown, or an empty // string if the index is out of bounds. // @see <a href="../SAX/IAttributes.html#getType.Integer">IAttributes.getType(Integer)</a> function getType(index : Integer) : SAXString; overload; // Look up an attribute's type by Namespace-qualified name. // // @param uri The Namespace URI, or the empty string for a name // with no explicit Namespace URI. // @param localName The local name. // @return The attribute's type, or an empty if there is no // matching attribute. // @see <a href="../SAX/IAttributes.html#getType.SAXString.SAXString">IAttributes.getType(SAXString,SAXString)</a> function getType(const uri, localName : SAXString) : SAXString; overload; // Look up an attribute's type by qualified (prefixed) name. // // @param qName The qualified name. // @return The attribute's type, or an empty string if there is no // matching attribute. // @see <a href="../SAX/IAttributes.html#getType.SAXString">IAttributes.getType(SAXString)</a> function getType(const qName : SAXString) : SAXString; overload; // Return an attribute's value by index. // // @param index The attribute's index (zero-based). // @return The attribute's value or an empty string if the index is // out of bounds. // @see <a href="../SAX/IAttributes.html#getValue.Integer">IAttributes.getValue(Integer)</a> function getValue(index : Integer) : SAXString; overload; // Look up an attribute's value by Namespace-qualified name. // // @param uri The Namespace URI, or the empty string for a name // with no explicit Namespace URI. // @param localName The local name. // @return The attribute's value, or an empty string if there is no // matching attribute. // @see <a href="../SAX/IAttributes.html#getValue.SAXString.SAXString">IAttributes.getValue(SAXString,SAXString)</a> function getValue(const uri, localName : SAXString) : SAXString; overload; // Look up an attribute's value by qualified (prefixed) name. // // @param qName The qualified name. // @return The attribute's value, or an empty string if there is no // matching attribute. // @see <a href="../SAX/IAttributes.html#getValue.SAXString">IAttributes.getValue(SAXString)</a> function getValue(const qName : SAXString) : SAXString; overload; // Look up an attribute's index by Namespace name. // // <p>In many cases, it will be more efficient to look up the name once and // use the index query methods rather than using the name query methods // repeatedly.</p> // // @param uri The attribute's Namespace URI, or the empty // string if none is available. // @param localName The attribute's local name. // @return The attribute's index, or -1 if none matches. // @see <a href="../SAX/IAttributes.html#getIndex.SAXString.SAXString">IAttributes.getIndex(SAXString,SAXString)</a> function getIndex(const uri, localName : SAXString) : Integer; overload; // Look up an attribute's index by qualified (prefixed) name. // // @param qName The qualified name. // @return The attribute's index, or -1 if none matches. // @see <a href="../SAX/IAttributes.html#getIndex.SAXString">IAttributes.getIndex(SAXString)</a> function getIndex(const qName : SAXString) : Integer; overload; public // Construct a new, empty AttributesImpl object. constructor Create(); overload; // Copy an existing Attributes object. // // <p>This constructor is especially useful inside a // <a href="../SAX/IContentHandler.html#startElement">startElement</a> event.</p> // // @param atts The existing Attributes object. constructor Create(const atts : IAttributes); overload; // Standard default destructor // // @see <a href="../SAXHelpers/TAttributesImpl.html#create">TAttributesImpl.create</a> destructor Destroy(); override; // Clear the attribute list for reuse. // // <p>Note that little memory is freed by this call: // the current array is kept so it can be // reused.</p> procedure clear(); // Copy an entire Attributes object. // // <p>It may be more efficient to reuse an existing object // rather than constantly allocating new ones.</p> // // @param atts The attributes to copy. procedure setAttributes(const atts : IAttributes); virtual; // Add an attribute to the end of the list. // // <p>For the sake of speed, this method does no checking // to see if the attribute is already in the list: that is // the responsibility of the application.</p> // // @param uri The Namespace URI, or the empty string if // none is available or Namespace processing is not // being performed. // @param localName The local name, or the empty string if // Namespace processing is not being performed. // @param qName The qualified (prefixed) name, or the empty string // if qualified names are not available. // @param type The attribute type as a string. // @param value The attribute value. procedure addAttribute(const uri, localName, qName, attrType, value : SAXString); virtual; // Set an attribute in the list. // // <p>For the sake of speed, this method does no checking // for name conflicts or well-formedness: such checks are the // responsibility of the application.</p> // // @param index The index of the attribute (zero-based). // @param uri The Namespace URI, or the empty string if // none is available or Namespace processing is not // being performed. // @param localName The local name, or the empty string if // Namespace processing is not being performed. // @param qName The qualified name, or the empty string // if qualified names are not available. // @param type The attribute type as a string. // @param value The attribute value. // @exception Exception when the supplied index does not // point to an attribute in the list. procedure setAttribute(index : Integer; const uri, localName, qName, attrType, value : SAXString); // Remove an attribute from the list. // // @param index The index of the attribute (zero-based). // @exception Exception when the supplied index does not // point to an attribute in the list. procedure removeAttribute(index : Integer); virtual; // Set the Namespace URI of a specific attribute. // // @param index The index of the attribute (zero-based). // @param uri The attribute's Namespace URI, or the empty // string for none. // @exception Exception when the supplied index does not // point to an attribute in the list. procedure setURI(index : Integer; const uri : SAXString); // Set the local name of a specific attribute. // // @param index The index of the attribute (zero-based). // @param localName The attribute's local name, or the empty // string for none. // @exception Exception when the supplied index does not // point to an attribute in the list. procedure setLocalName(index : Integer; const localName : SAXString); // Set the qualified name of a specific attribute. // // @param index The index of the attribute (zero-based). // @param qName The attribute's qualified name, or the empty // string for none. // @exception Exception when the supplied index does not // point to an attribute in the list. procedure setQName(index : Integer; const qName : SAXString); // Set the type of a specific attribute. // // @param index The index of the attribute (zero-based). // @param type The attribute's type. // @exception Exception when the supplied index does not // point to an attribute in the list. procedure setType(index : Integer; const attrType : SAXString); // Set the value of a specific attribute. // // @param index The index of the attribute (zero-based). // @param value The attribute's value. // @exception Exception when the supplied index does not // point to an attribute in the list. procedure setValue(index : Integer; const value : SAXString); end; // Default base class for SAX2 event handlers. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p>This class is available as a convenience base class for SAX2 // applications: it provides default implementations for all of the // callbacks in the four core SAX2 handler classes:</p> // // <ul> // <li><a href="../SAX/IEntityResolver.html">IEntityResolver</a></li> // <li><a href="../SAX/IDTDHandler.html">IDTDHandler</a></li> // <li><a href="../SAX/IContentHandler.html">IContentHandler</a></li> // <li><a href="../SAX/IErrorHandler.html">IErrorHandler</a></li> // </ul> // // <p>Application writers can extend this class when they need to // implement only part of an interface; parser writers can // instantiate this class to provide default handlers when the // application has not supplied its own.</p> // // <p>This class replaces the deprecated SAX1 // HandlerBase class.</p> // // @since SAX 2.0 // @see <a href="../SAX/IEntityResolver.html">IEntityResolver</a> // @see <a href="../SAX/IDTDHandler.html">IDTDHandler</a> // @see <a href="../SAX/IContentHandler.html">IContentHandler</a> // @see <a href="../SAX/IErrorHandler.html">IErrorHandler</a> TDefaultHandler = class(TInterfacedObject, IEntityResolver, IDTDHandler, IContentHandler, IErrorHandler) protected // Resolve an external entity. // // <p>Always return nil, so that the parser will use the system // identifier provided in the XML document. This method implements // the SAX default behaviour: application writers can override it // in a subclass to do special translations such as catalog lookups // or URI redirection.</p> // // @param publicId The public identifer, or an empty string if none is // available. // @param systemId The system identifier provided in the XML // document. // @return The new input source, or nil to require the // default behaviour. // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IEntityResolver.html#resolveEntity">IEntityResolver.resolveEntity</a> function resolveEntity(const publicId, systemId : SAXString) : IInputSource; virtual; // Receive notification of a notation declaration. // // <p>By default, do nothing. Application writers may override this // method in a subclass if they wish to keep track of the notations // declared in a document.</p> // // @param name The notation name. // @param publicId The notation public identifier, or an empty string // if not available. // @param systemId The notation system identifier. // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IDTDHandler.html#notationDecl">IDTDHandler.notationDecl</a> procedure notationDecl(const name, publicId, systemId : SAXString); virtual; // Receive notification of an unparsed entity declaration. // // <p>By default, do nothing. Application writers may override this // method in a subclass to keep track of the unparsed entities // declared in a document.</p> // // @param name The entity name. // @param publicId The entity public identifier, or an empty string // if not available. // @param systemId The entity system identifier. // @param notationName The name of the associated notation. // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IDTDHandler.html#unparsedEntityDecl">IDTDHandler.unparsedEntityDecl</a> procedure unparsedEntityDecl(const name, publicId, systemId, notationName : SAXString); virtual; // Receive a Locator object for document events. // // <p>By default, do nothing. Application writers may override this // method in a subclass if they wish to store the locator for use // with other document events.</p> // // @param locator A locator for all SAX document events. // @see <a href="../SAX/IContentHandler.html#setDocumentLocator">IContentHandler.setDocumentLocator</a> // @see <a href="../SAX/ILocator.html">ILocator</a> procedure setDocumentLocator(const Locator: ILocator); virtual; // Receive notification of the beginning of the document. // // <p>By default, do nothing. Application writers may override this // method in a subclass to take specific actions at the beginning // of a document (such as allocating the root node of a tree or // creating an output file).</p> // // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IContentHandler.html#startDocument">IContentHandler.startDocument</a> procedure startDocument(); virtual; // Receive notification of the end of the document. // // <p>By default, do nothing. Application writers may override this // method in a subclass to take specific actions at the end // of a document (such as finalising a tree or closing an output // file).</p> // // @exception ESAXException Any SAX exception // @see <a href="../SAX/IContentHandler.html#endDocument">IContentHandler.endDocument</a> procedure endDocument(); virtual; // Receive notification of the start of a Namespace mapping. // // <p>By default, do nothing. Application writers may override this // method in a subclass to take specific actions at the start of // each Namespace prefix scope (such as storing the prefix mapping).</p> // // @param prefix The Namespace prefix being declared. // @param uri The Namespace URI mapped to the prefix. // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IContentHandler.html#startPrefixMapping">IContentHandler.startPrefixMapping</a> procedure startPrefixMapping(const prefix, uri : SAXString); virtual; // Receive notification of the end of a Namespace mapping. // // <p>By default, do nothing. Application writers may override this // method in a subclass to take specific actions at the end of // each prefix mapping.</p> // // @param prefix The Namespace prefix being declared. // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IContentHandler.html#endPrefixMapping">IContentHandler.endPrefixMapping</a> procedure endPrefixMapping(const prefix : SAXString); virtual; // Receive notification of the start of an element. // // <p>By default, do nothing. Application writers may override this // method in a subclass to take specific actions at the start of // each element (such as allocating a new tree node or writing // output to a file).</p> // // @param uri The Namespace URI, or the empty string if the // element has no Namespace URI or if Namespace // processing is not being performed. // @param localName The local name (without prefix), or the // empty string if Namespace processing is not being // performed. // @param qName The qualified name (with prefix), or the // empty string if qualified names are not available. // @param atts The attributes attached to the element. If // there are no attributes, it shall be an empty // Attributes object. // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IContentHandler.html#startElement">IContentHandler.startElement</a> procedure startElement(const uri, localName, qName: SAXString; const atts: IAttributes); virtual; // Receive notification of the end of an element. // // <p>By default, do nothing. Application writers may override this // method in a subclass to take specific actions at the end of // each element (such as finalising a tree node or writing // output to a file).</p> // // @param uri The Namespace URI, or the empty string if the // element has no Namespace URI or if Namespace // processing is not being performed. // @param localName The local name (without prefix), or the // empty string if Namespace processing is not being // performed. // @param qName The qualified name (with prefix), or the // empty string if qualified names are not available. // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IContentHandler.html#endElement">IContentHandler.endElement</a> procedure endElement(const uri, localName, qName: SAXString); virtual; // Receive notification of character data inside an element. // // <p>By default, do nothing. Application writers may override this // method to take specific actions for each chunk of character data // (such as adding the data to a node or buffer, or printing it to // a file).</p> // // @param ch The characters from the XML Document. // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IContentHandler.html#characters">IContentHandler.characters</a> procedure characters(const ch : SAXString); virtual; // Receive notification of ignorable whitespace in element content. // // <p>By default, do nothing. Application writers may override this // method to take specific actions for each chunk of ignorable // whitespace (such as adding data to a node or buffer, or printing // it to a file).</p> // // @param ch The whitespace characters. // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IContentHandler.html#ignorableWhitespace">IContentHandler.ignorableWhitespace</a> procedure ignorableWhitespace(const ch : SAXString); virtual; // Receive notification of a processing instruction. // // <p>By default, do nothing. Application writers may override this // method in a subclass to take specific actions for each // processing instruction, such as setting status variables or // invoking other methods.</p> // // @param target The processing instruction target. // @param data The processing instruction data, or an empty string if // none is supplied. // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IContentHandler.html#processingInstruction">IContentHandler.processingInstruction</a> procedure processingInstruction(const target, data : SAXString); virtual; // Receive notification of a skipped entity. // // <p>By default, do nothing. Application writers may override this // method in a subclass to take specific actions for each // processing instruction, such as setting status variables or // invoking other methods.</p> // // @param name The name of the skipped entity. // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IContentHandler.html#processingInstruction">IContentHandler.processingInstruction</a> procedure skippedEntity(const name : SAXString); virtual; // Receive notification of a parser warning. // // <p>The default implementation does nothing. Application writers // may override this method in a subclass to take specific actions // for each warning, such as inserting the message in a log file or // printing it to the console.</p> // // @param e The warning information encoded as an exception. // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IErrorHandler.html#warning">IErrorHandler.warning</a> // @see <a href="../SAX/ESAXParseException.html">ESAXParseException</a> procedure warning(const e : ISAXParseError); virtual; // Receive notification of a recoverable parser error. // // <p>The default implementation does nothing. Application writers // may override this method in a subclass to take specific actions // for each error, such as inserting the message in a log file or // printing it to the console.</p> // // @param e The warning information encoded as an exception. // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IErrorHandler.html#warning">IErrorHandler.warning</a> // @see <a href="../SAX/ESAXParseException.html">ESAXParseException</a> procedure error(const e : ISAXParseError); virtual; // Report a fatal XML parsing error. // // <p>The default implementation throws a SAXParseException. // Application writers may override this method in a subclass if // they need to take specific actions for each fatal error (such as // collecting all of the errors into a single report): in any case, // the application must stop all regular processing when this // method is invoked, since the document is no longer reliable, and // the parser may no longer report parsing events.</p> // // @param e The error information encoded as an exception. // @exception ESAXException Any SAX exception. // @see <a href="../SAX/IErrorHandler.html#fatalError">IErrorHandler.fatalError</a> // @see <a href="../SAX/ESAXParseException.html">ESAXParseException</a> procedure fatalError(const e : ISAXParseError); virtual; end; // Provide an optional convenience implementation of Locator. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p>This class is available mainly for application writers, who // can use it to make a persistent snapshot of a locator at any // point during a document parse:</p> // // <pre> // TMyHandler = class(TInterfacedObject, IContentHandler) // Flocator : ILocator; // Fstartloc : ILocator; // [...] // end; // // procedure TMyHandler.setDocumentLocator(const locator: ILocator); // begin // // note the locator // Flocator:= locator; // end; // // procedure startDocument(); // begin // // save the location of the start of the document // // for future use. // Fstartloc:= TLocatorImpl.Create(locator) as ILocator; // end; //</pre> // // <p>Normally, parser writers will not use this class, since it // is more efficient to provide location information only when // requested, rather than constantly updating a Locator object.</p> // // @since SAX 1.0 // @see <a href="../SAX/ILocator.html">ILocator</a> TLocatorImpl = class(TInterfacedObject, ILocator) private FpublicId : PSAXChar; FsystemId : PSAXChar; FlineNumber : Integer; FcolumnNumber : Integer; protected // Return the saved public identifier. // // @return The public identifier as a string, or an empty string if none // is available. // @see <a href="../SAX/ILocator.html#getPublicId">ILocator.getPublicId</a> // @see <a href="../SAXHelpers/TLocatorImpl.html#setPublicId">TLocatorImpl.setPublicId</a> function getPublicId() : PSAXChar; // Return the saved system identifier. // // @return The system identifier as a string, or an empty string if none // is available. // @see <a href="../SAX/ILocator.html#getSystemId">ILocator.getSystemId</a> // @see <a href="../SAXHelpers/TLocatorImpl.html#setSystemId">TLocatorImpl.setSystemId</a> function getSystemId() : PSAXChar; // Return the saved line number (1-based). // // @return The line number as an integer, or -1 if none is available. // @see <a href="../SAX/ILocator.html#getLineNumber">ILocator.getLineNumber</a> // @see <a href="../SAXHelpers/TLocatorImpl.html#setLineNumber">TLocatorImpl.setLineNumber</a> function getLineNumber() : Integer; // Return the saved column number (1-based). // // @return The column number as an integer, or -1 if none is available. // @see <a href="../SAX/ILocator.html#getColumnNumber">ILocator.getColumnNumber</a> // @see <a href="../SAXHelpers/TLocatorImpl.html#setColumnNumber">TLocatorImpl.setColumnNumber</a> function getColumnNumber() : Integer; public // Zero-argument constructor. // // <p>This will not normally be useful, since the main purpose // of this class is to make a snapshot of an existing Locator.</p> constructor Create(); overload; virtual; // Copy constructor. // // <p>Create a persistent copy of the current state of a locator. // When the original locator changes, this copy will still keep // the original values (and it can be used outside the scope of // DocumentHandler methods).</p> // // @param locator The locator to copy. constructor Create(locator : ILocator); overload; virtual; // Set the public identifier for this locator. // // @param publicId The new public identifier, or an empty string // if none is available. // @see <a href="../SAXHelpers/TLocatorImpl.html#getPublicId">TLocatorImpl.getPublicId</a> procedure setPublicId(publicId : PSAXChar); // Set the system identifier for this locator. // // @param systemId The new system identifier, or an empty string // if none is available. // @see <a href="../SAXHelpers/TLocatorImpl.html#getSystemId">TLocatorImpl.getSystemId</a> procedure setSystemId(systemId : PSAXChar); // Set the line number for this locator (1-based). // // @param lineNumber The line number, or -1 if none is available. // @see <a href="../SAXHelpers/TLocatorImpl.html#getLineNumber">TLocatorImpl.getLineNumber</a> procedure setLineNumber(lineNumber : Integer); // Set the column number for this locator (1-based). // // @param columnNumber The column number, or -1 if none is available. // @see <a href="../SAXHelpers/TLocatorImpl.html#getColumnNumber">TLocatorImpl.getColumnNumber</a> procedure setColumnNumber(columnNumber : Integer); end; // Namespace Part TNamespacePart = (nsURI, nsLocal, nsQName); // An array of Namespace Parts TNamespaceParts = array [TNamespacePart] of SAXString; // Internal class for a single Namespace context. // // <p>This module caches and reuses Namespace contexts, // so the number allocated // will be equal to the element depth of the document, not to the total // number of elements (i.e. 5-10 rather than tens of thousands). // Also, data structures used to represent contexts are shared when // possible (child contexts without declarations) to further reduce // the amount of memory that's consumed. // </p> TNamespaceContext = class(TObject) private Fparent : TNamespaceContext; EMPTY_ENUMERATION : SAXStringArray; // Copy on write for the internal tables in this context. // // <p>This class is optimized for the normal case where most // elements do not contain Namespace declarations.</p> procedure copyTables(); function getDefaultNS: PSAXChar; function getPrefixTable: SAXStringArray; function getPrefixTableElements: SAXStringArray; function getPrefixTableLength: Integer; function getUriTable: SAXStringArray; function getUriTableElements: SAXStringArray; function getUriTableLength: Integer; function getDeclarations: SAXStringArray; protected FnamespaceDeclUris : Boolean; FdeclSeen : Boolean; FdeclsOK : Boolean; Fdeclarations : SAXStringArray; FprefixTable : SAXStringArray; FprefixTableElements : SAXStringArray; FprefixTableLength : Integer; FuriTable : SAXStringArray; FuriTableElements : SAXStringArray; FuriTableLength : Integer; FelementNameTable : SAXStringArray; FelementNameTableElements : array of TNamespaceParts; FelementNameTableLength : Integer; FattributeNameTable : SAXStringArray; FattributeNameTableElements : array of TNamespaceParts; FattributeNameTableLength : Integer; FdefaultNS : SAXString; // Extension properties to get properties from self or parent property prefixTable : SAXStringArray read getPrefixTable; property prefixTableElements : SAXStringArray read getPrefixTableElements; property prefixTableLength : Integer read getPrefixTableLength; property uriTable : SAXStringArray read getUriTable; property uriTableElements : SAXStringArray read getUriTableElements; property uriTableLength : Integer read getUriTableLength; property defaultNS : PSAXChar read getDefaultNS; property declarations : SAXStringArray read getDeclarations; public // Create the root-level Namespace context. constructor Create(); overload; // Standard default destructor // // @see <a href="../SAXHelpers/TNamespaceContext.html#create">TNamespaceContext.create</a> destructor Destroy(); override; // (Re)set the parent of this Namespace context. // The context must either have been freshly constructed, // or must have been cleared // // @param context The parent Namespace context object. procedure setParent(const parent: TNamespaceContext); // Makes associated state become collectible, // invalidating this context. // <a href="../SAXHelpers/TNamespaceSupport.html#setParent">setParent</a> must be called before // this context may be used again. procedure clear(); // Declare a Namespace prefix for this context. // // @param prefix The prefix to declare. // @param uri The associated Namespace URI. // @see <a href="../SAXHelpers/TNamespaceSupport.html#declarePrefix">TNamespaceSupport.declarePrefix</a> procedure declarePrefix(const prefix, uri : SAXString); overload; // Declare a Namespace prefix for this context. // // @param prefix The prefix to declare. // @param prefixLength The length of the prefix buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param uri The associated Namespace URI. // @param uriLength The length of the uri buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @see <a href="../SAXHelpers/TNamespaceSupport.html#declarePrefix">TNamespaceSupport.declarePrefix</a> procedure declarePrefix(prefix : PSAXChar; prefixLength : Integer; uri : PSAXChar; uriLength : Integer); overload; // Process a raw XML 1.0 name in this context. // // @param qName The raw XML 1.0 name. // @param isAttribute true if this is an attribute name. // @return An array of three strings containing the // URI part (or empty string), the local part, // and the raw name, all internalized, or empty // if there is an undeclared prefix. // @see <a href="../SAXHelpers/TNamespaceSupport.html#processName">TNamespaceSupport.processName</a> function processName(const qName : SAXString; isAttribute : Boolean) : TNamespaceParts; overload; // Process a raw XML 1.0 name in this context. // // @param qName The raw XML 1.0 name. // @param qNameLength The length of the qName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param isAttribute true if this is an attribute name. // @return An array of three PSAXChars (null terminated) containing the // URI part (or empty string), the local part, // and the raw name, all internalized, or empty // if there is an undeclared prefix. // @see <a href="../SAXHelpers/TNamespaceSupport.html#processName">TNamespaceSupport.processName</a> function processName(qName : PSAXChar; qNameLength : Integer; isAttribute : Boolean) : TNamespaceParts; overload; // Look up the URI associated with a prefix in this context. // // @param prefix The prefix to look up. // @return The associated Namespace URI, or empty if none is // declared. // @see <a href="../SAXHelpers/TNamespaceSupport.html#getURI">TNamespaceSupport.getURI</a> function getURI(const prefix : SAXString) : SAXString; overload; // Look up the URI associated with a prefix in this context. // // @param prefix The prefix to look up. // @param prefixLength The length of the prefix buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @return The associated Namespace URI, or empty if none is // declared. // @see <a href="../SAXHelpers/TNamespaceSupport.html#getURI">TNamespaceSupport.getURI</a> function getURI(prefix : PSAXChar; prefixLength : Integer) : PSAXChar; overload; // Look up one of the prefixes associated with a URI in this context. // // <p>Since many prefixes may be mapped to the same URI, // the return value may be unreliable.</p> // // @param uri The URI to look up. // @return The associated prefix, or empty if none is declared. // @see <a href="../SAXHelpers/TNamespaceSupport.html#getPrefix">TNamespaceSupport.getPrefix</a> function getPrefix(const uri : SAXString) : SAXString; overload; // Look up one of the prefixes associated with a URI in this context. // // <p>Since many prefixes may be mapped to the same URI, // the return value may be unreliable.</p> // // @param uri The URI to look up. // @param uriLength The length of the URI buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @return The associated prefix, or empty if none is declared. // @see <a href="../SAXHelpers/TNamespaceSupport.html#getPrefix">TNamespaceSupport.getPrefix</a> function getPrefix(uri : PSAXChar; uriLength : Integer) : PSAXChar; overload; // Return an enumeration of prefixes declared in this context. // // @return An enumeration of prefixes (possibly empty). // @see <a href="../SAXHelpers/TNamespaceSupport.html#getDeclaredPrefixes">TNamespaceSupport.getDeclaredPrefixes</a> function getDeclaredPrefixes() : SAXStringArray; // Return an enumeration of all prefixes currently in force. // // <p>The default prefix, if in force, is <em>not</em> // returned, and will have to be checked for separately.</p> // // @return An enumeration of prefixes (never empty). // @see <a href="../SAXHelpers/TNamespaceSupport.html#getPrefixes">TNamespaceSupport.getPrefixes</a> function getPrefixes() : SAXStringArray; end; // Encapsulate Namespace logic for use by applications using SAX, // or internally by SAX drivers. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p>This class encapsulates the logic of Namespace processing: // it tracks the declarations currently in force for each context // and automatically processes qualified XML 1.0 names into their // Namespace parts; it can also be used in reverse for generating // XML 1.0 from Namespaces.</p> // // <p>Namespace support objects are reusable, but the reset method // must be invoked between each session.</p> // // <p>Here is a simple session:</p> // // <pre> // var parts : TNamespaceParts; // support : TNamespaceSupport; // begin // SetLength(parts, 3); // support:= TNamespaceSupport.Create(); // // support.pushContext(); // support.declarePrefix('', 'http://www.w3.org/1999/xhtml"'; // support.declarePrefix('dc', 'http://www.purl.org/dc#'); // // parts:= support.processName('p', parts, false); // Showmessage('Namespace URI: ' + parts[0]); // Showmessage('Local name: ' + parts[1]); // Showmessage('Raw name: ' + parts[2]); // parts:= support.processName('dc:title', parts, false); // Showmessage('Namespace URI: ' + parts[0]); // Showmessage('Local name: ' + parts[1]); // Showmessage('Raw name: ' + parts[2]); // support.popContext(); // </pre> // // <p>Note that this class is optimized for the use case where most // elements do not contain Namespace declarations: if the same // prefix/URI mapping is repeated for each context (for example), this // class will be somewhat less efficient.</p> // <p>Although SAX drivers (parsers) may choose to use this class to // implement namespace handling, they are not required to do so. // Applications must track namespace information themselves if they // want to use namespace information.</p> // // @since SAX 2.0 TNamespaceSupport = class(TObject) private Fcontexts : TList; FcurrentContext : TNamespaceContext; FcontextPos : Integer; FnamespaceDeclUris : Boolean; // Internal method for destroying the Contexts that are created by this // class // // @see <a href="../SAXHelpers/TNamespaceSupport.html#destroy">TNamespaceSupport.destroy</a> // @see <a href="../SAXHelpers/TNamespaceSupport.html#reset">TNamespaceSupport.reset</a> procedure freeContexts(); public // Create a new Namespace support object. constructor Create(); // Standard default destructor // // @see <a href="../SAXHelpers/TNamespaceSupport.html#create">TNamespaceSupport.create</a> destructor Destroy; override; // Reset this Namespace support object for reuse. // // <p>It is necessary to invoke this method before reusing the // Namespace support object for a new session. If namespace // declaration URIs are to be supported, that flag must also // be set to a non-default value. // </p> // // @see <a href="../SAXHelpers/TNamespaceSupport.html#setNamespaceDeclUris">TNamespaceSupport.setNamespaceDeclUris</a> procedure reset(); // Start a new Namespace context. // // The new context will automatically inherit // the declarations of its parent context, but it will also keep // track of which declarations were made within this context. // // <p>Event callback code should start a new context once per element. // This means being ready to call this in either of two places. // For elements that don't include namespace declarations, the // <em>ContentHandler.startElement()</em> callback is the right place. // For elements with such a declaration, it'd done in the first // <em>ContentHandler.startPrefixMapping()</em> callback. // A boolean flag can be used to // track whether a context has been started yet. When either of // those methods is called, it checks the flag to see if a new context // needs to be started. If so, it starts the context and sets the // flag. After <em>ContentHandler.startElement()</em> // does that, it always clears the flag.</p> // // <p>Normally, SAX drivers would push a new context at the beginning // of each XML element. Then they perform a first pass over the // attributes to process all namespace declarations, making // <em>ContentHandler.startPrefixMapping()</em> callbacks. // Then a second pass is made, to determine the namespace-qualified // names for all attributes and for the element name. // Finally all the information for the // <em>ContentHandler.startElement()</em> callback is available, // so it can then be made.</p> // <p>The Namespace support object always starts with a base context // already in force: in this context, only the 'xml' prefix is // declared.</p> // // @see <a href="../SAX/IContentHandler.html">IContentHandler</a> // @see <a href="../SAXHelpers/TNamespaceSupport.html#popContext">TNamespaceSupport.popContext</a> procedure pushContext(); // Revert to the previous Namespace context. // // <p>Normally, you should pop the context at the end of each // XML element. After popping the context, all Namespace prefix // mappings that were previously in force are restored.</p> // // <p>You must not attempt to declare additional Namespace // prefixes after popping a context, unless you push another // context first.</p> // // @see <a href="../SAXHelpers/TNamespaceSupport.html#pushContext">TNamespaceSupport.pushContext</a> procedure popContext(); // Declare a Namespace prefix. All prefixes must be declared // before they are referenced. For example, a SAX driver (parser) // would scan an element's attributes // in two passes: first for namespace declarations, // then a second pass using <a href="../SAXHelpers/TNamespaceSupport.html#processName">processName</a> to // interpret prefixes against (potentially redefined) prefixes. // // <p>This method declares a prefix in the current Namespace // context; the prefix will remain in force until this context // is popped, unless it is shadowed in a descendant context.</p> // // <p>To declare the default element Namespace, use the empty string as // the prefix.</p> // // <p>Note that you must <em>not</em> declare a prefix after // you've pushed and popped another Namespace.</p> // // <p>Note that you must <em>not</em> declare a prefix after // you've pushed and popped another Namespace context, or // treated the declarations phase as complete by processing // a prefixed name.</p> // // <p>Note that there is an asymmetry in this library: // <a href="../SAXHelpers/TNamespaceSupport.html#getPrefix">getPrefix</a> // will not return the "" prefix, // even if you have declared a default element namespace. // To check for a default namespace, // you have to look it up explicitly using <a href="../SAXHelpers/TNamespaceSupport.html#getURI">getURI</a>. // This asymmetry exists to make it easier to look up prefixes // for attribute names, where the default prefix is not allowed.</p> // // @param prefix The prefix to declare, or the empty string to // indicate the default element namespace. This may never have // the value "xml" or "xmlns". // @param uri The Namespace URI to associate with the prefix. // @return true if the prefix was legal, false otherwise // @exception ESAXIllegalStateException when a prefix is declared // after looking up a name in the context, or after pushing // another context on top of it. // // @see <a href="../SAXHelpers/TNamespaceSupport.html#processName">TNamespaceSupport.processName</a> // @see <a href="../SAXHelpers/TNamespaceSupport.html#getURI">TNamespaceSupport.getURI</a> // @see <a href="../SAXHelpers/TNamespaceSupport.html#getPrefix">TNamespaceSupport.getPrefix</a> function declarePrefix(const prefix, uri : SAXString) : Boolean; overload; // Declare a Namespace prefix. // // @param prefix The prefix to declare, or the empty string to // indicate the default element namespace. This may never have // the value "xml" or "xmlns". // @param prefixLength The length of the prefix buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param uri The Namespace URI to associate with the prefix. // @param uriLength The length of the uri buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @return true if the prefix was legal, false otherwise // @exception ESAXIllegalStateException when a prefix is declared // after looking up a name in the context, or after pushing // another context on top of it. // @see <a href="../SAXHelpers/TNamespaceSupport.html#declarePrefix.SAXString. SAXString">TNamespaceSupport.declarePrefix(SAXString, SAXString)</a> function declarePrefix(prefix : PSAXChar; prefixLength : Integer; uri : PSAXChar; uriLength : Integer) : Boolean; overload; // Process a raw XML 1.0 name, after all declarations in the current // context have been handled by <a href="../SAXHelpers/TNamespaceSupport.html#declarePrefix">declarePrefix</a>. // // <p>This method processes a raw XML 1.0 name in the current // context by removing the prefix and looking it up among the // prefixes currently declared. The return value will be the // array supplied by the caller, filled in as follows:</p> // // <dl> // <dt>parts[0]</dt> // <dd>The Namespace URI, or an empty string if none is // in use.</dd> // <dt>parts[1]</dt> // <dd>The local name (without prefix).</dd> // <dt>parts[2]</dt> // <dd>The original raw name.</dd> // </dl> // // <p>If the raw name has a prefix that has not been declared, then // the return value will be an empty string.</p> // // <p>Note that attribute names are processed differently than // element names: an unprefixed element name will receive the // default Namespace (if any), while an unprefixed attribute name // will not.</p> // // @param qName The raw XML 1.0 name to be processed. // @param parts An array supplied by the caller, capable of // holding at least three members. // @param isAttribute A flag indicating whether this is an // attribute name (true) or an element name (false). // @return The supplied array holding three internalized strings // representing the Namespace URI (or empty string), the // local name, and the raw XML 1.0 name; or '' if there // is an undeclared prefix. // @see <a href="../SAXHelpers/TNamespaceSupport.html#declarePrefix">TNamespaceSupport.declarePrefix</a> function processName(const qName : SAXString; var parts : TNamespaceParts; isAttribute : Boolean) : TNamespaceParts; overload; // Process a raw XML 1.0 name, after all declarations in the current // context have been handled by <a href="../SAXHelpers/TNamespaceSupport.html#declarePrefix">declarePrefix</a>. // // @param qName The raw XML 1.0 name to be processed. // @param qNameLength The length of the qName buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param parts An array supplied by the caller, capable of // holding at least three members. // @param isAttribute A flag indicating whether this is an // attribute name (true) or an element name (false). // @return The supplied array holding three internalized strings // representing the Namespace URI (or empty string), the // local name, and the raw XML 1.0 name; or '' if there // is an undeclared prefix. // @see <a href="../SAXHelpers/TNamespaceSupport.html#declarePrefix.SAXString.TNamespaceParts.Boolean">TNamespaceSupport.declarePrefix(SAXString, TNamespaceParts, Boolean)</a> function processName(qName : PSAXChar; qNameLength : Integer; var parts : TNamespaceParts; isAttribute : Boolean) : TNamespaceParts; overload; // Look up a prefix and get the currently-mapped Namespace URI. // // <p>This method looks up the prefix in the current context. // Use the empty string ('') for the default Namespace.</p> // // @param prefix The prefix to look up. // @return The associated Namespace URI, or an empty string if the prefix // is undeclared in this context. // @see <a href="../SAXHelpers/TNamespaceSupport.html#getPrefix">TNamespaceSupport.getPrefix</a> // @see <a href="../SAXHelpers/TNamespaceSupport.html#getPrefixes">TNamespaceSupport.getPrefixes</a> function getURI(const prefix : SAXString) : SAXString; overload; // Look up a prefix and get the currently-mapped Namespace URI. // // @param prefix The prefix to look up. // @param prefixLength The length of the prefix buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @return The associated Namespace URI, or an empty string if the prefix // is undeclared in this context. // @see <a href="../SAXHelpers/TNamespaceSupport.html#getURI.SAXString">TNamespaceSupport.getURI(SAXString)</a> function getURI(prefix : PSAXChar; prefixLength : Integer) : PSAXChar; overload; // Return an enumeration of all prefixes whose declarations are // active in the current context. // This includes declarations from parent contexts that have // not been overridden. // // <p><strong>Note:</strong> if there is a default prefix, it will not be // returned in this enumeration; check for the default prefix // using the <a href="../SAXHelpers/TNamespaceSupport.html#getURI">getURI</a> with an argument of ''.</p> // // @return An enumeration of prefixes (never empty). // // @see <a href="../SAXHelpers/TNamespaceSupport.html#getDeclaredPrefixes">TNamespaceSupport.getDeclaredPrefixes</a> // @see <a href="../SAXHelpers/TNamespaceSupport.html#getURI">TNamespaceSupport.getURI</a> function getPrefixes() : SAXStringArray; overload; // Return one of the prefixes mapped to a Namespace URI. // // <p>If more than one prefix is currently mapped to the same // URI, this method will make an arbitrary selection; if you // want all of the prefixes, use the <a href="../SAXHelpers/TNamespaceSupport.html#getPrefixes">getPrefixes</a> // method instead.</p> // // <p><strong>Note:</strong> this will never return the empty (default) prefix; // to check for a default prefix, use the <a href="../SAXHelpers/TNamespaceSupport.html#getURI">getURI</a> // method with an argument of ''.</p> // // @param uri The Namespace URI. // @param isAttribute true if this prefix is for an attribute // (and the default Namespace is not allowed). // @return One of the prefixes currently mapped to the URI supplied, // or an empty string if none is mapped or if the URI is assigned to // the default Namespace. // @see <a href="../SAXHelpers/TNamespaceSupport.html#getPrefixes.SAXString">TNamespaceSupport.getPrefixes(SAXString)</a> // @see <a href="../SAXHelpers/TNamespaceSupport.html#getURI">TNamespaceSupport.getURI</a> function getPrefix(const uri : SAXString) : SAXString; overload; // Return one of the prefixes mapped to a Namespace URI. // // @param uri The Namespace URI. // @param uriLength The length of the uri buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @param isAttribute true if this prefix is for an attribute // (and the default Namespace is not allowed). // @return One of the prefixes currently mapped to the URI supplied, // or an empty string if none is mapped or if the URI is assigned to // the default Namespace. // @see <a href="../SAXHelpers/TNamespaceSupport.html#getPrefix.SAXString">TNamespaceSupport.getPrefix(SAXString)</a> function getPrefix(uri : PSAXChar; uriLength : Integer) : PSAXChar; overload; // Return an enumeration of all prefixes for a given URI whose // declarations are active in the current context. // This includes declarations from parent contexts that have // not been overridden. // // <p>This method returns prefixes mapped to a specific Namespace // URI. The xml: prefix will be included. If you want only one // prefix that's mapped to the Namespace URI, and you don't care // which one you get, use the <a href="../SAXHelpers/TNamespaceSupport.html#getPrefix">getPrefix</a> // method instead.</p> // // <p><strong>Note:</strong> the empty (default) prefix is <em>never</em> included // in this enumeration; to check for the presence of a default // Namespace, use the <a href="../SAXHelpers/TNamespaceSupport.html#getURI">getURI</a> method with an // argument of ''.</p> // // @param uri The Namespace URI. // @return An enumeration of prefixes (never empty). // // @see <a href="../SAXHelpers/TNamespaceSupport.html#getPrefix">TNamespaceSupport.getPrefix</a> // @see <a href="../SAXHelpers/TNamespaceSupport.html#getDeclaredPrefixes">TNamespaceSupport.getDeclaredPrefixes</a> // @see <a href="../SAXHelpers/TNamespaceSupport.html#getURI">TNamespaceSupport.getURI</a> function getPrefixes(const uri : SAXString) : SAXStringArray; overload; // Return an enumeration of all prefixes currently declared for a URI. // // @param uri The Namespace URI. // @param uriLength The length of the uri buffer // The value may be -1 which indicates that the buffer is // null-terminated. If the value is 0 then the buffer may be nil. // @return An enumeration of all prefixes declared in the // current context. // @see <a href="../SAXHelpers/TNamespaceSupport.html#getPrefixes.SAXString">TNamespaceSupport.getPrefixes(SAXString)</a> function getPrefixes(uri : PSAXChar; uriLength : Integer) : SAXStringArray; overload; // Return an enumeration of all prefixes declared in this context. // // <p>The empty (default) prefix will be included in this // enumeration; note that this behaviour differs from that of // <a href="../SAXHelpers/TNamespaceSupport.html#getPrefix">getPrefix</a> and // <a href="../SAXHelpers/TNamespaceSupport.html#getPrefixes">getPrefixes</a>.</p> // // @return An enumeration of all prefixes declared in this // context. // @see <a href="../SAXHelpers/TNamespaceSupport.html#getPrefixes">TNamespaceSupport.getPrefixes</a> // @see <a href="../SAXHelpers/TNamespaceSupport.html#getURI">TNamespaceSupport.getURI</a> function getDeclaredPrefixes() : SAXStringArray; // Controls whether namespace declaration attributes are placed // into the <code>http://www.w3.org/xmlns/2000/</code> namespace // by <a href="../SAXHelpers/TNamespaceSupport.html#processName">processName</a>. This may only be // changed before any contexts have been pushed. // // @since SAX 2.1 alpha // // @exception EIllegalStateException when attempting to set this // after any context has been pushed. procedure setNamespaceDeclUris(value : Boolean); // Returns true if namespace declaration attributes are placed into // a namespace. This behavior is not the default. // // @since SAX 2.1 alpha /// function isNamespaceDeclUris() : Boolean; end; // Buffered Base class for deriving an XML filter. // // <p>This class is designed to sit between an <a href="../SAX/IXMLReader.html">IXMLReader</a> // and the client application's event handlers. By default, it // does nothing but pass requests up to the reader and events // on to the handlers unmodified, but subclasses can override // specific methods to modify the event stream or the configuration // requests as they pass through.</p> // TXMLFilterImpl = class(TInterfacedObject, IXMLFilter, IXMLReader, IEntityResolver, IDTDHandler, IContentHandler, IErrorHandler) private Fparent : IXMLReader; Flocator : ILocator; FentityResolver : IEntityResolver; FdtdHandler : IDTDHandler; FcontentHandler : IContentHandler; FerrorHandler : IErrorHandler; // Set up before a parse. // // <p>Before every parse, check whether the parent is // non-nil, and re-register the filter for all of the // events.</p> procedure setupParse(); protected // Set the parent reader. // // <p>This is the <a href="../SAX/IXMLReader.html">IXMLReader</a> from which // this filter will obtain its events and to which it will pass its // configuration requests. The parent may itself be another filter.</p> // // <p>If there is no parent reader set, any attempt to parse // or to set or get a feature or property will fail.</p> // @param parent The parent reader. // @see <a href="../SAXHelpers/TXMLFilterImpl.html#getParent">TXMLFilterImpl.getParent</a> procedure setParent(const parent : IXMLReader); virtual; // Get the parent reader. // // <p>This method allows the application to query the parent // reader (which may be another filter). It is generally a // bad idea to perform any operations on the parent reader // directly: they should all pass through this filter.</p> // // @return The parent filter, or nil if none has been set. // @see <a href="../SAXHelpers/TXMLFilterImpl.html#setParent">TXMLFilterImpl.setParent</a> function getParent() : IXMLReader; virtual; // Look up the value of a feature. // // <p>This will always fail if the parent is nil.</p> // // @param name The feature name. // @return The current value of the feature. // @exception ESAXNotRecognizedException If the feature // value can't be assigned or retrieved from the parent. // @exception ESAXNotSupportedException When the // parent recognizes the feature name but // cannot determine its value at this time. function getFeature(const name : SAXString) : Boolean; virtual; // Set the value of a feature. // // <p>This will always fail if the parent is nil.</p> // // @param name The feature name. // @param value The requested feature value. // @exception ESAXNotRecognizedException If the feature // value can't be assigned or retrieved from the parent. // @exception ESAXNotSupportedException When the // parent recognizes the feature name but // cannot set the requested value. procedure setFeature(const name : SAXString; value : Boolean); virtual; // Look up the interface value of a property. // // @param name The property name. // @param value The current value of the property as an interface. // @exception ESAXNotRecognizedException If the property interface // value can't be retrieved from the parent. // @exception ESAXNotSupportedException When the // parent recognizes the property name but // cannot determine its interface at this time. function getProperty(const name : SAXString) : IProperty; virtual; // Set the entity resolver. // // @param resolver The new entity resolver. procedure setEntityResolver(const resolver : IEntityResolver); virtual; // Get the current entity resolver. // // @return The current entity resolver, or nil if none was set. function getEntityResolver() : IEntityResolver; virtual; // Set the DTD event handler. // // @param resolver The new DTD handler. procedure setDTDHandler(const handler : IDTDHandler); virtual; // Get the current DTD event handler. // // @return The current DTD handler, or nil if none was set. function getDTDHandler() : IDTDHandler; virtual; // Set the content event handler. // // @param resolver The new content handler. procedure setContentHandler(const handler : IContentHandler); virtual; // Get the content event handler. // // @return The current content handler, or nil if none was set. function getContentHandler() : IContentHandler; virtual; // Set the error event handler. // // @param handle The new error handler. procedure setErrorHandler(const handler : IErrorHandler); virtual; // Get the current error event handler. // // @return The current error handler, or nil if none was set. function getErrorHandler() : IErrorHandler; virtual; // Parse a document. // // @param input The input source for the document entity. // @exception ESAXException Any SAX exception. procedure parse(const input : IInputSource); overload; virtual; // Parse a document. // // @param systemId The system identifier as a fully-qualified URI. // @exception ESAXException Any SAX exception. procedure parse(const systemId : SAXString); overload; virtual; // Filter an external entity resolution. // // @param publicId The entity's public identifier, or null. // @param systemId The entity's system identifier. // @return A new InputSource or null for the default. // @exception ESAXException The client may throw // an exception during processing. function resolveEntity(const publicId, systemId : SAXString) : IInputSource; virtual; // Filter a notation declaration event. // // @param name The notation name. // @param publicId The notation's public identifier, or null. // @param systemId The notation's system identifier, or null. // @exception ESAXException The client may throw // an exception during processing. procedure notationDecl(const name, publicId, systemId : SAXString); virtual; // Filter an unparsed entity declaration event. // // @param name The entity name. // @param publicId The entity's public identifier, or null. // @param systemId The entity's system identifier, or null. // @param notationName The name of the associated notation. // @exception ESAXException The client may throw // an exception during processing. procedure unparsedEntityDecl(const name, publicId, systemId, notationName : SAXString); virtual; // Filter a new document locator event. // // @param locator The document locator. procedure setDocumentLocator(const locator: ILocator); virtual; // Filter a start document event. // // @exception ESAXException The client may throw // an exception during processing. procedure startDocument(); virtual; // Filter an end document event. // // @exception ESAXException The client may throw // an exception during processing. procedure endDocument(); virtual; // Filter a start Namespace prefix mapping event. // // @param prefix The Namespace prefix. // @param uri The Namespace URI. // @exception ESAXException The client may throw // an exception during processing. procedure startPrefixMapping(const prefix, uri : SAXString); virtual; // Filter an end Namespace prefix mapping event. // // @param prefix The Namespace prefix. // @exception ESAXException The client may throw // an exception during processing. procedure endPrefixMapping(const prefix : SAXString); virtual; // Filter a start element event. // // @param uri The element's Namespace URI, or the empty string. // @param localName The element's local name, or the empty string. // @param qName The element's qualified (prefixed) name, or the empty // string. // @param atts The element's attributes. // @exception ESAXException The client may throw // an exception during processing. procedure startElement(const uri, localName, qName: SAXString; const atts: IAttributes); virtual; // Filter an end element event. // // @param uri The element's Namespace URI, or the empty string. // @param localName The element's local name, or the empty string. // @param qName The element's qualified (prefixed) name, or the empty // string. // @exception ESAXException The client may throw // an exception during processing. procedure endElement(const uri, localName, qName: SAXString); virtual; // Filter a character data event. // // @param ch The characters in the XML Document. // @exception ESAXException The client may throw // an exception during processing. procedure characters(const ch : SAXString); virtual; // Filter an ignorable whitespace event. // // @param ch The characters in the XML Document. // @exception ESAXException The client may throw // an exception during processing. procedure ignorableWhitespace(const ch : SAXString); virtual; // Filter a processing instruction event. // // @param target The processing instruction target. // @param data The text following the target. // @exception ESAXException The client may throw // an exception during processing. procedure processingInstruction(const target, data : SAXString); virtual; // Filter a skipped entity event. // // @param name The name of the skipped entity. // @exception ESAXException The client may throw // an exception during processing. procedure skippedEntity(const name : SAXString); virtual; // Filter a warning event. // // @param e The warning as an exception. // @exception ESAXException The client may throw // an exception during processing. procedure warning(const e : ISAXParseError); virtual; // Filter an error event. // // @param e The error as an exception. // @exception ESAXException The client may throw // an exception during processing. procedure error(const e : ISAXParseError); virtual; // Filter a fatal error event. // // @param e The error as an exception. // @exception ESAXException The client may throw // an exception during processing. procedure fatalError(const e : ISAXParseError); virtual; public // Construct an empty XML filter, with no parent. // // <p>This filter will have no parent: you must assign a parent // before you start a parse or do any configuration with // setFeature or getProperty.</p> // // @see <a href="../SAXHelpers/TXMLFilterImpl.html#setParent">TXMLFilterImpl.setParent</a> // @see <a href="../SAXHelpers/TXMLFilterImpl.html#setFeature">TXMLFilterImpl.setFeature</a> // @see <a href="../SAXHelpers/TXMLFilterImpl.html#getProperty">TXMLFilterImpl.getProperty</a> constructor create(); overload; // Construct an XML filter with the specified parent. // // @see <a href="../SAXHelpers/TXMLFilterImpl.html#setParent">TXMLFilterImpl.setParent</a> // @see <a href="../SAXHelpers/TXMLFilterImpl.html#getParent">TXMLFilterImpl.getParent</a> constructor create(const parent : IXMLReader); overload; end; // Base class for deriving an XML Reader. TXMLReaderImpl = class(TInterfacedObject, IXMLReader, ILocator) private FcontentHandler: IContentHandler; FdtdHandler: IDTDHandler; FentityResolver: IEntityResolver; FerrorHandler: IErrorHandler; FlineNumber: Integer; FcolumnNumber: Integer; FpublicId: SAXString; FsystemId: SAXString; Fnamespaces: Boolean; Fprefixes: Boolean; Fparsing: Boolean; // Check if we are already parsing // // <p>Throw an exception if we are parsing. Use this method to // detect illegal feature or property changes.</p> // // @param propType A string value containing the type of property that // cannot be changed while parsing. // @param name A string value containing the name of the property that // cannot be changed while parsing. procedure checkNotParsing(const propType, name: SAXString); protected procedure setColumnNumber(value: Integer); virtual; procedure setLineNumber(value: Integer); virtual; procedure setPublicId(value: PSAXChar); virtual; procedure setSystemId(value: PSAXChar); virtual; procedure parseInput(const input: IInputSource); virtual; abstract; property useNamespaces: Boolean read Fnamespaces write Fnamespaces; property usePrefixes: Boolean read Fprefixes write Fprefixes; // Look up the value of a feature. // // <p>The feature name is any fully-qualified URI. It is // possible for an XMLReader to recognize a feature name but // to be unable to return its value; this is especially true // in the case of an adapter for a SAX1 Parser, which has // no way of knowing whether the underlying parser is // performing validation or expanding external entities.</p> // // <p>All XMLReaders are required to recognize the // http://xml.org/sax/features/namespaces and the // http://xml.org/sax/features/namespace-prefixes feature names.</p> // // <p>Some feature values may be available only in specific // contexts, such as before, during, or after a parse.</p> // // <p>Typical usage is something like this:</p> // // <pre> // var // r : IXMLReader; // begin // r:= TMySAXDriver.Create() as IXMLReader; // // // try to activate validation // try // r.setFeature('http://xml.org/sax/features/validation', true); // except // on e : ESAXException do // begin // Showmessage('Cannot activate validation.'); // end; // end; // // // register event handlers // r.setContentHandler(TMyContentHandler.Create() as IContentHandler); // r.setErrorHandler(TMyErrorHandler.Create() as IErrorHandler); // // // parse the first document // try // r.parse('file://c:/mydoc.xml'); // except // on e : ESAXException do // begin // Showmessage('XML exception reading document.'); // end; // on e : Exception do // begin // Showmessage('Exception reading document.'); // end; // end; // </pre> // // <p>Implementors are free (and encouraged) to invent their own features, // using names built on their own URIs.</p> // // @param name The feature name, which is a fully-qualified URI. // @return The current state of the feature (true or false). // @exception ESAXNotRecognizedException When the // XMLReader does not recognize the feature name. // @exception ESAXNotSupportedException When the // XMLReader recognizes the feature name but // cannot determine its value at this time. // @see <a href="../SAXHelpers/TXMLReaderImpl.html#setFeature">TXMLReaderImpl.setFeature</a> function getFeature(const name : SAXString) : Boolean; virtual; // Set the state of a feature. // // <p>The feature name is any fully-qualified URI. It is // possible for an XMLReader to recognize a feature name but // to be unable to set its value; this is especially true // in the case of an adapter for a SAX1 <a href="../SAX/IParser.html">Parser</a>, // which has no way of affecting whether the underlying parser is // validating, for example.</p> // // <p>All XMLReaders are required to support setting // http://xml.org/sax/features/namespaces to true and // http://xml.org/sax/features/namespace-prefixes to false.</p> // // <p>Some feature values may be immutable or mutable only // in specific contexts, such as before, during, or after // a parse.</p> // // @param name The feature name, which is a fully-qualified URI. // @param state The requested state of the feature (true or false). // @exception ESAXNotRecognizedException When the // XMLReader does not recognize the feature name. // @exception ESAXNotSupportedException When the // XMLReader recognizes the feature name but // cannot set the requested value. // @see <a href="../SAXHelpers/TXMLReaderImpl.html#getFeature">TXMLReaderImpl.getFeature</a> procedure setFeature(const name : SAXString; value : Boolean); virtual; // Look up the value of a property. // // <p>The property name is any fully-qualified URI. It is // possible for an XMLReader to recognize a property name but // temporarily be unable to return its value // Some property values may be available only in specific // contexts, such as before, during, or after a parse.</p> // // <p>XMLReaders are not required to recognize any specific // property names, though an initial core set is documented for // SAX2.</p> // // <p>Implementors are free (and encouraged) to invent their own properties, // using names built on their own URIs.</p> // // <p> Within SAX for Pascal property setting is handled through // the interface that is returned by the call to getProperty. This // eliminates the need for multiple lookups in tight loop situations // as a user can maintain a reference to the interface.</p> // // @param name The property name, which is a fully-qualified URI. // @returns An Interface that allows the getting and setting of the property // @exception ESAXNotRecognizedException If the property // interface cannot be retrieved. // @exception ESAXNotSupportedException When the // XMLReader recognizes the property name but // cannot determine its interface value at this time. function getProperty(const name : SAXString) : IProperty; virtual; // Allow an application to register an entity resolver. // // <p>If the application does not register an entity resolver, // the XMLReader will perform its own default resolution.</p> // // <p>Applications may register a new or different resolver in the // middle of a parse, and the SAX parser must begin using the new // resolver immediately.</p> // // @param resolver The entity resolver. // @exception Exception If the resolver argument is nil. // @see <a href="../SAXHelpers/TXMLReaderImpl.html#getEntityResolver">TXMLReaderImpl.getEntityResolver</a> procedure setEntityResolver(const resolver : IEntityResolver); virtual; // Return the current entity resolver. // // @return The current entity resolver, or nil if none // has been registered. // @see <a href="../SAXHelpers/TXMLReaderImpl.html#setEntityResolver">TXMLReaderImpl.setEntityResolver</a> function getEntityResolver() : IEntityResolver; virtual; // Allow an application to register a DTD event handler. // // <p>If the application does not register a DTD handler, all DTD // events reported by the SAX parser will be silently ignored.</p> // // <p>Applications may register a new or different handler in the // middle of a parse, and the SAX parser must begin using the new // handler immediately.</p> // // @param handler The DTD handler. // @exception Exception If the handler argument is nil. // @see <a href="../SAXHelpers/TXMLReaderImpl.html#getDTDHandler">TXMLReaderImpl.getDTDHandler</a> procedure setDTDHandler(const handler : IDTDHandler); virtual; // Return the current DTD handler. // // @return The current DTD handler, or nil if none // has been registered. // @see <a href="../SAXHelpers/TXMLReaderImpl.html#setDTDHandler">TXMLReaderImpl.setDTDHandler</a> function getDTDHandler() : IDTDHandler; virtual; // Allow an application to register a content event handler. // // <p>If the application does not register a content handler, all // content events reported by the SAX parser will be silently // ignored.</p> // // <p>Applications may register a new or different handler in the // middle of a parse, and the SAX parser must begin using the new // handler immediately.</p> // // @param handler The content handler. // @exception Exception If the handler argument is nil. // @see <a href="../SAXHelpers/TXMLReaderImpl.html#getContentHandler">TXMLReaderImpl.getContentHandler</a> procedure setContentHandler(const handler : IContentHandler); virtual; // Return the current content handler. // // @return The current content handler, or nil if none // has been registered. // @see <a href="../SAXHelpers/TXMLReaderImpl.html#setContentHandler">TXMLReaderImpl.setContentHandler</a> function getContentHandler() : IContentHandler; virtual; // Allow an application to register an error event handler. // // <p>If the application does not register an error handler, all // error events reported by the SAX parser will be silently // ignored; however, normal processing may not continue. It is // highly recommended that all SAX applications implement an // error handler to avoid unexpected bugs.</p> // // <p>Applications may register a new or different handler in the // middle of a parse, and the SAX parser must begin using the new // handler immediately.</p> // // @param handler The error handler. // @exception Exception If the handler argument is nil. // @see <a href="../SAXHelpers/TXMLReaderImpl.html#getErrorHandler">TXMLReaderImpl.getErrorHandler</a> procedure setErrorHandler(const handler : IErrorHandler); virtual; // Return the current error handler. // // @return The current error handler, or nil if none // has been registered. // @see <a href="../SAXHelpers/TXMLReaderImpl.html#setErrorHandler">TXMLReaderImpl.setErrorHandler</a> function getErrorHandler() : IErrorHandler; virtual; // Parse an XML document. // // <p>The application can use this method to instruct the XML // reader to begin parsing an XML document from any valid input // source (a character stream, a byte stream, or a URI).</p> // // <p>Applications may not invoke this method while a parse is in // progress (they should create a new XMLReader instead for each // nested XML document). Once a parse is complete, an // application may reuse the same XMLReader object, possibly with a // different input source.</p> // // <p>During the parse, the XMLReader will provide information // about the XML document through the registered event // handlers.</p> // // <p>This method is synchronous: it will not return until parsing // has ended. If a client application wants to terminate // parsing early, it should throw an exception.</p> // // @param source The input source for the top-level of the // XML document. // @exception ESAXException Any SAX exception. // @exception Exception An IO exception from the parser, // possibly from a byte stream or character stream // supplied by the application. // @see <a href="../SAX/TInputSource.html">TInputSource</a> // @see <a href="../SAXHelpers/TXMLReaderImpl.html#parse.SAXString">TXMLReaderImpl.parse(SAXString)</a> // @see <a href="../SAXHelpers/TXMLReaderImpl.html#setEntityResolver">TXMLReaderImpl.setEntityResolver</a> // @see <a href="../SAXHelpers/TXMLReaderImpl.html#setDTDHandler">TXMLReaderImpl.setDTDHandler</a> // @see <a href="../SAXHelpers/TXMLReaderImpl.html#setContentHandler">TXMLReaderImpl.setContentHandler</a> // @see <a href="../SAXHelpers/TXMLReaderImpl.html#setErrorHandler">TXMLReaderImpl.setErrorHandler</a> procedure parse(const input : IInputSource); overload; virtual; // Parse an XML document from a system identifier (URI). // // <p>This method is a shortcut for the common case of reading a // document from a system identifier. It is the exact // equivalent of the following:</p> // // <pre> // input:= TInputSource.Create(systemId); // try // parse(input); // finally // input.Free; // end; // </pre> // // <p>If the system identifier is a URL, it must be fully resolved // by the application before it is passed to the parser.</p> // // @param systemId The system identifier (URI). // @exception ESAXException Any SAX exception. // @exception Exception An IO exception from the parser, // possibly from a byte stream or character stream // supplied by the application. // @see <a href="../SAXHelpers/TXMLReaderImpl.html#parse.TInputSource">TXMLReaderImpl.parse(TInputSource)</a> procedure parse(const systemId : SAXString); overload; virtual; // Return the public identifier for the current document event. // // <p>The return value is the public identifier of the document // entity or of the external parsed entity in which the markup // triggering the event appears.</p> // // @return A string containing the public identifier, or // empty if none is available. // @see <a href="../SAXHelpers/TXMLReaderImpl.html#getSystemId">TXMLReaderImpl.getSystemId</a> function getPublicId() : PSAXChar; virtual; // Return the system identifier for the current document event. // // <p>The return value is the system identifier of the document // entity or of the external parsed entity in which the markup // triggering the event appears.</p> // // <p>If the system identifier is a URL, the parser must resolve it // fully before passing it to the application.</p> // // @return A string containing the system identifier, or empty // if none is available. // @see <a href="../SAXHelpers/TXMLReaderImpl.html#getPublicId">TXMLReaderImpl.getPublicId</a> function getSystemId() : PSAXChar; virtual; // Return the line number where the current document event ends. // // <p><strong>Warning:</strong> The return value from the method // is intended only as an approximation for the sake of error // reporting; it is not intended to provide sufficient information // to edit the character content of the original XML document.</p> // // <p>The return value is an approximation of the line number // in the document entity or external parsed entity where the // markup triggering the event appears.</p> // // <p>If possible, the SAX driver should provide the line position // of the first character after the text associated with the document // event. The first line in the document is line 1.</p> // // @return The line number, or -1 if none is available. // @see <a href="../SAXHelpers/TXMLReaderImpl.html#getColumnNumber">TXMLReaderImpl.getColumnNumber</a> function getLineNumber() : Integer; virtual; // Return the column number where the current document event ends. // // <p><strong>Warning:</strong> The return value from the method // is intended only as an approximation for the sake of error // reporting; it is not intended to provide sufficient information // to edit the character content of the original XML document.</p> // // <p>The return value is an approximation of the column number // in the document entity or external parsed entity where the // markup triggering the event appears.</p> // // <p>If possible, the SAX driver should provide the line position // of the first character after the text associated with the document // event.</p> // // <p>If possible, the SAX driver should provide the line position // of the first character after the text associated with the document // event. The first column in each line is column 1.</p> // // @return The column number, or -1 if none is available. // @see <a href="../SAXHelpers/TXMLReaderImpl.html#getLineNumber">TXMLReaderImpl.getLineNumber</a> function getColumnNumber() : Integer; virtual; public // Construct an empty XML Reader, and initializes its values. constructor Create; virtual; // Default destructor for an XML Reader, freeing any items created during // intialization destructor Destroy; override; end; // SAX2 extension helper for additional Attributes information, // implementing the <a href="../SAXExt/IAttributes2.html">IAttributes2</a> interface. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p>This is not part of core-only SAX2 distributions.</p> // // <p>The <em>specified</em> flag for each attribute will always // be true, unless it has been set to false in the copy constructor // or using <a href="../SAXHelpers/TAttributes2Impl.html#setSpecified">setSpecified</a>. // Similarly, the <em>declared</em> flag for each attribute will // always be false, except for defaulted attributes (<em>specified</em> // is false), non-CDATA attributes, or when it is set to true using // <a href="../SAXHelpers/TAttributes2Impl.html#setDeclared">setDeclared</a>. // If you change an attribute's type by hand, you may need to modify // its <em>declared</em> flag to match. // </p> // // @since SAX 2.0 (extensions 1.1 alpha) TAttributes2Impl = class(TAttributesImpl, IAttributes2) private Fdeclared : array of Boolean; Fspecified : array of Boolean; protected // Returns false unless the attribute was declared in the DTD. // This helps distinguish two kinds of attributes that SAX reports // as CDATA: ones that were declared (and hence are usually valid), // and those that were not (and which are never valid). // // @param index The attribute index (zero-based). // @return true if the attribute was declared in the DTD, // false otherwise. // @exception Exception When the // supplied index does not identify an attribute. // function isDeclared(index : Integer) : Boolean; overload; // Returns false unless the attribute was declared in the DTD. // This helps distinguish two kinds of attributes that SAX reports // as CDATA: ones that were declared (and hence are usually valid), // and those that were not (and which are never valid). // // @param qName The XML 1.0 qualified name. // @return true if the attribute was declared in the DTD, // false otherwise. // @exception ESAXIllegalArgumentException When the // supplied name does not identify an attribute. function isDeclared(const qName : SAXString) : Boolean; overload; // Returns false unless the attribute was declared in the DTD. // This helps distinguish two kinds of attributes that SAX reports // as CDATA: ones that were declared (and hence are usually valid), // and those that were not (and which are never valid). // // <p>Remember that since DTDs do not "understand" namespaces, the // namespace URI associated with an attribute may not have come from // the DTD. The declaration will have applied to the attribute's // <em>qName</em>.</p> // // @param uri The Namespace URI, or the empty string if // the name has no Namespace URI. // @param localName The attribute's local name. // @return true if the attribute was declared in the DTD, // false otherwise. // @exception ESAXIllegalArgumentException When the // supplied names do not identify an attribute. function isDeclared(const uri, localName : SAXString) : Boolean; overload; // Returns the current value of an attribute's "specified" flag. // // @param index The attribute index (zero-based). // @return current flag value // @exception EIllegalArgumentException When the // supplied index does not identify an attribute. function isSpecified(index : Integer) : Boolean; overload; // Returns the current value of an attribute's "specified" flag. // // @param uri The Namespace URI, or the empty string if // the name has no Namespace URI. // @param localName The attribute's local name. // @return current flag value // @exception ESAXIllegalArgumentException When the // supplied names do not identify an attribute. function isSpecified(const uri, localName : SAXString) : Boolean; overload; // Returns the current value of an attribute's "specified" flag. // // @param qName The XML 1.0 qualified name. // @return current flag value // @exception ESAXIllegalArgumentException When the // supplied name does not identify an attribute. function isSpecified(const qName : SAXString) : Boolean; overload; public // Copy an entire Attributes object. The "specified" flags are // assigned as true, unless the object is an Attributes2 object // in which case those values are copied. // // @see <a href="../SAXHelpers/TAttributesImpl.html#setAttributes">TAttributesImpl.setAttributes</a> procedure setAttributes(const atts : IAttributes); override; // Add an attribute to the end of the list, setting its // "specified" flag to true. To set that flag's value // to false, use <a href="../SAXHelpers/TAttributes2Impl.html#setSpecified">setSpecified</a>. // // <p>Unless the attribute <em>type</em> is CDATA, this attribute // is marked as being declared in the DTD. To set that flag's value // to true for CDATA attributes, use <a href="../SAXHelpers/TAttributes2Impl.html#setDeclared">setDeclared</a>.</p> // // @see <a href="../SAXHelpers/TAttributesImpl.html#addAttribute">TAttributesImpl.addAttribute</a> procedure addAttribute (const uri, localName, qName, attrType, value : SAXString); override; // Remove an attribute declaration. // // @param index The index of the attribute (zero-based). procedure removeAttribute(index : Integer); override; // Assign a value to the "declared" flag of a specific attribute. // This is normally needed only for attributes of type CDATA, // including attributes whose type is changed to or from CDATA. // // @param index The index of the attribute (zero-based). // @param value The desired flag value. // @exception ESAXIllegalArgumentException When the // supplied index does not identify an attribute. // @see <a href="../SAXHelpers/TAttributes2Impl.html#setType">TAttributes2Impl.setType</a> procedure setDeclared(index : Integer; value : Boolean); // Assign a value to the "specified" flag of a specific attribute. // This is the only way this flag can be cleared, except clearing // by initialization with the copy constructor. // // @param index The index of the attribute (zero-based). // @param value The desired flag value. // @exception ESAXIllegalArgumentException When the // supplied index does not identify an attribute. procedure setSpecified(index : Integer; value : Boolean); end; // This class extends the SAX2 base handler class to support the // SAX2 <a href="../SAXExt/ILexicalHandler.html">ILexicalHandler</a>, // <a href="../SAXExt/IDeclHandler.html">IDeclHandler</a>, and // <a href="../SAXExt/IEntityResolver2.html">IEntityResolver2</a> extensions. // Except for overriding the // original SAX1 <a href="../SAXHelpers/TDefaultHandler.html#resolveEntity">resolveEntity</a> // method the added handler methods just return. Subclassers may // override everything on a method-by-method basis. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p> <em>Note:</em> this class might yet learn that the // <em>IContentHandler.setDocumentLocator()</em> call might be passed a // <a href="../SAXExt/ILocator2.html">ILocator2</a> object, and that the // <em>IContentHandler.startElement()</em> call might be passed a // <a href="../SAXExt/IAttributes2.html">IAttributes2</a> object.</p> // // @since SAX 2.0 (extensions 1.1 alpha) TDefaultHandler2 = class(TDefaultHandler, ILexicalHandler, IDeclHandler, IEntityResolver2) protected // Report an element type declaration. // // @param name The element type name. // @param model The content model as a normalized string. // @exception ESAXException The application may raise an exception. /// procedure elementDecl(const name, model : SAXString); virtual; // Report an attribute type declaration. // // @param eName The name of the associated element. // @param aName The name of the attribute. // @param attrType A string representing the attribute type. // @@param mode A string representing the attribute defaulting mode // ("#IMPLIED", "#REQUIRED", or "#FIXED") or '' if // none of these applies. // @param value A string representing the attribute's default value, // or '' if there is none. // @exception ESAXException The application may raise an exception. procedure attributeDecl(const eName, aName, attrType, mode, value: SAXString); virtual; // Report an internal entity declaration. // // @param name The name of the entity. If it is a parameter // entity, the name will begin with '%'. // @param value The replacement text of the entity. // @exception ESAXException The application may raise an exception. // @see <a href="../SAXHelpers/TDefaultHandler2.html#externalEntityDecl">TDefaultHandler2.externalEntityDecl</a> // @see <a href="../SAX/IDTDHandler.html#unparsedEntityDecl">IDTDHandler.unparsedEntityDecl</a> procedure internalEntityDecl(const name, value : SAXString); virtual; // Report a parsed external entity declaration. // // @param name The name of the entity. If it is a parameter // entity, the name will begin with '%'. // @param publicId The declared public identifier of the entity, or // an empty string if none was declared. // @param systemId The declared system identifier of the entity. // @exception ESAXException The application may raise an exception. // @see <a href="../SAXHelpers/TDefaultHandler2.html#internalEntityDecl">TDefaultHandler2.internalEntityDecl</a> // @see <a href="../SAX/IDTDHandler.html#unparsedEntityDecl">IDTDHandler.unparsedEntityDecl</a> procedure externalEntityDecl(const name, publicId, systemId : SAXString); virtual; // Report the start of DTD declarations, if any. // // @param name The document type name. // @param publicId The declared public identifier for the // external DTD subset, or an empty string if none was declared. // @param systemId The declared system identifier for the // external DTD subset, or an empty string if none was declared. // (Note that this is not resolved against the document // base URI.) // @exception ESAXException The application may raise an // exception. // @see <a href="../SAXHelpers/TDefaultHandler2.html#endDTD">TDefaultHandler2.endDTD</a> // @see <a href="../SAXHelpers/TDefaultHandler2.html#startEntity">TDefaultHandler2.startEntity</a> procedure startDTD(const name, publicId, systemId : SAXString); virtual; // Report the end of DTD declarations. // // @exception ESAXException The application may raise an exception. // @see <a href="../SAXHelpers/TDefaultHandler2.html#startDTD">TDefaultHandler2.startDTD</a> procedure endDTD(); virtual; // Report the beginning of some internal and external XML entities. // // <ul> // <li>general entities within attribute values</li> // <li>parameter entities within declarations</li> // </ul> // // <p>These will be silently expanded, with no indication of where // the original entity boundaries were.</p> // // <p>Note also that the boundaries of character references (which // are not really entities anyway) are not reported.</p> // // <p>All start/endEntity events must be properly nested.</p> // // @param name The name of the entity. If it is a parameter // entity, the name will begin with '%', and if it is the // external DTD subset, it will be "[dtd]". // @exception SAXException The application may raise an exception. // @see <a href="../SAXHelpers/TDefaultHandler2.html#endEntity">TDefaultHandler2.endEntity</a> // @see <a href="../SAXExt/IDeclHandler.html#internalEntityDecl">IDeclHandler.internalEntityDecl</a> // @see <a href="../SAXExt/IDeclHandler.html#externalEntityDecl">IDeclHandler.externalEntityDecl</a> procedure startEntity(const name : SAXString); virtual; // Report the end of an entity. // // @param name The name of the entity that is ending. // @exception ESAXException The application may raise an exception. // @see <a href="../SAXHelpers/TDefaultHandler2.html#startEntity">TDefaultHandler2.startEntity</a> procedure endEntity(const name : SAXString); virtual; // Report the start of a CDATA section. // // @exception ESAXException The application may raise an exception. // @see <a href="../SAXHelpers/TDefaultHandler2.html#endCDATA">TDefaultHandler2.endCDATA</a> procedure startCDATA(); virtual; // Report the end of a CDATA section. // // @exception ESAXException The application may raise an exception. // @see <a href="../SAXHelpers/TDefaultHandler2.html#startCDATA">TDefaultHandler2.startCDATA</a> procedure endCDATA(); virtual; // Report an XML comment anywhere in the document. // // @param ch The characters in the comment. // @exception ESAXException The application may raise an exception. procedure comment(const ch : SAXString); virtual; // Allows applications to provide an external subset for documents // that don't explicitly define one. // // @param name Identifies the document root element. This name comes // from a DOCTYPE declaration (where available) or from the actual // root element. // @param baseURI The document's base URI, serving as an additional // hint for selecting the external subset. This is always an absolute // URI, unless it is an empty string because the IXMLReader was given an // IInputSource without one. // // @return An InputSource object describing the new external subset // to be used by the parser, or nil to indicate that no external // subset is provided. // // @exception ESAXException Any SAX exception. function getExternalSubset(const name, baseURI : SAXString) : IInputSource; virtual; // Tells the parser to resolve the systemId against the baseURI // and read the entity text from that resulting absolute URI. // Note that because the older // <a href="../SAXHelpers/TDefaultHandler.html#resolveEntity">TDefaultHandler.resolveEntity</a> // method is overridden to call this one, this method may sometimes // be invoked with null <em>name</em> and <em>baseURI</em>, and // with the <em>systemId</em> already absolutized. // // @param name Identifies the external entity being resolved. // Either '[dtd]' for the external subset, or a name starting // with '%' to indicate a parameter entity, or else the name of // a general entity. // @param publicId The public identifier of the external entity being // referenced (normalized as required by the XML specification), or // an empty string if none was supplied. // @param baseURI The URI with respect to which relative systemIDs // are interpreted. This is always an absolute URI, unless it is // nil because the XMLReader was given an IInputSource without one. // This URI is defined by the XML specification to be the one // associated with the '&lt;' starting the relevant declaration. // @param systemId The system identifier of the external entity // being referenced; either a relative or absolute URI. // // @return An IInputSource object describing the new input source to // be used by the parser. Returning nil directs the parser to // resolve the system ID against the base URI and open a connection // to resulting URI. // // @exception ESAXException Any SAX exception. function resolveEntity(const name, publicId, baseURI, systemId : SAXString) : IInputSource; reintroduce; overload; virtual; // Invokes // <a href="../SAXExt/IEntityResolver2.html#resolveEntity">IEntityResolver2.resolveEntity</a> // with empty entity name and base URI. // You only need to override that method to use this class. function resolveEntity(const publicId, systemId : SAXString) : IInputSource; reintroduce; overload; virtual; end; // SAX2 extension helper for holding additional Entity information, // implementing the <a href="../SAXExt/ILocator2.html">ILocator2</a> interface. // // <blockquote> // <em>This module, both source code and documentation, is in the // Public Domain, and comes with <strong>NO WARRANTY</strong>.</em> // </blockquote> // // <p> This is not part of core-only SAX2 distributions.</p> // // @since SAX 2.0 (extensions 1.1 alpha) TLocator2Impl = class(TLocatorImpl, ILocator2) private Fencoding : PSAXChar; Fversion : PSAXChar; protected // Returns the current value of the version property. // // @see <a href="../SAXHelpers/TLocator2Impl.html#setXMLVersion">TLocator2Impl.setXMLVersion</a> /// function getXMLVersion() : PSAXChar; // Returns the current value of the encoding property. // // @see <a href="../SAXHelpers/TLocator2Impl.html#setEncoding">TLocator2Impl.setEncoding</a> /// function getEncoding() : PSAXChar; public // Copy an existing ILocator or ILocator2 object. // If the object implements ILocator2, values of the // <em>encoding</em> and <em>version</em>strings are copied, // otherwise they set to an empty string. // // @param locator The existing ILocator object. constructor Create(locator : ILocator); override; // Assigns the current value of the version property. // // @param version the new "version" value // @see <a href="../SAXHelpers/TLocator2Impl.html#getXMLVersion">TLocator2Impl.getXMLVersion</a> /// procedure setXMLVersion(version : PSAXChar); // Assigns the current value of the encoding property. // // @param version the new "encoding" value // @see <a href="../SAXHelpers/TLocator2Impl.html#getEncoding">TLocator2Impl.getEncoding</a> /// procedure setEncoding(encoding : PSAXChar); end; // In this implementation, the lifetime of FMessage only spans // the call where it is returned through the error handler interface TSAXError = class(TInterfacedObject, ISAXError) private FMessage: PSAXChar; protected function getNativeError: IUnknown; virtual; public constructor create(message : PSAXChar); procedure init(message : PSAXChar); virtual; function getMessage() : PSAXChar; virtual; end; // In this implementation, the lifetime of FpublicId and FsystemId only spans // the call where it is returned through the error handler interface TSAXParseError = class(TSAXError, ISAXParseError) private FpublicId : PSAXChar; FsystemId : PSAXChar; FlineNumber : Integer; FcolumnNumber : Integer; public constructor create(message : PSAXChar; const locator: ILocator); overload; constructor create(const message : SAXString; publicId, systemId : PSAXChar; lineNumber, columnNumber : Integer); overload; procedure init(message: PSAXChar; const locator: ILocator); reintroduce; function getPublicId() : PSAXChar; function getSystemId() : PSAXChar; function getLineNumber() : Integer; function getColumnNumber() : Integer; end; TSAXNotRecognizedError = class(TSAXError, ISAXNotRecognizedError); TSAXNotSupportedError = class(TSAXError, ISAXNotSupportedError); TSAXIllegalStateError = class(TSAXError, ISAXIllegalStateError); TSAXIllegalArgumentError = class(TSAXError, ISAXIllegalArgumentError); var HandlerDefault: TDefaultHandler; implementation resourcestring sBadIndex = 'Attempt to modify attribute at illegal index: %d'; sCantChange = 'Cannot change %s %s while parsing'; sFeatureName = 'Feature: %s'; sFeatureCheck = 'feature'; sNoParent = 'No parent for filter'; sPropertyName = 'Property: %s'; sStackEmpty = 'Namespace stack empty'; sCantDeclare = 'Cannot declare any more prefixes in this context'; sNoAttributeAtIndex = 'No attribute at index: %d'; sNoAttributeLocalUri = 'No such attribute: local= %s, namespace= %s'; sNoAttributeQName = 'No such attribute: %s'; { TAttributesImpl } constructor TAttributesImpl.Create; begin inherited Create(); Flength:= 0; Fdata:= nil; end; constructor TAttributesImpl.Create(const atts: IAttributes); begin inherited Create(); Flength:= 0; Fdata:= nil; setAttributes(atts); end; destructor TAttributesImpl.Destroy; begin Fdata:= nil; inherited Destroy(); end; function TAttributesImpl.getLength: Integer; begin Result:= Flength; end; function TAttributesImpl.getURI(index: Integer): SAXString; begin if ((index >= 0) and (index < Flength)) then Result:= Fdata[index*5] else Result:= ''; end; function TAttributesImpl.getLocalName(index: Integer): SAXString; begin if ((index >= 0) and (index < Flength)) then Result:= Fdata[index*5+1] else Result:= ''; end; function TAttributesImpl.getQName(index: Integer): SAXString; begin if ((index >= 0) and (index < Flength)) then Result:= Fdata[index*5+2] else Result:= ''; end; function TAttributesImpl.getType(index: Integer): SAXString; begin if ((index >= 0) and (index < Flength)) then Result:= Fdata[index*5+3] else Result:= ''; end; function TAttributesImpl.getType(const uri, localName: SAXString): SAXString; var max, I : Integer; begin max:= Flength * 5; I:= 0; while I < max do begin if ((Fdata[I] = uri) and (Fdata[I+1] = localName)) then begin Result:= Fdata[I+3]; Exit; end; Inc(I, 5); end; Result:= ''; end; function TAttributesImpl.getType(const qName: SAXString): SAXString; var max, I : Integer; begin max:= Flength * 5; I:= 0; while I < max do begin if (Fdata[I+2] = qName) then begin Result:= Fdata[I+3]; Exit; end; Inc(I, 5); end; Result:= ''; end; function TAttributesImpl.getValue(index: Integer): SAXString; begin if ((index >= 0) and (index < Flength)) then Result:= Fdata[index*5+4] else Result:= ''; end; function TAttributesImpl.getValue(const uri, localName: SAXString): SAXString; var max, I : Integer; begin max:= Flength * 5; I:= 0; while I < max do begin if ((Fdata[I] = uri) and (Fdata[I+1] = localName)) then begin Result:= Fdata[I+4]; Exit; end; Inc(I, 5); end; Result:= ''; end; function TAttributesImpl.getValue(const qName: SAXString): SAXString; var max, I : Integer; begin max:= Flength * 5; I:= 0; while I < max do begin if (Fdata[I+2] = qName) then begin Result:= Fdata[I+4]; Exit; end; Inc(I, 5); end; Result:= ''; end; function TAttributesImpl.getIndex(const uri, localName: SAXString): Integer; var max, I : Integer; begin max:= Flength * 5; I:= 0; while I < max do begin if ((Fdata[I] = uri) and (Fdata[I+1] = localName)) then begin Result:= I div 5; Exit; end; Inc(I, 5); end; Result:= -1; end; function TAttributesImpl.getIndex(const qName: SAXString): Integer; var max, I : Integer; begin max:= Flength * 5; I:= 0; while I < max do begin if (Fdata[I+2] = qName) then begin Result:= I div 5; Exit; end; Inc(I, 5); end; Result:= -1; end; procedure TAttributesImpl.clear; var i : Integer; begin if (Fdata <> nil) then begin for i:= 0 to (Flength * 5)-1 do Fdata[i]:= ''; end; Flength:= 0; end; procedure TAttributesImpl.setAttributes(const atts: IAttributes); var I : Integer; begin // Can this be sped up with a move or copy? clear(); Flength:= atts.getLength(); if (Flength > 0) then begin Fdata:= nil; SetLength(Fdata, Flength * 5); for I:= 0 to Flength-1 do begin Fdata[I*5]:= atts.getURI(I); Fdata[I*5+1]:= atts.getLocalName(I); Fdata[I*5+2]:= atts.getQName(I); Fdata[I*5+3]:= atts.getType(I); Fdata[I*5+4]:= atts.getValue(I); end; end; end; procedure TAttributesImpl.addAttribute(const uri, localName, qName, attrType, value: SAXString); begin ensureCapacity(Flength + 1); Fdata[Flength*5]:= uri; Fdata[Flength*5+1]:= localName; Fdata[Flength*5+2]:= qName; Fdata[Flength*5+3]:= attrType; Fdata[Flength*5+4]:= value; Inc(Flength); end; procedure TAttributesImpl.setAttribute(index : Integer; const uri, localName, qName, attrType, value: SAXString); begin if ((index >= 0) and (index < Flength)) then begin Fdata[index*5]:= uri; Fdata[index*5+1]:= localName; Fdata[index*5+2]:= qName; Fdata[index*5+3]:= attrType; Fdata[index*5+4]:= value; end else badIndex(index); end; procedure TAttributesImpl.removeAttribute(index: Integer); var Source : Pointer; Dest : Pointer; FromBytes, ToBytes, TotalBytes, NewLen, I : Integer; FromIndex, ToIndex : Integer; aIndex : Integer; begin if ((index >= 0) and (index < Flength)) then begin if (index < Flength-1) then begin // Deletes a block from the array FromIndex:= index*5; ToIndex:= index*5+4; for I:= FromIndex to ToIndex do FData[I]:= ''; Dest:= Pointer(FData); Source:= Pointer(FData); FromBytes:= SizeOf(SAXString) * FromIndex; ToBytes:= SizeOf(SAXString) * (ToIndex + 1); TotalBytes:= SizeOf(SAXString) * (Length(FData) - ToIndex); NewLen:= Length(FData) - ((ToIndex - FromIndex) + 1); Inc(Cardinal(Dest), FromBytes); Inc(Cardinal(Source), ToBytes); Move(Source^, Dest^, TotalBytes); SetLength(FData, NewLen); end; aIndex:= (Flength - 1) * 5; Fdata[aIndex]:= ''; Fdata[aIndex+1]:= ''; Fdata[aIndex+2]:= ''; Fdata[aIndex+3]:= ''; Fdata[aIndex+4]:= ''; Dec(Flength); end else badIndex(index); end; procedure TAttributesImpl.setURI(index: Integer; const uri: SAXString); begin if ((index >= 0) and (index < Flength)) then Fdata[index*5]:= uri else badIndex(index); end; procedure TAttributesImpl.setLocalName(index: Integer; const localName: SAXString); begin if ((index >= 0) and (index < Flength)) then Fdata[index*5+1]:= localName else badIndex(index); end; procedure TAttributesImpl.setQName(index: Integer; const qName: SAXString); begin if ((index >= 0) and (index < Flength)) then Fdata[index*5+2]:= qName else badIndex(index); end; procedure TAttributesImpl.setType(index: Integer; const attrType: SAXString); begin if ((index >= 0) and (index < Flength)) then Fdata[index*5+3]:= attrType else badIndex(index); end; procedure TAttributesImpl.setValue(index: Integer; const value: SAXString); begin if ((index >= 0) and (index < Flength)) then Fdata[index*5+4]:= value else badIndex(index); end; procedure TAttributesImpl.ensureCapacity(n: Integer); var max : Integer; begin if (n <= 0) then begin Exit; end; if ((Fdata = nil) or (Length(Fdata)=0)) then begin max:= 25; end else if (Length(Fdata) >= n * 5) then begin Exit; end else begin max:= Length(Fdata); end; while (max < n * 5) do max:= max * 2; SetLength(Fdata, max); end; procedure TAttributesImpl.badIndex(index: Integer); begin raise Exception.Create(Format(sBadIndex, [index])); end; { TDefaultHandler } function TDefaultHandler.resolveEntity(const publicId, systemId: SAXString): IInputSource; begin Result:= nil; end; procedure TDefaultHandler.notationDecl(const name, publicId, systemId: SAXString); begin // no op end; procedure TDefaultHandler.unparsedEntityDecl(const name, publicId, systemId, notationName: SAXString); begin // no op end; procedure TDefaultHandler.setDocumentLocator(const Locator: ILocator); begin // no op end; procedure TDefaultHandler.startDocument; begin // no op end; procedure TDefaultHandler.endDocument; begin // no op end; procedure TDefaultHandler.startPrefixMapping(const prefix, uri: SAXString); begin // no op end; procedure TDefaultHandler.endPrefixMapping(const prefix: SAXString); begin // no op end; procedure TDefaultHandler.startElement(const uri, localName, qName: SAXString; const atts: IAttributes); begin // no op end; procedure TDefaultHandler.endElement(const uri, localName, qName: SAXString); begin // no op end; procedure TDefaultHandler.characters(const ch : SAXString); begin // no op end; procedure TDefaultHandler.ignorableWhitespace(const ch : SAXString); begin // no op end; procedure TDefaultHandler.processingInstruction(const target, data: SAXString); begin // no op end; procedure TDefaultHandler.skippedEntity(const name: SAXString); begin // no op end; procedure TDefaultHandler.warning(const e: ISAXParseError); begin // no op end; procedure TDefaultHandler.error(const e: ISAXParseError); begin // no op end; procedure TDefaultHandler.fatalError(const e: ISAXParseError); begin // no op end; { TLocatorImpl } constructor TLocatorImpl.Create; begin inherited Create(); end; constructor TLocatorImpl.Create(locator: ILocator); begin inherited Create(); setPublicId(locator.getPublicId()); setSystemId(locator.getSystemId()); setLineNumber(locator.getLineNumber()); setColumnNumber(locator.getColumnNumber()); end; procedure TLocatorImpl.setPublicId(publicId: PSAXChar); begin FpublicId:= publicId; end; procedure TLocatorImpl.setSystemId(systemId: PSAXChar); begin FsystemId:= systemId; end; procedure TLocatorImpl.setLineNumber(lineNumber: Integer); begin FlineNumber:= lineNumber; end; procedure TLocatorImpl.setColumnNumber(columnNumber: Integer); begin FcolumnNumber:= columnNumber; end; function TLocatorImpl.getPublicId: PSAXChar; begin Result:= FpublicId; end; function TLocatorImpl.getSystemId: PSAXChar; begin Result:= FsystemId; end; function TLocatorImpl.getLineNumber: Integer; begin Result:= FlineNumber; end; function TLocatorImpl.getColumnNumber: Integer; begin Result:= FcolumnNumber; end; { TContext } constructor TNamespaceContext.Create; begin inherited Create(); FprefixTableLength:= 0; FuriTableLength:= 0; FelementNameTableLength:= 0; FattributeNameTableLength:= 0; FdeclSeen:= False; FdeclsOK:= true; FdefaultNS:= ''; copyTables(); end; destructor TNamespaceContext.Destroy; begin inherited Destroy(); end; procedure TNamespaceContext.setParent(const parent: TNamespaceContext); begin Fparent:= parent; Fdeclarations:= nil; FdefaultNS:= Fparent.defaultNS; FdeclSeen:= false; FdeclsOK:= true; end; procedure TNamespaceContext.clear; begin Fparent:= nil; Fdeclarations:= nil; FprefixTableLength:= 0; FuriTableLength:= 0; FelementNameTableLength:= 0; FattributeNameTableLength:= 0; FdefaultNS:= ''; end; procedure TNamespaceContext.declarePrefix(const prefix, uri: SAXString); begin declarePrefix(PSAXChar(prefix), Length(prefix), PSAXChar(uri), Length(uri)); end; procedure TNamespaceContext.declarePrefix(prefix : PSAXChar; prefixLength : Integer; uri : PSAXChar; uriLength : Integer); var i : Integer; found : Boolean; begin // Lazy Processing... if (not FdeclsOK) then raise ESAXIllegalStateException.Create(sCantDeclare); if (not FdeclSeen) then begin // It is a ref to the parent tables and we need to modify-- copy and then modify copyTables(); end; if (Fdeclarations = nil) then begin SetLength(Fdeclarations, 0); end; if (prefixLength = 0) or (prefix = '') then begin if (uriLength = 0) or (uri = '') then FdefaultNS:= '' else FdefaultNS:= PSAXCharToSAXString(uri, uriLength); end else begin found:= False; for i:= 0 to FprefixTableLength-1 do begin if (SAXStrEqual(PSAXChar(FprefixTable[i]), -1, prefix, prefixLength)) then begin found:= true; FprefixTableElements[i]:= PSAXCharToSAXString(uri, uriLength); break; end; end; if (not found) then begin Inc(FprefixTableLength); if (Length(FprefixTable) < FprefixTableLength) then SetLength(FprefixTable, FprefixTableLength); if (Length(FprefixTableElements) < FprefixTableLength) then SetLength(FprefixTableElements, FprefixTableLength); FprefixTable[FprefixTableLength-1]:= PSAXCharToSAXString(prefix, prefixLength); FprefixTableElements[FprefixTableLength-1]:= PSAXCharToSAXString(uri, uriLength); end; // may wipe out another prefix found:= False; for i:= 0 to FuriTableLength-1 do begin if (SAXStrEqual(PSAXChar(FuriTable[i]), -1, uri, uriLength)) then begin found:= true; FuriTableElements[i]:= PSAXCharToSAXString(prefix, prefixLength); break; end; end; if (not found) then begin Inc(FuriTableLength); if (Length(FuriTable) < FuriTableLength) then SetLength(FuriTable, FuriTableLength); if (Length(FuriTableElements) < FuriTableLength) then SetLength(FuriTableElements, FuriTableLength); FuriTable[FuriTableLength-1]:= PSAXCharToSAXString(uri, uriLength); FuriTableElements[FuriTableLength-1]:= PSAXCharToSAXString(prefix, prefixLength); end; end; SetLength(Fdeclarations, Length(Fdeclarations) + 1); Fdeclarations[Length(Fdeclarations)-1]:= PSAXCharToSAXString(prefix, prefixLength); end; function TNamespaceContext.processName(const qName: SAXString; isAttribute: Boolean): TNamespaceParts; begin Result:= processName(PSAXChar(qName), -1, isAttribute); end; function TNamespaceContext.processName(qName : PSAXChar; qNameLength : Integer; isAttribute : Boolean) : TNamespaceParts; var name : TNamespaceParts; index, i : Integer; prefix, local, uri : SAXString; begin // detect errors in call sequence FdeclsOK:= false; // Start by looking in the cache, and return immediately if the name is already // known in this content if (isAttribute) then begin for i:= 0 to FattributeNameTableLength-1 do begin if (SAXStrEqual(PSAXChar(FattributeNameTable[i]), -1, qName, qNameLength)) then begin Result:= FattributeNameTableElements[i]; Exit; end; end; end else begin for i:= 0 to FelementNameTableLength-1 do begin if (SAXStrEqual(PSAXChar(FelementNameTable[i]), -1, qName, qNameLength)) then begin Result:= FelementNameTableElements[i]; Exit; end; end; end; // We haven't seen this name in this // context before. Maybe in the parent // context, but we can't assume prefix // bindings are the same. name[nsQName]:= PSAXCharToSAXString(qName, qNameLength); index:= Pos(':', name[nsQName]); // No prefix. if (index < 1) then begin if (isAttribute) then begin if (qName = 'xmlns') and (FnamespaceDeclUris) then name[nsURI]:= XML_NSDECL else name[nsURI]:= ''; end else if (FdefaultNS = '') then name[nsURI]:= '' else name[nsURI]:= FdefaultNS; name[nsLocal]:= name[nsQName]; end else // Prefix begin prefix:= Copy(qName, 1, index-1); local:= Copy(qName, index+1, Length(qName)); if ('' = prefix) then uri:= FdefaultNS else begin // again we have to check if we should use the parent uri:= ''; for i:= 0 to prefixTableLength-1 do begin if (prefix = prefixTable[i]) then begin uri:= prefixTableElements[i]; break; end; end; end; if ('' = uri) or ((not isAttribute) and ('xmlns' = prefix)) then begin name[nsURI]:= ''; name[nsLocal]:= ''; name[nsQName]:= ''; Result:= name; Exit; end; name[nsURI]:= uri; name[nsLocal]:= local; end; // Save in the cache for future use. // (Could be shared with parent context...) if (isAttribute) then begin index:= -1; for i:= 0 to FattributeNameTableLength-1 do begin if (FattributeNameTable[i] = name[nsQName]) then begin FattributeNameTableElements[index]:= name; index:= i; break; end; end; if (index = -1) then begin Inc(FattributeNameTableLength); if (Length(FattributeNameTable) < FattributeNameTableLength) then SetLength(FattributeNameTable, FattributeNameTableLength); if (Length(FattributeNameTableElements) < FattributeNameTableLength) then SetLength(FattributeNameTableElements, FattributeNameTableLength); FattributeNameTable[FattributeNameTableLength-1]:= name[nsQName]; FattributeNameTableElements[FattributeNameTableLength-1]:= name; end; end else begin index:= -1; for i:= 0 to FelementNameTableLength-1 do begin if (FelementNameTable[i] = name[nsQName]) then begin FelementNameTableElements[index]:= name; index:= i; break; end; end; if (index = -1) then begin Inc(FelementNameTableLength); if (Length(FelementNameTable) < FelementNameTableLength) then SetLength(FelementNameTable, FelementNameTableLength); if (Length(FelementNameTableElements) < FelementNameTableLength) then SetLength(FelementNameTableElements, FelementNameTableLength); FelementNameTable[FelementNameTableLength-1]:= name[nsQName]; FelementNameTableElements[FelementNameTableLength-1]:= name; end; end; Result:= name; end; function TNamespaceContext.getURI(const prefix: SAXString): SAXString; begin Result:= getURI(PSAXChar(prefix), -1); end; function TNamespaceContext.getURI(prefix : PSAXChar; prefixLength : Integer) : PSAXChar; var i : Integer; begin if ((prefixLength = 0) or ('' = prefix)) then Result:= PSAXChar(FdefaultNS) else if (FprefixTable = nil) then Result:= '' else begin // again we have to check if we should use the parent Result:= ''; for i:= 0 to prefixTableLength-1 do begin if (SAXStrEqual(PSAXChar(prefixTable[i]), -1, prefix, prefixLength)) then begin Result:= PSAXChar(prefixTableElements[i]); break; end; end; end; end; function TNamespaceContext.getPrefix(const uri: SAXString): SAXString; begin end; function TNamespaceContext.getPrefix(uri : PSAXChar; uriLength : Integer) : PSAXChar; var i : Integer; begin if (FuriTable = nil) then Result:= '' else begin // again we have to check if we should use the parent Result:= ''; for i:= 0 to uriTableLength-1 do begin if (SAXStrEqual(PSAXChar(uriTable[i]), -1, uri, uriLength)) then begin Result:= PSAXChar(uriTableElements[i]); break; end; end; end; end; function TNamespaceContext.getDeclaredPrefixes: SAXStringArray; begin if (Fdeclarations = nil) then Result:= EMPTY_ENUMERATION else begin Result:= Copy(declarations, 0, Length(declarations)-1); end; end; function TNamespaceContext.getPrefixes: SAXStringArray; begin if (FprefixTable <> nil) then Result:= EMPTY_ENUMERATION else begin Result:= Copy(prefixTable, 0, prefixTableLength-1); end; end; procedure TNamespaceContext.copyTables; var i : Integer; begin if (Fparent <> nil) then begin // Create a clone FprefixTableLength:= Fparent.prefixTableLength; if (Length(FprefixTable) < FprefixTableLength) then SetLength(FprefixTable, FprefixTableLength); if (Length(FprefixTableElements) < FprefixTableLength) then SetLength(FprefixTableElements, FprefixTableLength); for i:= 0 to Fparent.prefixTableLength-1 do begin FprefixTable[i]:= Fparent.prefixTable[i]; FprefixTableElements[i]:= Fparent.prefixTableElements[i]; end; FuriTableLength:= Fparent.uriTableLength; if (Length(FuriTable) < FuriTableLength) then SetLength(FuriTable, FuriTableLength); if (Length(FuriTableElements) < FuriTableLength) then SetLength(FuriTableElements, FuriTableLength); for i:= 0 to Fparent.uriTableLength-1 do begin FuriTable[i]:= Fparent.uriTable[i]; FuriTableElements[i]:= Fparent.uriTableElements[i]; end; end; // Simply override the refs FelementNameTableLength:= 0; FattributeNameTableLength:= 0; // It's dirty FdeclSeen:= True; end; { TNamespaceSupport } constructor TNamespaceSupport.Create; begin inherited Create(); Fcontexts:= TList.Create; reset(); end; destructor TNamespaceSupport.Destroy; begin freeContexts(); Fcontexts.Free; inherited Destroy(); end; procedure TNamespaceSupport.freeContexts; var I : Integer; begin for I:= 0 to Fcontexts.Count-1 do begin if (Fcontexts[i] <> nil) then TNamespaceContext(Fcontexts[i]).Free; end; Fcontexts.Clear; Fcontexts.Count:= 32; end; procedure TNamespaceSupport.reset; begin freeContexts(); FnamespaceDeclUris:= false; FcontextPos:= 0; FcurrentContext:= TNamespaceContext.Create(); FcurrentContext.declarePrefix('xml', XML_XMLNS); FcurrentContext.FnamespaceDeclUris:= FnamespaceDeclUris; Fcontexts[FcontextPos]:= FcurrentContext; end; procedure TNamespaceSupport.pushContext; var max : Integer; begin max:= Fcontexts.Count; TNamespaceContext(Fcontexts[FcontextPos]).FdeclsOK:= false; TNamespaceContext(Fcontexts[FcontextPos]).FnamespaceDeclUris:= FnamespaceDeclUris; Inc(FcontextPos); // Extend the array if necessary if (FcontextPos >= max) then begin Fcontexts.Count:= max * 2; end; // Allocate the context if necessary. FcurrentContext:= Fcontexts[FcontextPos]; if (FcurrentContext = nil) then begin FcurrentContext:= TNamespaceContext.Create; FcurrentContext.FnamespaceDeclUris:= FnamespaceDeclUris; Fcontexts[FcontextPos]:= FcurrentContext; end; // Set the parent, if any. if (FcontextPos > 0) then FcurrentContext.setParent(Fcontexts[FcontextPos-1]); end; procedure TNamespaceSupport.popContext; begin // We need to clear the current context FcurrentContext.clear(); // Back to normal Dec(FcontextPos); if (FcontextPos < 0) then raise Exception.Create(sStackEmpty); FcurrentContext:= Fcontexts[FcontextPos]; end; function TNamespaceSupport.declarePrefix(const prefix, uri: SAXString) : Boolean; begin Result:= declarePrefix(PSAXChar(prefix), -1, PSAXChar(uri), -1); end; function TNamespaceSupport.declarePrefix(prefix : PSAXChar; prefixLength : Integer; uri : PSAXChar; uriLength : Integer) : Boolean; var xml, xmlns : SAXString; begin xml:= 'xml'; xmlns:= 'xmlns'; if (SAXStrEqual(PSAXChar(xml), -1, prefix, prefixLength) or SAXStrEqual(PSAXChar(xmlns), -1, prefix, prefixLength)) then Result:= False else begin FcurrentContext.declarePrefix(prefix, prefixLength, uri, uriLength); Result:= True; end; end; function TNamespaceSupport.processName(const qName: SAXString; var parts : TNamespaceParts; isAttribute: Boolean): TNamespaceParts; begin Result:= processName(PSAXChar(qName), -1, parts, isAttribute); end; function TNamespaceSupport.processName(qName : PSAXChar; qNameLength : Integer; var parts : TNamespaceParts; isAttribute : Boolean) : TNamespaceParts; var myParts : TNamespaceParts; begin myParts:= FcurrentContext.processName(qName, qNameLength, isAttribute); if (myParts[nsURI] = '') and (myParts[nsLocal] = '') and (myParts[nsQName] = '') then Result:= myParts else begin parts[nsURI] := myParts[nsURI]; parts[nsLocal]:= myParts[nsLocal]; parts[nsQName]:= myParts[nsQName]; Result:= parts; end; end; function TNamespaceSupport.getURI(const prefix: SAXString): SAXString; begin Result:= getURI(PSAXChar(prefix), -1); end; function TNamespaceSupport.getURI(prefix : PSAXChar; prefixLength : Integer) : PSAXChar; begin Result:= FcurrentContext.getURI(prefix, prefixLength); end; function TNamespaceSupport.getPrefixes: SAXStringArray; begin Result:= FcurrentContext.getPrefixes(); end; function TNamespaceSupport.getPrefix(const uri: SAXString): SAXString; begin Result:= getPrefix(PSAXChar(uri), -1); end; function TNamespaceSupport.getPrefix(uri : PSAXChar; uriLength : Integer) : PSAXChar; begin Result:= FcurrentContext.getPrefix(uri, uriLength); end; function TNamespaceSupport.getPrefixes(const uri : SAXString) : SAXStringArray; begin Result:= getPrefixes(PSAXChar(uri), -1); end; function TNamespaceSupport.getPrefixes(uri : PSAXChar; uriLength : Integer) : SAXStringArray; var prefixes : SAXStringArray; allPrefixes : SAXStringArray; i, Len : Integer; prefix : SAXString; begin Len:= 0; SetLength(prefixes, Len); allPrefixes:= getPrefixes(); for i:= 0 to Length(allPrefixes)-1 do begin prefix:= allPrefixes[i]; if (SAXStrEqual(PSAXChar(getURI(prefix)), -1, uri, uriLength)) then begin Inc(Len); SetLength(prefixes, Len); prefixes[Len-1]:= prefix; end; end; Result:= prefixes; end; function TNamespaceSupport.getDeclaredPrefixes: SAXStringArray; begin Result:= FcurrentContext.getDeclaredPrefixes(); end; procedure TNamespaceSupport.setNamespaceDeclUris(value : Boolean); begin if (FcontextPos <> 0) then raise ESAXIllegalStateException.Create(''); if (value = FnamespaceDeclUris) then Exit; FnamespaceDeclUris:= value; if (value) then FcurrentContext.declarePrefix('xmlns', XML_NSDECL) else begin // Allocate the context if necessary. FcurrentContext:= Fcontexts[FcontextPos]; if (FcurrentContext = nil) then begin FcurrentContext:= TNamespaceContext.Create; FcurrentContext.FnamespaceDeclUris:= FnamespaceDeclUris; Fcontexts[FcontextPos]:= FcurrentContext; end; FcurrentContext.declarePrefix('xml', XML_XMLNS); end; end; function TNamespaceSupport.isNamespaceDeclUris() : Boolean; begin Result:= FnamespaceDeclUris; end; { TXMLFilterImpl } constructor TXMLFilterImpl.Create; begin inherited Create(); Fparent:= nil; Flocator:= nil; FentityResolver:= nil; FdtdHandler:= nil; FcontentHandler:= nil; FerrorHandler:= nil; end; constructor TXMLFilterImpl.Create(const parent: IXMLReader); begin inherited Create(); setParent(parent); Flocator:= nil; FentityResolver:= nil; FdtdHandler:= nil; FcontentHandler:= nil; FerrorHandler:= nil; end; procedure TXMLFilterImpl.setParent(const parent: IXMLReader); begin Fparent:= parent; end; function TXMLFilterImpl.getParent: IXMLReader; begin Result:= Fparent; end; procedure TXMLFilterImpl.setFeature(const name: SAXString; value: Boolean); begin if (Fparent <> nil) then Fparent.setFeature(name, value) else raise ESAXNotRecognizedException.Create(Format(sFeatureName, [Name])); end; function TXMLFilterImpl.getFeature(const name: SAXString): Boolean; begin if (Fparent <> nil) then Result:= Fparent.getFeature(name) else raise ESAXNotRecognizedException.Create(Format(sFeatureName, [Name])); end; function TXMLFilterImpl.getProperty(const name: SAXString) : IProperty; begin if (Fparent <> nil) then Result:= Fparent.getProperty(name) else raise ESAXNotRecognizedException.Create(Format(sPropertyName, [Name])); end; procedure TXMLFilterImpl.setEntityResolver( const resolver: IEntityResolver); begin FentityResolver:= resolver; end; function TXMLFilterImpl.getEntityResolver: IEntityResolver; begin Result:= FentityResolver; end; procedure TXMLFilterImpl.setDTDHandler(const handler: IDTDHandler); begin FdtdHandler:= handler; end; function TXMLFilterImpl.getDTDHandler: IDTDHandler; begin Result:= FdtdHandler; end; procedure TXMLFilterImpl.setContentHandler( const handler: IContentHandler); begin FcontentHandler:= handler; end; function TXMLFilterImpl.getContentHandler: IContentHandler; begin Result:= FcontentHandler; end; procedure TXMLFilterImpl.setErrorHandler(const handler: IErrorHandler); begin FerrorHandler:= handler; end; function TXMLFilterImpl.getErrorHandler: IErrorHandler; begin Result:= FerrorHandler; end; procedure TXMLFilterImpl.parse(const input: IInputSource); begin setupParse(); Fparent.parse(input); end; procedure TXMLFilterImpl.parse(const systemId: SAXString); var source : IInputSource; begin source:= TInputSource.Create(systemId) as IInputSource; try parse(source); finally source:= nil; end; end; function TXMLFilterImpl.resolveEntity(const publicId, systemId: SAXString): IInputSource; begin if (FentityResolver <> nil) then Result:= FentityResolver.resolveEntity(publicId, systemId) else Result:= nil; end; procedure TXMLFilterImpl.notationDecl(const name, publicId, systemId: SAXString); begin if (FdtdHandler <> nil) then FdtdHandler.notationDecl(name, publicId, systemId); end; procedure TXMLFilterImpl.unparsedEntityDecl(const name, publicId, systemId, notationName: SAXString); begin if (FdtdHandler <> nil) then FdtdHandler.unparsedEntityDecl(name, publicId, systemId, notationName); end; procedure TXMLFilterImpl.setDocumentLocator(const locator: ILocator); begin Flocator:= locator; if (FcontentHandler <> nil) then FcontentHandler.setDocumentLocator(locator); end; procedure TXMLFilterImpl.startDocument; begin if (FcontentHandler <> nil) then FcontentHandler.startDocument(); end; procedure TXMLFilterImpl.endDocument; begin if (FcontentHandler <> nil) then FcontentHandler.endDocument(); end; procedure TXMLFilterImpl.startPrefixMapping(const prefix, uri: SAXString); begin if (FcontentHandler <> nil) then FcontentHandler.startPrefixMapping(prefix, uri); end; procedure TXMLFilterImpl.endPrefixMapping(const prefix: SAXString); begin if (FcontentHandler <> nil) then FcontentHandler.endPrefixMapping(prefix); end; procedure TXMLFilterImpl.startElement(const uri, localName, qName: SAXString; const atts: IAttributes); begin if (FcontentHandler <> nil) then FcontentHandler.startElement(uri, localName, qName, atts); end; procedure TXMLFilterImpl.endElement(const uri, localName, qName: SAXString); begin if (FcontentHandler <> nil) then FcontentHandler.endElement(uri, localName, qName); end; procedure TXMLFilterImpl.characters(const ch : SAXString); begin if (FcontentHandler <> nil) then FcontentHandler.characters(ch); end; procedure TXMLFilterImpl.ignorableWhitespace(const ch : SAXString); begin if (FcontentHandler <> nil) then FcontentHandler.ignorableWhitespace(ch); end; procedure TXMLFilterImpl.processingInstruction(const target, data: SAXString); begin if (FcontentHandler <> nil) then FcontentHandler.processingInstruction(target, data); end; procedure TXMLFilterImpl.skippedEntity(const name: SAXString); begin if (FcontentHandler <> nil) then FcontentHandler.skippedEntity(name); end; procedure TXMLFilterImpl.warning(const e: ISAXParseError); begin if (FerrorHandler <> nil) then FerrorHandler.warning(e); end; procedure TXMLFilterImpl.error(const e: ISAXParseError); begin if (FerrorHandler <> nil) then FerrorHandler.error(e); end; procedure TXMLFilterImpl.fatalError(const e: ISAXParseError); begin if (FerrorHandler <> nil) then FerrorHandler.fatalError(e); end; procedure TXMLFilterImpl.setupParse; begin if (Fparent = nil) then raise ESAXException.Create(sNoParent) else begin Fparent.setEntityResolver(self); Fparent.setDTDHandler(self); Fparent.setContentHandler(self); Fparent.setErrorHandler(self); end; end; { TXMLReaderImpl } constructor TXMLReaderImpl.Create; begin inherited Create; setContentHandler(nil); setDTDHandler(nil); setEntityResolver(nil); setErrorHandler(nil); FcolumnNumber := -1; FlineNumber := -1; Fnamespaces := True; Fparsing := False; Fprefixes := False; FpublicId := ''; FsystemId := ''; end; destructor TXMLReaderImpl.Destroy; begin FcontentHandler:= nil; FdtdHandler := nil; FentityResolver:= nil; FerrorHandler := nil; inherited; end; procedure TXMLReaderImpl.checkNotParsing(const propType, name: SAXString); begin if Fparsing then raise ESAXNotSupportedException.Create(Format(sCantChange, [propType, name])); end; function TXMLReaderImpl.getColumnNumber: Integer; begin Result:= FcolumnNumber; end; function TXMLReaderImpl.getContentHandler: IContentHandler; begin Result:= FcontentHandler; end; function TXMLReaderImpl.getDTDHandler: IDTDHandler; begin Result:= FdtdHandler; end; function TXMLReaderImpl.getEntityResolver: IEntityResolver; begin Result:= FentityResolver; end; function TXMLReaderImpl.getErrorHandler: IErrorHandler; begin Result:= FerrorHandler; end; function TXMLReaderImpl.getFeature(const name: SAXString): Boolean; begin if (name = NamespacesFeature) then Result:= Fnamespaces else if (name = NamespacePrefixesFeature) then Result:= FPrefixes else if (name = ValidationFeature) or (name = ExternalGeneralFeature) or (name = ExternalParameterFeature) then raise ESAXNotSupportedException.Create(Format(sFeatureName, [name])) else raise ESAXNotRecognizedException.Create(Format(sFeatureName, [name])); end; function TXMLReaderImpl.getLineNumber: Integer; begin Result:= FlineNumber; end; function TXMLReaderImpl.getProperty(const name: SAXString) : IProperty; begin raise ESAXNotRecognizedException.Create(Format(sPropertyName, [name])); end; function TXMLReaderImpl.getPublicId: PSAXChar; begin Result:= PSAXChar(FpublicId); end; function TXMLReaderImpl.getSystemId: PSAXChar; begin Result:= PSAXChar(FsystemId); end; procedure TXMLReaderImpl.parse(const input: IInputSource); begin FpublicId:= input.publicId; FsystemId:= input.systemId; Fparsing := True; try parseInput(input); finally Fparsing:= False; end; end; procedure TXMLReaderImpl.parse(const systemId: SAXString); var input: IInputSource; resolver : IEntityResolver; begin resolver:= getEntityResolver(); if Assigned(resolver) then input:= resolver.resolveEntity('', systemId); if not Assigned(input) then input:= TInputSource.Create(systemId) as IInputSource; try parse(input); finally input:= nil; end; end; procedure TXMLReaderImpl.setColumnNumber(value: Integer); begin FcolumnNumber:= value; end; procedure TXMLReaderImpl.setContentHandler(const handler: IContentHandler); begin if Assigned(handler) then FcontentHandler:= handler else FcontentHandler:= handlerDefault; end; procedure TXMLReaderImpl.setDTDHandler(const handler: IDTDHandler); begin if Assigned(handler) then FdtdHandler:= handler else FdtdHandler:= handlerDefault; end; procedure TXMLReaderImpl.setEntityResolver( const resolver: IEntityResolver); begin if Assigned(resolver) then FentityResolver:= resolver else FentityResolver:= handlerDefault; end; procedure TXMLReaderImpl.setErrorHandler(const handler: IErrorHandler); begin if Assigned(handler) then FerrorHandler:= handler else FerrorHandler:= handlerDefault; end; procedure TXMLReaderImpl.setFeature(const name: SAXString; value: Boolean); begin // The only features supported are namespaces and namespace-prefixes. if name = namespacesFeature then begin checkNotParsing(sFeatureCheck, name); Fnamespaces:= value; if not Fnamespaces and not Fprefixes then Fprefixes:= True; end else if name = namespacePrefixesFeature then begin checkNotParsing(sFeatureCheck, name); Fprefixes:= Value; if not Fprefixes and not Fnamespaces then Fnamespaces:= True; end else if (name = ValidationFeature) or (name = ExternalGeneralFeature) or (name = ExternalParameterFeature) then raise ESAXNotSupportedException.Create(Format(sFeatureName, [name])) else raise ESAXNotRecognizedException.Create(Format(sFeatureName, [name])); end; procedure TXMLReaderImpl.setLineNumber(value: Integer); begin FlineNumber:= value; end; procedure TXMLReaderImpl.setPublicId(value: PSAXChar); begin FpublicId:= value; end; procedure TXMLReaderImpl.setSystemId(value: PSAXChar); begin FsystemId:= value; end; { TNamespaceContext } function TNamespaceContext.getDefaultNS: PSAXChar; begin if (FdeclSeen) then Result:= PSAXChar(FdefaultNS) else Result:= PSAXChar(Fparent.defaultNS); end; function TNamespaceContext.getPrefixTable: SAXStringArray; begin if (FdeclSeen) then Result:= FprefixTable else Result:= Fparent.prefixTable; end; function TNamespaceContext.getPrefixTableElements: SAXStringArray; begin if (FdeclSeen) then Result:= FprefixTableElements else Result:= Fparent.prefixTableElements; end; function TNamespaceContext.getPrefixTableLength: Integer; begin if (FdeclSeen) then Result:= FprefixTableLength else Result:= Fparent.prefixTableLength; end; function TNamespaceContext.getUriTable: SAXStringArray; begin if (FdeclSeen) then Result:= FuriTable else Result:= Fparent.uriTable; end; function TNamespaceContext.getUriTableElements: SAXStringArray; begin if (FdeclSeen) then Result:= FuriTableElements else Result:= Fparent.uriTableElements; end; function TNamespaceContext.getUriTableLength: Integer; begin if (FdeclSeen) then Result:= FuriTableLength else Result:= Fparent.uriTableLength; end; function TNamespaceContext.getDeclarations: SAXStringArray; begin if (FdeclSeen) then Result:= Fdeclarations else Result:= Fparent.declarations; end; { TAttributes2Impl } procedure TAttributes2Impl.addAttribute(const uri, localName, qName, attrType, value: SAXString); var len : Integer; begin inherited addAttribute(uri, localName, qName, attrType, value); len:= getLength(); if (len < Length(Fspecified)) then begin SetLength(Fdeclared, len); SetLength(Fspecified, len); end; Fspecified[len - 1]:= true; Fdeclared[len - 1]:= not (attrType = 'CDATA'); end; function TAttributes2Impl.isDeclared(index : Integer) : Boolean; begin if ((index < 0) or (index >= getLength())) then raise ESAXIllegalArgumentException.CreateFmt(sNoAttributeAtIndex, [index]); Result:= Fdeclared[index]; end; function TAttributes2Impl.isDeclared(const qName : SAXString) : Boolean; var index : Integer; begin index:= getIndex(qName); if (index < 0) then raise ESAXIllegalArgumentException.CreateFmt(sNoAttributeQName, [qName]); Result:= Fdeclared[index]; end; function TAttributes2Impl.isDeclared(const uri, localName : SAXString) : Boolean; var index : Integer; begin index:= getIndex(uri, localName); if (index < 0) then raise ESAXIllegalArgumentException.CreateFmt(sNoAttributeLocalUri, [localName, uri]); Result:= Fdeclared[index]; end; function TAttributes2Impl.isSpecified(const uri, localName: SAXString): Boolean; var index : Integer; begin index:= getIndex(uri, localName); if (index < 0) then raise ESAXIllegalArgumentException.CreateFmt(sNoAttributeLocalUri, [localName, uri]); Result:= Fspecified[index]; end; function TAttributes2Impl.isSpecified(index: Integer): Boolean; begin if ((index < 0) or (index >= getLength())) then raise ESAXIllegalArgumentException.CreateFmt(sNoAttributeAtIndex, [index]); Result:= Fspecified[index]; end; function TAttributes2Impl.isSpecified(const qName: SAXString): Boolean; var index : Integer; begin index:= getIndex(qName); if (index < 0) then raise ESAXIllegalArgumentException.CreateFmt(sNoAttributeQName, [qName]); Result:= Fspecified[index]; end; procedure TAttributes2Impl.removeAttribute(index: Integer); var origMax : Integer; PDest, PSource : Pointer; begin origMax:= getLength() - 1; inherited removeAttribute(index); if (index <> origMax) then begin // This is just a faster way of deleting an item PDest:= Pointer(Fspecified); Inc(Cardinal(PDest), index); PSource:= PDest; Inc(Cardinal(PSource), 1); Move(PSource^, PDest^, origMax-index); SetLength(fspecified, origMax-1); // This is just a faster way of deleting an item PDest:= Pointer(Fdeclared); Inc(Cardinal(PDest), index); PSource:= PDest; Inc(Cardinal(PSource), 1); Move(PSource^, PDest^, origMax-index); SetLength(fdeclared, origMax-1); end; end; procedure TAttributes2Impl.setAttributes(const atts: IAttributes); var length, I : Integer; flags : array of Boolean; a2 : IAttributes2; begin length:= atts.getLength(); inherited setAttributes(atts); SetLength(flags, length); if (atts.QueryInterface(IAttributes2, a2) = 0) then begin for I := 0 to length-1 do flags[I]:= a2.isSpecified(I); end else begin for I := 0 to length-1 do flags[I]:= true; end; end; procedure TAttributes2Impl.setDeclared(index: Integer; value: Boolean); begin if ((index < 0) or (index >= getLength())) then raise ESAXIllegalArgumentException.CreateFmt(sNoAttributeAtIndex, [index]); Fdeclared[index]:= value; end; procedure TAttributes2Impl.setSpecified(index: Integer; value: Boolean); begin if ((index < 0) or (index >= getLength())) then raise ESAXIllegalArgumentException.CreateFmt(sNoAttributeAtIndex, [index]); Fspecified[index]:= value; end; { TDefaultHandler2 } procedure TDefaultHandler2.attributeDecl(const eName, aName, attrType, mode, value: SAXString); begin // do nothing end; procedure TDefaultHandler2.comment(const ch : SAXString); begin // do nothing end; procedure TDefaultHandler2.elementDecl(const name, model: SAXString); begin // do nothing end; procedure TDefaultHandler2.endCDATA; begin // do nothing end; procedure TDefaultHandler2.endDTD; begin // do nothing end; procedure TDefaultHandler2.endEntity(const name: SAXString); begin // do nothing end; procedure TDefaultHandler2.externalEntityDecl(const name, publicId, systemId: SAXString); begin // do nothing end; function TDefaultHandler2.getExternalSubset(const name, baseURI: SAXString): IInputSource; begin Result:= nil; end; procedure TDefaultHandler2.internalEntityDecl(const name, value: SAXString); begin // do nothing end; function TDefaultHandler2.resolveEntity(const name, publicId, baseURI, systemId: SAXString): IInputSource; begin Result:= nil; end; function TDefaultHandler2.resolveEntity(const publicId, systemId : SAXString) : IInputSource; begin Result:= resolveEntity('', publicId, '', systemId); end; procedure TDefaultHandler2.startCDATA; begin // do nothing end; procedure TDefaultHandler2.startDTD(const name, publicId, systemId: SAXString); begin // do nothing end; procedure TDefaultHandler2.startEntity(const name: SAXString); begin // do nothing end; { TLocator2Impl } constructor TLocator2Impl.Create(locator: ILocator); var l2 : ILocator2; begin inherited create(locator); if (locator.QueryInterface(ILocator2, l2) = 0) then begin Fversion:= l2.getXMLVersion(); Fencoding:= l2.getEncoding(); end; end; function TLocator2Impl.getEncoding: PSAXChar; begin Result:= Fencoding; end; function TLocator2Impl.getXMLVersion: PSAXChar; begin Result:= Fversion; end; procedure TLocator2Impl.setEncoding(encoding: PSAXChar); begin Fencoding:= encoding; end; procedure TLocator2Impl.setXMLVersion(version: PSAXChar); begin Fversion:= version; end; { TSAXError } constructor TSAXError.create(message: PSAXChar); begin inherited create(); init(message); end; function TSAXError.getMessage: PSAXChar; begin Result:= Fmessage; end; function TSAXError.getNativeError: IUnknown; begin Result:= nil; end; procedure TSAXError.init(message: PSAXChar); begin Fmessage:= message; end; { TSAXParseError } constructor TSAXParseError.create(message: PSAXChar; const locator: ILocator); begin inherited create(message); FpublicId:= locator.getPublicId(); FsystemId:= locator.getSystemId(); FlineNumber:= locator.getLineNumber(); FcolumnNumber:= locator.getColumnNumber(); end; constructor TSAXParseError.create(const message : SAXString; publicId, systemId: PSAXChar; lineNumber, columnNumber: Integer); begin inherited create(PSAXChar(message)); FpublicId:= publicId; FsystemId:= systemId; FlineNumber:= lineNumber; FcolumnNumber:= columnNumber; end; function TSAXParseError.getColumnNumber: Integer; begin Result:= FcolumnNumber; end; function TSAXParseError.getLineNumber: Integer; begin Result:= FlineNumber; end; function TSAXParseError.getPublicId: PSAXChar; begin Result:= FpublicId; end; function TSAXParseError.getSystemId: PSAXChar; begin Result:= FsystemId; end; procedure TSAXParseError.init(message: PSAXChar; const locator: ILocator); begin inherited init(message); FpublicId:= locator.getPublicId(); FsystemId:= locator.getSystemId(); FlineNumber:= locator.getLineNumber(); FcolumnNumber:= locator.getColumnNumber(); end; initialization // Create a default handler object HandlerDefault := TDefaultHandler.Create; // Keep it around HandlerDefault._AddRef; finalization // Release the reference HandlerDefault._Release; end.
unit acFilterController; interface uses SysUtils, Classes; type TFilterInfo = class name: string; views: variant; end; TacFilterController = class(TComponent) private filters: TList; public constructor Create(owner: TComponent); override; destructor Destroy; override; procedure addFilter(name: string; views: variant); function findFilter(name: string): variant; published { Published declarations } end; procedure Register; implementation procedure TacFilterController.addFilter(name: string; views: variant); var filter: TFilterInfo; begin filter := TFilterInfo.Create; filter.name := name; filter.views := views; filters.Add(filter); end; constructor TacFilterController.Create(owner: TComponent); begin inherited create(owner); filters := TList.Create; end; destructor TacFilterController.Destroy; begin inherited; FreeAndNil(filters); end; function TacFilterController.findFilter(name: string): variant; var i: integer; begin for i := 0 to filters.Count-1 do begin if UpperCase(TFilterInfo(filters.Items[i]).name)= UpperCase(name) then result := TFilterInfo(filters.Items[i]).views; end; end; procedure Register; begin RegisterComponents('Acras', [TacFilterController]); end; end.
{ Clever Internet Suite Copyright (C) 2014 Clever Components All Rights Reserved www.CleverComponents.com } unit clSshKeyExchanger; interface {$I ..\common\clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, Windows, {$ELSE} System.Classes, System.SysUtils, Winapi.Windows, {$ENDIF} clConfig, clUtils, clCryptHash, clSshPacket; type TclSshKeyExchanger = class(TclConfigObject) private FGuessAlgorithms: TStrings; procedure SetGuessAlgorithms(const Value: TStrings); protected FConfig: TclConfig; FSha: TclHash; FK: TclByteArray; FH: TclByteArray; FK_S: TclByteArray; public constructor Create; override; destructor Destroy; override; class function Guess(const AI_S, AI_C: TclByteArray): TStrings; procedure Init(AConfig: TclConfig; const AV_S, AV_C, AI_S, AI_C: TclByteArray; var pp: TclPacket); virtual; abstract; function Next(ABuf: TclPacket; var pp: TclPacket): Boolean; virtual; abstract; function GetKeyType: string; virtual; abstract; function GetState: Integer; virtual; abstract; function GetFingerPrint(AHash: TclHash; const AData: TclByteArray): string; overload; function GetFingerPrint: string; overload; function GetK: TclByteArray; function GetH: TclByteArray; function GetHash: TclHash; function GetHostKey: TclByteArray; function GetSignature(const ASignature: TclByteArray): TclByteArray; property GuessAlgorithms: TStrings read FGuessAlgorithms write SetGuessAlgorithms; end; const PROPOSAL_KEX_ALGS = 0; PROPOSAL_SERVER_HOST_KEY_ALGS = 1; PROPOSAL_ENC_ALGS_CTOS = 2; PROPOSAL_ENC_ALGS_STOC = 3; PROPOSAL_MAC_ALGS_CTOS = 4; PROPOSAL_MAC_ALGS_STOC = 5; PROPOSAL_COMP_ALGS_CTOS = 6; PROPOSAL_COMP_ALGS_STOC = 7; PROPOSAL_LANG_CTOS = 8; PROPOSAL_LANG_STOC = 9; PROPOSAL_MAX = 10; STATE_END = 0; implementation uses clTranslator, clSshUtils, clCryptUtils; { TclSshKeyExchanger } constructor TclSshKeyExchanger.Create; begin inherited Create(); FGuessAlgorithms := TStringList.Create(); FConfig := nil; FSha := nil; SetLength(FK, 0); SetLength(FH, 0); SetLength(FK_S, 0); end; destructor TclSshKeyExchanger.Destroy; begin FSha.Free(); FGuessAlgorithms.Free(); inherited Destroy(); end; function TclSshKeyExchanger.GetFingerPrint: string; var hash: TclHash; begin hash := TclHash(FConfig.CreateInstance('md5')); try Result := GetFingerPrint(hash, GetHostKey()); finally hash.Free(); end; end; function TclSshKeyExchanger.GetFingerPrint(AHash: TclHash; const AData: TclByteArray): string; var buf: TclByteArray; begin {$IFNDEF DELPHI2005}buf := nil;{$ENDIF} AHash.Init(); AHash.Update(AData, 0, Length(AData)); buf := AHash.Digest(); Result := BytesToHex(buf, ':'); end; function TclSshKeyExchanger.GetH: TclByteArray; begin Result := FH; end; function TclSshKeyExchanger.GetHash: TclHash; begin Result := FSha; end; function TclSshKeyExchanger.GetHostKey: TclByteArray; begin Result := FK_S; end; function TclSshKeyExchanger.GetK: TclByteArray; begin Result := FK; end; function TclSshKeyExchanger.GetSignature(const ASignature: TclByteArray): TclByteArray; var i, j: Integer; begin {$IFNDEF DELPHI2005}Result := nil;{$ENDIF} if (Length(ASignature) < 8) then begin RaiseCryptError(CryptInvalidArgument, CryptInvalidArgumentCode); end; if (ASignature[0] = 0) and (ASignature[1] = 0) and (ASignature[2] = 0) then begin i := 0; j := ByteArrayReadDWord(ASignature, i); Inc(i, j); j := ByteArrayReadDWord(ASignature, i); SetLength(Result, j); if (Length(ASignature) < i + j) then begin RaiseCryptError(CryptInvalidArgument, CryptInvalidArgumentCode); end; System.Move(ASignature[i], Result[0], j); end else begin Result := ASignature; end; end; class function TclSshKeyExchanger.Guess(const AI_S, AI_C: TclByteArray): TStrings; label _BREAK; var sb, cb: TclPacket; sp, cp: TclByteArray; i, j, k, l, m: Integer; algorithm: string; begin {$IFNDEF DELPHI2005}sp := nil; cp := nil;{$ENDIF} Result := TStringList.Create(); try sb := nil; cb := nil; try sb := TclPacket.Create(AI_S); sb.SetOffSet(17); cb := TclPacket.Create(AI_C); cb.SetOffSet(17); for i := 0 to PROPOSAL_MAX - 1 do begin Result.Add(''); sp := sb.GetString(); // server proposal cp := cb.GetString(); // client proposal j := 0; k := 0; while (j < Length(cp)) do begin while (j < Length(cp)) and (cp[j] <> $2c) do Inc(j); // ',' if (k = j) then begin Result.Clear(); Exit; end; algorithm := TclTranslator.GetString(cp, k, j - k); l := 0; m := 0; while (l < Length(sp)) do begin while (l < Length(sp)) and (sp[l] <> $2c) do Inc(l); // ',' if (m = l) then begin Result.Clear(); Exit; end; if SameText(algorithm, TclTranslator.GetString(sp, m, l - m)) then begin guess[i] := algorithm; goto _BREAK; end; Inc(l); m := l; end; Inc(j); k := j; end; _BREAK: if (j = 0) then begin guess[i] := ''; end; end; finally cb.Free(); sb.Free(); end; except Result.Free(); raise; end; end; procedure TclSshKeyExchanger.SetGuessAlgorithms(const Value: TStrings); begin FGuessAlgorithms.Assign(Value); end; end.
unit dcIndexCheckBox; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, dbctrls, datacontroller,db; type TdcIndexCheckBox = class(TCheckBox) private { Private declarations } fdcLink : TdcLink; fStrIndex : integer; fReadOnly : boolean; FValueUnChecked: string; FValueChecked: string; procedure SetValueChecked(const Value: string); procedure SetValueUnChecked(const Value: string); function GetDataBufIndex: integer; procedure SetDataBufIndex(const Value: integer); protected { Protected declarations } // std data awareness function GetDataSource:TDataSource; procedure SetDataSource(value:Tdatasource); function GetDataField:string; procedure SetDataField(value:string); // data controller function GetDataController:TDataController; procedure SetDataController(value:TDataController); procedure ReadData(sender:TObject); procedure WriteData(sender:TObject); procedure ClearData(sender:TObject); //implement readonly procedure Toggle;override; // procedure MouseUp(Button:TMouseButton;Shift:TShiftState;x:integer;y:integer);override; // procedure KeyDown(var Key:word;shift:TShiftState);override; public { Public declarations } constructor Create(AOwner:Tcomponent);override; destructor Destroy;override; published { Published declarations } property DataController : TDataController read GetDataController write setDataController; property DataField : String read GetDataField write SetDataField; property DataSource : TDataSource read getDataSource write SetDatasource; property StrIndex : integer read fstrIndex write fStrIndex; property ReadOnly : boolean read freadonly write freadonly; property ValueChecked:string read FValueChecked write SetValueChecked; property ValueUnChecked:string read FValueUnChecked write SetValueUnChecked; property DataBufIndex:integer read GetDataBufIndex write SetDataBufIndex; property ctl3d; end; procedure Register; implementation constructor TdcIndexCheckBox.Create(AOwner:Tcomponent); begin inherited; fdclink := tdclink.create(self); fdclink.OnReadData := ReadData; fdclink.OnWriteData := WriteData; fdclink.OnClearData := ClearData; fStrIndex := 1; fValueChecked := 'Y'; fValueUnChecked := 'N'; end; destructor TdcIndexCheckBox.Destroy; begin fdclink.Free; inherited; end; procedure TdcIndexCheckBox.Toggle; begin if not readonly then inherited Toggle; end; procedure TdcIndexCheckBox.SetDataController(value:TDataController); begin fdcLink.datacontroller := value; end; function TdcIndexCheckBox.GetDataController:TDataController; begin result := fdcLink.DataController; end; procedure TdcIndexCheckBox.SetDataSource(value:TDataSource); begin end; function TdcIndexCheckBox.GetDataField:string; begin result := fdclink.FieldName; end; function TdcIndexCheckBox.GetDataSource:TDataSource; begin result := fdclink.DataSource; end; procedure TdcIndexCheckBox.SetDataField(value:string); begin fdclink.FieldName := value; end; procedure TdcIndexCheckBox.ReadData; var s : string; begin if fdclink.DataController <> nil then begin s := ''; if assigned(fdclink.datacontroller.databuf) then s := fdclink.datacontroller.databuf.AsString[DataBufIndex]; if fStrIndex <= length(s) then checked := pos(copy(s,fStrIndex,1), ValueChecked) > 0 else checked := false; end else checked := false; end; procedure TdcIndexCheckBox.WriteData; var s : string; begin if ReadOnly then exit; if assigned(fdclink.DataController) then begin if assigned(fdclink.datacontroller.databuf) then s := fdclink.datacontroller.databuf.asString[DataBufIndex]; while (length(s) < fStrIndex) do s := s + ' '; if checked then s[fStrIndex] := ValueChecked[1] else s[fstrIndex] := ValueUnChecked[1]; if assigned(fdclink.datacontroller.databuf) then fdclink.datacontroller.databuf.asString[DataBufIndex] := s; end; end; procedure TdcIndexCheckBox.ClearData; begin if fdclink.Field <> nil then checked := false; end; procedure Register; begin RegisterComponents('FFS Data Entry', [TdcIndexCheckBox]); end; procedure TdcIndexCheckBox.SetValueChecked(const Value: string); begin if FValueChecked = Value then exit; if Value > '' then FValueChecked := copy(Value,1,1); end; procedure TdcIndexCheckBox.SetValueUnChecked(const Value: string); begin if FValueUnChecked = Value then exit; if Value > '' then FValueUnChecked := copy(Value,1,1); end; function TdcIndexCheckBox.GetDataBufIndex: integer; begin result := 0; if assigned(fdclink.Datacontroller) then if assigned(fdclink.datacontroller.databuf) then result := fdclink.datacontroller.databuf.FieldNameToIndex(fdclink.FieldName); end; procedure TdcIndexCheckBox.SetDataBufIndex(const Value: integer); begin end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpECPoint; {$I ..\..\Include\CryptoLib.inc} interface uses Generics.Collections, Classes, SysUtils, ClpBits, ClpCryptoLibTypes, ClpSetWeakRef, ClpBigInteger, ClpIPreCompInfo, ClpIPreCompCallBack, ClpValidityPrecompInfo, ClpIValidityPrecompInfo, ClpIECFieldElement, ClpIECInterface, ClpECAlgorithms, ClpECFieldElement; resourcestring SUnSupportedCoordinateSystem = 'UnSupported Coordinate System'; SUnknownCoordSystem = 'Unknown Coordinate System'; SPointNotInNormalForm = 'Point not in Normal Form'; SNotProjectiveCoordSystem = 'Not a Projective Coordinate System'; SCannotBeNegative = 'Cannot be Negative, "e"'; SNilFieldElement = 'Exactly one of the Field Elements is Nil'; type /// <summary> /// base class for points on elliptic curves. /// </summary> TECPoint = class abstract(TInterfacedObject, IECPoint) strict private type IValidityCallback = interface(IPreCompCallback) ['{FD571D52-9852-45A6-BD53-47765EB86F20}'] end; type TValidityCallback = class(TInterfacedObject, IPreCompCallback, IValidityCallback) strict private var Fm_outer: IECPoint; Fm_decompressed, Fm_checkOrder: Boolean; public constructor Create(const outer: IECPoint; decompressed, checkOrder: Boolean); function Precompute(const existing: IPreCompInfo): IPreCompInfo; end; function GetIsInfinity: Boolean; inline; function GetIsCompressed: Boolean; inline; function GetpreCompTable: TDictionary<String, IPreCompInfo>; inline; procedure SetpreCompTable(const Value : TDictionary<String, IPreCompInfo>); inline; function GetCurve: IECCurve; virtual; function GetCurveCoordinateSystem: Int32; virtual; function GetAffineXCoord: IECFieldElement; virtual; function GetAffineYCoord: IECFieldElement; virtual; function GetXCoord: IECFieldElement; virtual; class constructor ECPoint(); strict protected class var FEMPTY_ZS: TCryptoLibGenericArray<IECFieldElement>; var Fm_zs: TCryptoLibGenericArray<IECFieldElement>; Fm_withCompression: Boolean; Fm_curve: IECCurve; Fm_x, Fm_y: IECFieldElement; function GetCompressionYTilde: Boolean; virtual; abstract; constructor Create(const curve: IECCurve; const x, y: IECFieldElement; withCompression: Boolean); overload; function SatisfiesOrder(): Boolean; virtual; function SatisfiesCurveEquation(): Boolean; virtual; abstract; function Detach(): IECPoint; virtual; abstract; function RawXCoord: IECFieldElement; inline; function RawYCoord: IECFieldElement; inline; function RawZCoords: TCryptoLibGenericArray<IECFieldElement>; inline; function CreateScaledPoint(const sx, sy: IECFieldElement) : IECPoint; virtual; procedure CheckNormalized(); virtual; property CurveCoordinateSystem: Int32 read GetCurveCoordinateSystem; property CompressionYTilde: Boolean read GetCompressionYTilde; class function GetInitialZCoords(const curve: IECCurve) : TCryptoLibGenericArray<IECFieldElement>; static; public var // Dictionary is (string -> PreCompInfo) Fm_preCompTable: TDictionary<String, IPreCompInfo>; function GetYCoord: IECFieldElement; virtual; constructor Create(const curve: IECCurve; const x, y: IECFieldElement; const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean); overload; destructor Destroy; override; function GetDetachedPoint(): IECPoint; inline; function GetZCoord(index: Int32): IECFieldElement; virtual; function GetZCoords(): TCryptoLibGenericArray<IECFieldElement>; virtual; function IsNormalized(): Boolean; virtual; /// <summary> /// Normalization ensures that any projective coordinate is 1, and /// therefore that the x, y <br />coordinates reflect those of the /// equivalent point in an affine coordinate system. /// </summary> /// <returns> /// a new ECPoint instance representing the same point, but with /// normalized coordinates /// </returns> function Normalize(): IECPoint; overload; virtual; function Normalize(const zInv: IECFieldElement): IECPoint; overload; virtual; function ImplIsValid(decompressed, checkOrder: Boolean): Boolean; function IsValid(): Boolean; inline; function IsValidPartial(): Boolean; inline; function ScaleX(const scale: IECFieldElement): IECPoint; virtual; function ScaleY(const scale: IECFieldElement): IECPoint; virtual; function GetEncoded(): TCryptoLibByteArray; overload; virtual; function GetEncoded(compressed: Boolean): TCryptoLibByteArray; overload; virtual; abstract; function Add(const b: IECPoint): IECPoint; virtual; abstract; function Subtract(const b: IECPoint): IECPoint; virtual; abstract; function Negate(): IECPoint; virtual; abstract; function TimesPow2(e: Int32): IECPoint; virtual; function Twice(): IECPoint; virtual; abstract; function Multiply(b: TBigInteger): IECPoint; virtual; abstract; function TwicePlus(const b: IECPoint): IECPoint; virtual; function ThreeTimes(): IECPoint; virtual; function Equals(const other: IECPoint): Boolean; reintroduce; function GetHashCode(): {$IFDEF DELPHI}Int32; {$ELSE}PtrInt; {$ENDIF DELPHI}override; function ToString(): String; override; property preCompTable: TDictionary<String, IPreCompInfo> read GetpreCompTable write SetpreCompTable; /// <summary> /// Returns the affine x-coordinate after checking that this point is /// normalized. /// </summary> /// <value> /// The affine x-coordinate of this point /// </value> /// <exception cref="ClpCryptoLibTypes|EInvalidOperationCryptoLibException"> /// if the point is not normalized /// </exception> property AffineXCoord: IECFieldElement read GetAffineXCoord; /// <summary> /// Returns the affine y-coordinate after checking that this point is /// normalized. /// </summary> /// <value> /// The affine y-coordinate of this point /// </value> /// <exception cref="ClpCryptoLibTypes|EInvalidOperationCryptoLibException"> /// if the point is not normalized /// </exception> property AffineYCoord: IECFieldElement read GetAffineYCoord; /// <summary> /// Returns the x-coordinate. <br />Caution: depending on the curve's /// coordinate system, this may not be the same value as in an <br /> /// affine coordinate system; use Normalize() to get a point where the /// coordinates have their <br />affine values, or use AffineXCoord if /// you expect the point to already have been normalized. /// </summary> /// <value> /// the x-coordinate of this point /// </value> property XCoord: IECFieldElement read GetXCoord; /// <summary> /// Returns the y-coordinate. <br />Caution: depending on the curve's /// coordinate system, this may not be the same value as in an <br /> /// affine coordinate system; use Normalize() to get a point where the /// coordinates have their <br />affine values, or use AffineYCoord if /// you expect the point to already have been normalized. /// </summary> /// <value> /// the y-coordinate of this point /// </value> property YCoord: IECFieldElement read GetYCoord; property curve: IECCurve read GetCurve; property IsInfinity: Boolean read GetIsInfinity; property IsCompressed: Boolean read GetIsCompressed; end; type TECPointBase = class abstract(TECPoint, IECPointBase) strict protected constructor Create(const curve: IECCurve; const x, y: IECFieldElement; withCompression: Boolean); overload; constructor Create(const curve: IECCurve; const x, y: IECFieldElement; const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean); overload; public destructor Destroy; override; /// <summary> /// return the field element encoded with point compression. (S 4.3.6) /// </summary> function GetEncoded(compressed: Boolean): TCryptoLibByteArray; override; /// <summary> /// Multiplies this <c>ECPoint</c> by the given number. /// </summary> /// <param name="k"> /// The multiplicator. /// </param> /// <returns> /// <c>k * this</c> /// </returns> function Multiply(k: TBigInteger): IECPoint; override; end; type TAbstractFpPoint = class abstract(TECPointBase, IAbstractFpPoint) strict protected constructor Create(const curve: IECCurve; const x, y: IECFieldElement; withCompression: Boolean); overload; constructor Create(const curve: IECCurve; const x, y: IECFieldElement; const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean); overload; function GetCompressionYTilde(): Boolean; override; function SatisfiesCurveEquation(): Boolean; override; property CompressionYTilde: Boolean read GetCompressionYTilde; public destructor Destroy; override; function Subtract(const b: IECPoint): IECPoint; override; end; type /// <summary> /// Elliptic curve points over Fp /// </summary> TFpPoint = class(TAbstractFpPoint, IFpPoint) strict protected function Detach(): IECPoint; override; function Two(const x: IECFieldElement): IECFieldElement; virtual; function Three(const x: IECFieldElement): IECFieldElement; virtual; function Four(const x: IECFieldElement): IECFieldElement; virtual; function Eight(const x: IECFieldElement): IECFieldElement; virtual; function DoubleProductFromSquares(const a, b, aSquared, bSquared: IECFieldElement): IECFieldElement; virtual; function CalculateJacobianModifiedW(const Z: IECFieldElement; const ZSquared: IECFieldElement): IECFieldElement; virtual; function GetJacobianModifiedW(): IECFieldElement; virtual; function TwiceJacobianModified(calculateW: Boolean): IFpPoint; virtual; public /// <summary> /// Create a point which encodes without point compression. /// </summary> /// <param name="curve"> /// curve the curve to use /// </param> /// <param name="x"> /// affine x co-ordinate /// </param> /// <param name="y"> /// affine y co-ordinate /// </param> constructor Create(const curve: IECCurve; const x, y: IECFieldElement); overload; deprecated 'Use ECCurve.CreatePoint to construct points'; /// <summary> /// Create a point which encodes without point compression. /// </summary> /// <param name="curve"> /// curve the curve to use /// </param> /// <param name="x"> /// affine x co-ordinate /// </param> /// <param name="y"> /// affine y co-ordinate /// </param> /// <param name="withCompression"> /// if true encode with point compression /// </param> constructor Create(const curve: IECCurve; const x, y: IECFieldElement; withCompression: Boolean); overload; deprecated 'Per-point compression property will be removed, see GetEncoded(boolean)'; constructor Create(const curve: IECCurve; const x, y: IECFieldElement; const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean); overload; destructor Destroy; override; function GetZCoord(index: Int32): IECFieldElement; override; // B.3 pg 62 function Add(const b: IECPoint): IECPoint; override; // B.3 pg 62 function Twice(): IECPoint; override; function TwicePlus(const b: IECPoint): IECPoint; override; function ThreeTimes(): IECPoint; override; function TimesPow2(e: Int32): IECPoint; override; function Negate(): IECPoint; override; end; type TAbstractF2mPoint = class abstract(TECPointBase, IAbstractF2mPoint) strict protected constructor Create(const curve: IECCurve; const x, y: IECFieldElement; withCompression: Boolean); overload; constructor Create(const curve: IECCurve; const x, y: IECFieldElement; const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean); overload; function SatisfiesOrder(): Boolean; override; function SatisfiesCurveEquation(): Boolean; override; public destructor Destroy; override; function ScaleX(const scale: IECFieldElement): IECPoint; override; function ScaleY(const scale: IECFieldElement): IECPoint; override; function Subtract(const b: IECPoint): IECPoint; override; function Tau(): IAbstractF2mPoint; virtual; function TauPow(pow: Int32): IAbstractF2mPoint; virtual; end; type /// <summary> /// Elliptic curve points over F2m /// </summary> TF2mPoint = class(TAbstractF2mPoint, IF2mPoint) strict protected function GetCompressionYTilde: Boolean; override; function Detach(): IECPoint; override; property CompressionYTilde: Boolean read GetCompressionYTilde; public function GetYCoord: IECFieldElement; override; /// <param name="curve"> /// base curve /// </param> /// <param name="x"> /// x point /// </param> /// <param name="y"> /// y point /// </param> constructor Create(const curve: IECCurve; const x, y: IECFieldElement); overload; deprecated 'Use ECCurve.CreatePoint to construct points'; /// <param name="curve"> /// base curve /// </param> /// <param name="x"> /// x point /// </param> /// <param name="y"> /// y point /// </param> /// <param name="withCompression"> /// true if encode with point compression. /// </param> constructor Create(const curve: IECCurve; const x, y: IECFieldElement; withCompression: Boolean); overload; deprecated 'Per-point compression property will be removed, see GetEncoded(boolean)'; constructor Create(const curve: IECCurve; const x, y: IECFieldElement; const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean); overload; destructor Destroy; override; function Add(const b: IECPoint): IECPoint; override; function Twice(): IECPoint; override; function TwicePlus(const b: IECPoint): IECPoint; override; function Negate(): IECPoint; override; property YCoord: IECFieldElement read GetYCoord; end; implementation uses ClpECCurve; // included here to avoid circular dependency :) { TECPoint } function TECPoint.GetIsCompressed: Boolean; begin result := Fm_withCompression; end; function TECPoint.GetIsInfinity: Boolean; begin // result := (Fm_x = Nil) and (Fm_y = Nil); result := (Fm_x = Nil) or (Fm_y = Nil) or ((System.Length(Fm_zs) > 0) and (Fm_zs[0].IsZero)); end; function TECPoint.RawXCoord: IECFieldElement; begin result := Fm_x; end; function TECPoint.RawYCoord: IECFieldElement; begin result := Fm_y; end; function TECPoint.RawZCoords: TCryptoLibGenericArray<IECFieldElement>; begin result := Fm_zs; end; function TECPoint.Normalize: IECPoint; var Z1: IECFieldElement; begin if (IsInfinity) then begin result := Self; Exit; end; case CurveCoordinateSystem of TECCurve.COORD_AFFINE, TECCurve.COORD_LAMBDA_AFFINE: begin result := Self; Exit; end else begin Z1 := RawZCoords[0]; if (Z1.IsOne) then begin result := Self; Exit; end; result := Normalize(Z1.Invert()); end; end; end; function TECPoint.SatisfiesOrder: Boolean; var n: TBigInteger; begin if (TBigInteger.One.Equals(curve.getCofactor())) then begin result := True; Exit; end; n := curve.getOrder(); // TODO Require order to be available for all curves result := (not(n.IsInitialized)) or TECAlgorithms.ReferenceMultiply (Self as IECPoint, n).IsInfinity; end; function TECPoint.ScaleX(const scale: IECFieldElement): IECPoint; begin if IsInfinity then begin result := Self; end else begin result := curve.CreateRawPoint(RawXCoord.Multiply(scale), RawYCoord, RawZCoords, IsCompressed); end; end; function TECPoint.ScaleY(const scale: IECFieldElement): IECPoint; begin if IsInfinity then begin result := Self; end else begin result := curve.CreateRawPoint(RawXCoord, RawYCoord.Multiply(scale), RawZCoords, IsCompressed); end; end; procedure TECPoint.SetpreCompTable(const Value : TDictionary<String, IPreCompInfo>); begin Fm_preCompTable := Value; end; function TECPoint.ThreeTimes: IECPoint; begin result := TwicePlus(Self); end; function TECPoint.TimesPow2(e: Int32): IECPoint; var p: IECPoint; begin if (e < 0) then begin raise EArgumentCryptoLibException.CreateRes(@SCannotBeNegative); end; p := Self; System.Dec(e); while (e >= 0) do begin p := p.Twice(); System.Dec(e); end; result := p; end; function TECPoint.ToString: String; var sl: TStringList; i: Int32; begin if (IsInfinity) then begin result := 'INF'; Exit; end; sl := TStringList.Create(); sl.LineBreak := ''; try sl.Add('('); sl.Add(RawXCoord.ToString); sl.Add(','); sl.Add(RawYCoord.ToString); for i := 0 to System.Pred(System.Length(Fm_zs)) do begin sl.Add(','); sl.Add(Fm_zs[i].ToString); end; sl.Add(')'); result := sl.Text; finally sl.Free; end; end; function TECPoint.TwicePlus(const b: IECPoint): IECPoint; begin result := Twice().Add(b); end; constructor TECPoint.Create(const curve: IECCurve; const x, y: IECFieldElement; withCompression: Boolean); begin Create(curve, x, y, GetInitialZCoords(curve), withCompression); end; procedure TECPoint.CheckNormalized; begin if (not IsNormalized()) then begin raise EInvalidOperationCryptoLibException.CreateRes(@SPointNotInNormalForm); end; end; constructor TECPoint.Create(const curve: IECCurve; const x, y: IECFieldElement; const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean); begin Inherited Create(); // Fm_curve := curve; TSetWeakRef.SetWeakReference(@Fm_curve, curve); Fm_x := x; Fm_y := y; Fm_zs := zs; Fm_withCompression := withCompression; end; function TECPoint.CreateScaledPoint(const sx, sy: IECFieldElement): IECPoint; begin result := curve.CreateRawPoint(RawXCoord.Multiply(sx), RawYCoord.Multiply(sy), IsCompressed); end; destructor TECPoint.Destroy; begin TSetWeakRef.SetWeakReference(@Fm_curve, Nil); Fm_preCompTable.Free; inherited Destroy; end; class constructor TECPoint.ECPoint; begin System.SetLength(FEMPTY_ZS, 0); end; function TECPoint.Equals(const other: IECPoint): Boolean; var c1, c2: IECCurve; n1, n2, i1, i2: Boolean; p1, p2: IECPoint; points: TCryptoLibGenericArray<IECPoint>; begin if ((Self as IECPoint) = other) then begin result := True; Exit; end; if (other = Nil) then begin result := false; Exit; end; c1 := Self.curve; c2 := other.curve; n1 := (c1 = Nil); n2 := (c2 = Nil); i1 := IsInfinity; i2 := other.IsInfinity; if (i1 or i2) then begin result := (i1 and i2) and (n1 or n2 or c1.Equals(c2)); Exit; end; p1 := Self as IECPoint; p2 := other; if (n1 and n2) then begin // Points with null curve are in affine form, so already normalized end else if (n1) then begin p2 := p2.Normalize(); end else if (n2) then begin p1 := p1.Normalize(); end else if (not c1.Equals(c2)) then begin result := false; Exit; end else begin // TODO Consider just requiring already normalized, to avoid silent performance degradation points := TCryptoLibGenericArray<IECPoint>.Create(Self, c1.ImportPoint(p2)); // TODO This is a little strong, really only requires coZNormalizeAll to get Zs equal c1.NormalizeAll(points); p1 := points[0]; p2 := points[1]; end; result := p1.XCoord.Equals(p2.XCoord) and p1.YCoord.Equals(p2.YCoord); end; function TECPoint.GetEncoded: TCryptoLibByteArray; begin result := GetEncoded(Fm_withCompression); end; function TECPoint.GetHashCode: {$IFDEF DELPHI}Int32; {$ELSE}PtrInt; {$ENDIF DELPHI} var c: IECCurve; p: IECPoint; hc: Int32; begin c := curve; if c = Nil then begin hc := 0; end else begin hc := not c.GetHashCode(); end; if (not IsInfinity) then begin // TODO Consider just requiring already normalized, to avoid silent performance degradation p := Normalize(); hc := hc xor (p.XCoord.GetHashCode() * 17); hc := hc xor (p.YCoord.GetHashCode() * 257); end; result := hc; end; class function TECPoint.GetInitialZCoords(const curve: IECCurve) : TCryptoLibGenericArray<IECFieldElement>; var coord: Int32; One: IECFieldElement; begin // Cope with null curve, most commonly used by implicitlyCa if curve = Nil then begin coord := TECCurve.COORD_AFFINE; end else begin coord := curve.CoordinateSystem; end; case coord of TECCurve.COORD_AFFINE, TECCurve.COORD_LAMBDA_AFFINE: begin result := FEMPTY_ZS; Exit; end; end; One := curve.FromBigInteger(TBigInteger.One); case coord of TECCurve.COORD_HOMOGENEOUS, TECCurve.COORD_JACOBIAN, TECCurve.COORD_LAMBDA_PROJECTIVE: begin result := TCryptoLibGenericArray<IECFieldElement>.Create(One); Exit; end; TECCurve.COORD_JACOBIAN_CHUDNOVSKY: begin result := TCryptoLibGenericArray<IECFieldElement>.Create(One, One, One); Exit; end; TECCurve.COORD_JACOBIAN_MODIFIED: begin result := TCryptoLibGenericArray<IECFieldElement>.Create(One, curve.a); Exit; end else begin raise EArgumentCryptoLibException.CreateRes(@SUnknownCoordSystem); end; end; end; function TECPoint.GetpreCompTable: TDictionary<String, IPreCompInfo>; begin result := Fm_preCompTable; end; function TECPoint.GetXCoord: IECFieldElement; begin result := Fm_x; end; function TECPoint.GetYCoord: IECFieldElement; begin result := Fm_y; end; function TECPoint.GetZCoord(index: Int32): IECFieldElement; begin if ((index < 0) or (index >= System.Length(Fm_zs))) then begin result := Nil; end else begin result := Fm_zs[index]; end; end; function TECPoint.GetZCoords: TCryptoLibGenericArray<IECFieldElement>; var zsLen: Int32; begin zsLen := System.Length(Fm_zs); if (zsLen = 0) then begin result := Fm_zs; Exit; end; System.SetLength(result, zsLen); result := System.Copy(Fm_zs, 0, zsLen); end; function TECPoint.ImplIsValid(decompressed, checkOrder: Boolean): Boolean; var Validity: IValidityPrecompInfo; callback: IValidityCallback; begin if (IsInfinity) then begin result := True; Exit; end; callback := TValidityCallback.Create(Self as IECPoint, decompressed, checkOrder); Validity := curve.Precompute(Self as IECPoint, TValidityPrecompInfo.PRECOMP_NAME, callback) as IValidityPrecompInfo; result := not(Validity.hasFailed()); end; function TECPoint.IsNormalized: Boolean; var coord: Int32; begin coord := CurveCoordinateSystem; result := (coord = TECCurve.COORD_AFFINE) or (coord = TECCurve.COORD_LAMBDA_AFFINE) or (IsInfinity) or (RawZCoords[0].IsOne); end; function TECPoint.IsValid: Boolean; begin result := ImplIsValid(false, True); end; function TECPoint.IsValidPartial: Boolean; begin result := ImplIsValid(false, false); end; function TECPoint.Normalize(const zInv: IECFieldElement): IECPoint; var zInv2, zInv3: IECFieldElement; begin case CurveCoordinateSystem of TECCurve.COORD_HOMOGENEOUS, TECCurve.COORD_LAMBDA_PROJECTIVE: begin result := CreateScaledPoint(zInv, zInv); Exit; end; TECCurve.COORD_JACOBIAN, TECCurve.COORD_JACOBIAN_CHUDNOVSKY, TECCurve.COORD_JACOBIAN_MODIFIED: begin zInv2 := zInv.Square(); zInv3 := zInv2.Multiply(zInv); result := CreateScaledPoint(zInv2, zInv3); Exit; end else begin raise EInvalidOperationCryptoLibException.CreateRes (@SNotProjectiveCoordSystem); end; end; end; function TECPoint.GetAffineXCoord: IECFieldElement; begin CheckNormalized(); result := XCoord; end; function TECPoint.GetAffineYCoord: IECFieldElement; begin CheckNormalized(); result := YCoord; end; function TECPoint.GetCurve: IECCurve; begin result := Fm_curve; end; function TECPoint.GetCurveCoordinateSystem: Int32; begin // Cope with null curve, most commonly used by implicitlyCa if Fm_curve = Nil then begin result := TECCurve.COORD_AFFINE; end else begin result := Fm_curve.CoordinateSystem; end; end; function TECPoint.GetDetachedPoint: IECPoint; begin result := Normalize().Detach(); end; { TF2mPoint } constructor TF2mPoint.Create(const curve: IECCurve; const x, y: IECFieldElement); begin Create(curve, x, y, false); end; constructor TF2mPoint.Create(const curve: IECCurve; const x, y: IECFieldElement; withCompression: Boolean); begin Inherited Create(curve, x, y, withCompression); if ((x = Nil) <> (y = Nil)) then begin raise EArgumentCryptoLibException.CreateRes(@SNilFieldElement); end; if (x <> Nil) then begin // Check if x and y are elements of the same field TF2mFieldElement.CheckFieldElements(x, y); // Check if x and a are elements of the same field if (curve <> Nil) then begin TF2mFieldElement.CheckFieldElements(x, curve.a); end; end; end; function TF2mPoint.Add(const b: IECPoint): IECPoint; var ecCurve: IECCurve; coord: Int32; X1, X2, Y1, Y2, dx, dy, L, X3, Y3, Z1, Z2, U1, V1, U2, V2, U, V, Vsq, Vcu, W, a, VSqZ2, uv, Z3, L3, L1, L2, S2, S1, ABZ2, AU1, AU2, bigB: IECFieldElement; Z1IsOne, Z2IsOne: Boolean; p: IECPoint; begin if (IsInfinity) then begin result := b; Exit; end; if (b.IsInfinity) then begin result := Self; Exit; end; ecCurve := curve; coord := ecCurve.CoordinateSystem; X1 := RawXCoord; X2 := b.RawXCoord; case coord of TECCurve.COORD_AFFINE: begin Y1 := RawYCoord; Y2 := b.RawYCoord; dx := X1.Add(X2); dy := Y1.Add(Y2); if (dx.IsZero) then begin if (dy.IsZero) then begin result := Twice(); Exit; end; result := ecCurve.Infinity; Exit; end; L := dy.Divide(dx); X3 := L.Square().Add(L).Add(dx).Add(ecCurve.a); Y3 := L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); result := TF2mPoint.Create(ecCurve, X3, Y3, IsCompressed); Exit; end; TECCurve.COORD_HOMOGENEOUS: begin Y1 := RawYCoord; Z1 := RawZCoords[0]; Y2 := b.RawYCoord; Z2 := b.RawZCoords[0]; Z1IsOne := Z1.IsOne; U1 := Y2; V1 := X2; if (not Z1IsOne) then begin U1 := U1.Multiply(Z1); V1 := V1.Multiply(Z1); end; Z2IsOne := Z2.IsOne; U2 := Y1; V2 := X1; if (not Z2IsOne) then begin U2 := U2.Multiply(Z2); V2 := V2.Multiply(Z2); end; U := U1.Add(U2); V := V1.Add(V2); if (V.IsZero) then begin if (U.IsZero) then begin result := Twice(); Exit; end; result := ecCurve.Infinity; Exit; end; Vsq := V.Square(); Vcu := Vsq.Multiply(V); if Z1IsOne then begin W := Z2; end else if Z2IsOne then begin W := Z1; end else begin W := Z1.Multiply(Z2); end; uv := U.Add(V); a := uv.MultiplyPlusProduct(U, Vsq, ecCurve.a).Multiply(W).Add(Vcu); X3 := V.Multiply(a); if Z2IsOne then begin VSqZ2 := Vsq; end else begin VSqZ2 := Vsq.Multiply(Z2); end; Y3 := U.MultiplyPlusProduct(X1, V, Y1).MultiplyPlusProduct (VSqZ2, uv, a); Z3 := Vcu.Multiply(W); result := TF2mPoint.Create(ecCurve, X3, Y3, TCryptoLibGenericArray<IECFieldElement>.Create(Z3), IsCompressed); Exit; end; TECCurve.COORD_LAMBDA_PROJECTIVE: begin if (X1.IsZero) then begin if (X2.IsZero) then begin result := ecCurve.Infinity; Exit; end; result := b.Add(Self); Exit; end; L1 := RawYCoord; Z1 := RawZCoords[0]; L2 := b.RawYCoord; Z2 := b.RawZCoords[0]; Z1IsOne := Z1.IsOne; U2 := X2; S2 := L2; if (not Z1IsOne) then begin U2 := U2.Multiply(Z1); S2 := S2.Multiply(Z1); end; Z2IsOne := Z2.IsOne; U1 := X1; S1 := L1; if (not Z2IsOne) then begin U1 := U1.Multiply(Z2); S1 := S1.Multiply(Z2); end; a := S1.Add(S2); bigB := U1.Add(U2); if (bigB.IsZero) then begin if (a.IsZero) then begin result := Twice(); Exit; end; result := ecCurve.Infinity; Exit; end; if (X2.IsZero) then begin // TODO This can probably be optimized quite a bit p := Normalize(); X1 := p.RawXCoord; Y1 := p.YCoord; Y2 := L2; L := Y1.Add(Y2).Divide(X1); X3 := L.Square().Add(L).Add(X1).Add(ecCurve.a); if (X3.IsZero) then begin result := TF2mPoint.Create(ecCurve, X3, ecCurve.b.Sqrt(), IsCompressed); Exit; end; Y3 := L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); L3 := Y3.Divide(X3).Add(X3); Z3 := ecCurve.FromBigInteger(TBigInteger.One); end else begin bigB := bigB.Square(); AU1 := a.Multiply(U1); AU2 := a.Multiply(U2); X3 := AU1.Multiply(AU2); if (X3.IsZero) then begin result := TF2mPoint.Create(ecCurve, X3, ecCurve.b.Sqrt(), IsCompressed); Exit; end; ABZ2 := a.Multiply(bigB); if (not Z2IsOne) then begin ABZ2 := ABZ2.Multiply(Z2); end; L3 := AU2.Add(bigB).SquarePlusProduct(ABZ2, L1.Add(Z1)); Z3 := ABZ2; if (not Z1IsOne) then begin Z3 := Z3.Multiply(Z1); end; end; result := TF2mPoint.Create(ecCurve, X3, L3, TCryptoLibGenericArray<IECFieldElement>.Create(Z3), IsCompressed); Exit; end else begin raise EInvalidOperationCryptoLibException.CreateRes (@SUnSupportedCoordinateSystem); end; end; end; constructor TF2mPoint.Create(const curve: IECCurve; const x, y: IECFieldElement; const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean); begin Inherited Create(curve, x, y, zs, withCompression); end; destructor TF2mPoint.Destroy; begin inherited Destroy; end; function TF2mPoint.Detach: IECPoint; begin result := TF2mPoint.Create(Nil, AffineXCoord, AffineYCoord, false); end; function TF2mPoint.GetCompressionYTilde: Boolean; var lx, ly: IECFieldElement; begin lx := RawXCoord; if (lx.IsZero) then begin result := false; Exit; end; ly := RawYCoord; case CurveCoordinateSystem of TECCurve.COORD_LAMBDA_AFFINE, TECCurve.COORD_LAMBDA_PROJECTIVE: begin // Y is actually Lambda (X + Y/X) here result := ly.TestBitZero() <> lx.TestBitZero(); Exit; end else begin result := ly.Divide(lx).TestBitZero(); end; end; end; function TF2mPoint.GetYCoord: IECFieldElement; var coord: Int32; lx, L, ly, Z: IECFieldElement; begin coord := CurveCoordinateSystem; case coord of TECCurve.COORD_LAMBDA_AFFINE, TECCurve.COORD_LAMBDA_PROJECTIVE: begin lx := RawXCoord; L := RawYCoord; if (IsInfinity or lx.IsZero) then begin result := L; Exit; end; // Y is actually Lambda (X + Y/X) here; convert to affine value on the fly ly := L.Add(lx).Multiply(lx); if (TECCurve.COORD_LAMBDA_PROJECTIVE = coord) then begin Z := RawZCoords[0]; if (not Z.IsOne) then begin ly := ly.Divide(Z); end; end; result := ly; Exit; end else begin result := RawYCoord; end; end; end; function TF2mPoint.Negate: IECPoint; var lx, ly, bigY, Z, L: IECFieldElement; ecCurve: IECCurve; coord: Int32; begin if (IsInfinity) then begin result := Self; Exit; end; lx := RawXCoord; if (lx.IsZero) then begin result := Self; Exit; end; ecCurve := curve; coord := ecCurve.CoordinateSystem; case coord of TECCurve.COORD_AFFINE: begin bigY := RawYCoord; result := TF2mPoint.Create(ecCurve, lx, bigY.Add(lx), IsCompressed); Exit; end; TECCurve.COORD_HOMOGENEOUS: begin ly := RawYCoord; Z := RawZCoords[0]; result := TF2mPoint.Create(ecCurve, lx, ly.Add(lx), TCryptoLibGenericArray<IECFieldElement>.Create(Z), IsCompressed); Exit; end; TECCurve.COORD_LAMBDA_AFFINE: begin L := RawYCoord; result := TF2mPoint.Create(ecCurve, lx, L.AddOne(), IsCompressed); Exit; end; TECCurve.COORD_LAMBDA_PROJECTIVE: begin // L is actually Lambda (X + Y/X) here L := RawYCoord; Z := RawZCoords[0]; result := TF2mPoint.Create(ecCurve, lx, L.Add(Z), TCryptoLibGenericArray<IECFieldElement>.Create(Z), IsCompressed); Exit; end else begin raise EInvalidOperationCryptoLibException.CreateRes (@SUnSupportedCoordinateSystem); end; end; end; function TF2mPoint.Twice: IECPoint; var ecCurve: IECCurve; X1, Y1, L1, X3, Y3, Z1, X1Z1, X1Sq, Y1Z1, S, V, vSquared, sv, h, Z3, L1Z1, Z1Sq, a, aZ1Sq, L3, T, b, t1, t2: IECFieldElement; coord: Int32; Z1IsOne: Boolean; begin if (IsInfinity) then begin result := Self; Exit; end; ecCurve := curve; X1 := RawXCoord; if (X1.IsZero) then begin // A point with X == 0 is it's own additive inverse result := ecCurve.Infinity; Exit; end; coord := ecCurve.CoordinateSystem; case coord of TECCurve.COORD_AFFINE: begin Y1 := RawYCoord; L1 := Y1.Divide(X1).Add(X1); X3 := L1.Square().Add(L1).Add(ecCurve.a); Y3 := X1.SquarePlusProduct(X3, L1.AddOne()); result := TF2mPoint.Create(ecCurve, X3, Y3, IsCompressed); Exit; end; TECCurve.COORD_HOMOGENEOUS: begin Y1 := RawYCoord; Z1 := RawZCoords[0]; Z1IsOne := Z1.IsOne; if Z1IsOne then begin X1Z1 := X1; end else begin X1Z1 := X1.Multiply(Z1); end; if Z1IsOne then begin Y1Z1 := Y1; end else begin Y1Z1 := Y1.Multiply(Z1); end; X1Sq := X1.Square(); S := X1Sq.Add(Y1Z1); V := X1Z1; vSquared := V.Square(); sv := S.Add(V); h := sv.MultiplyPlusProduct(S, vSquared, ecCurve.a); X3 := V.Multiply(h); Y3 := X1Sq.Square().MultiplyPlusProduct(V, h, sv); Z3 := V.Multiply(vSquared); result := TF2mPoint.Create(ecCurve, X3, Y3, TCryptoLibGenericArray<IECFieldElement>.Create(Z3), IsCompressed); Exit; end; TECCurve.COORD_LAMBDA_PROJECTIVE: begin L1 := RawYCoord; Z1 := RawZCoords[0]; Z1IsOne := Z1.IsOne; if Z1IsOne then begin L1Z1 := L1; end else begin L1Z1 := L1.Multiply(Z1); end; if Z1IsOne then begin Z1Sq := Z1; end else begin Z1Sq := Z1.Square(); end; a := ecCurve.a; if Z1IsOne then begin aZ1Sq := a; end else begin aZ1Sq := a.Multiply(Z1Sq); end; T := L1.Square().Add(L1Z1).Add(aZ1Sq); if (T.IsZero) then begin result := TF2mPoint.Create(ecCurve, T, ecCurve.b.Sqrt(), IsCompressed); Exit; end; X3 := T.Square(); if Z1IsOne then begin Z3 := T; end else begin Z3 := T.Multiply(Z1Sq); end; b := ecCurve.b; if (b.BitLength < (TBits.Asr32(ecCurve.FieldSize, 1))) then begin t1 := L1.Add(X1).Square(); if (b.IsOne) then begin t2 := aZ1Sq.Add(Z1Sq).Square(); end else begin // TODO Can be calculated with one square if we pre-compute sqrt(b) t2 := aZ1Sq.SquarePlusProduct(b, Z1Sq.Square()); end; L3 := t1.Add(T).Add(Z1Sq).Multiply(t1).Add(t2).Add(X3); if (a.IsZero) then begin L3 := L3.Add(Z3); end else if (not a.IsOne) then begin L3 := L3.Add(a.AddOne().Multiply(Z3)); end end else begin if Z1IsOne then begin X1Z1 := X1; end else begin X1Z1 := X1.Multiply(Z1); end; L3 := X1Z1.SquarePlusProduct(T, L1Z1).Add(X3).Add(Z3); end; result := TF2mPoint.Create(ecCurve, X3, L3, TCryptoLibGenericArray<IECFieldElement>.Create(Z3), IsCompressed); Exit; end else begin raise EInvalidOperationCryptoLibException.CreateRes (@SUnSupportedCoordinateSystem); end; end; end; function TF2mPoint.TwicePlus(const b: IECPoint): IECPoint; var ecCurve: IECCurve; X1, X2, Z2, L1, L2, Z1, X1Sq, L1Sq, Z1Sq, L1Z1, T, L2plus1, a, X2Z1Sq, bigB, X3, L3, Z3: IECFieldElement; coord: Int32; begin if (IsInfinity) then begin result := b; Exit; end; if (b.IsInfinity) then begin result := Twice(); Exit; end; ecCurve := curve; X1 := RawXCoord; if (X1.IsZero) then begin // A point with X == 0 is it's own additive inverse result := b; Exit; end; coord := ecCurve.CoordinateSystem; case coord of TECCurve.COORD_LAMBDA_PROJECTIVE: begin // NOTE: twicePlus() only optimized for lambda-affine argument X2 := b.RawXCoord; Z2 := b.RawZCoords[0]; if ((X2.IsZero) or (not Z2.IsOne)) then begin result := Twice().Add(b); Exit; end; L1 := RawYCoord; Z1 := RawZCoords[0]; L2 := b.RawYCoord; X1Sq := X1.Square(); L1Sq := L1.Square(); Z1Sq := Z1.Square(); L1Z1 := L1.Multiply(Z1); T := ecCurve.a.Multiply(Z1Sq).Add(L1Sq).Add(L1Z1); L2plus1 := L2.AddOne(); a := ecCurve.a.Add(L2plus1).Multiply(Z1Sq).Add(L1Sq) .MultiplyPlusProduct(T, X1Sq, Z1Sq); X2Z1Sq := X2.Multiply(Z1Sq); bigB := X2Z1Sq.Add(T).Square(); if (bigB.IsZero) then begin if (a.IsZero) then begin result := b.Twice(); Exit; end; result := ecCurve.Infinity; Exit; end; if (a.IsZero) then begin result := TF2mPoint.Create(ecCurve, a, ecCurve.b.Sqrt(), IsCompressed); Exit; end; X3 := a.Square().Multiply(X2Z1Sq); Z3 := a.Multiply(bigB).Multiply(Z1Sq); L3 := a.Add(bigB).Square().MultiplyPlusProduct(T, L2plus1, Z3); result := TF2mPoint.Create(ecCurve, X3, L3, TCryptoLibGenericArray<IECFieldElement>.Create(Z3), IsCompressed); Exit; end else begin result := Twice().Add(b); Exit; end; end; end; { TECPointBase } constructor TECPointBase.Create(const curve: IECCurve; const x, y: IECFieldElement; withCompression: Boolean); begin Inherited Create(curve, x, y, withCompression); end; constructor TECPointBase.Create(const curve: IECCurve; const x, y: IECFieldElement; const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean); begin Inherited Create(curve, x, y, zs, withCompression); end; destructor TECPointBase.Destroy; begin inherited Destroy; end; function TECPointBase.GetEncoded(compressed: Boolean): TCryptoLibByteArray; var normed: IECPoint; lx, ly, PO: TCryptoLibByteArray; begin if (IsInfinity) then begin System.SetLength(result, 1); Exit; end; normed := Normalize(); lx := normed.XCoord.GetEncoded(); if (compressed) then begin System.SetLength(PO, System.Length(lx) + 1); if normed.CompressionYTilde then begin PO[0] := Byte($03); end else begin PO[0] := Byte($02); end; System.Move(lx[0], PO[1], System.Length(lx) * System.SizeOf(Byte)); result := PO; Exit; end; ly := normed.YCoord.GetEncoded(); System.SetLength(PO, System.Length(lx) + System.Length(ly) + 1); PO[0] := $04; System.Move(lx[0], PO[1], System.Length(lx) * System.SizeOf(Byte)); System.Move(ly[0], PO[System.Length(lx) + 1], System.Length(ly) * System.SizeOf(Byte)); result := PO; end; function TECPointBase.Multiply(k: TBigInteger): IECPoint; begin result := curve.GetMultiplier().Multiply(Self as IECPoint, k); end; { TAbstractFpPoint } function TAbstractFpPoint.GetCompressionYTilde: Boolean; begin result := AffineYCoord.TestBitZero(); end; constructor TAbstractFpPoint.Create(const curve: IECCurve; const x, y: IECFieldElement; withCompression: Boolean); begin Inherited Create(curve, x, y, withCompression); end; constructor TAbstractFpPoint.Create(const curve: IECCurve; const x, y: IECFieldElement; const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean); begin Inherited Create(curve, x, y, zs, withCompression); end; destructor TAbstractFpPoint.Destroy; begin inherited Destroy; end; function TAbstractFpPoint.SatisfiesCurveEquation: Boolean; var lx, ly, a, b, lhs, rhs, Z, Z2, Z3, Z4, Z6: IECFieldElement; begin lx := RawXCoord; ly := RawYCoord; a := curve.a; b := curve.b; lhs := ly.Square(); case CurveCoordinateSystem of TECCurve.COORD_AFFINE: begin // do nothing end; TECCurve.COORD_HOMOGENEOUS: begin Z := RawZCoords[0]; if (not Z.IsOne) then begin Z2 := Z.Square(); Z3 := Z.Multiply(Z2); lhs := lhs.Multiply(Z); a := a.Multiply(Z2); b := b.Multiply(Z3); end; end; TECCurve.COORD_JACOBIAN, TECCurve.COORD_JACOBIAN_CHUDNOVSKY, TECCurve.COORD_JACOBIAN_MODIFIED: begin Z := RawZCoords[0]; if (not Z.IsOne) then begin Z2 := Z.Square(); Z4 := Z2.Square(); Z6 := Z2.Multiply(Z4); a := a.Multiply(Z4); b := b.Multiply(Z6); end; end else begin raise EInvalidOperationCryptoLibException.CreateRes (@SUnSupportedCoordinateSystem); end; end; rhs := lx.Square().Add(a).Multiply(lx).Add(b); result := lhs.Equals(rhs); end; function TAbstractFpPoint.Subtract(const b: IECPoint): IECPoint; begin if (b.IsInfinity) then begin result := Self; Exit; end; // Add -b result := Add(b.Negate()); end; { TFpPoint } function TFpPoint.Add(const b: IECPoint): IECPoint; var ecCurve: IECCurve; coord: Int32; gamma, X1, X2, Y1, Y2, dx, dy, X3, Y3, Z1, Z2, U1, V1, U2, V2, U, V, W, a, Z3, S2, S1, vSquared, vCubed, vSquaredV2, Z1Squared, bigU2, Z3Squared, c, W1, W2, A1, Z1Cubed, Z2Squared, bigU1, h, R, HSquared, G, W3, Z2Cubed: IECFieldElement; zs: TCryptoLibGenericArray<IECFieldElement>; Z1IsOne, Z2IsOne: Boolean; begin if (IsInfinity) then begin result := b; Exit; end; if (b.IsInfinity) then begin result := Self; Exit; end; if (Self as IECPoint = b) then begin result := Twice(); Exit; end; ecCurve := curve; coord := ecCurve.CoordinateSystem; X1 := RawXCoord; Y1 := RawYCoord; X2 := b.RawXCoord; Y2 := b.RawYCoord; case coord of TECCurve.COORD_AFFINE: begin dx := X2.Subtract(X1); dy := Y2.Subtract(Y1); if (dx.IsZero) then begin if (dy.IsZero) then begin // this == b, i.e. this must be doubled result := Twice(); Exit; end; // this == -b, i.e. the result is the point at infinity result := curve.Infinity; Exit; end; gamma := dy.Divide(dx); X3 := gamma.Square().Subtract(X1).Subtract(X2); Y3 := gamma.Multiply(X1.Subtract(X3)).Subtract(Y1); result := TFpPoint.Create(curve, X3, Y3, IsCompressed); Exit; end; TECCurve.COORD_HOMOGENEOUS: begin Z1 := RawZCoords[0]; Z2 := b.RawZCoords[0]; Z1IsOne := Z1.IsOne; Z2IsOne := Z2.IsOne; if Z1IsOne then begin U1 := Y2; end else begin U1 := Y2.Multiply(Z1); end; if Z2IsOne then begin U2 := Y1; end else begin U2 := Y1.Multiply(Z2); end; U := U1.Subtract(U2); if Z1IsOne then begin V1 := X2; end else begin V1 := X2.Multiply(Z1); end; if Z2IsOne then begin V2 := X1; end else begin V2 := X1.Multiply(Z2); end; V := V1.Subtract(V2); // Check if b = this or b = -this if (V.IsZero) then begin if (U.IsZero) then begin // this = b, i.e. this must be doubled result := Twice(); Exit; end; // this = -b, i.e. the result is the point at infinity result := ecCurve.Infinity; Exit; end; // TODO Optimize for when w = 1 if Z1IsOne then begin W := Z2; end else if Z2IsOne then begin W := Z1; end else begin W := Z1.Multiply(Z2); end; vSquared := V.Square(); vCubed := vSquared.Multiply(V); vSquaredV2 := vSquared.Multiply(V2); a := U.Square().Multiply(W).Subtract(vCubed).Subtract(Two(vSquaredV2)); X3 := V.Multiply(a); Y3 := vSquaredV2.Subtract(a).MultiplyMinusProduct(U, U2, vCubed); Z3 := vCubed.Multiply(W); result := TFpPoint.Create(ecCurve, X3, Y3, TCryptoLibGenericArray<IECFieldElement>.Create(Z3), IsCompressed); Exit; end; TECCurve.COORD_JACOBIAN, TECCurve.COORD_JACOBIAN_MODIFIED: begin Z1 := RawZCoords[0]; Z2 := b.RawZCoords[0]; Z1IsOne := Z1.IsOne; X3 := Nil; Y3 := Nil; Z3 := Nil; Z3Squared := Nil; if ((not Z1IsOne) and (Z1.Equals(Z2))) then begin // TODO Make this available as public method coZAdd? dx := X1.Subtract(X2); dy := Y1.Subtract(Y2); if (dx.IsZero) then begin if (dy.IsZero) then begin result := Twice(); Exit; end; result := ecCurve.Infinity; Exit; end; c := dx.Square(); W1 := X1.Multiply(c); W2 := X2.Multiply(c); A1 := W1.Subtract(W2).Multiply(Y1); X3 := dy.Square().Subtract(W1).Subtract(W2); Y3 := W1.Subtract(X3).Multiply(dy).Subtract(A1); Z3 := dx; if (Z1IsOne) then begin Z3Squared := c; end else begin Z3 := Z3.Multiply(Z1); end end else begin if (Z1IsOne) then begin Z1Squared := Z1; bigU2 := X2; S2 := Y2; end else begin Z1Squared := Z1.Square(); bigU2 := Z1Squared.Multiply(X2); Z1Cubed := Z1Squared.Multiply(Z1); S2 := Z1Cubed.Multiply(Y2); end; Z2IsOne := Z2.IsOne; if (Z2IsOne) then begin Z2Squared := Z2; bigU1 := X1; S1 := Y1; end else begin Z2Squared := Z2.Square(); bigU1 := Z2Squared.Multiply(X1); Z2Cubed := Z2Squared.Multiply(Z2); S1 := Z2Cubed.Multiply(Y1); end; h := bigU1.Subtract(bigU2); R := S1.Subtract(S2); // Check if b == this or b == -this if (h.IsZero) then begin if (R.IsZero) then begin // this == b, i.e. this must be doubled result := Twice(); Exit; end; // this == -b, i.e. the result is the point at infinity result := ecCurve.Infinity; Exit; end; HSquared := h.Square(); G := HSquared.Multiply(h); V := HSquared.Multiply(bigU1); X3 := R.Square().Add(G).Subtract(Two(V)); Y3 := V.Subtract(X3).MultiplyMinusProduct(R, G, S1); Z3 := h; if (not Z1IsOne) then begin Z3 := Z3.Multiply(Z1); end; if (not Z2IsOne) then begin Z3 := Z3.Multiply(Z2); end; // Alternative calculation of Z3 using fast square // X3 := four(X3); // Y3 := eight(Y3); // Z3 := doubleProductFromSquares(Z1, Z2, Z1Squared, Z2Squared).Multiply(H); if (Z3 = h) then begin Z3Squared := HSquared; end; end; if (coord = TECCurve.COORD_JACOBIAN_MODIFIED) then begin // TODO If the result will only be used in a subsequent addition, we don't need W3 W3 := CalculateJacobianModifiedW(Z3, Z3Squared); zs := TCryptoLibGenericArray<IECFieldElement>.Create(Z3, W3); end else begin zs := TCryptoLibGenericArray<IECFieldElement>.Create(Z3); end; result := TFpPoint.Create(ecCurve, X3, Y3, zs, IsCompressed); Exit; end else begin raise EInvalidOperationCryptoLibException.CreateRes (@SUnSupportedCoordinateSystem); end; end; end; function TFpPoint.CalculateJacobianModifiedW(const Z: IECFieldElement; const ZSquared: IECFieldElement): IECFieldElement; var a4, W, a4Neg, LZSquared: IECFieldElement; begin a4 := curve.a; LZSquared := ZSquared; if ((a4.IsZero) or (Z.IsOne)) then begin result := a4; Exit; end; if (LZSquared = Nil) then begin LZSquared := Z.Square(); end; W := LZSquared.Square(); a4Neg := a4.Negate(); if (a4Neg.BitLength < a4.BitLength) then begin W := W.Multiply(a4Neg).Negate(); end else begin W := W.Multiply(a4); end; result := W; end; constructor TFpPoint.Create(const curve: IECCurve; const x, y: IECFieldElement; const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean); begin Inherited Create(curve, x, y, zs, withCompression); end; constructor TFpPoint.Create(const curve: IECCurve; const x, y: IECFieldElement; withCompression: Boolean); begin Inherited Create(curve, x, y, withCompression); if ((x = Nil) <> (y = Nil)) then begin raise EArgumentCryptoLibException.CreateRes(@SNilFieldElement); end; end; constructor TFpPoint.Create(const curve: IECCurve; const x, y: IECFieldElement); begin Create(curve, x, y, false); end; destructor TFpPoint.Destroy; begin inherited Destroy; end; function TFpPoint.Detach: IECPoint; begin result := TFpPoint.Create(Nil, AffineXCoord, AffineYCoord, false); end; function TFpPoint.DoubleProductFromSquares(const a, b, aSquared, bSquared: IECFieldElement): IECFieldElement; begin // /* // * NOTE: If squaring in the field is faster than multiplication, then this is a quicker // * way to calculate 2.A.B, if A^2 and B^2 are already known. // */ result := a.Add(b).Square().Subtract(aSquared).Subtract(bSquared); end; function TFpPoint.Eight(const x: IECFieldElement): IECFieldElement; begin result := Four(Two(x)); end; function TFpPoint.Four(const x: IECFieldElement): IECFieldElement; begin result := Two(Two(x)); end; function TFpPoint.GetJacobianModifiedW: IECFieldElement; var ZZ: TCryptoLibGenericArray<IECFieldElement>; W: IECFieldElement; begin ZZ := RawZCoords; W := ZZ[1]; if (W = Nil) then begin // NOTE: Rarely, TwicePlus will result in the need for a lazy W1 calculation here W := CalculateJacobianModifiedW(ZZ[0], Nil); ZZ[1] := W; end; result := W; end; function TFpPoint.GetZCoord(index: Int32): IECFieldElement; begin if ((index = 1) and (TECCurve.COORD_JACOBIAN_MODIFIED = CurveCoordinateSystem)) then begin result := GetJacobianModifiedW(); Exit; end; result := (Inherited GetZCoord(index)); end; function TFpPoint.Negate: IECPoint; var Lcurve: IECCurve; coord: Int32; begin if (IsInfinity) then begin result := Self; Exit; end; Lcurve := curve; coord := Lcurve.CoordinateSystem; if (TECCurve.COORD_AFFINE <> coord) then begin result := TFpPoint.Create(Lcurve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed); Exit; end; result := TFpPoint.Create(Lcurve, RawXCoord, RawYCoord.Negate(), IsCompressed); end; function TFpPoint.Three(const x: IECFieldElement): IECFieldElement; begin result := Two(x).Add(x); end; function TFpPoint.ThreeTimes: IECPoint; var Y1, X1, _2Y1, lx, Z, ly, d, bigD, i, L1, L2, X4, Y4: IECFieldElement; ecCurve: IECCurve; coord: Int32; begin if (IsInfinity) then begin result := Self; Exit; end; Y1 := RawYCoord; if (Y1.IsZero) then begin result := Self; Exit; end; ecCurve := curve; coord := ecCurve.CoordinateSystem; case coord of TECCurve.COORD_AFFINE: begin X1 := RawXCoord; _2Y1 := Two(Y1); lx := _2Y1.Square(); Z := Three(X1.Square()).Add(curve.a); ly := Z.Square(); d := Three(X1).Multiply(lx).Subtract(ly); if (d.IsZero) then begin result := curve.Infinity; Exit; end; bigD := d.Multiply(_2Y1); i := bigD.Invert(); L1 := d.Multiply(i).Multiply(Z); L2 := lx.Square().Multiply(i).Subtract(L1); X4 := (L2.Subtract(L1)).Multiply(L1.Add(L2)).Add(X1); Y4 := (X1.Subtract(X4)).Multiply(L2).Subtract(Y1); result := TFpPoint.Create(curve, X4, Y4, IsCompressed); Exit; end; TECCurve.COORD_JACOBIAN_MODIFIED: begin result := TwiceJacobianModified(false).Add(Self); Exit; end else begin // NOTE: Be careful about recursions between TwicePlus and ThreeTimes result := Twice().Add(Self); end; end; end; function TFpPoint.TimesPow2(e: Int32): IECPoint; var ecCurve: IECCurve; Y1, W1, X1, Z1, Z1Sq, X1Squared, M, _2Y1, _2Y1Squared, S, _4T, _8T, zInv, zInv2, zInv3: IECFieldElement; coord, i: Int32; begin if (e < 0) then begin raise EArgumentCryptoLibException.CreateRes(@SCannotBeNegative); end; if ((e = 0) or (IsInfinity)) then begin result := Self; Exit; end; if (e = 1) then begin result := Twice(); Exit; end; ecCurve := curve; Y1 := RawYCoord; if (Y1.IsZero) then begin result := ecCurve.Infinity; Exit; end; coord := ecCurve.CoordinateSystem; W1 := ecCurve.a; X1 := RawXCoord; if RawZCoords = Nil then begin Z1 := ecCurve.FromBigInteger(TBigInteger.One); end else begin Z1 := RawZCoords[0]; end; if (not Z1.IsOne) then begin case coord of TECCurve.COORD_HOMOGENEOUS: begin Z1Sq := Z1.Square(); X1 := X1.Multiply(Z1); Y1 := Y1.Multiply(Z1Sq); W1 := CalculateJacobianModifiedW(Z1, Z1Sq); end; TECCurve.COORD_JACOBIAN: begin W1 := CalculateJacobianModifiedW(Z1, Nil); end; TECCurve.COORD_JACOBIAN_MODIFIED: begin W1 := GetJacobianModifiedW(); end; end; end; i := 0; while i < e do begin if (Y1.IsZero) then begin result := ecCurve.Infinity; Exit; end; X1Squared := X1.Square(); M := Three(X1Squared); _2Y1 := Two(Y1); _2Y1Squared := _2Y1.Multiply(Y1); S := Two(X1.Multiply(_2Y1Squared)); _4T := _2Y1Squared.Square(); _8T := Two(_4T); if (not W1.IsZero) then begin M := M.Add(W1); W1 := Two(_8T.Multiply(W1)); end; X1 := M.Square().Subtract(Two(S)); Y1 := M.Multiply(S.Subtract(X1)).Subtract(_8T); if Z1.IsOne then begin Z1 := _2Y1; end else begin Z1 := _2Y1.Multiply(Z1); end; System.Inc(i); end; case coord of TECCurve.COORD_AFFINE: begin zInv := Z1.Invert(); zInv2 := zInv.Square(); zInv3 := zInv2.Multiply(zInv); result := TFpPoint.Create(ecCurve, X1.Multiply(zInv2), Y1.Multiply(zInv3), IsCompressed); Exit; end; TECCurve.COORD_HOMOGENEOUS: begin X1 := X1.Multiply(Z1); Z1 := Z1.Multiply(Z1.Square()); result := TFpPoint.Create(ecCurve, X1, Y1, TCryptoLibGenericArray<IECFieldElement>.Create(Z1), IsCompressed); Exit; end; TECCurve.COORD_JACOBIAN: begin result := TFpPoint.Create(ecCurve, X1, Y1, TCryptoLibGenericArray<IECFieldElement>.Create(Z1), IsCompressed); Exit; end; TECCurve.COORD_JACOBIAN_MODIFIED: begin result := TFpPoint.Create(ecCurve, X1, Y1, TCryptoLibGenericArray<IECFieldElement>.Create(Z1, W1), IsCompressed); Exit; end else begin raise EInvalidOperationCryptoLibException.CreateRes (@SUnSupportedCoordinateSystem); end; end; end; function TFpPoint.Twice: IECPoint; var ecCurve: IECCurve; Y1, X1, X1Squared, gamma, X3, Y3, Z1, W, S, T, b, _4B, h, _2s, _2t, _4sSquared, Z3, M, Y1Squared, a4, a4Neg, Z1Squared, Z1Pow4: IECFieldElement; coord: Int32; Z1IsOne: Boolean; begin if (IsInfinity) then begin result := Self; Exit; end; ecCurve := curve; Y1 := RawYCoord; if (Y1.IsZero) then begin result := ecCurve.Infinity; Exit; end; coord := ecCurve.CoordinateSystem; X1 := RawXCoord; case coord of TECCurve.COORD_AFFINE: begin X1Squared := X1.Square(); gamma := Three(X1Squared).Add(curve.a).Divide(Two(Y1)); X3 := gamma.Square().Subtract(Two(X1)); Y3 := gamma.Multiply(X1.Subtract(X3)).Subtract(Y1); result := TFpPoint.Create(curve, X3, Y3, IsCompressed); Exit; end; TECCurve.COORD_HOMOGENEOUS: begin Z1 := RawZCoords[0]; Z1IsOne := Z1.IsOne; // TODO Optimize for small negative a4 and -3 W := ecCurve.a; if ((not W.IsZero) and (not Z1IsOne)) then begin W := W.Multiply(Z1.Square()); end; W := W.Add(Three(X1.Square())); if Z1IsOne then begin S := Y1; end else begin S := Y1.Multiply(Z1); end; if Z1IsOne then begin T := Y1.Square(); end else begin T := S.Multiply(Y1); end; b := X1.Multiply(T); _4B := Four(b); h := W.Square().Subtract(Two(_4B)); _2s := Two(S); X3 := h.Multiply(_2s); _2t := Two(T); Y3 := _4B.Subtract(h).Multiply(W).Subtract(Two(_2t.Square())); if Z1IsOne then begin _4sSquared := Two(_2t); end else begin _4sSquared := _2s.Square(); end; Z3 := Two(_4sSquared).Multiply(S); result := TFpPoint.Create(ecCurve, X3, Y3, TCryptoLibGenericArray<IECFieldElement>.Create(Z3), IsCompressed); Exit; end; TECCurve.COORD_JACOBIAN: begin Z1 := RawZCoords[0]; Z1IsOne := Z1.IsOne; Y1Squared := Y1.Square(); T := Y1Squared.Square(); a4 := ecCurve.a; a4Neg := a4.Negate(); if (a4Neg.ToBigInteger().Equals(TBigInteger.ValueOf(3))) then begin if Z1IsOne then begin Z1Squared := Z1; end else begin Z1Squared := Z1.Square(); end; M := Three(X1.Add(Z1Squared).Multiply(X1.Subtract(Z1Squared))); S := Four(Y1Squared.Multiply(X1)); end else begin X1Squared := X1.Square(); M := Three(X1Squared); if (Z1IsOne) then begin M := M.Add(a4); end else if (not a4.IsZero) then begin if Z1IsOne then begin Z1Squared := Z1; end else begin Z1Squared := Z1.Square(); end; Z1Pow4 := Z1Squared.Square(); if (a4Neg.BitLength < a4.BitLength) then begin M := M.Subtract(Z1Pow4.Multiply(a4Neg)); end else begin M := M.Add(Z1Pow4.Multiply(a4)); end end; // S := two(doubleProductFromSquares(X1, Y1Squared, X1Squared, T)); S := Four(X1.Multiply(Y1Squared)); end; X3 := M.Square().Subtract(Two(S)); Y3 := S.Subtract(X3).Multiply(M).Subtract(Eight(T)); Z3 := Two(Y1); if (not Z1IsOne) then begin Z3 := Z3.Multiply(Z1); end; // Alternative calculation of Z3 using fast square // Z3 := doubleProductFromSquares(Y1, Z1, Y1Squared, Z1Squared); result := TFpPoint.Create(ecCurve, X3, Y3, TCryptoLibGenericArray<IECFieldElement>.Create(Z3), IsCompressed); Exit; end; TECCurve.COORD_JACOBIAN_MODIFIED: begin result := TwiceJacobianModified(True); Exit; end else begin raise EInvalidOperationCryptoLibException.CreateRes (@SUnSupportedCoordinateSystem); end; end; end; function TFpPoint.TwiceJacobianModified(calculateW: Boolean): IFpPoint; var X1, Y1, Z1, W1, X1Squared, M, _2Y1, _2Y1Squared, S, X3, _4T, _8T, Y3, W3, Z3: IECFieldElement; begin X1 := RawXCoord; Y1 := RawYCoord; Z1 := RawZCoords[0]; W1 := GetJacobianModifiedW(); X1Squared := X1.Square(); M := Three(X1Squared).Add(W1); _2Y1 := Two(Y1); _2Y1Squared := _2Y1.Multiply(Y1); S := Two(X1.Multiply(_2Y1Squared)); X3 := M.Square().Subtract(Two(S)); _4T := _2Y1Squared.Square(); _8T := Two(_4T); Y3 := M.Multiply(S.Subtract(X3)).Subtract(_8T); if calculateW then begin W3 := Two(_8T.Multiply(W1)); end else begin W3 := Nil; end; if Z1.IsOne then begin Z3 := _2Y1; end else begin Z3 := _2Y1.Multiply(Z1); end; result := TFpPoint.Create(curve, X3, Y3, TCryptoLibGenericArray<IECFieldElement>.Create(Z3, W3), IsCompressed); end; function TFpPoint.TwicePlus(const b: IECPoint): IECPoint; var Y1, X1, X2, Y2, dx, dy, lx, ly, d, i, L1, L2, X4, Y4, bigD: IECFieldElement; ecCurve: IECCurve; coord: Int32; begin if (Self as IECPoint = b) then begin result := ThreeTimes(); Exit; end; if (IsInfinity) then begin result := b; Exit; end; if (b.IsInfinity) then begin result := Twice(); Exit; end; Y1 := RawYCoord; if (Y1.IsZero) then begin result := b; Exit; end; ecCurve := curve; coord := ecCurve.CoordinateSystem; case coord of TECCurve.COORD_AFFINE: begin X1 := RawXCoord; X2 := b.RawXCoord; Y2 := b.RawYCoord; dx := X2.Subtract(X1); dy := Y2.Subtract(Y1); if (dx.IsZero) then begin if (dy.IsZero) then begin // this == b i.e. the result is 3P result := ThreeTimes(); Exit; end; // this == -b, i.e. the result is P result := Self; Exit; end; // / * * Optimized calculation of 2 p + Q, as described // in " Trading Inversions for * Multiplications // in Elliptic curve Cryptography ", by Ciet, Joye, Lauter, // Montgomery. * / lx := dx.Square(); ly := dy.Square(); d := lx.Multiply(Two(X1).Add(X2)).Subtract(ly); if (d.IsZero) then begin result := curve.Infinity; Exit; end; bigD := d.Multiply(dx); i := bigD.Invert(); L1 := d.Multiply(i).Multiply(dy); L2 := Two(Y1).Multiply(lx).Multiply(dx).Multiply(i).Subtract(L1); X4 := (L2.Subtract(L1)).Multiply(L1.Add(L2)).Add(X2); Y4 := (X1.Subtract(X4)).Multiply(L2).Subtract(Y1); result := TFpPoint.Create(curve, X4, Y4, IsCompressed); Exit; end; TECCurve.COORD_JACOBIAN_MODIFIED: begin result := TwiceJacobianModified(false).Add(b); Exit; end else begin result := Twice().Add(b); Exit; end; end; end; function TFpPoint.Two(const x: IECFieldElement): IECFieldElement; begin result := x.Add(x); end; { TAbstractF2mPoint } constructor TAbstractF2mPoint.Create(const curve: IECCurve; const x, y: IECFieldElement; withCompression: Boolean); begin Inherited Create(curve, x, y, withCompression); end; constructor TAbstractF2mPoint.Create(const curve: IECCurve; const x, y: IECFieldElement; const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean); begin Inherited Create(curve, x, y, zs, withCompression); end; destructor TAbstractF2mPoint.Destroy; begin inherited Destroy; end; function TAbstractF2mPoint.SatisfiesCurveEquation: Boolean; var Z, Z2, Z3, x, ly, a, b, lhs, rhs, L, X2, Z4: IECFieldElement; ecCurve: IECCurve; coord: Int32; ZIsOne: Boolean; begin ecCurve := curve; x := RawXCoord; ly := RawYCoord; a := ecCurve.a; b := ecCurve.b; coord := ecCurve.CoordinateSystem; if (coord = TECCurve.COORD_LAMBDA_PROJECTIVE) then begin Z := RawZCoords[0]; ZIsOne := Z.IsOne; if (x.IsZero) then begin // NOTE: For x == 0, we expect the affine-y instead of the lambda-y lhs := ly.Square(); rhs := b; if (not ZIsOne) then begin Z2 := Z.Square(); rhs := rhs.Multiply(Z2); end end else begin L := ly; X2 := x.Square(); if (ZIsOne) then begin lhs := L.Square().Add(L).Add(a); rhs := X2.Square().Add(b); end else begin Z2 := Z.Square(); Z4 := Z2.Square(); lhs := L.Add(Z).MultiplyPlusProduct(L, a, Z2); // TODO If sqrt(b) is precomputed this can be simplified to a single square rhs := X2.SquarePlusProduct(b, Z4); end; lhs := lhs.Multiply(X2); end end else begin lhs := ly.Add(x).Multiply(ly); case coord of TECCurve.COORD_AFFINE: begin // do nothing; end; TECCurve.COORD_HOMOGENEOUS: begin Z := RawZCoords[0]; if (not Z.IsOne) then begin Z2 := Z.Square(); Z3 := Z.Multiply(Z2); lhs := lhs.Multiply(Z); a := a.Multiply(Z); b := b.Multiply(Z3); end; end else begin raise EInvalidOperationCryptoLibException.CreateRes (@SUnSupportedCoordinateSystem); end; end; rhs := x.Add(a).Multiply(x.Square()).Add(b); end; result := lhs.Equals(rhs); end; function TAbstractF2mPoint.SatisfiesOrder: Boolean; var cofactor: TBigInteger; n: IECPoint; x, rhs, lambda, W, T: IECFieldElement; Lcurve: IECCurve; begin Lcurve := curve; cofactor := Lcurve.getCofactor(); if (TBigInteger.Two.Equals(cofactor)) then begin // /* // * Check that the trace of (X + A) is 0, then there exists a solution to L^2 + L = X + A, // * and so a halving is possible, so this point is the double of another. // */ n := Normalize(); x := n.AffineXCoord; rhs := x.Add(Lcurve.a); result := (rhs as IAbstractF2mFieldElement).Trace() = 0; Exit; end; if (TBigInteger.Four.Equals(cofactor)) then begin // /* // * Solve L^2 + L = X + A to find the half of this point, if it exists (fail if not). // * Generate both possibilities for the square of the half-point's x-coordinate (w), // * and check if Tr(w + A) == 0 for at least one; then a second halving is possible // * (see comments for cofactor 2 above), so this point is four times another. // * // * Note: Tr(x^2) == Tr(x). // */ n := Normalize(); x := n.AffineXCoord; lambda := (Lcurve as IAbstractF2mCurve).SolveQuadraticEquation (x.Add(curve.a)); if (lambda = Nil) then begin result := false; Exit; end; W := x.Multiply(lambda).Add(n.AffineYCoord); T := W.Add(Lcurve.a); result := ((T as IAbstractF2mFieldElement).Trace() = 0) or ((T.Add(x) as IAbstractF2mFieldElement).Trace() = 0); Exit; end; result := Inherited SatisfiesOrder(); end; function TAbstractF2mPoint.ScaleX(const scale: IECFieldElement): IECPoint; var lx, L, X2, L2, Z, Z2: IECFieldElement; begin if (IsInfinity) then begin result := Self; Exit; end; case CurveCoordinateSystem of TECCurve.COORD_LAMBDA_AFFINE: begin // Y is actually Lambda (X + Y/X) here lx := RawXCoord; L := RawYCoord; X2 := lx.Multiply(scale); L2 := L.Add(lx).Divide(scale).Add(X2); result := curve.CreateRawPoint(lx, L2, RawZCoords, IsCompressed); Exit; end; TECCurve.COORD_LAMBDA_PROJECTIVE: begin // Y is actually Lambda (X + Y/X) here lx := RawXCoord; L := RawYCoord; Z := RawZCoords[0]; // We scale the Z coordinate also, to avoid an inversion X2 := lx.Multiply(scale.Square()); L2 := L.Add(lx).Add(X2); Z2 := Z.Multiply(scale); result := curve.CreateRawPoint(lx, L2, TCryptoLibGenericArray<IECFieldElement>.Create(Z2), IsCompressed); Exit; end else begin result := (Inherited ScaleX(scale)); end; end; end; function TAbstractF2mPoint.ScaleY(const scale: IECFieldElement): IECPoint; var lx, L, L2: IECFieldElement; begin if (IsInfinity) then begin result := Self; Exit; end; case CurveCoordinateSystem of TECCurve.COORD_LAMBDA_AFFINE, TECCurve.COORD_LAMBDA_PROJECTIVE: begin lx := RawXCoord; L := RawYCoord; // Y is actually Lambda (X + Y/X) here L2 := L.Add(lx).Multiply(scale).Add(lx); result := curve.CreateRawPoint(lx, L2, RawZCoords, IsCompressed); Exit; end else begin result := (Inherited ScaleY(scale)); end; end; end; function TAbstractF2mPoint.Subtract(const b: IECPoint): IECPoint; begin if (b.IsInfinity) then begin result := Self; end; // Add -b result := Add(b.Negate()); end; function TAbstractF2mPoint.Tau: IAbstractF2mPoint; var ecCurve: IECCurve; coord: Int32; X1, Y1, Z1: IECFieldElement; begin if (IsInfinity) then begin result := Self; Exit; end; ecCurve := curve; coord := ecCurve.CoordinateSystem; X1 := RawXCoord; case coord of TECCurve.COORD_AFFINE, TECCurve.COORD_LAMBDA_AFFINE: begin Y1 := RawYCoord; result := ecCurve.CreateRawPoint(X1.Square(), Y1.Square(), IsCompressed) as IAbstractF2mPoint; Exit; end; TECCurve.COORD_HOMOGENEOUS, TECCurve.COORD_LAMBDA_PROJECTIVE: begin Y1 := RawYCoord; Z1 := RawZCoords[0]; result := ecCurve.CreateRawPoint(X1.Square(), Y1.Square(), TCryptoLibGenericArray<IECFieldElement>.Create(Z1.Square()), IsCompressed) as IAbstractF2mPoint; Exit; end else begin raise EInvalidOperationCryptoLibException.CreateRes (@SUnSupportedCoordinateSystem); end; end; end; function TAbstractF2mPoint.TauPow(pow: Int32): IAbstractF2mPoint; var ecCurve: IECCurve; coord: Int32; X1, Y1, Z1: IECFieldElement; begin if (IsInfinity) then begin result := Self; Exit; end; ecCurve := curve; coord := ecCurve.CoordinateSystem; X1 := RawXCoord; case coord of TECCurve.COORD_AFFINE, TECCurve.COORD_LAMBDA_AFFINE: begin Y1 := RawYCoord; result := ecCurve.CreateRawPoint(X1.SquarePow(pow), Y1.SquarePow(pow), IsCompressed) as IAbstractF2mPoint; Exit; end; TECCurve.COORD_HOMOGENEOUS, TECCurve.COORD_LAMBDA_PROJECTIVE: begin Y1 := RawYCoord; Z1 := RawZCoords[0]; result := ecCurve.CreateRawPoint(X1.SquarePow(pow), Y1.SquarePow(pow), TCryptoLibGenericArray<IECFieldElement>.Create(Z1.SquarePow(pow)), IsCompressed) as IAbstractF2mPoint; Exit; end else begin raise EInvalidOperationCryptoLibException.CreateRes (@SUnSupportedCoordinateSystem); end; end; end; { TECPoint.TValidityCallback } constructor TECPoint.TValidityCallback.Create(const outer: IECPoint; decompressed, checkOrder: Boolean); begin Inherited Create(); Fm_outer := outer; Fm_decompressed := decompressed; Fm_checkOrder := checkOrder; end; function TECPoint.TValidityCallback.Precompute(const existing: IPreCompInfo) : IPreCompInfo; var info: IValidityPrecompInfo; begin if (not(Supports(existing, IValidityPrecompInfo, info))) then begin info := TValidityPrecompInfo.Create(); end; if (info.hasFailed()) then begin result := info; Exit; end; if (not(info.hasCurveEquationPassed())) then begin if (not(Fm_decompressed) and not(Fm_outer.SatisfiesCurveEquation())) then begin info.reportFailed(); result := info; Exit; end; info.reportCurveEquationPassed(); end; if ((Fm_checkOrder) and (not(info.HasOrderPassed()))) then begin if (not(Fm_outer.SatisfiesOrder())) then begin info.reportFailed(); result := info; Exit; end; info.reportOrderPassed(); end; result := info; end; end.
unit TreeAttributeSelectKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы TreeAttributeSelect } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\LiteSearch\TreeAttributeSelectKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "TreeAttributeSelectKeywordsPack" MUID: (6CF70A33ED1E) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , vtPanel {$If Defined(Nemesis)} , nscContextFilter {$IfEnd} // Defined(Nemesis) {$If Defined(Nemesis)} , nscTreeViewHotTruck {$IfEnd} // Defined(Nemesis) , SearchLite_Strange_Controls ; {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , TreeAttributeSelect_Form , tfwControlString {$If NOT Defined(NoVCL)} , kwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) , tfwScriptingInterfaces , tfwPropertyLike , TypInfo , tfwTypeInfo , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes ; type Tkw_Form_TreeAttributeSelect = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы TreeAttributeSelect ---- *Пример использования*: [code] 'aControl' форма::TreeAttributeSelect TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_TreeAttributeSelect Tkw_TreeAttributeSelect_Control_BackgroundPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола BackgroundPanel ---- *Пример использования*: [code] контрол::BackgroundPanel TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TreeAttributeSelect_Control_BackgroundPanel Tkw_TreeAttributeSelect_Control_BackgroundPanel_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола BackgroundPanel ---- *Пример использования*: [code] контрол::BackgroundPanel:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TreeAttributeSelect_Control_BackgroundPanel_Push Tkw_TreeAttributeSelect_Control_ContextFilter = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ContextFilter ---- *Пример использования*: [code] контрол::ContextFilter TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TreeAttributeSelect_Control_ContextFilter Tkw_TreeAttributeSelect_Control_ContextFilter_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола ContextFilter ---- *Пример использования*: [code] контрол::ContextFilter:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TreeAttributeSelect_Control_ContextFilter_Push Tkw_TreeAttributeSelect_Control_AttributeTree = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола AttributeTree ---- *Пример использования*: [code] контрол::AttributeTree TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TreeAttributeSelect_Control_AttributeTree Tkw_TreeAttributeSelect_Control_AttributeTree_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола AttributeTree ---- *Пример использования*: [code] контрол::AttributeTree:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_TreeAttributeSelect_Control_AttributeTree_Push TkwEfTreeAttributeSelectBackgroundPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TefTreeAttributeSelect.BackgroundPanel } private function BackgroundPanel(const aCtx: TtfwContext; aefTreeAttributeSelect: TefTreeAttributeSelect): TvtPanel; {* Реализация слова скрипта .TefTreeAttributeSelect.BackgroundPanel } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEfTreeAttributeSelectBackgroundPanel TkwEfTreeAttributeSelectContextFilter = {final} class(TtfwPropertyLike) {* Слово скрипта .TefTreeAttributeSelect.ContextFilter } private function ContextFilter(const aCtx: TtfwContext; aefTreeAttributeSelect: TefTreeAttributeSelect): TnscContextFilter; {* Реализация слова скрипта .TefTreeAttributeSelect.ContextFilter } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEfTreeAttributeSelectContextFilter TkwEfTreeAttributeSelectAttributeTree = {final} class(TtfwPropertyLike) {* Слово скрипта .TefTreeAttributeSelect.AttributeTree } private function AttributeTree(const aCtx: TtfwContext; aefTreeAttributeSelect: TefTreeAttributeSelect): TnscTreeViewHotTruck; {* Реализация слова скрипта .TefTreeAttributeSelect.AttributeTree } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEfTreeAttributeSelectAttributeTree function Tkw_Form_TreeAttributeSelect.GetString: AnsiString; begin Result := 'efTreeAttributeSelect'; end;//Tkw_Form_TreeAttributeSelect.GetString class function Tkw_Form_TreeAttributeSelect.GetWordNameForRegister: AnsiString; begin Result := 'форма::TreeAttributeSelect'; end;//Tkw_Form_TreeAttributeSelect.GetWordNameForRegister function Tkw_TreeAttributeSelect_Control_BackgroundPanel.GetString: AnsiString; begin Result := 'BackgroundPanel'; end;//Tkw_TreeAttributeSelect_Control_BackgroundPanel.GetString class procedure Tkw_TreeAttributeSelect_Control_BackgroundPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_TreeAttributeSelect_Control_BackgroundPanel.RegisterInEngine class function Tkw_TreeAttributeSelect_Control_BackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel'; end;//Tkw_TreeAttributeSelect_Control_BackgroundPanel.GetWordNameForRegister procedure Tkw_TreeAttributeSelect_Control_BackgroundPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('BackgroundPanel'); inherited; end;//Tkw_TreeAttributeSelect_Control_BackgroundPanel_Push.DoDoIt class function Tkw_TreeAttributeSelect_Control_BackgroundPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel:push'; end;//Tkw_TreeAttributeSelect_Control_BackgroundPanel_Push.GetWordNameForRegister function Tkw_TreeAttributeSelect_Control_ContextFilter.GetString: AnsiString; begin Result := 'ContextFilter'; end;//Tkw_TreeAttributeSelect_Control_ContextFilter.GetString class procedure Tkw_TreeAttributeSelect_Control_ContextFilter.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscContextFilter); end;//Tkw_TreeAttributeSelect_Control_ContextFilter.RegisterInEngine class function Tkw_TreeAttributeSelect_Control_ContextFilter.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ContextFilter'; end;//Tkw_TreeAttributeSelect_Control_ContextFilter.GetWordNameForRegister procedure Tkw_TreeAttributeSelect_Control_ContextFilter_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ContextFilter'); inherited; end;//Tkw_TreeAttributeSelect_Control_ContextFilter_Push.DoDoIt class function Tkw_TreeAttributeSelect_Control_ContextFilter_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ContextFilter:push'; end;//Tkw_TreeAttributeSelect_Control_ContextFilter_Push.GetWordNameForRegister function Tkw_TreeAttributeSelect_Control_AttributeTree.GetString: AnsiString; begin Result := 'AttributeTree'; end;//Tkw_TreeAttributeSelect_Control_AttributeTree.GetString class procedure Tkw_TreeAttributeSelect_Control_AttributeTree.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscTreeViewHotTruck); end;//Tkw_TreeAttributeSelect_Control_AttributeTree.RegisterInEngine class function Tkw_TreeAttributeSelect_Control_AttributeTree.GetWordNameForRegister: AnsiString; begin Result := 'контрол::AttributeTree'; end;//Tkw_TreeAttributeSelect_Control_AttributeTree.GetWordNameForRegister procedure Tkw_TreeAttributeSelect_Control_AttributeTree_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('AttributeTree'); inherited; end;//Tkw_TreeAttributeSelect_Control_AttributeTree_Push.DoDoIt class function Tkw_TreeAttributeSelect_Control_AttributeTree_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::AttributeTree:push'; end;//Tkw_TreeAttributeSelect_Control_AttributeTree_Push.GetWordNameForRegister function TkwEfTreeAttributeSelectBackgroundPanel.BackgroundPanel(const aCtx: TtfwContext; aefTreeAttributeSelect: TefTreeAttributeSelect): TvtPanel; {* Реализация слова скрипта .TefTreeAttributeSelect.BackgroundPanel } begin Result := aefTreeAttributeSelect.BackgroundPanel; end;//TkwEfTreeAttributeSelectBackgroundPanel.BackgroundPanel class function TkwEfTreeAttributeSelectBackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := '.TefTreeAttributeSelect.BackgroundPanel'; end;//TkwEfTreeAttributeSelectBackgroundPanel.GetWordNameForRegister function TkwEfTreeAttributeSelectBackgroundPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwEfTreeAttributeSelectBackgroundPanel.GetResultTypeInfo function TkwEfTreeAttributeSelectBackgroundPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEfTreeAttributeSelectBackgroundPanel.GetAllParamsCount function TkwEfTreeAttributeSelectBackgroundPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TefTreeAttributeSelect)]); end;//TkwEfTreeAttributeSelectBackgroundPanel.ParamsTypes procedure TkwEfTreeAttributeSelectBackgroundPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству BackgroundPanel', aCtx); end;//TkwEfTreeAttributeSelectBackgroundPanel.SetValuePrim procedure TkwEfTreeAttributeSelectBackgroundPanel.DoDoIt(const aCtx: TtfwContext); var l_aefTreeAttributeSelect: TefTreeAttributeSelect; begin try l_aefTreeAttributeSelect := TefTreeAttributeSelect(aCtx.rEngine.PopObjAs(TefTreeAttributeSelect)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aefTreeAttributeSelect: TefTreeAttributeSelect : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(BackgroundPanel(aCtx, l_aefTreeAttributeSelect)); end;//TkwEfTreeAttributeSelectBackgroundPanel.DoDoIt function TkwEfTreeAttributeSelectContextFilter.ContextFilter(const aCtx: TtfwContext; aefTreeAttributeSelect: TefTreeAttributeSelect): TnscContextFilter; {* Реализация слова скрипта .TefTreeAttributeSelect.ContextFilter } begin Result := aefTreeAttributeSelect.ContextFilter; end;//TkwEfTreeAttributeSelectContextFilter.ContextFilter class function TkwEfTreeAttributeSelectContextFilter.GetWordNameForRegister: AnsiString; begin Result := '.TefTreeAttributeSelect.ContextFilter'; end;//TkwEfTreeAttributeSelectContextFilter.GetWordNameForRegister function TkwEfTreeAttributeSelectContextFilter.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscContextFilter); end;//TkwEfTreeAttributeSelectContextFilter.GetResultTypeInfo function TkwEfTreeAttributeSelectContextFilter.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEfTreeAttributeSelectContextFilter.GetAllParamsCount function TkwEfTreeAttributeSelectContextFilter.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TefTreeAttributeSelect)]); end;//TkwEfTreeAttributeSelectContextFilter.ParamsTypes procedure TkwEfTreeAttributeSelectContextFilter.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ContextFilter', aCtx); end;//TkwEfTreeAttributeSelectContextFilter.SetValuePrim procedure TkwEfTreeAttributeSelectContextFilter.DoDoIt(const aCtx: TtfwContext); var l_aefTreeAttributeSelect: TefTreeAttributeSelect; begin try l_aefTreeAttributeSelect := TefTreeAttributeSelect(aCtx.rEngine.PopObjAs(TefTreeAttributeSelect)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aefTreeAttributeSelect: TefTreeAttributeSelect : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ContextFilter(aCtx, l_aefTreeAttributeSelect)); end;//TkwEfTreeAttributeSelectContextFilter.DoDoIt function TkwEfTreeAttributeSelectAttributeTree.AttributeTree(const aCtx: TtfwContext; aefTreeAttributeSelect: TefTreeAttributeSelect): TnscTreeViewHotTruck; {* Реализация слова скрипта .TefTreeAttributeSelect.AttributeTree } begin Result := aefTreeAttributeSelect.AttributeTree; end;//TkwEfTreeAttributeSelectAttributeTree.AttributeTree class function TkwEfTreeAttributeSelectAttributeTree.GetWordNameForRegister: AnsiString; begin Result := '.TefTreeAttributeSelect.AttributeTree'; end;//TkwEfTreeAttributeSelectAttributeTree.GetWordNameForRegister function TkwEfTreeAttributeSelectAttributeTree.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscTreeViewHotTruck); end;//TkwEfTreeAttributeSelectAttributeTree.GetResultTypeInfo function TkwEfTreeAttributeSelectAttributeTree.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEfTreeAttributeSelectAttributeTree.GetAllParamsCount function TkwEfTreeAttributeSelectAttributeTree.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TefTreeAttributeSelect)]); end;//TkwEfTreeAttributeSelectAttributeTree.ParamsTypes procedure TkwEfTreeAttributeSelectAttributeTree.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству AttributeTree', aCtx); end;//TkwEfTreeAttributeSelectAttributeTree.SetValuePrim procedure TkwEfTreeAttributeSelectAttributeTree.DoDoIt(const aCtx: TtfwContext); var l_aefTreeAttributeSelect: TefTreeAttributeSelect; begin try l_aefTreeAttributeSelect := TefTreeAttributeSelect(aCtx.rEngine.PopObjAs(TefTreeAttributeSelect)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aefTreeAttributeSelect: TefTreeAttributeSelect : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(AttributeTree(aCtx, l_aefTreeAttributeSelect)); end;//TkwEfTreeAttributeSelectAttributeTree.DoDoIt initialization Tkw_Form_TreeAttributeSelect.RegisterInEngine; {* Регистрация Tkw_Form_TreeAttributeSelect } Tkw_TreeAttributeSelect_Control_BackgroundPanel.RegisterInEngine; {* Регистрация Tkw_TreeAttributeSelect_Control_BackgroundPanel } Tkw_TreeAttributeSelect_Control_BackgroundPanel_Push.RegisterInEngine; {* Регистрация Tkw_TreeAttributeSelect_Control_BackgroundPanel_Push } Tkw_TreeAttributeSelect_Control_ContextFilter.RegisterInEngine; {* Регистрация Tkw_TreeAttributeSelect_Control_ContextFilter } Tkw_TreeAttributeSelect_Control_ContextFilter_Push.RegisterInEngine; {* Регистрация Tkw_TreeAttributeSelect_Control_ContextFilter_Push } Tkw_TreeAttributeSelect_Control_AttributeTree.RegisterInEngine; {* Регистрация Tkw_TreeAttributeSelect_Control_AttributeTree } Tkw_TreeAttributeSelect_Control_AttributeTree_Push.RegisterInEngine; {* Регистрация Tkw_TreeAttributeSelect_Control_AttributeTree_Push } TkwEfTreeAttributeSelectBackgroundPanel.RegisterInEngine; {* Регистрация efTreeAttributeSelect_BackgroundPanel } TkwEfTreeAttributeSelectContextFilter.RegisterInEngine; {* Регистрация efTreeAttributeSelect_ContextFilter } TkwEfTreeAttributeSelectAttributeTree.RegisterInEngine; {* Регистрация efTreeAttributeSelect_AttributeTree } TtfwTypeRegistrator.RegisterType(TypeInfo(TefTreeAttributeSelect)); {* Регистрация типа TefTreeAttributeSelect } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel)); {* Регистрация типа TvtPanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TnscContextFilter)); {* Регистрация типа TnscContextFilter } TtfwTypeRegistrator.RegisterType(TypeInfo(TnscTreeViewHotTruck)); {* Регистрация типа TnscTreeViewHotTruck } {$IfEnd} // NOT Defined(NoScripts) end.
unit MVCBr.VCL.PageView; interface uses VCL.Forms, VCL.Controls, System.Classes, System.SysUtils, MVCBr.Interf, MVCBr.PageView, MVCBr.FormView, VCL.ComCtrls; type TVCLpageViewOnQueryClose = procedure(APageView: IPageView; var ACanClose: boolean) of object; TVCLPageViewManager = class(TCustomPageViewFactory, IPageViews) private FOldPageChange: TNotifyEvent; FOnQueryClose: TVCLpageViewOnQueryClose; FAfterTabCreate: TNotifyEvent; FAfterCreateComplete: TNotifyEvent; procedure Init(APageView: IPageView); override; procedure SetPageControlEx(const Value: TPageControl); function GetPageControlEx: TPageControl; procedure SetOnQueryClose(const Value: TVCLpageViewOnQueryClose); procedure SetAfterTabCreate(const Value: TNotifyEvent); procedure SetAfterCreateComplete(const Value: TNotifyEvent); procedure DoPageChange(Sender: TObject); procedure DoFormCloseQuery(Sender: TObject; var canClose: boolean); function TabsheetIndexOf(tab: TObject): integer; protected Procedure DoQueryClose(const APageView: IPageView; var ACanClose: boolean); override; procedure SetActivePage(Const tab: TObject); override; procedure Notification(AComponent: TComponent; AOperation: TOperation); override; public class function New(AController: IController): IPageViews; function Update: IModel; virtual; function GetPageTabClass: TComponentClass; override; function GetPageContainerClass: TComponentClass; override; function NewTab(APageView: IPageView): TObject; override; function AddView(AView: IView): IPageView; override; function AddView(Const AController: TGuid): IPageView; overload; override; published property PageControl: TPageControl read GetPageControlEx write SetPageControlEx; property AfterViewCreate; property AfterCreateComplete: TNotifyEvent read FAfterCreateComplete write SetAfterCreateComplete; property AfterTabCreate: TNotifyEvent read FAfterTabCreate write SetAfterTabCreate; property OnQueryClose: TVCLpageViewOnQueryClose read FOnQueryClose write SetOnQueryClose; end; procedure register; implementation uses MVCBr.Controller; procedure register; begin RegisterComponents('MVCBr', [TVCLPageViewManager]); end; { TVCLPageViewFactory } function TVCLPageViewManager.AddView(AView: IView): IPageView; begin result := inherited AddView(AView); end; function TVCLPageViewManager.AddView(const AController: TGuid): IPageView; begin result := inherited AddView(AController); end; procedure TVCLPageViewManager.DoQueryClose(const APageView: IPageView; var ACanClose: boolean); begin inherited; if assigned(FOnQueryClose) then FOnQueryClose(APageView, ACanClose); end; procedure TVCLPageViewManager.DoFormCloseQuery(Sender: TObject; var canClose: boolean); var LPageView: IPageView; i: integer; tab: TObject; pgIndex: integer; begin LPageView := FindViewByClassName(Sender.ClassName); if not assigned(LPageView) then exit; DoQueryClose(LPageView, canClose); if not canClose then abort; pgIndex := PageViewIndexOf(LPageView); if (pgIndex >= 0) and assigned(LPageView) then begin i := TabsheetIndexOf(LPageView.This.tab); if (i >= 0) and (pgIndex >= 0) then begin TForm(LPageView.This.View.This).OnCloseQuery := nil; LPageView.This.tab.Free; end; end; end; procedure TVCLPageViewManager.DoPageChange(Sender: TObject); begin if assigned(FOldPageChange) then FOldPageChange(Sender); ActivePageIndex := TPageControl(FPageContainer).ActivePageIndex; end; function TVCLPageViewManager.GetPageContainerClass: TComponentClass; begin result := TPageControl; end; function TVCLPageViewManager.GetPageControlEx: TPageControl; begin result := TPageControl(FPageContainer); end; type TTabSheetView = class(TTabsheet) public PageView: IPageView; destructor destroy; override; procedure canClose(var ACanClose: boolean); end; procedure TTabSheetView.canClose(var ACanClose: boolean); var form: TForm; ref: TVCLPageViewManager; begin // chamado quando a tabsheet é apagada. ref := TVCLPageViewManager(PageView.This.GetOwner); if assigned(ref) and assigned(ref.OnQueryClose) then TVCLPageViewManager(ref).OnQueryClose(PageView, ACanClose); if ACanClose then if assigned(PageView) then if assigned(PageView.This.View) then begin form := TForm(PageView.This.View.This); if assigned(form) then if assigned(form.OnCloseQuery) then form.OnCloseQuery(self, ACanClose); if ACanClose then begin TControllerFactory.RevokeInstance(PageView.This.View.GetController); // apaga a instancia da lista de controller instaciados. end; end; end; destructor TTabSheetView.destroy; var LCanClose: boolean; begin LCanClose := true; canClose(LCanClose); if not LCanClose then abort; if assigned(PageView) then begin TForm(PageView.This.View.This).OnCloseQuery := nil; PageView.remove; PageView := nil; end; inherited destroy; end; function TVCLPageViewManager.GetPageTabClass: TComponentClass; begin result := TTabSheetView; end; procedure TVCLPageViewManager.Init(APageView: IPageView); var frm: TForm; begin if assigned(APageView) then if assigned(APageView.This.View) then begin if APageView.This.View.This.InheritsFrom(TViewFactoryAdapter) then begin frm := TForm(TViewFactoryAdapter(APageView.This.View.This).form); APageView.This.text := frm.Caption; end else frm := TForm(APageView.This.View.This); with frm do begin parent := TTabsheet(APageView.This.tab); Align := alClient; BorderStyle := bsNone; TTabsheet(APageView.This.tab).Caption := APageView.This.text; if APageView.This.View.This.InheritsFrom(TFormFactory) then begin with TFormFactory(APageView.This.View.This) do begin OnCloseQuery := DoFormCloseQuery; isShowModal := false; end; APageView.This.View.ShowView(nil); APageView.This.View.Init; show; end else show; if assigned(FAfterCreateComplete) then FAfterCreateComplete(APageView.This); end; end; end; class function TVCLPageViewManager.New(AController: IController): IPageViews; begin result := TVCLPageViewManager.Create(nil); result.Controller(AController); end; function TVCLPageViewManager.NewTab(APageView: IPageView): TObject; var tab: TTabSheetView; begin tab := GetPageTabClass.Create(FPageContainer) as TTabSheetView; tab.PageControl := TPageControl(FPageContainer); tab.PageView := APageView; TPageControl(FPageContainer).ActivePage := tab; result := tab; if assigned(FAfterTabCreate) then FAfterTabCreate(tab); end; procedure TVCLPageViewManager.Notification(AComponent: TComponent; AOperation: TOperation); begin inherited; end; procedure TVCLPageViewManager.SetActivePage(const tab: TObject); begin inherited; TPageControl(FPageContainer).ActivePage := TTabsheet(tab); end; procedure TVCLPageViewManager.SetAfterCreateComplete(const Value: TNotifyEvent); begin FAfterCreateComplete := Value; end; procedure TVCLPageViewManager.SetAfterTabCreate(const Value: TNotifyEvent); begin FAfterTabCreate := Value; end; procedure TVCLPageViewManager.SetOnQueryClose(const Value : TVCLpageViewOnQueryClose); begin FOnQueryClose := Value; end; procedure TVCLPageViewManager.SetPageControlEx(const Value: TPageControl); begin if assigned(Value) then begin FOldPageChange := Value.OnChange; Value.OnChange := DoPageChange; end else begin FOldPageChange := nil; end; FPageContainer := Value; end; function TVCLPageViewManager.TabsheetIndexOf(tab: TObject): integer; var i: integer; begin result := -1; with TPageControl(FPageContainer) do for i := 0 to PageCount - 1 do if Pages[i].Equals(tab) then begin result := i; exit; end; end; function TVCLPageViewManager.Update: IModel; var APageView: IPageView; begin ActivePageIndex := TPageControl(FPageContainer).ActivePageIndex; APageView := ActivePage; Init(APageView); end; end.
unit UDemo; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.TMSBaseControl, FMX.TMSPlannerBase, FMX.TMSPlannerData, FMX.TMSPlanner, FMX.TMSBitmapContainer, FMX.ListBox; type TForm1 = class(TForm) TMSFMXPlanner1: TTMSFMXPlanner; TMSFMXBitmapContainer1: TTMSFMXBitmapContainer; Panel1: TPanel; ComboBox1: TComboBox; Label1: TLabel; procedure FormCreate(Sender: TObject); procedure TMSFMXPlanner1AfterDrawPositionEmptySpace(Sender: TObject; ACanvas: TCanvas; ARect: TRectF; ASpace: TTMSFMXPlannerPositionEmptySpace); procedure TMSFMXPlanner1GetTimeText(Sender: TObject; AValue: Double; ARow: Integer; ASubUnit: Boolean; AKind: TTMSFMXPlannerCacheItemKind; var AText: string); procedure ComboBox1Change(Sender: TObject); private { Private declarations } public { Public declarations } procedure ChangeMode; end; var Form1: TForm1; implementation {$R *.fmx} uses UIConsts, DateUtils; procedure TForm1.ChangeMode; var I: Integer; it: TTMSFMXPlannerItem; begin TMSFMXPlanner1.BeginUpdate; TMSFMXPlanner1.CustomDateTimes.Clear; case ComboBox1.ItemIndex of 0: begin for I := 0 to 15 do TMSFMXPlanner1.CustomDateTimes.Add(I); TMSFMXPlanner1.TimeLineAppearance.Stretch := True; TMSFMXPlanner1.ItemsAppearance.TextHorizontalTextAlign := ptaTrailing; TMSFMXPlanner1.Positions.Count := 3; end; 1: begin for I := 0 to 44 do TMSFMXPlanner1.CustomDateTimes.Add(I); TMSFMXPlanner1.TimeLineAppearance.Stretch := False; TMSFMXPlanner1.ItemsAppearance.TextHorizontalTextAlign := ptaLeading; TMSFMXPlanner1.Positions.Count := 4; end; end; TMSFMXPlanner1.EndUpdate; TMSFMXPlanner1.BeginUpdate; TMSFMXPlanner1.Items.Clear; case ComboBox1.ItemIndex of 0: begin TMSFMXPlanner1.AddOrUpdateItem(0, 12.5, '', '<img height="35" src="Ariel"/> Ariel 12.5 seconds').Resource := 0; TMSFMXPlanner1.AddOrUpdateItem(0, 10, '', '<img height="35" src="Pepsi"/> Pepsi 10 seconds').Resource := 0; TMSFMXPlanner1.AddOrUpdateItem(0, 8, '', '<img height="35" src="Coca Cola"/> Coca Cola 8 seconds').Resource := 0; TMSFMXPlanner1.AddOrUpdateItem(0, 12, '', '<img height="35" src="Jack Wolfskin"/> Jack Wolfskin 12 seconds').Resource := 0; TMSFMXPlanner1.AddOrUpdateItem(0, 10, '', '<img height="35" src="Ariel"/> Ariel 10 seconds').Resource := 1; TMSFMXPlanner1.AddOrUpdateItem(0, 12.5, '', '<img height="35" src="Pepsi"/> Pepsi 12.5 seconds').Resource := 1; TMSFMXPlanner1.AddOrUpdateItem(0, 7, '', '<img height="35" src="Coca Cola"/> Coca Cola 7 seconds').Resource := 1; TMSFMXPlanner1.AddOrUpdateItem(0, 6, '', '<img height="35" src="Burger King"/> Burger King 6 seconds').Resource := 1; TMSFMXPlanner1.AddOrUpdateItem(0, 6.5, '', '<img height="35" src="Ariel"/> Ariel 6.5 seconds').Resource := 2; TMSFMXPlanner1.AddOrUpdateItem(0, 10, '', '<img height="35" src="Burger King"/> Burger King 10 seconds').Resource := 2; TMSFMXPlanner1.AddOrUpdateItem(0, 8, '', '<img height="35" src="Coca Cola"/> Coca Cola 8 seconds').Resource := 2; TMSFMXPlanner1.AddOrUpdateItem(0, 12, '', '<img height="35" src="Jack Wolfskin"/> Jack Wolfskin 12 seconds').Resource := 2; TMSFMXPlanner1.AddOrUpdateItem(0, 10.5, '', '<img height="35" src="Jack Wolfskin"/> Jack Wolfskin 10.5 seconds').Resource := 3; TMSFMXPlanner1.AddOrUpdateItem(0, 10, '', '<img height="35" src="Burger King"/> Burger King 10 seconds').Resource := 3; TMSFMXPlanner1.AddOrUpdateItem(0, 8, '', '<img height="35" src="Ariel"/> Ariel 8 seconds').Resource := 3; TMSFMXPlanner1.AddOrUpdateItem(0, 8, '', '<img height="35" src="Coca Cola"/> Coca Cola 8 seconds').Resource := 3; end; 1: begin it := TMSFMXPlanner1.AddOrUpdateItem(0, 12.5, '', '<img height="80" src="Ariel"/> Ariel 12.5 seconds'); it.Resource := 0; it := TMSFMXPlanner1.AddOrUpdateItem(it.EndTime, it.EndTime + 9.5, '', '<img height="80" src="Pepsi"/> Pepsi 9.5 seconds'); it.Resource := 0; it := TMSFMXPlanner1.AddOrUpdateItem(it.EndTime, it.EndTime + 7, '', '<img height="80" src="Coca Cola"/> Coca Cola 7 seconds'); it.Resource := 0; it := TMSFMXPlanner1.AddOrUpdateItem(it.EndTime, it.EndTime + 12, '', '<img height="80" src="Jack Wolfskin"/> Jack Wolfskin 12 seconds'); it.Resource := 0; it := TMSFMXPlanner1.AddOrUpdateItem(0, 10, '', '<img height="80" src="Pepsi"/> Pepsi 10 seconds'); it.Resource := 1; it := TMSFMXPlanner1.AddOrUpdateItem(it.EndTime, it.EndTime + 12, '', '<img height="80" src="Jack Wolfskin"/> Jack Wolfskin 12 seconds'); it.Resource := 1; it := TMSFMXPlanner1.AddOrUpdateItem(it.EndTime, it.EndTime + 7, '', '<img height="80" src="Coca Cola"/> Coca Cola 7 seconds'); it.Resource := 1; it := TMSFMXPlanner1.AddOrUpdateItem(it.EndTime, it.EndTime + 6, '', '<img height="80" src="Burger King"/> Burger King 6 seconds'); it.Resource := 1; it := TMSFMXPlanner1.AddOrUpdateItem(0, 6.5, '', '<img height="80" src="Burger King"/> Burger King 6.5 seconds'); it.Resource := 2; it := TMSFMXPlanner1.AddOrUpdateItem(it.EndTime, it.EndTime + 11.5, '', '<img height="80" src="Coca Cola"/> Coca Cola 11.5 seconds'); it.Resource := 2; it := TMSFMXPlanner1.AddOrUpdateItem(it.EndTime, it.EndTime + 8, '', '<img height="80" src="Ariel"/> Ariel 8 seconds'); it.Resource := 2; it := TMSFMXPlanner1.AddOrUpdateItem(it.EndTime, it.EndTime + 12, '', '<img height="80" src="Jack Wolfskin"/> Jack Wolfskin 12 seconds'); it.Resource := 2; it := TMSFMXPlanner1.AddOrUpdateItem(0, 8, '', '<img height="80" src="Coca Cola"/> Coca Cola 8 seconds'); it.Resource := 3; it := TMSFMXPlanner1.AddOrUpdateItem(it.EndTime, it.EndTime + 10, '', '<img height="80" src="Jack Wolfskin"/> Jack Wolfskin 10 seconds'); it.Resource := 3; it := TMSFMXPlanner1.AddOrUpdateItem(it.EndTime, it.EndTime + 8.5, '', '<img height="80" src="Ariel"/> Ariel 8.5 seconds'); it.Resource := 3; it := TMSFMXPlanner1.AddOrUpdateItem(it.EndTime, it.EndTime + 11.5, '', '<img height="80" src="Burger King"/> Burger King 11.5 seconds'); it.Resource := 3; end; end; TMSFMXPlanner1.EndUpdate; end; procedure TForm1.ComboBox1Change(Sender: TObject); begin ChangeMode; end; procedure TForm1.FormCreate(Sender: TObject); var res: TTMSFMXPlannerResource; begin TMSFMXPlanner1.BeginUpdate; TMSFMXPlanner1.Fill.Color := claLightslategray; TMSFMXPlanner1.Stroke.Color := claGhostWhite; TMSFMXPlanner1.TimeLineAppearance.LeftFontColor := claGhostwhite; TMSFMXPlanner1.GridCellAppearance.VerticalStroke.Color := claGhostwhite; TMSFMXPlanner1.GridCellAppearance.HorizontalStroke.Color := claGhostwhite; TMSFMXPlanner1.PositionsAppearance.TopStroke.Color := claGhostwhite; TMSFMXPlanner1.GroupsAppearance.TopStroke.Color := claGhostwhite; TMSFMXPlanner1.TimeLineAppearance.LeftStroke.Color := claGhostwhite; TMSFMXPlanner1.GroupsAppearance.BottomStroke.Color := claGhostwhite; TMSFMXPlanner1.TimeLineAppearance.RightStroke.Color := claGhostwhite; TMSFMXPlanner1.ItemsAppearance.TextVerticalTextAlign := ptaCenter; TMSFMXPlanner1.ModeSettings.InActiveDays := []; TMSFMXPlanner1.Mode := pmCustom; TMSFMXPlanner1.TimeLineAppearance.LeftSize := 50; TMSFMXPlanner1.TimeLineAppearance.LeftHorizontalTextAlign := ptaTrailing; TMSFMXPlanner1.TimeLine.DisplayUnitSize := 50; TMSFMXPlanner1.OrientationMode := pomHorizontal; TMSFMXPlanner1.BitmapContainer := TMSFMXBitmapContainer1; TMSFMXPlanner1.PositionsAppearance.TopVerticalTextMode := pvtmNone; TMSFMXPlanner1.PositionsAppearance.TopSize := 150; TMSFMXPlanner1.Resources.Clear; res := TMSFMXPlanner1.Resources.Add; res.Name := 'National Geographic'; res.Text := '<img width="140" src="'+res.Name+'"/>'; res := TMSFMXPlanner1.Resources.Add; res.Name := 'BBC'; res.Text := '<img width="140"src="'+res.Name+'"/>'; res := TMSFMXPlanner1.Resources.Add; res.Name := 'Discovery Channel'; res.Text := '<img width="140" src="'+res.Name+'"/>'; res := TMSFMXPlanner1.Resources.Add; res.Name := 'Nickelodeon'; res.Text := '<img width="140" src="'+res.Name+'"/>'; TMSFMXPlanner1.Interaction.ShowSelection := False; TMSFMXPlanner1.Interaction.ReadOnly := True; TMSFMXPlanner1.ItemsAppearance.ShowItemHelpers := False; TMSFMXPlanner1.SelectItem(nil); TMSFMXPlanner1.EndUpdate; ChangeMode; end; procedure TForm1.TMSFMXPlanner1AfterDrawPositionEmptySpace(Sender: TObject; ACanvas: TCanvas; ARect: TRectF; ASpace: TTMSFMXPlannerPositionEmptySpace); begin if ASpace = ppesTopLeft then begin ACanvas.Fill.Color := claWhite; ACanvas.Font.Size := 16; ACanvas.FillText(ARect, 'Commercials per channel (sec)', True, 1, [], TTextAlign.taCenter); end; end; procedure TForm1.TMSFMXPlanner1GetTimeText(Sender: TObject; AValue: Double; ARow: Integer; ASubUnit: Boolean; AKind: TTMSFMXPlannerCacheItemKind; var AText: string); begin AText := FloatToStr(AValue); end; end.
unit Map; interface uses Generics.Collections; const test1: string = 'XX .. .. .. .. .. XX' + #13#10 + '.. 39 45 15 .. .. 34' + #13#10 + '.. 44 10 14 17 .. 32' + #13#10 + '.. .. .. 12 .. 19 ..' + #13#10 + '.. 04 01 .. .. .. ..' + #13#10 + '05 .. .. 28 .. 22 ..' + #13#10 + 'XX .. .. 26 24 .. XX'; test2: string = '.. .. 08 .. .. .. .. 49' + #13#10 + '.. 01 06 09 44 45 .. ..' + #13#10 + '.. .. .. .. 42 51 .. ..' + #13#10 + '.. .. 12 XX XX .. 39 ..' + #13#10 + '.. 15 13 XX XX .. .. 38' + #13#10 + '.. 19 27 28 .. .. .. ..' + #13#10 + '21 .. 25 .. 29 34 59 ..' + #13#10 + '.. .. .. .. .. .. .. 60'; test3: string = 'XX 64 XX 61 XX .. XX .. XX' + #13#10 + '65 .. .. .. .. .. 50 49 ..' + #13#10 + 'XX .. 11 .. .. 52 .. .. XX' + #13#10 + '.. 08 .. 12 53 .. .. .. 45' + #13#10 + 'XX 07 16 .. 24 .. .. 43 XX' + #13#10 + '05 .. .. .. 25 32 .. .. ..' + #13#10 + 'XX .. .. 22 .. 30 .. .. XX' + #13#10 + '01 .. 19 .. .. 29 37 34 ..' + #13#10 + 'XX .. XX .. XX .. XX .. XX'; test4: string = '26 .. 30 32 .. .. .. 39 .. ..' + #13#10 + '.. 28 .. .. 34 35 37 .. 40 ..' + #13#10 + '.. 22 XX XX XX XX XX XX .. 45' + #13#10 + '21 .. XX 78 .. .. .. XX 47 ..' + #13#10 + '20 19 XX .. 76 .. 73 XX 51 ..' + #13#10 + '.. 17 XX .. .. 68 .. XX .. 52' + #13#10 + '.. 14 XX .. 82 71 .. XX 55 ..' + #13#10 + '.. 13 XX XX 01 66 XX XX .. 54' + #13#10 + '.. 10 .. .. 04 .. .. .. 58 ..' + #13#10 + '.. 09 07 05 .. .. .. .. .. 60'; test5: string = '-2 -2 15 00 00 00 00 45' + #13#10 + '-2 -2 00 19 17 42 41 00' + #13#10 + '00 00 -2 -2 00 00 00 00' + #13#10 + '00 12 -2 -2 00 48 00 00' + #13#10 + '00 00 24 00 -2 -2 00 34' + #13#10 + '08 00 26 00 -2 -2 00 00' + #13#10 + '05 07 01 00 28 00 -2 -2' + #13#10 + '00 00 00 00 00 31 -2 -2'; test6: string = '-2 -2 31 00 33 34 00 00 07 -2' + #13#10 + '00 28 00 00 00 03 00 00 06 -2' + #13#10 + '00 00 37 00 20 18 01 15 09 00' + #13#10 + '00 00 00 00 00 00 00 00 00 00' + #13#10 + '00 00 22 00 40 00 00 44 13 00' + #13#10 + '87 86 90 92 00 53 42 00 00 47' + #13#10 + '00 83 00 00 00 00 00 50 00 68' + #13#10 + '82 00 56 58 61 00 00 49 00 00' + #13#10 + '-2 00 00 77 00 00 00 00 00 00' + #13#10 + '-2 79 78 00 75 73 71 00 -2 -2'; type TPointPos = class X, Y, V : Integer; constructor Create(AV, AX, AY : Integer); function Clone: TPointPos; end; TPointPosList = TObjectList<TPointPos>; TJumpState = (jsSolved, jsOneSol, jsPartial, jsNoSol); TJump = class private public Steps: TObjectList<TPointPosList>; PartList: TPointPosList; ForceUse: TPointPosList; PointLow: TPointPos; PointHigh: TPointPos; Solved: Boolean; constructor Create(P1, P2: TPointPos); destructor Destroy; override; procedure PrepareSolve; function NrSteps: Integer; function GetState: TJumpState; end; type TMap = class private FWidth: Integer; FHeight: Integer; procedure SetHeight(const Value: Integer); procedure SetWidth(const Value: Integer); procedure SolveJump(Index: Integer); function SolveJumpPart(const Jump: TJump; const StartPoint: TPointPos; const StepIndex, DepthLeft: Integer): Boolean; function AllSolved: Boolean; public StartMap: array of array of Integer; WorkMap: array of array of Integer; CoverageMap: array of array of Integer; JumpList: TObjectlist<TJump>; constructor Create(const Width, Height: Integer); destructor Destroy; override; procedure BuildJumps; procedure CreateWorkMap; procedure CheckCoverage; procedure SolveJumps(ExcludeJump: TJump = nil); procedure SolveAndFixJumps; procedure Solve(Jump: TJump); function TrySolve: boolean; class function FromString(const s: string): TMap; class function FromFile(const Filename: string): TMap; property Width: Integer read FWidth write SetWidth; property Height: Integer read FHeight write SetHeight; end; implementation uses Math, Classes, SysUtils, IntegerList; procedure TMap.CheckCoverage; var i, j, jmp: Integer; Jump: TJump; CheckValue: Integer; begin SetLength(CoverageMap, FWidth, FHeight); for i := 0 to FWidth - 1 do begin for j := 0 to FHeight - 1 do begin CoverageMap[i,j] := 0; end; end; // fillmap for jmp := 0 to JumpList.Count - 1 do begin Jump := JumpList[jmp]; if Jump.Solved then CONTINUE; CheckValue := Jump.PointLow.V; for i := 0 to Jump.NrSteps - 1 do begin for j := 0 to Jump.Steps[i].Count - 1 do begin if CoverageMap[jump.Steps[i][j].X, jump.Steps[i][j].Y] = 0 then CoverageMap[jump.Steps[i][j].X, jump.Steps[i][j].Y] := CheckValue else if CoverageMap[jump.Steps[i][j].X, jump.Steps[i][j].Y] <> CheckValue then CoverageMap[jump.Steps[i][j].X, jump.Steps[i][j].Y] := -1; end; end; end; for jmp := 0 to JumpList.Count - 1 do begin Jump := JumpList[jmp]; if Jump.Solved then CONTINUE; CheckValue := Jump.PointLow.V; Jump.ForceUse.Clear; for i := 0 to FWidth - 1 do begin for j := 0 to FHeight - 1 do begin if CoverageMap[i,j] = CheckValue then begin Jump.ForceUse.Add(TPointPos.Create(0,i,j)); end; end; end; end; end; constructor TMap.Create(const Width, Height: Integer); begin inherited Create; FWidth := Width; FHeight := Height; SetLength(StartMap, FWidth, FHeight); SetLength(CoverageMap, FWidth, FHeight); end; procedure TMap.CreateWorkMap; var i, j: Integer; begin SetLength(WorkMap, FWidth, FHeight); for i := 0 to FWidth - 1 do begin for j := 0 to FHeight - 1 do begin WorkMap[i,j] := StartMap[i,j]; end; end; end; destructor TMap.Destroy; begin JumpList.Free; inherited; end; class function TMap.FromFile(const Filename: string): TMap; var i: integer; sl: TStringlist; s: string; descr: string; Correctfile: Boolean; begin Correctfile := False; sl := TStringList.Create; sl.LoadFromFile(Filename); if Sl.Count > 10 then begin Descr := trim(sl[5]); s := ''; for i := 7 to sl.Count - 1 do begin if pos('========= www.Hidato.com ===========', sl[i]) > 0 then begin Correctfile := True; BREAK; end; if s ='' then s := trim(sl[i]) else s := s + #13#10 + trim(sl[i]); end; end; if Correctfile then Result := FromString(s) else REsult := nil; sl.Free; end; class function TMap.FromString(const s: string): TMap; var i, j: Integer; slRows, slRow: TStringlist; begin slRows := TStringList.Create; slRow := TStringList.Create; slRows.Text := s; slRow.Delimiter := ' '; slRow.DelimitedText := slRows[0]; Result := TMap.Create(slRows.Count, slRow.Count); for i := 0 to slRows.Count - 1 do begin slRow.DelimitedText := slRows[i]; for j := 0 to slRow.Count - 1 do begin if slRow[j][1] = 'X' then Result.StartMap[j,i] := -1 else if slRow[j][1] = '.' then Result.StartMap[j,i] := 0 else Result.StartMap[j,i] := StrToIntDef(slRow[j], 0); end; end; slRow.Free; slRows.Free; end; function TMap.AllSolved: Boolean; var i: integer; begin Result := True; for i := 0 to JumpList.Count - 1 do begin Result := Result and JumpList[i].Solved; end; end; procedure TMap.BuildJumps; var i, j: Integer; Points: TIntegerList; begin Points := TIntegerList.Create; for i := 0 to FWidth - 1 do begin for j := 0 to FHeight - 1 do begin if StartMap[j,i] > 0 then Points.AddObject(StartMap[j,i], TPointPos.Create(StartMap[j,i], j, i)); end; end; Points.Sort; JumpList := TObjectlist<TJump>.Create; for i := 0 to Points.Count - 2 do begin if Points[i+1] - Points[i] > 1 then begin JumpList.Add(TJump.Create(TPointPos(Points.Objects[i]).Clone, TPointPos(Points.Objects[i+1]).Clone)); end; end; for i := 0 to Points.Count - 1 do TPointPos(Points.Objects[i]).Free; Points.Free; end; procedure TMap.SetHeight(const Value: Integer); begin FHeight := Value; end; procedure TMap.SetWidth(const Value: Integer); begin FWidth := Value; end; procedure TMap.Solve(Jump: TJump); var i: integer; begin if Jump.Solved then Exit; case Jump.GetState of jsOneSol: begin Jump.Solved := True; for i := 0 to Jump.NrSteps - 2 do begin WorkMap[Jump.Steps[i][0].X, Jump.Steps[i][0].Y] := Jump.PointLow.V + i + 1; end; Jump.Solved := True; end; jsPartial: begin for i := 0 to Jump.NrSteps - 2 do begin if Jump.Steps[i].Count = 1 then begin WorkMap[Jump.Steps[i][0].X, Jump.Steps[i][0].Y] := Jump.PointLow.V + i + 1; Jump.PartList.Add(Jump.Steps[i][0].Clone); end; end; end; end; end; procedure TMap.SolveAndFixJumps; var i: integer; begin for i := 0 to JumpList.Count - 1 do begin if JumpList[i].Solved then CONTINUE; SolveJump(i); Solve(JumpList[i]); end; end; function TMap.TrySolve: boolean; const MAXTRIES = 10; var i: integer; begin BuildJumps; CreateWorkMap; Result := False; for i := 0 to MAXTRIES do begin SolveAndFixJumps; CheckCoverage; if AllSolved then begin Result := True; BREAK; end; end; end; procedure TMap.SolveJump(Index: Integer); var Jump: TJump; i: Integer; begin Jump := JumpList[Index]; if jump.Solved then EXIT; Jump.PrepareSolve; for i := 0 to Jump.PartList.Count - 1 do begin WorkMap[Jump.PartList[i].X, Jump.PartList[i].Y] := 0; end; Jump.PartList.Clear; SolveJumpPart(Jump, Jump.PointLow, 0, Jump.NrSteps -1) end; function TMap.SolveJumpPart(const Jump: TJump; const StartPoint: TPointPos; const StepIndex, DepthLeft: Integer): Boolean; var i, x, y: integer; Nx,Ny: integer; NewPoint: TPointPos; CanStore: Boolean; begin Result := False; for x := -1 to 1 do begin for y := -1 to 1 do begin Nx := StartPoint.X + X; Ny := StartPoint.Y + Y; if Nx < 0 then CONTINUE; if Ny < 0 then CONTINUE; if Nx >= width then CONTINUE; if Ny >= Height then CONTINUE; if WorkMap[Nx,Ny] <> 0 then CONTINUE; if Max(Abs(Nx - Jump.PointHigh.X), Abs(Ny - Jump.PointHigh.Y)) > DepthLeft then CONTINUE; WorkMap[Nx,Ny] := 1; NewPoint := TPointPos.Create(0,Nx,Ny); if DepthLeft = 1 then begin CanStore := True; for i := 0 to Jump.ForceUse.Count - 1 do begin if WorkMap[Jump.ForceUse[i].x, Jump.ForceUse[i].y] = 0 then begin CanStore := False; BREAK end; end; end else begin CanStore := SolveJumpPart(Jump, NewPoint, StepIndex + 1, DepthLeft - 1); end; if CanStore then begin if (Jump.Steps[StepIndex].Count = 1) and (Jump.Steps[StepIndex][0].X = NewPoint.X) and (Jump.Steps[StepIndex][0].Y = NewPoint.Y) then begin NewPoint.Free; end else begin Jump.Steps[StepIndex].Add(NewPoint); end; Result := True end; WorkMap[Nx,Ny] := 0; end; end; end; procedure TMap.SolveJumps(ExcludeJump: TJump); var i: integer; begin for i := 0 to JumpList.Count - 1 do begin if JumpList[i] <> ExcludeJump then begin SolveJump(i); end; end; end; { TPointPos } function TPointPos.Clone: TPointPos; begin Result := TPointPos.Create(V,X,Y); end; constructor TPointPos.Create(AV, AX, AY: Integer); begin inherited Create; V := AV; X := AX; Y := AY; end; { TJump } constructor TJump.Create(P1, P2: TPointPos); begin inherited Create; PointLow := P1; PointHigh := P2; Solved := False; PartList := TPointPosList.Create; ForceUse := TPointPosList.Create; end; destructor TJump.Destroy; begin Steps.Free; PartList.Free; ForceUse.Free; inherited; end; function TJump.NrSteps: Integer; begin Result := PointHigh.V - PointLow.V; end; function TJump.GetState: TJumpState; var i: integer; begin if Solved then begin Result := jsSolved; EXIT; end; if Steps[0].Count = 1 then Result := jsOneSol else Result := jsNoSol; for i := 0 to NrSteps - 2 do begin if Steps[i].Count = 1 then begin if Result = jsNoSol then begin Result := jsPartial; BREAK; end; end else begin if Result = jsOneSol then begin Result := jsPartial; BREAK; end; end; end; end; procedure TJump.PrepareSolve; var i: integer; begin if assigned(Steps) then Steps.Free; Steps := TObjectList<TObjectList<TPointPos>>.Create; for i := 0 to NrSteps - 1 do Steps.Add(TObjectList<TPointPos>.Create); end; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} (* Version History 03/10/2001 Fixed possible memory leaks that could happen when item is deleted. Minor optimization on deletion. *) unit ElArray; interface uses SysUtils, {$ifndef KYLIX_USED} Windows, {$else} Libc, {$endif} ElContBase; type TElArraySortCompare = function(Item1, Item2: TxListItem; Cargo: TxListItem): Integer; TElArrayDeleteEvent = procedure(Sender: TObject; Item: TxListItem) of object; TElArray = class protected FList: PPointerList; FCount: Integer; FCapacity: Integer; FAutoClearObjects: Boolean; FOnDelete: TElArrayDeleteEvent; function Get(Index: Integer): TxListItem; virtual; procedure Grow; virtual; procedure Put(Index: Integer; const Item: TxListItem); virtual; procedure SetCapacity(NewCapacity: Integer); procedure SetCount(NewCount: Integer); procedure TriggerDeleteEvent(const Item: TxListItem); virtual; class procedure Error(const Msg: string; Data: Integer); public constructor Create; destructor Destroy; override; procedure CheckRange(Index:Integer); function Add(const Item: TxListItem): Integer; procedure Clear; procedure Assign(AList: TElArray); procedure Delete(Index: Integer); virtual; procedure Exchange(Index1, Index2: Integer); function Expand: TElArray; function First: TxListItem; function IndexOf(const Item: TxListItem): Integer; function IndexOfFrom(StartIndex: integer; const Item: TxListItem): Integer; function IndexOfBack(StartIndex: integer; const Item: TxListItem): Integer; procedure Insert(Index: Integer; const Item: TxListItem); function Last: TxListItem; procedure Move(CurIndex, NewIndex: Integer); procedure MoveRange(CurStart, CurEnd, NewStart: integer); function Remove(const Item: TxListItem): Integer; procedure Pack; procedure Sort(Compare: TElArraySortCompare; const Cargo: TxListItem); property Capacity: Integer read FCapacity write SetCapacity default 0; property Count: Integer read FCount write SetCount default 0; property Items[Index: Integer]: TxListItem read Get write Put; default; property List: PPointerList read FList; property AutoClearObjects: Boolean read FAutoClearObjects write FAutoClearObjects default False; { Published } property OnDelete: TElArrayDeleteEvent read FOnDelete write FOnDelete; end; implementation type EElArrayError = class(Exception); //T & R resourcestring rs_ListIndexOutOfBounds = 'List index [%d] out of bounds...'; procedure RaiseOutOfBoundsError(Ind: integer); begin raise EElArrayError.CreateFmt(rs_ListIndexOutOfBounds, [Ind]); end; class procedure TElArray.Error(const Msg: string; Data: Integer); function ReturnAddr: TxListItem; asm MOV EAX,[EBP+4] end; begin raise EElArrayError.CreateFmt(Msg, [Data])at ReturnAddr; end; constructor TElArray.Create; begin inherited; FList := nil; FCount := 0; FCapacity := 0; FAutoClearObjects := FALSE; FOnDelete := nil; end; destructor TElArray.Destroy; begin Clear; inherited; end; function TElArray.Add(const Item: TxListItem): Integer; begin Result := FCount; if Result = FCapacity then Grow; FList[Result] := Item; Inc(FCount); end; procedure TElArray.Assign(AList: TElArray); begin Clear; SetCapacity(AList.Capacity); SetCount(AList.Count); System.Move(AList.FList^[0], FList^[0], FCount); end; procedure TElArray.Clear; var I: integer; p: TxListItem; begin if Assigned(FOnDelete) then for i := 0 to Count - 1 do if FList[i] <> nil then TriggerDeleteEvent(FList[i]); if AutoClearObjects then for i := 0 to Count - 1 do begin p := Get(i); try if (P <> nil) and (TObject(P) is TObject) then TObject(P).Free; except end; end; SetCount(0); SetCapacity(0); end; procedure TElArray.CheckRange(Index:Integer); begin if (Index < 0) or (Index >= FCount) then RaiseOutOfBoundsError(Index); end; procedure TElArray.Delete(Index: Integer); begin CheckRange(Index); if Assigned(FList[Index]) then begin TriggerDeleteEvent(FList[Index]); if AutoClearObjects then try TObject(FList[Index]).Free; except FList[Index] := nil; end; end; Dec(FCount); if Index < FCount then System.Move(FList^[Index + 1], FList^[Index], (FCount - Index) * SizeOf(TxListItem)) else FList[Index] := nil; if FCount < (FCapacity div 2) then SetCapacity(FCapacity div 2); end; procedure TElArray.Exchange(Index1, Index2: Integer); var Item: TxListItem; begin CheckRange(Index1); CheckRange(Index2); if (Index1 >= FCount) then Count := Index1 + 1; if (Index2 >= FCount) then Count := Index2 + 1; Item := FList[Index1]; FList[Index1] := FList[Index2]; FList[Index2] := Item; end; function TElArray.Expand: TElArray; begin if FCount = FCapacity then Grow; Result := Self; end; function TElArray.First: TxListItem; begin CheckRange(0); Result := Get(0); end; function TElArray.Get(Index: Integer): TxListItem; begin if (Index < 0) then RaiseOutOfBoundsError(Index); if (Index >= FCount) then Result := nil else Result := FList[Index]; end; procedure TElArray.Grow; var Delta: Integer; begin if FCapacity > 64 then Delta := FCapacity div 4 else if FCapacity > 8 then Delta := 16 else Delta := 4; SetCapacity(FCapacity + Delta); end; function TElArray.IndexOfFrom(StartIndex: integer; const Item: TxListItem): Integer; begin if (StartIndex < 0) then RaiseOutOfBoundsError(StartIndex); if (StartIndex >= FCount) then Result := -1 else begin Result := StartIndex; while (Result < FCount) and (FList[Result] <> Item) do Inc(Result); if Result = FCount then Result := -1; end; end; function TElArray.IndexOfBack(StartIndex: integer; const Item: TxListItem): Integer; begin if (StartIndex < 0) then RaiseOutOfBoundsError(StartIndex); if (StartIndex >= FCount) then Result := FCount - 1 else Result := StartIndex; while (Result >= 0) and (FList[Result] <> Item) do dec(Result); end; function TElArray.IndexOf(const Item: TxListItem): Integer; begin Result := 0; while (Result < FCount) and (FList[Result] <> Item) do Inc(Result); if Result = FCount then Result := -1; end; procedure TElArray.Insert(Index: Integer; const Item: TxListItem); begin if (Index < 0) or (Index > FCount) then RaiseOutOfBoundsError(Index); if FCount = FCapacity then Grow; if Index < FCount then System.Move(FList^[Index], FList^[Index + 1], (FCount - Index) * SizeOf(TxListItem)); FList[Index] := Item; Inc(FCount); end; function TElArray.Last: TxListItem; begin Result := Get(FCount - 1); end; procedure TElArray.MoveRange(CurStart, CurEnd, NewStart: integer); var bs: integer; P: PChar; begin if CurStart <> NewStart then begin CheckRange(CurStart); CheckRange(CurEnd); CheckRange(NewStart); if ((NewStart >= CurStart) and (NewStart <= CurEnd)) then // vAd: shift without overhead diapasone RaiseOutOfBoundsError(NewStart); if CurStart > NewStart then begin bs := CurEnd - CurStart + 1; GetMem(P, bs * SizeOf(TxListItem)); System.Move(FList^[CurStart], P^, BS * SizeOf(TxListItem)); System.Move(FList^[NewStart], FList^[NewStart + BS], (CurStart - NewStart) * SizeOf(TxListItem)); System.Move(P^, FList^[NewStart], BS * SizeOf(TxListItem)); FreeMem(P); end else begin bs := CurEnd - CurStart + 1; GetMem(P, BS * SizeOf(TxListItem)); System.Move(FList^[CurStart], P^, BS * SizeOf(TxListItem)); System.Move(FList^[CurEnd + 1], FList^[CurStart], (NewStart - CurEnd) * SizeOf(TxListItem)); NewStart := CurStart - 1 + NewStart - CurEnd; System.Move(P^, FList^[NewStart], BS * SizeOf(TxListItem)); FreeMem(P); end; end; end; procedure TElArray.Move(CurIndex, NewIndex: Integer); var Item: TxListItem; begin if CurIndex <> NewIndex then begin if (NewIndex < 0) then RaiseOutOfBoundsError(NewIndex); if (NewIndex >= FCount) then Count := NewIndex + 1; Item := Get(CurIndex); { OLD CODE: //vAd: ??? вызовется .Free для Delete(CurIndex). В ElList для этого есть специальный intDelete. Кто то невнимательно переносил ? Delete(CurIndex); Insert(NewIndex, Item); {} //NEW CODE: меньше перемещений памяти: if NewIndex<CurIndex then // Shift Left System.Move(FList[NewIndex], FList[NewIndex+1], (CurIndex-NewIndex) * SizeOf(TxListItem)) else // Shift Right System.Move(FList[CurIndex+1], FList[CurIndex], (NewIndex-CurIndex) * SizeOf(TxListItem)); FList[NewIndex] := Item; end; end; procedure TElArray.Put(Index: Integer; const Item: TxListItem); begin if (Index < 0) then RaiseOutOfBoundsError(Index); if (Index >= FCount) then Count := Index + 1; if FList[Index] <> Item then begin if Assigned(FList[Index]) then begin TriggerDeleteEvent(FList[Index]); if AutoClearObjects then try TObject(FList[Index]).Free; except FList[Index] := nil; end; end; FList[Index] := Item; end; end; function TElArray.Remove(const Item: TxListItem): Integer; begin Result := IndexOf(Item); if Result <> -1 then Delete(Result); end; procedure TElArray.Pack; var I: Integer; begin for I := FCount - 1 downto 0 do if Items[I] = nil then Delete(I); end; procedure TElArray.SetCapacity(NewCapacity: Integer); begin if (NewCapacity < FCount) or (NewCapacity > MaxListSize) then RaiseOutOfBoundsError(NewCapacity); if NewCapacity <> FCapacity then begin ReallocMem(FList, NewCapacity * SizeOf(TxListItem)); if NewCapacity > FCapacity then {$ifndef KYLIX_USED} FillMemory(@FList[FCapacity], (NewCapacity - FCapacity) * SizeOf(TxListItem), 0); {$else} memset(@FList[FCapacity], 0, (NewCapacity - FCapacity) * SizeOf(TxListItem)); {$endif} FCapacity := NewCapacity; end; end; procedure TElArray.SetCount(NewCount: Integer); begin if (NewCount < 0) or (NewCount > MaxListSize) then RaiseOutOfBoundsError(NewCount); if NewCount > FCapacity then SetCapacity(NewCount); if NewCount > FCount then FillChar(FList^[FCount], (NewCount - FCount) * SizeOf(TxListItem), 0); FCount := NewCount; end; procedure QuickSort(const SortList: PPointerList; L, R: Integer; SCompare: TElArraySortCompare; const Cargo: TxListItem); var I, J, rI, rJ: Integer; P, T: TxListItem; begin repeat I := L; J := R; P := SortList[(L + R) shr 1]; repeat rI := SCompare(SortList[I], P, Cargo); rJ := SCompare(SortList[J], P, Cargo); while rI < 0 do begin Inc(I); rI := SCompare(SortList[I], P, Cargo); end; while rJ > 0 do begin Dec(J); rJ := SCompare(SortList[J], P, Cargo); end; if I <= J then begin if (I <> J) and ((rI <> 0) or (rJ <> 0)) then begin T := SortList[I]; SortList[I] := SortList[J]; SortList[J] := T; end; Inc(I); Dec(J); end; until I > J; if L < J then QuickSort(SortList, L, J, SCompare, Cargo); L := I; until I >= R; end; procedure TElArray.Sort(Compare: TElArraySortCompare; const Cargo: TxListItem); begin if (FList <> nil) and (Count > 0) then QuickSort(FList, 0, Count - 1, Compare, Cargo); end; procedure TElArray.TriggerDeleteEvent(const Item: TxListItem); begin if (Assigned(FOnDelete)) then FOnDelete(Self, Item); end; end.
unit BaseOptimizationExampleUnit; interface uses SysUtils, BaseExampleUnit, DataObjectUnit; type TBaseOptimizationExample = class abstract (TBaseExample) protected procedure PrintExampleOptimizationResult(ExampleName: String; DataObject: TDataObject; ErrorString: String); end; implementation { TBaseOptimizationExample } uses AddressUnit, EnumsUnit; procedure TBaseOptimizationExample.PrintExampleOptimizationResult(ExampleName: String; DataObject: TDataObject; ErrorString: String); var UserError: String; Address: TAddress; AddressesSorted: TAddressesArray; begin Writeln(''); if (DataObject <> nil) then begin WriteLn(Format('%s executed successfully', [ExampleName])); WriteLn(''); WriteLn(Format('Optimization Problem ID: %s', [DataObject.OptimizationProblemId])); WriteLn(Format('State: %s', [TOptimizationDescription[TOptimizationState(DataObject.State)]])); for UserError in DataObject.UserErrors do WriteLn(Format('UserError : "$s"', [UserError])); WriteLn(''); // Sort addresses by sequence order AddressesSorted := AddressUnit.SortAddresses(DataObject.Addresses); for Address in AddressesSorted do begin WriteLn(Format('Address: %s', [Address.AddressString])); WriteLn(Format('Route ID: %s', [Address.RouteId.ToString])); end; end else WriteLn(Format('%s error: "%s"', [ExampleName, ErrorString])); end; end.
{*******************************************************} { } { Log4Pascal } { https://github.com/martinusso/log4pascal } { } { This software is open source, } { licensed under the The MIT License (MIT). } { } {*******************************************************} unit Log4Pascal; interface uses SyncObjs; type TLogTypes = (ltTrace, ltDebug, ltInfo, ltWarning, ltError, ltFatal); TLogger = class private FRC: TCriticalSection; FFileName: string; FIsInit: Boolean; FOutFile: TextFile; FQuietMode: Boolean; FQuietTypes: set of TLogTypes; procedure Initialize; procedure CreateFoldersIfNecessary; procedure Finalize; procedure Write(const Msg: string); public constructor Create(const FileName: string); destructor Destroy; override; property FileName: string read FFileName; procedure SetQuietMode; procedure DisableTraceLog; procedure DisableDebugLog; procedure DisableInfoLog; procedure DisableWarningLog; procedure DisableErrorLog; procedure DisableFatalLog; procedure SetNoisyMode; procedure EnableTraceLog; procedure EnableDebugLog; procedure EnableInfoLog; procedure EnableWarningLog; procedure EnableErrorLog; procedure EnableFatalLog; procedure Clear; procedure Trace(const Msg: string); procedure Debug(const AMsg: string; const AArgs: array of const); overload; procedure Debug(const Msg: string); overload; procedure Info(const Msg: string); procedure Warning(const Msg: string); procedure Error(const AMsg: string; const AArgs: array of const); overload; procedure Error(const Msg: string); overload; procedure Fatal(const Msg: string); end; var Logger: TLogger; implementation uses Forms, SysUtils, Windows; const FORMAT_LOG = '%s %s'; PREFIX_TRACE = 'TRACE|'; PREFIX_DEBUG = 'DEBUG|'; PREFIX_INFO = 'INFO|'; PREFIX_WARN = 'WARN |'; PREFIX_ERROR = 'ERROR|'; PREFIX_FATAL = 'FATAL|'; { TLogger } procedure TLogger.Clear; begin if not FileExists(FFileName) then Exit; if FIsInit then CloseFile(FOutFile); SysUtils.DeleteFile(FFileName); FIsInit := False; end; constructor TLogger.Create(const FileName: string); begin FRC := TCriticalSection.Create; FFileName := FileName; FIsInit := False; Self.SetNoisyMode; FQuietTypes := []; end; procedure TLogger.CreateFoldersIfNecessary; var FilePath: string; FullApplicationPath: string; begin FilePath := ExtractFilePath(FFileName); if Pos(':', FilePath) > 0 then ForceDirectories(FilePath) else begin FullApplicationPath := ExtractFilePath(Application.ExeName); ForceDirectories(IncludeTrailingPathDelimiter(FullApplicationPath) + FilePath); end; end; procedure TLogger.Debug(const Msg: string); begin {$IFNDEF DEBUG} Exit; {$ENDIF} if not (ltDebug in FQuietTypes) then Self.Write(Format(FORMAT_LOG, [PREFIX_DEBUG, Msg])); end; procedure TLogger.Debug(const AMsg: string; const AArgs: array of const); begin Debug(Format(AMsg, AArgs)); end; destructor TLogger.Destroy; begin FRC.Free; Self.Finalize; inherited; end; procedure TLogger.DisableDebugLog; begin Include(FQuietTypes, ltDebug); end; procedure TLogger.DisableErrorLog; begin Include(FQuietTypes, ltError); end; procedure TLogger.DisableFatalLog; begin Include(FQuietTypes, ltFatal); end; procedure TLogger.DisableInfoLog; begin Include(FQuietTypes, ltInfo); end; procedure TLogger.DisableTraceLog; begin Include(FQuietTypes, ltTrace); end; procedure TLogger.DisableWarningLog; begin Include(FQuietTypes, ltWarning); end; procedure TLogger.EnableDebugLog; begin Exclude(FQuietTypes, ltDebug); end; procedure TLogger.EnableErrorLog; begin Exclude(FQuietTypes, ltError); end; procedure TLogger.EnableFatalLog; begin Exclude(FQuietTypes, ltFatal); end; procedure TLogger.EnableInfoLog; begin Exclude(FQuietTypes, ltInfo); end; procedure TLogger.EnableTraceLog; begin Exclude(FQuietTypes, ltTrace); end; procedure TLogger.EnableWarningLog; begin Exclude(FQuietTypes, ltWarning); end; procedure TLogger.Error(const AMsg: string; const AArgs: array of const); begin Error(Format(AMsg, AArgs)); end; procedure TLogger.Error(const Msg: string); begin if not (ltError in FQuietTypes) then Self.Write(Format(FORMAT_LOG, [PREFIX_ERROR, Msg])); end; procedure TLogger.Fatal(const Msg: string); begin if not (ltFatal in FQuietTypes) then Self.Write(Format(FORMAT_LOG, [PREFIX_FATAL, Msg])); end; procedure TLogger.Finalize; begin if (FIsInit and (not FQuietMode)) then CloseFile(FOutFile); FIsInit := False; end; procedure TLogger.Initialize; begin if FIsInit then CloseFile(FOutFile); if not FQuietMode then begin Self.CreateFoldersIfNecessary; AssignFile(FOutFile, FFileName); if not FileExists(FFileName) then Rewrite(FOutFile) else Append(FOutFile); end; FIsInit := True; end; procedure TLogger.Info(const Msg: string); begin if not (ltInfo in FQuietTypes) then Self.Write(Format(FORMAT_LOG, [PREFIX_INFO, Msg])); end; procedure TLogger.SetNoisyMode; begin FQuietMode := False; end; procedure TLogger.SetQuietMode; begin FQuietMode := True; end; procedure TLogger.Trace(const Msg: string); begin if not (ltTrace in FQuietTypes) then Self.Write(Format(FORMAT_LOG, [PREFIX_TRACE, Msg])); end; procedure TLogger.Warning(const Msg: string); begin if not (ltWarning in FQuietTypes) then Self.Write(Format(FORMAT_LOG, [PREFIX_WARN, Msg])); end; procedure TLogger.Write(const Msg: string); const FORMAT_DATETIME_DEFAULT = 'yyyy-mm-dd hh:nn:ss'; begin if FQuietMode then Exit; FRC.Acquire; try Self.Initialize; try if FIsInit then Writeln(FOutFile, Format('[%s] [TID %d] %s ', [FormatDateTime(FORMAT_DATETIME_DEFAULT, Now), GetCurrentThreadId, Msg])); finally Self.Finalize; end; finally FRC.Release; end; end; end.
{ 一个简单的矩阵运算库 (只)支持加、减、数乘、乘 除非你能保证满足运算条件,否则请在运算完后查看errmsg 采用动态内存实现,使用完请Destroy 注意:横纵坐标从0开始 FPC5719 2018.9 } {$MODE OBJFPC} unit matrix; interface type generic TMatrix<T>=class public type PT=^T; private data:PT; h,w:DWord; public constructor Create(); constructor Create(hh,ww:DWord);overload; destructor Destroy();override; procedure SetSize(hh,ww:DWord); property Height:DWord read h; property Width:DWord read w; function GetValue(i,j:DWord):T; procedure SetValue(i,j:DWord;d:T); property Items[i,j:DWord]:T read GetValue write SetValue; end; generic TMatrixOperator<T>=class public type TM=specialize TMatrix<T>; private errmsg:string; public constructor Create(); function Add(a,b:TM):TM; function Sub(a,b:TM):TM; function Mul(a:TM;b:T):TM; function Mul(a,b:TM):TM; function GetErr:string; end; implementation constructor TMatrix.Create(); begin data:=NIL; end; constructor TMatrix.Create(hh,ww:DWord);overload; begin data:=NIL; h:=hh; w:=ww; data:=GetMem(h*w*sizeof(T)); end; destructor TMatrix.Destroy(); begin FreeMem(data); end; procedure TMatrix.SetSize(hh,ww:DWord); begin h:=hh; w:=ww; FreeMem(data); data:=GetMem(h*w*sizeof(T)); end; function TMatrix.GetValue(i,j:DWord):T; begin if(i>h)or(j>w)then exit; exit(data[(i-1)*w+j]); end; procedure TMatrix.SetValue(i,j:DWord;d:T); begin if(i>h)or(j>w)then exit; data[(i-1)*w+j]:=d; end; constructor TMatrixOperator.Create(); begin errmsg:=''; end; function TMatrixOperator.Add(a,b:TM):TM; var i,j:longint; res:TM; begin if(a.w<>b.w)or(a.h<>b.h)then begin errmsg:='Different sizes between parameters!'; exit; end; res:=TM.Create(a.h,a.w); for i:=0 to res.h-1 do for j:=0 to res.w-1 do res.Items[i,j]:=a.Items[i,j]+b.Items[i,j]; exit(res); end; function TMatrixOperator.Sub(a,b:TM):TM; var i,j:longint; res:TM; begin if(a.w<>b.w)or(a.h<>b.h)then begin errmsg:='Different sizes between parameters!'; exit; end; res:=TM.Create(a.h,a.w); for i:=0 to res.h-1 do for j:=0 to res.w-1 do res.Items[i,j]:=a.Items[i,j]-b.Items[i,j]; exit(res); end; function TMatrixOperator.Mul(a:TM;b:T):TM; var i,j:longint; res:TM; begin res:=TM.Create(a.h,a.w); for i:=0 to res.h-1 do for j:=0 to res.w-1 do res.Items[i,j]:=a.Items[i,j]*b; exit(res); end; function TMatrixOperator.Mul(a,b:TM):TM; var i,j,k:longint; res:TM; begin if(a.w<>b.h)then begin errmsg:='Different sizes between parameters!'; exit; end; res:=TM.Create(a.h,b.w); for i:=0 to a.h-1 do for j:=0 to b.w-1 do for k:=0 to a.w-1 do res.Items[i,j]:=res.Items[i,j]+a.Items[i,k]*b.Items[k,j]; exit(res); end; function TMatrixOperator.GetErr:string; var s:string; begin s:=errmsg; errmsg:=''; exit(s); end; end.
unit RDOQueries; interface uses SysUtils, Classes, SocketComp; type TRDOQueryKind = (qkNone, qkAnswer, qkGeID, qkSetProp, qkGetProp, qkCallRet, qkCallNoRet, qkError); TRDOParamKind = (pkInteger, pkShortString, pkString, pkSingle, pkDouble, pkEmpty, pkOutParam, pkBuffer); TRDOQueryPriority = (qpNormal, qpAboveNormal, qpBelowNormal, qpHighest, qpIdle, qpLowest, qpTimeCritical); type ERDOQueryError = class(Exception); ERDOCorruptQuery = class(Exception); type TQueryStream = class; TRDOQuery = class; TRDOQuerySize = record Value : integer; Mask : integer; end; TQueryStreamHeader = record Count : byte; case integer of 0: (Size : TRDOQuerySize); 1: (Bytes : array[0..sizeof(TRDOQuerySize) - 1] of byte); end; PQueryStreamData = ^TQueryStreamData; TQueryStreamData = record Size : TRDOQuerySize; Data : array[0..0] of char; end; TQueryStream = class(TStream) public destructor Destroy; override; private fHeader : TQueryStreamHeader; fData : PQueryStreamData; fPos : integer; private function CheckSize(QuerySize : TRDOQuerySize) : boolean; public procedure Clear; function Receive(Socket : TCustomWinSocket) : boolean; function Send(Socket : TCustomWinSocket) : boolean; function Read(var buffer; count : longint): longint; override; function Write(const buffer; count : longint): longint; override; function Seek(offset : longint; origin : word): longint; override; protected function GetSize : integer; procedure SetSize(aSize : integer); override; public property Position : longint read fPos write fPos; property Size : longint read GetSize write SetSize; end; TRDOQuery = class public constructor Create(aQueryKind : TRDOQueryKind; anId : word); constructor Read(Stream : TStream); procedure Write(Stream : TStream); destructor Destroy; override; private fName : string; fId : word; fQKind : TRDOQueryKind; fObject : integer; fPriority : TRDOQueryPriority; fParamCount : byte; fParamSize : integer; fParams : pchar; public property Id : word read fId write fId; property QKind : TRDOQueryKind read fQKind write fQKind; property Name : string read fName write fName; property ObjId : integer read fObject write fObject; property ParamCount : byte read fParamCount; property Priority : TRDOQueryPriority read fPriority write fPriority; private procedure SetParamSize(aSize : integer); protected property ParamSize : integer read fParamSize write SetParamSize; private procedure PushString(const str : string); procedure PushValue(const value; k : TRDOParamKind; size : integer); public procedure Clear; procedure PushParam(const value : variant); procedure PushParamRef; procedure PushPtr(ptr : pointer; size : integer); protected function PopInteger(var idx : integer) : integer; function PopShortString(var idx : integer) : string; function PopString(var idx : integer) : string; function PopSingle(var idx : integer) : single; function PopDouble(var idx : integer) : double; function PopPtr(var idx : integer) : variant; virtual; public {$IFDEF AUTO} function PopParam(var idx : integer) : OleVariant; {$ELSE} function PopParam(var idx : integer) : variant; {$ENDIF} function ToStr : string; end; function QueryPriorityToThreadPriority(prior : TRDOQueryPriority) : integer; function ThreadPriorityToQueryPriority(prior : integer) : TRDOQueryPriority; implementation uses Windows, RDOVariantUtils, MathUtils; const MAXQUERYSIZE = 10*1024*1024; function QueryPriorityToThreadPriority(prior : TRDOQueryPriority) : integer; begin case prior of qpLowest : result := THREAD_PRIORITY_LOWEST; qpBelowNormal : result := THREAD_PRIORITY_BELOW_NORMAL; qpNormal : result := THREAD_PRIORITY_NORMAL; qpHighest : result := THREAD_PRIORITY_HIGHEST; qpAboveNormal : result := THREAD_PRIORITY_ABOVE_NORMAL; qpTimeCritical : result := THREAD_PRIORITY_TIME_CRITICAL; qpIdle : result := THREAD_PRIORITY_IDLE; else result := THREAD_PRIORITY_NORMAL; end end; function ThreadPriorityToQueryPriority(prior : integer) : TRDOQueryPriority; begin case prior of THREAD_PRIORITY_LOWEST: result := qpLowest; THREAD_PRIORITY_BELOW_NORMAL: result := qpBelowNormal; THREAD_PRIORITY_NORMAL: result := qpNormal; THREAD_PRIORITY_HIGHEST: result := qpHighest; THREAD_PRIORITY_ABOVE_NORMAL: result := qpAboveNormal; THREAD_PRIORITY_TIME_CRITICAL: result := qpTimeCritical; THREAD_PRIORITY_IDLE: result := qpIdle; else result := qpNormal; end end; procedure WriteStrOnStr(var dest : string; src : string; var pos : integer; fmsz : byte); var len : integer; begin len := length(src); move(len, dest[pos], fmsz); inc(pos, fmsz); if len > 0 then move(src[1], dest[pos], len); end; // TRDOQueryStream destructor TQueryStream.Destroy; begin ReallocMem(fData, 0); inherited; end; function TQueryStream.CheckSize(QuerySize : TRDOQuerySize) : boolean; begin result := (QuerySize.Value > 0) and (QuerySize.Value < MAXQUERYSIZE) and (QuerySize.Value and QuerySize.Mask = 0); end; procedure TQueryStream.Clear; begin SetSize(0); fPos := 0; fillchar(fHeader, sizeof(fHeader), 0); end; function TQueryStream.Receive(Socket : TCustomWinSocket) : boolean; var cnt : integer; sz : integer; len : integer; begin if Size = 0 then begin len := MathUtils.min(Socket.ReceiveLength, sizeof(fHeader.Size) - fHeader.Count); if len > 0 then begin len := Socket.ReceiveBuf(fHeader.Bytes[fHeader.Count], len); if len > 0 then inc(fHeader.Count, len); end; if fHeader.Count = sizeof(fHeader.Size) then if CheckSize(fHeader.Size) then SetSize(fHeader.Size.Value) else raise ERDOCorruptQuery.Create('Invalid size for query'); fPos := 0; end; sz := Size; if sz > 0 then begin cnt := Socket.ReceiveBuf(fData.Data[fPos], sz - fPos); inc(fPos, cnt); end; result := (sz > 0) and (fPos = sz); end; function TQueryStream.Send(Socket : TCustomWinSocket) : boolean; begin try if fData <> nil then begin Socket.SendBuf(fData^, Size + sizeof(fData.Size)); result := true; end else result := false; except result := false; end; end; function TQueryStream.Read(var buffer; count : longint) : longint; var sz : integer; begin sz := Size; if fPos + count > sz then result := sz - fPos else result := count; if result > 0 then begin move(fData.Data[fPos], buffer, result); inc(fPos, result); end else result := 0; end; function TQueryStream.Write(const buffer; count : longint) : longint; var sz : integer; begin sz := Size; try if fPos + count > sz then Size := fPos + count; move(buffer, fData.Data[fPos], count); inc(fPos, count); result := count; except result := 0; end; end; function TQueryStream.Seek(offset : longint; origin : word): longint; var sz : integer; begin sz := Size; case origin of soFromBeginning : fPos := offset; soFromCurrent : inc(fPos, offset); soFromEnd : fPos := sz - offset; end; if fPos < 0 then fPos := 0 else if fPos > sz then fPos := sz; result := fPos; end; function TQueryStream.GetSize : integer; begin if fData <> nil then result := fData.Size.Value else result := 0; end; procedure TQueryStream.SetSize(aSize : integer); begin ReallocMem(fData, aSize + sizeof(fData.Size)); if fData <> nil then begin fData.Size.Value := aSize; fData.Size.Mask := not aSize; end; end; // TRDOQuery constructor TRDOQuery.Create(aQueryKind : TRDOQueryKind; anId : word); begin inherited Create; fId := anId; fQKind := aQueryKind; fPriority := qpNormal; end; constructor TRDOQuery.Read(Stream : TStream); var len : integer; begin Stream.Read(fId, sizeof(fId)); Stream.Read(fPriority, sizeof(fPriority)); Stream.Read(fQKind, sizeof(fQKind)); case fQKind of qkError, qkAnswer : begin Stream.Read(fParamCount, sizeof(fParamCount)); len := Stream.Size - Stream.Position; ParamSize := len; if len > 0 then Stream.Read(fParams[0], len) else fParams := nil; end; qkGeID : begin fillchar(len, sizeof(len), 0); Stream.Read(len, 1); if len > 0 then begin SetLength(fName, len); Stream.Read(fName[1], len); end else fName := ''; end; qkSetProp, qkGetProp, qkCallRet, qkCallNoRet : begin Stream.Read(fObject, sizeof(fObject)); fillchar(len, sizeof(len), 0); Stream.Read(len, 1); if len > 0 then begin SetLength(fName, len); Stream.Read(fName[1], len); end else fName := ''; Stream.Read(fParamCount, sizeof(fParamCount)); len := Stream.Size - Stream.Position; if len > 0 then begin ParamSize := len; Stream.Read(fParams[0], len); end else fParams := nil; end; else raise ERDOQueryError.Create('Unknown query kind'); end; end; procedure TRDOQuery.Write(Stream : TStream); var pSz : integer; len : integer; begin Stream.Write(fId, sizeof(fId)); Stream.Write(fPriority, sizeof(fPriority)); Stream.Write(fQKind, sizeof(fQKind)); pSz := ParamSize; case fQKind of qkError, qkAnswer : begin Stream.Write(fParamCount, sizeof(fParamCount)); if pSz > 0 then Stream.Write(fParams[0], pSz); end; qkGeID : begin len := length(fName); Stream.Write(len, 1); // lo-byte of length if len > 0 then Stream.Write(fName[1], len); end; qkSetProp, qkGetProp, qkCallRet, qkCallNoRet : begin Stream.Write(fObject, sizeof(fObject)); len := length(fName); Stream.Write(len, 1); // lo-byte of length if len > 0 then Stream.Write(fName[1], len); Stream.Write(fParamCount, sizeof(fParamCount)); if pSz > 0 then Stream.Write(fParams[0], pSz); end; end; end; destructor TRDOQuery.Destroy; begin Clear; inherited; end; procedure TRDOQuery.SetParamSize(aSize : integer); begin if aSize < 0 then aSize := 0; fParamSize := aSize; ReallocMem(fParams, aSize); end; procedure TRDOQuery.PushString(const str : string); var strln : integer; len : integer; fmsz : byte; k : TRDOParamKind; begin len := ParamSize; strln := length(str); if strln < high(byte) then begin k := pkShortString; fmsz := sizeof(byte); end else begin k := pkString; fmsz := sizeof(integer); end; ParamSize := len + sizeof(k) + fmsz + strln; move(k, fParams[len], sizeof(k)); inc(len, sizeof(k)); move(strln, fParams[len], fmsz); inc(len, fmsz); if strln > 0 then move(str[1], fParams[len], strln); end; procedure TRDOQuery.PushValue(const value; k : TRDOParamKind; size : integer); var len : integer; begin len := ParamSize; ParamSize := len + sizeof(k) + size; move(k, fParams[len], sizeof(k)); inc(len, sizeof(k)); move(value, fParams[len], size); end; procedure TRDOQuery.Clear; begin fName := ''; fParamCount := 0; fObject := 0; fQKind := qkNone; ParamSize := 0; end; procedure TRDOQuery.PushParam(const value : variant); var vt : word; str : string; i : integer; s : single; d : double; mp : TMarshalPtr; begin inc(fParamCount); vt := TVarData(value).VType and varTypeMask; case vt of varOleStr, varString: begin str := value; PushString(str); end; varBoolean : begin if value then i := 1 else i := 0; PushValue(i, pkInteger, sizeof(integer)); end; varSmallint, varInteger, varError, varByte: begin i := value; PushValue(i, pkInteger, sizeof(integer)); end; varSingle: begin s := value; PushValue(s, pkSingle, sizeof(single)); end; varDouble, varDate, varCurrency: begin d := value; PushValue(d, pkDouble, sizeof(double)); end; varVariant, varEmpty: begin i := 0; PushValue(i, pkEmpty, 0); end; varPointer, varByRef, varUnknown: begin mp := GetMarshalPtr(value); PushPtr(mp.ptr, mp.size); end; else raise ERDOQueryError.Create('Illegal type found.'); end; end; procedure TRDOQuery.PushParamRef; var useless : integer; begin inc(fParamCount); PushValue(useless, pkOutParam, 0); end; procedure TRDOQuery.PushPtr(ptr : pointer; size : integer); var sz : integer; begin inc(fParamCount); PushValue(size, pkBuffer, sizeof(size)); sz := ParamSize; ParamSize := size + sz; move(ptr^, fParams[sz], size); end; function TRDOQuery.PopInteger(var idx : integer) : integer; begin result := 0; if idx + sizeof(result) <= ParamSize then move(fParams[idx], result, sizeof(result)) else raise ERDOQueryError.Create('Out of range parameter'); inc(idx, sizeof(result)); end; function TRDOQuery.PopShortString(var idx : integer) : string; var sz : byte; len : integer; begin len := ParamSize; if idx <= len then begin sz := byte(fParams[idx]); inc(idx); if idx + sz <= len then if sz > 0 then begin SetLength(result, sz); move(fParams[idx], result[1], sz); inc(idx, sz); end else result := '' else begin result := ''; raise ERDOQueryError.Create('Out of range parameter'); end; end else result := ''; end; function TRDOQuery.PopString(var idx : integer) : string; var sz : integer; begin sz := PopInteger(idx); if idx + sz <= ParamSize then if sz > 0 then begin SetLength(result, sz); move(fParams[idx], result[1], sz); inc(idx, sz); end else result := '' else begin raise ERDOQueryError.Create('Out of range parameter'); result := ''; end; end; function TRDOQuery.PopSingle(var idx : integer) : single; begin result := 0; if idx + sizeof(result) <= ParamSize then move(fParams[idx], result, sizeof(result)) else raise ERDOQueryError.Create('Out of range parameter'); inc(idx, sizeof(result)); end; function TRDOQuery.PopDouble(var idx : integer) : double; begin result := 0; if idx + sizeof(result) <= ParamSize then move(fParams[idx], result, sizeof(result)) else raise ERDOQueryError.Create('Out of range parameter'); inc(idx, sizeof(result)); end; function TRDOQuery.PopPtr(var idx : integer) : variant; var size : integer; ptr : pointer; begin size := PopInteger(idx); if size > 0 then if fQKind = qkAnswer then begin GetMem(ptr, size); move(fParams[idx], ptr^, size); inc(idx, size); end else ptr := fParams + idx else ptr := nil; result := integer(ptr); inc(idx, size); end; {$IFDEF AUTO} function TRDOQuery.PopParam(var idx : integer) : OleVariant; {$ELSE} function TRDOQuery.PopParam(var idx : integer) : variant; {$ENDIF} var k : TRDOParamKind; len : integer; begin len := ParamSize; if idx + sizeof(k) <= len then begin move(fParams[idx], k, sizeof(k)); inc(idx, sizeof(k)); case k of pkInteger : result := PopInteger(idx); pkShortString : result := PopShortString(idx); pkString : result := PopString(idx); pkSingle : result := PopSingle(idx); pkDouble : result := PopDouble(idx); pkOutParam : TVarData(result).VType := varVariant; pkBuffer : result := PopPtr(idx); else result := integer(0); end; end else result := integer(0); end; function TRDOQuery.ToStr : string; function RenderParams : string; var i : integer; idx : integer; v : variant; begin result := ''; idx := 0; for i := 1 to fParamCount do begin v := PopParam(idx); if TVarData(v).VType and varTypeMask <> varVariant then result := result + VarToStr(v) else result := result + '?'; if i < fParamCount then result := result + ', '; end; if result <> '' then result := '(' + result + ')'; end; begin case fQKind of qkAnswer : result := 'Answer' + RenderParams; qkError : result := 'Error' + RenderParams; qkGeID : result := 'IdOf(' + fName + ')'; qkSetProp : result := IntToStr(fObject) + '.Set' + fName + RenderParams; qkGetProp : result := IntToStr(fObject) + '.Get' + fName; qkCallRet, qkCallNoRet : result := IntToStr(fObject) + '.' + fName + RenderParams; end; result := 'Query#' + IntToStr(fId) + ' = ' + result; end; end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.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. * ********************************************************************************************************************** * TERRA_GIF * Implements GIF loader *********************************************************************************************************************** } Unit TERRA_GIF; {$I terra.inc} Interface Uses TERRA_Error, TERRA_Utils, TERRA_Application, TERRA_Stream, TERRA_Image, TERRA_Math, TERRA_Color; Implementation Type GIFHeader=Packed Record Signature:Array[1..3] Of AnsiChar; Version:Array[1..3] Of AnsiChar; Width,Height:Word; Flags:Byte; Background:Byte; AspectRatio:Byte; End; GIFImageDescriptor=Packed Record x,y:Word; xd,yd:word; Flags:byte; End; GIFExtensionBlock=Packed Record FunctionCode:Byte; End; GIFGraphicControlExtension=Packed Record BlockSize:Byte; Flags:Byte; DelayTime:Word; TransparencyColor:Byte; End; GIFRGB=Record Red,Green,Blue:Byte; End; Const ilStart:Array[1..4] Of longint=(0,4,2,1); ilStep:Array[1..4] Of longint=(8,8,4,2); Type PPalette=^GIFPalette; GIFPalette=Array[0..255] Of Color; GIFLoader = Class(TERRAObject) Protected MyImage:Image; TransparencyColor:Integer; Procedure DecodeGIFLZW(Source:Stream; FrameBuffer:Image; Palette:PPalette; Interlaced:Boolean); Procedure CopyFrame(FrameBuffer:Image; X,Y,FrameWidth,FrameHeight:Word); Procedure MaskFrame; Procedure Load(Source:Stream); End; Procedure DumpData(Source:Stream); Var Count:Byte; Begin Repeat Source.Read(@Count,1); Source.Skip(Count); Until (Count=0) Or (Source.EOF); End; Procedure GIFLoader.MaskFrame(); Var Src,Dest:PColor; I,J:Cardinal; CurrentFrame:Integer; Begin Exit; CurrentFrame := MyImage.CurrentFrame; If CurrentFrame<=0 Then Exit; For J:=0 To Pred(MyImage.Height) Do For I:=0 To Pred(MyImage.Width) Do Begin MyImage.SetCurrentFrame(Pred(CurrentFrame)); Src := MyImage.GetPixelOffset(I, J); MyImage.SetCurrentFrame(CurrentFrame); Dest := MyImage.GetPixelOffset(I, J); If (Dest.A=0) And (Src.A=255) Then Dest^ := Src^; End; End; Procedure GIFLoader.CopyFrame(FrameBuffer:Image; X,Y,FrameWidth,FrameHeight:Word); Var J:Cardinal; PrevFrame:Pointer; {$IFDEF PIXEL8} Src, Dest:PByte; {$ENDIF} {$IFDEF PIXEL32} Src, Dest:PColor; {$ENDIF} Begin If MyImage.CurrentFrame<=0 Then Begin MyImage.Copy(FrameBuffer); Exit; End; {MyImage.SetCurrentFrame(Pred(MyImage.CurrentFrame)); PrevFrame := MyImage.Pixels; MyImage.SetCurrentFrame(Succ(MyImage.CurrentFrame)); Move(PrevFrame^, MyImage.Pixels^, MyImage.Size);} Move(FrameBuffer.Pixels^, MyImage.Pixels^, MyImage.Size); Exit; For J:=0 To Pred(FrameHeight) Do Begin Src := MyImage.GetPixelOffset(X, Y + J); Dest := FrameBuffer.GetPixelOffset(X, Y + J); {$IFDEF PIXEL8} Move(Dest^, Src^,FrameWidth); {$ENDIF} {$IFDEF PIXEL32} Move(Dest^, Src^, FrameWidth*PixelSize); {$ENDIF} End; End; Procedure GIFLoader.DecodeGIFLZW(Source:Stream; FrameBuffer:Image; Palette:PPalette; Interlaced:Boolean); Var xd,yd:Cardinal; Const Tablen=4095; Type PStr=^TStr; TStr=Record Prefix:Pstr; Suffix:Longint; End; PStrTab=^TStrTab; TStrTab=Array[0..TabLen] Of TStr; Var StrTab:PStrTab; OldCode,CurCode:Longint; Clearcode,EndCode:Longint; CodeSize,CodeLen,CodeMask:Longint; StrIdx:Longint; BitBuf,BitSinBuf:Longint; BytBuf:Array[0..255] Of Byte; BytInBuf,BytBufIdx:Byte; EndOfSrc:Boolean; xcnt,ycnt,pcnt,ystep,pass:Cardinal; Dest:PColor; Procedure InitStringTable; Var I:Longint; Begin System.New(StrTab); Clearcode:=1 Shl CodeSize; EndCode := Succ(ClearCode); StrIdx := Succ(EndCode); CodeLen:=Succ(CodeSize); CodeMask:=Pred(1 Shl CodeLen); For I:=0 To Pred(ClearCode) Do Begin StrTab^[I].Prefix:=Nil; StrTab^[I].Suffix:=I; End; For I:=ClearCode To TabLen Do Begin StrTab^[I].Prefix:=Nil; StrTab^[I].Suffix:=0; End; End; Procedure ClearStringTable; Var I:Longint; Begin ClearCode:=1 Shl CodeSize; EndCode:=Succ(ClearCode); StrIdx:=Succ(EndCode); CodeLen:=Succ(CodeSize); CodeMask:=Pred(1 Shl CodeLen); For I:=ClearCode To TabLen Do Begin StrTab^[I].Prefix:=Nil; StrTab^[I].Suffix:=0; End; End; Procedure DoneStringTable; Begin Dispose(StrTab); End; Function GetNextCode:Longint; Begin While (BitsInBuf<CodeLen) Do Begin If (BytInBuf=0) Then Begin Source.Read(@BytInBuf,1); If (BytInBuf=0) Then EndOfSrc:=True; Source.Read(@BytBuf,BytInBuf); BytBufIdx:=0; End; BitBuf:=BitBuf Or (Longint(Byte(BytBuf[BytBufIdx])) Shl BitsInBuf); Inc(BytBufIdx); Dec(BytInBuf); Inc(BitsInBuf,8); End; Result:=Bitbuf And CodeMask; BitBuf:=Bitbuf Shr CodeLen; Dec(BitsInBuf,CodeLen); End; Procedure AddStrToTab(Prefix:PStr;Suffix:Longint); Begin StrTab^[StrIdx].Prefix:=Prefix; StrTab^[StrIdx].Suffix:=Suffix; Inc(StrIdx); Case StrIdx Of 0..1: CodeLen:=1; 2..3: CodeLen:=2; 4..7: CodeLen:=3; 8..15: CodeLen:=4; 16..31: CodeLen:=5; 32..63: CodeLen:=6; 64..127: CodeLen:=7; 128..255: CodeLen:=8; 256..511: CodeLen:=9; 512..1023: CodeLen:=10; 1024..2047: CodeLen:=11; 2048..4096: CodeLen:=12; End; CodeMask:=Pred(1 Shl CodeLen); End; Function CodeToStr(Code:Longint):PStr; Begin Result:=Addr(StrTab^[Code]); End; Procedure WritePixels(S:PStr); Begin If (Assigned(S^.Prefix)) Then WritePixels(S^.Prefix); If (ycnt>=yd) Then Begin If Interlaced Then Begin While (ycnt>=yd) And (pass<5) Do Begin Inc(Pass); ycnt := ilstart[Pass]; ystep := ilstep[Pass]; End; End; End; Dest := FrameBuffer.GetPixelOffset(xcnt, ycnt); {$IFDEF PIXEL8} If S^.Suffix = TransparencyColor Then Dest^ := 0 Else Dest^ := ColorRGB32To8(Palette^[S^.Suffix]); {$ENDIF} {$IFDEF PIXEL32} If S^.Suffix = TransparencyColor Then Dest^ := ColorNull Else Dest ^:= Palette^[S^.Suffix]; {$ENDIF} Inc(xcnt); If (xcnt>=xd) Then Begin Inc(pcnt); xcnt:=0; Inc(ycnt,ystep); Dest := FrameBuffer.GetPixelOffset(0, ystep); If (Not Interlaced )Then Begin If (ycnt>=yd) Then Inc(Pass); End; End; End; Function FirstChar(S:PStr):Byte; Begin While (S^.Prefix<>Nil) Do S:=S^.Prefix; Result:=S^.Suffix; End; Begin EndOfSrc:=False; xd := MyImage.Width; yd := MyImage.Height; xcnt:=0; pcnt:=0; If Interlaced Then Begin Pass:=1; ycnt:=ilStart[Pass]; ystep:=ilStep[Pass]; End Else Begin Pass:=4; ycnt:=0; ystep:=1; End; OldCode:=0; BitBuf:=0; BitsInBuf:=0; BytInBuf:=0; BytBufIdx:=0; EndCode := 0; ClearCode := 0; StrIdx := 0; CodeSize := 0; Source.Read(@CodeSize,1); InitStringTable(); CurCode := GetNextCode; While (CurCode<>EndCode) And (Pass<5) And (Not EndOfSrc) Do Begin If (CurCode=ClearCode) Then Begin ClearStringTable; Repeat CurCode := GetNextCode; Until (CurCode<>ClearCode); If (CurCode=EndCode) Then Break; WritePixels(CodeToStr(curcode)); OldCode:=CurCode; End Else Begin If (CurCode<StrIdx) Then Begin WritePixels(CodeToStr(CurCode)); AddStrToTab(CodeToStr(OldCode),FirstChar(CodeToStr(CurCode))); OldCode:=CurCode; End Else Begin If (CurCode>StrIdx) Then Break; AddStrToTab(CodeToStr(OldCode),FirstChar(CodeToStr(OldCode))); WritePixels(CodeToStr(StrIdx-1)); OldCode:=CurCode; End; End; Curcode:=GetNextCode; End; DoneStringTable; If Not EndOfSrc Then DumpData(Source); End; Procedure GIFLoader.Load(Source:Stream); var GIFHeader:TERRA_GIF.GIFHeader; GIFBlockID:AnsiChar; GIFImageDescriptor:TERRA_GIF.GIFImageDescriptor; GIFExtensionBlock:TERRA_GIF.GIFExtensionBlock; GIFGraphicControlExtension:TERRA_GIF.GIFGraphicControlExtension; Xd,Yd:Longint; I,K:Integer; Frame:Integer; GlobalPalette,LocalPalette:GIFPalette; Palette:PPalette; RGB:GIFRGB; Interlaced:Boolean; FrameBuffer:Image; Begin TransparencyColor:=-1; Frame:=0; FrameBuffer := Nil; Source.Read(@GIFHeader,SizeOf(GIFHeader)); If (GIFHeader.Signature<>'GIF') Then Begin RaiseError('Invalid header.'); Exit; End; If (GIFHeader.Flags And $80<>0) Then Begin K:=(1 Shl (GIFHeader.Flags And $07+1)); For I:=0 To Pred(K) Do Begin Source.Read(@rgb,3); {$IFDEF RGB} GlobalPalette[i].R := RGB.Red; GlobalPalette[i].G := RGB.Green; GlobalPalette[i].B := RGB.Blue; {$ENDIF} {$IFDEF BGR} GlobalPalette[i].B := RGB.Red; GlobalPalette[i].G := RGB.Green; GlobalPalette[i].R := RGB.Blue; {$ENDIF} GlobalPalette[i].A := 255; End; For I:=K To 255 Do GlobalPalette[i] := ColorBlack; End; Repeat Source.Read(@GIFBlockID,1); Case GIFBlockID Of ';':Begin End; ',':Begin //image separator Palette := @GlobalPalette; Source.Read(@GIFImageDescriptor,SizeOf(GIFImageDescriptor)); If (GIFImageDescriptor.Flags And $80<>0) Then Begin Palette:=@LocalPalette; K:=(2 Shl (GIFImageDescriptor.Flags AND $07)); For I:=0 To Pred(K) Do Begin Source.Read(@rgb,3); LocalPalette[I].R := rgb.Red; LocalPalette[I].G := rgb.Green; LocalPalette[I].B := rgb.Blue; LocalPalette[I].A := 255; End; For I:=K To 255 Do LocalPalette[i] := ColorBlack; End; xd := GIFImageDescriptor.xd; yd := GIFImageDescriptor.yd; If Frame=0 Then Begin MyImage.New(xd, yd); FrameBuffer := Image.Create(xd, yd); End Else MyImage.AddFrame(); Case Frame Mod 4 Of 0: FrameBuffer.FillRectangleByUV(0, 0, 1, 1, ColorRed); 1: FrameBuffer.FillRectangleByUV(0, 0, 1, 1, ColorBlue); 2: FrameBuffer.FillRectangleByUV(0, 0, 1, 1, ColorGreen); 3: FrameBuffer.FillRectangleByUV(0, 0, 1, 1, ColorYellow); End; Interlaced := (GIFImageDescriptor.flags AND $40=$40); DecodeGIFLZW(Source, FrameBuffer, Palette, Interlaced ); // FrameBuffer.Save('debug\temp\bframe'+IntToString(Frame)+'.png'); CopyFrame(FrameBuffer, GIFImageDescriptor.x, GIFImageDescriptor.y, GIFImageDescriptor.xd, GIFImageDescriptor.yd); //MyImage.Save('debug\temp\cframe'+IntToString(Frame)+'.png'); {$IFDEF PIXEL32} MaskFrame(); {$ENDIF} Inc(Frame); End; '!':Begin Source.Read(@GIFExtensionBlock, SizeOf(GIFExtensionBlock)); Case GIFExtensionBlock.FunctionCode Of $F9:Begin Source.Read(@GIFGraphicControlExtension,SizeOf(GIFGraphicControlExtension)); TransparencyColor := GIFGraphicControlExtension.TransparencyColor; DumpData(Source); End; Else DumpData(Source); End; End; Else Exit; End; Until (GIFBlockID=';') Or (Source.EOF); ReleaseObject(FrameBuffer); MyImage.SetCurrentFrame(0); End; Procedure GIFLoad(Source:Stream; MyImage:Image); Var Loader:GIFLoader; Begin Loader := GIFLoader.Create; Loader.MyImage := MyImage; Loader.Load(Source); ReleaseObject(Loader); MyImage.Process(IMP_SetColorKey, ColorCreate(255,0, 255, 255)); End; Function ValidateGIF(Stream:Stream):Boolean; Var ID:Array[1..3] Of AnsiChar; Begin Stream.Read(@ID,3); Result:=(ID='GIF'); End; Begin RegisterImageFormat('GIF', ValidateGIF, GIFLoad); End.
unit DAO.ManutencaoVeiculos; interface uses DAO.base, Model.ManutencaoVeiculos, Generics.Collections, System.Classes; type TManutencaoVeiculosDAO = class(TDAO) public function Insert(aManutencao: Model.ManutencaoVeiculos.TManutencaoVeiculos): Boolean; function Update(aManutencao: Model.ManutencaoVeiculos.TManutencaoVeiculos): Boolean; function Delete(sFiltro: String): Boolean; function FindManutencao(sFiltro: String): TObjectList<Model.ManutencaoVeiculos.TManutencaoVeiculos>; end; const TABLENAME = 'tbmanutencaoveiculos'; implementation uses System.SysUtils, FireDAC.Comp.Client, Data.DB; function TManutencaoVeiculosDAO.Insert(aManutencao: TManutencaoVeiculos): Boolean; var sSQL: String; begin Result := False; aManutencao.ID := GetKeyValue(TABLENAME, 'ID_MANUTENCAO'); sSQL := 'INSERT INTO ' + TABLENAME + ' ' + '(ID_MANUTENCAO, DES_TIPO, COD_VEICULO, COD_MOTORISTA, ID_ITEM, DAT_MANUTENCAO, QTD_KM_MANUTENCAO, DAT_PREVISAO, ' + 'QTD_KM_PREVISAO, VAL_CUSTO_MANUTENCAO, DAT_LIBERACAO, DOM_SITUACAO, DES_OBS, DES_ARQUIVO, COD_CCUSTO, DES_LOG) ' + 'VALUES ' + '(:ID, :TIPO, :VEICULO, :MOTORISTA, :ITEM, :DATAMANUTENCAO, :KMMANUTENCAO, :DATAPREVISAO, :KMPREVISAO, :VALOR, ' + ':DATALIBERACAO, :SITUACAO, :OBS, :ARQUIVO, :CCUSTO, :LOG);'; Connection.ExecSQL(sSQL,[aManutencao.ID, aManutencao.Tipo, aManutencao.Veiculo, aManutencao.Motorista, aManutencao.Item, aManutencao.DataManutencao, aManutencao.KMManutencao, aManutencao.DataPrevisao, aManutencao.KMPrevisao, aManutencao.Valor, aManutencao.DataLiberacao, aManutencao.Situacao, aManutencao.Obs, aManutencao.Arquivo, aManutencao.CCusto, aManutencao.Log], [ftInteger, ftString, ftInteger, ftInteger, ftinteger, ftDate, ftFloat, ftDate, ftFloat, ftFloat, ftDate, ftInteger, ftString, ftString, ftInteger, ftString]); Result := True; end; function TManutencaoVeiculosDAO.Update(aManutencao: TManutencaoVeiculos): Boolean; var sSQL: String; begin Result := False; sSQL := 'UPDATE ' + TABLENAME + ' ' + 'SET ' + 'DES_TIPO = :TIPO, COD_VEICULO = :VEICULO, COD_MOTORISTA = : MOTORISTA, ID_ITEM = :ITEM, ' + 'DAT_MANUTENCAO = :DATAMANUTENCAO, QTD_KM_MANUTENCAO = :KMMANUTENCAO, DAT_PREVISAO = :DATAPREVISAO, ' + 'QTD_KM_PREVISAO = :KMPREVISAO, VAL_CUSTO_MANUTENCAO = :VALOR, DAT_LIBERACAO = :DATALIBERACAO, ' + 'DOM_SITUACAO = :SITUACAO, DES_OBS = :OBS, DES_ARQUIVO = :ARQUIVO, COD_CCUSTO = :CCUSTO, DES_LOG = :LOG ' + 'WHERE ID_MANUTENCAO = :ID;'; Connection.ExecSQL(sSQL,[aManutencao.Tipo, aManutencao.Veiculo, aManutencao.Motorista, aManutencao.Item, aManutencao.DataManutencao, aManutencao.KMManutencao, aManutencao.DataPrevisao, aManutencao.KMPrevisao, aManutencao.Valor, aManutencao.DataLiberacao, aManutencao.Situacao, aManutencao.Obs, aManutencao.Arquivo, aManutencao.CCusto, aManutencao.Log, aManutencao.ID], [FtString, ftInteger, ftInteger, ftinteger, ftDate, ftFloat, ftDate, ftFloat, ftFloat, ftDate, ftInteger, ftString, ftString, ftInteger, ftString, ftInteger]); Result := True; end; function TManutencaoVeiculosDAO.Delete(sFiltro: string): Boolean; var sSQL : String; begin Result := False; sSQL := 'DELETE FROM ' + TABLENAME + ' '; if not sFiltro.IsEmpty then begin sSQl := sSQL + sFiltro; end else begin Exit; end; Result := True; end; function TManutencaoVeiculosDAO.FindManutencao(sFiltro: string): TObjectList<TManutencaoVeiculos>; var FDQuery: TFDQuery; manutencao: TObjectList<TManutencaoVeiculos>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); if not sFiltro.IsEmpty then begin FDQuery.SQL.Add(sFiltro); end; FDQuery.Open(); manutencao := TObjectList<TManutencaoVeiculos>.Create(); while not FDQuery.Eof do begin manutencao.Add(TManutencaoVeiculos.Create(FDQuery.FieldByName('ID_MANUTENCAO').AsInteger, FDQuery.FieldByName('DES_TIPO').AsString, FDQuery.FieldByName('COD_VEICULO').AsInteger, FDQuery.FieldByName('COD_MOTORISTA').AsInteger, FDQuery.FieldByName('ID_ITEM').AsInteger, FDQuery.FieldByName('DAT_MANUTENCAO').AsDateTime, FDQuery.FieldByName('QTD_KM_MANUTENCAO').AsFloat, FDQuery.FieldByName('DAT_PREVISAO').AsDateTime, FDQuery.FieldByName('QTD_KM_PREVISAO').AsFloat, FDQuery.FieldByName('VAL_CUSTO_MANUTENCAO').AsFloat, FDQuery.FieldByName('DAT_LIBERACAO').AsDateTime, FDQuery.FieldByName('DOM_SITUACAO').AsInteger, FDQuery.FieldByName('DES_OBS').AsString, FDQuery.FieldByName('DES_ARQUIVO').AsString, FDQuery.FieldByName('COD_CCUSTO').AsInteger, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := manutencao; end; end.
unit DelphiUp.View.Components.Buttons.Interfaces; interface uses System.SysUtils, System.UITypes, FMX.Types; type iComponentButtonAttributes<T> = interface ['{ACE053BA-1FBC-4AB2-AD65-0D7F7224BEDC}'] function Title ( aValue : String ) : iComponentButtonAttributes<T>; overload; function Title : String; overload; function SubTitle ( aValue : String ) : iComponentButtonAttributes<T>; overload; function SubTitle : String; overload; function Image ( aValue : String ) : iComponentButtonAttributes<T>; overload; function Image : String; overload; function OnClick ( aValue : TProc<TObject> ) : iComponentButtonAttributes<T>; overload; function OnClick : TProc<TObject>; overload; function Background ( aValue : TAlphaColor ) : iComponentButtonAttributes<T>; overload; function Background : TAlphaColor; overload; function DestBackground ( aValue : TAlphaColor ) : iComponentButtonAttributes<T>; overload; function DestBackground : TAlphaColor; overload; function Align ( aValue : TAlignLayout ) : iComponentButtonAttributes<T>; overload; function Align : TAlignLayout; overload; function FontSize ( aValue : Integer ) : iComponentButtonAttributes<T>; overload; function FontSize : Integer; overload; function FontSizeSubTitle ( aValue : Integer ) : iComponentButtonAttributes<T>; overload; function FontSizeSubTitle : Integer; overload; function FontColor ( aValue : TAlphaColor ) : iComponentButtonAttributes<T>; overload; function FontColor : TAlphaColor; overload; function &End : T; end; implementation end.
{$WARNINGS OFF} unit ssGradientPanel; interface uses Windows, SysUtils, Classes, Controls, ExtCtrls, Graphics, ssGraphUtil; type TssGradientPanel = class(TPanel) private FGrStartColor: TColor; FGrEndColor: TColor; FGrDirection: TGradientDirection; FRightMargin: Cardinal; procedure SetGrStartColor(const Value: TColor); procedure SetGrEndColor(const Value: TColor); procedure SetGrDirection(const Value: TGradientDirection); procedure SetRightMargin(const Value: Cardinal); protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; published property GrStartColor: TColor read FGrStartColor write SetGrStartColor; property GrEndColor: TColor read FGrEndColor write SetGrEndColor; property GrDirection: TGradientDirection read FGrDirection write SetGrDirection; property RightMargin: Cardinal read FRightMargin write SetRightMargin default 0; end; //============================================================================================== //============================================================================================== //============================================================================================== implementation uses Types; //============================================================================================== constructor TssGradientPanel.Create(AOwner: TComponent); begin inherited; FGrStartColor := Color; FGrEndColor := Color; end; //============================================================================================== procedure TssGradientPanel.Paint; const Alignments: array[TAlignment] of Longint = (DT_LEFT, DT_RIGHT, DT_CENTER); var TopColor, BottomColor: TColor; FontHeight: integer; Rect: TRect; Flags: Longint; procedure AdjustColors(Bevel: TPanelBevel); begin TopColor := clBtnHighlight; if Bevel = bvLowered then TopColor := clBtnShadow; BottomColor := clBtnShadow; if Bevel = bvLowered then BottomColor := clBtnHighlight; end; begin Rect := ClientRect; if not DrawGradient(Canvas, Rect, FGrStartColor, FGrEndColor, FGrDirection) then begin Canvas.Brush.Color := Color; Canvas.FillRect(ClientRect); end; if BevelOuter <> bvNone then begin AdjustColors(BevelOuter); Frame3D(Canvas, Rect, TopColor, BottomColor, BevelWidth); end; Frame3D(Canvas, Rect, Color, Color, BorderWidth); if BevelInner <> bvNone then begin AdjustColors(BevelInner); Frame3D(Canvas, Rect, TopColor, BottomColor, BevelWidth); end; with Canvas do begin Brush.Style := bsClear; Font := Self.Font; FontHeight := TextHeight('W'); with Rect do begin Left := 18; // reserve for glyph Top := ((Bottom + Top) - FontHeight) div 2; Bottom := Top + FontHeight; Right := Right - RightMargin - Left; end; Flags := DT_EXPANDTABS or DT_VCENTER or Alignments[Alignment]; Flags := DrawTextBiDiModeFlags(Flags); DrawText(Handle, PChar(Caption), -1, Rect, Flags); end; end; //============================================================================================== procedure TssGradientPanel.SetGrDirection(const Value: TGradientDirection); begin FGrDirection := Value; Invalidate; end; //============================================================================================== procedure TssGradientPanel.SetGrEndColor(const Value: TColor); begin FGrEndColor := Value; Invalidate; end; //============================================================================================== procedure TssGradientPanel.SetGrStartColor(const Value: TColor); begin FGrStartColor := Value; Invalidate; end; //============================================================================================== procedure TssGradientPanel.SetRightMargin(const Value: Cardinal); begin FRightMargin := Value; Invalidate; end; end.
unit uExportarDepartamento; interface uses System.SysUtils, System.Classes, uArquivoTexto, uDM, uFireDAC, uDepartamentoVO, System.Generics.Collections, uGenericDAO, uDepartamentoAcessoVO, uExportarDepartamentoAcesso; type TExportarDepartamento = class private FArquivo: string; public procedure Exportar(); function Importar(): TObjectList<TDepartamentoVO>; constructor Create(); overload; end; implementation { TExportarDepartamento } constructor TExportarDepartamento.Create; begin inherited Create; FArquivo := 'D:\DOMPER\SIDomper\Banco\Departamento.txt'; end; procedure TExportarDepartamento.Exportar; var obj: TFireDAC; Arq: TArquivoTexto; DepAcesso: TExportarDepartamentoAcesso; begin obj := TFireDAC.create; Arq := TArquivoTexto.Create(FArquivo, tpExportar); try obj.OpenSQL('SELECT TOP(1) * FROM Departamento'); while not obj.Model.Eof do begin Arq.ExportarInt(obj.Model.FieldByName('Dep_Codigo').AsInteger, 001, 005); Arq.ExportarString(obj.Model.FieldByName('Dep_Nome').AsString, 006, 050); Arq.ExportarBool(obj.Model.FieldByName('Dep_Ativo').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('Dep_SolicitaAbertura').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('Dep_SolicitaAnalise').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('Dep_SolicitaOcorGeral').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('Dep_SolicitaOcorTecnica').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('Dep_SolicitaStatus').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('Dep_SolicitaQuadro').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('Dep_ChamadoAbertura').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('Dep_ChamadoStatus').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('Dep_ChamadoQuadro').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('Dep_ChamadoOcor').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('Dep_AtividadeAbertura').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('Dep_AtividadeStatus').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('Dep_AtividadeQuadro').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('Dep_AtividadeOcor').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('Dep_AgendamentoQuadro').AsBoolean); Arq.ExportarBool(obj.Model.FieldByName('Dep_MostrarAnexos').AsBoolean); Arq.NovaLinha(); obj.Model.Next; end; finally FreeAndNil(obj); FreeAndNil(Arq); end; DepAcesso := TExportarDepartamentoAcesso.Create; try DepAcesso.Exportar(); finally FreeAndNil(DepAcesso); end; end; function TExportarDepartamento.Importar: TObjectList<TDepartamentoVO>; var model: TDepartamentoVO; lista: TObjectList<TDepartamentoVO>; Arq: TArquivoTexto; ArqItem: TArquivoTexto; sArqItem: string; Item: TDepartamentoAcessoVO; begin lista := TObjectList<TDepartamentoVO>.Create(); Arq := TArquivoTexto.Create(FArquivo, tpImportar); sArqItem := 'D:\DOMPER\SIDomper\Banco\DepartamentoAcesso.txt'; ArqItem := TArquivoTexto.Create(sArqItem, tpImportar); try while not (Arq.FimArquivo()) do begin Arq.ProximoRegistro(); model := TDepartamentoVO.Create; model.Id := 0; model.Codigo := Arq.ImportarInt(001, 005); model.Nome := Arq.ImportarString(006, 050); model.Ativo := Arq.ImportarBool(056, 001); model.SolicitacaoAbertura := Arq.ImportarBool(057, 001); model.SolicitacaoAnalise := Arq.ImportarBool(058, 001); model.SolicitacaoOcorrenciaGeral := Arq.ImportarBool(059, 001); model.SolicitacaoOcorrenciaTecnica := Arq.ImportarBool(060, 001); model.SolicitacaoStatus := Arq.ImportarBool(061, 001); model.SolicitacaoQuadro := Arq.ImportarBool(062, 001); model.ChamadoAbertura := Arq.ImportarBool(063, 001); model.ChamadoStatus := Arq.ImportarBool(064, 001); model.ChamadoQuadro := Arq.ImportarBool(065, 001); model.ChamadoOcorrencia := Arq.ImportarBool(066, 001); model.AtividadeAbertura := Arq.ImportarBool(067, 001); model.AtividadeStatus := Arq.ImportarBool(068, 001); model.AtividadeQuadro := Arq.ImportarBool(069, 001); model.AtividadeOcorrencia := Arq.ImportarBool(070, 001); model.AgendamentoQuadro := Arq.ImportarBool(071, 001); model.MostrarAnexos := Arq.ImportarBool(072, 001); while not ArqItem.FimArquivo do begin ArqItem.ProximoRegistro(); Item := TDepartamentoAcessoVO.Create; Item.Id := 0; Item.IdDepartamento := ArqItem.ImportarInt(001,005); Item.Programa := ArqItem.ImportarInt(006,005); Item.Acesso := ArqItem.ImportarBool(011,001); Item.Incluir := ArqItem.ImportarBool(012,001); Item.Editar := ArqItem.ImportarBool(013,001); Item.Excluir := ArqItem.ImportarBool(014,001); Item.Relatorio := ArqItem.ImportarBool(015,001); model.DepartamentoAcesso.Add(Item); end; lista.Add(model); end; finally FreeAndNil(ArqItem); FreeAndNil(Arq); end; Result := lista; end; end.
unit UTipos; interface type TJSONType = (jtJSONDefault, jtJSONFiredac); type TResult = class private FReturnCode: Integer; FErrorMessage: String; FValor: String; procedure SetReturnCode(const Value: Integer); procedure SetErrorMessage(const Value: String); procedure SetValor(const Value: String); protected public published property ReturnCode: Integer read FReturnCode write SetReturnCode; property ErrorMessage: String read FErrorMessage write SetErrorMessage; property Valor: String read FValor write SetValor; end; implementation { TResult } procedure TResult.SetErrorMessage(const Value: String); begin FErrorMessage := Value; end; procedure TResult.SetReturnCode(const Value: Integer); begin FReturnCode := Value; end; procedure TResult.SetValor(const Value: String); begin FValor := Value; end; end.
unit nsTagNodePrim; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "f1DocumentTagsImplementation" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/f1DocumentTagsImplementation/nsTagNodePrim.pas" // Начат: 19.08.2010 15:27 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> F1 Базовые определения предметной области::LegalDomain::f1DocumentTagsImplementation::DocumentTagNodes::TnsTagNodePrim // // Реализация тега, представляющего данные из адаптерной ноды // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses IOUnit, k2Interfaces, l3CustomString, k2Base, k2BaseStruct, nsTagNodePrimPrim, F1TagDataProviderInterface, l3Interfaces, nevBase, DocumentUnit, l3IID ; type DocTagNodeType = F1TagDataProviderInterface.If1TagDataProvider; _StyleParser_Parent_ = TnsTagNodePrimPrim; {$Include ..\f1DocumentTagsImplementation\StyleParser.imp.pas} TnsTagNodePrim = {abstract} class(_StyleParser_) {* Реализация тега, представляющего данные из адаптерной ноды } private // private fields f_TagDataProvider : DocTagNodeType; {* Поле для свойства TagDataProvider} protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } {$If not defined(_Box_) AND not defined(k2TagIsAtomic)} function GetHasSubAtom(aProp: Tk2Prop): Boolean; override; {$IfEnd} //not _Box_ AND not k2TagIsAtomic {$If not defined(_Box_)} function GetSubAtom(aProp: Tk2Prop; out Data: Integer): Boolean; override; {$IfEnd} //not _Box_ procedure IterateProperties(Action: Ik2Tag_IterateProperties_Action; All: Boolean); override; function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; override; {* Реализация запроса интерфейса } procedure SetSubAtom(var aProp: _PropIn_; const aSubAtom); override; function MarkModified: Boolean; override; procedure ClearFields; override; protected // protected fields f_State : TnsNodeStates; protected // protected methods procedure ParseStyle; function GetTextAtomFromCaption(aProp: Tk2Prop; out Data: Integer): Boolean; procedure DoParseStyle; virtual; procedure DoSetSubAtom(var aProp: _PropIn_; const aSubAtom); virtual; function DoGetSubAtom(aProp: Tk2Prop; out Data: Integer): Boolean; virtual; public // public methods procedure ResetStyle; function CheckAtom(aProp: Tk2Prop): Ik2Tag; constructor Create(aType: Tk2Type; const aNode: DocTagNodeType; aState: TnsNodeStates); reintroduce; class function MakeNodeTag(const aNode: DocTagNodeType; aState: TnsNodeStates = []): Ik2Tag; function HasTagDataProvider: Boolean; protected // protected properties property TagDataProvider: DocTagNodeType read f_TagDataProvider write f_TagDataProvider; {* Источник данных тега } end;//TnsTagNodePrim implementation uses nsTagString, k2Tags, SysUtils, k2Facade, k2Const, l3Base, evdVer, DynamicTreeUnit, BitmapPara_Const, nsStyleParser ; type _Instance_R_ = TnsTagNodePrim; {$Include ..\f1DocumentTagsImplementation\StyleParser.imp.pas} // start class TnsTagNodePrim procedure TnsTagNodePrim.ParseStyle; //#UC START# *4C6D1CE80342_467FCCB101CF_var* //#UC END# *4C6D1CE80342_467FCCB101CF_var* begin //#UC START# *4C6D1CE80342_467FCCB101CF_impl* if not (ns_nsStyleParsed in f_State) then begin Include(f_State, ns_nsStyleParsed); DoParseStyle; end;//not (ns_nsStyleParsed in f_State) //#UC END# *4C6D1CE80342_467FCCB101CF_impl* end;//TnsTagNodePrim.ParseStyle function TnsTagNodePrim.GetTextAtomFromCaption(aProp: Tk2Prop; out Data: Integer): Boolean; //#UC START# *4C6D1D74024A_467FCCB101CF_var* //#UC END# *4C6D1D74024A_467FCCB101CF_var* var l_Text : Tl3CustomString; l_String : IString; begin //#UC START# *4C6D1D74024A_467FCCB101CF_impl* Result := false; l_String := f_TagDataProvider.Caption; if (l_String <> nil) then begin l_Text := TnsTagString.Create(l_String); try StoreObjAtom(aProp, l_Text); Result := true; Data := Integer(l_Text); finally FreeAndNil(l_Text); end;//try..finally end;//l_String <> nil //#UC END# *4C6D1D74024A_467FCCB101CF_impl* end;//TnsTagNodePrim.GetTextAtomFromCaption procedure TnsTagNodePrim.ResetStyle; //#UC START# *4C6D1DCA021E_467FCCB101CF_var* //#UC END# *4C6D1DCA021E_467FCCB101CF_var* begin //#UC START# *4C6D1DCA021E_467FCCB101CF_impl* Exclude(f_State, ns_nsStyleParsed); Attr[k2_tiChildren] := nil; //#UC END# *4C6D1DCA021E_467FCCB101CF_impl* end;//TnsTagNodePrim.ResetStyle function TnsTagNodePrim.CheckAtom(aProp: Tk2Prop): Ik2Tag; //#UC START# *4C6D1DEE0339_467FCCB101CF_var* var l_Data : Integer; //#UC END# *4C6D1DEE0339_467FCCB101CF_var* begin //#UC START# *4C6D1DEE0339_467FCCB101CF_impl* if BaseGetSubAtom(aProp, l_Data) then Result := Tk2Type(aProp.AtomType).IntToTag(l_Data) else begin Result := Tk2Type(aProp.AtomType).MakeTag; StoreTagAtom(aProp, Result); end;//BaseGetSubAtom(aProp, l_Data) //#UC END# *4C6D1DEE0339_467FCCB101CF_impl* end;//TnsTagNodePrim.CheckAtom constructor TnsTagNodePrim.Create(aType: Tk2Type; const aNode: DocTagNodeType; aState: TnsNodeStates); //#UC START# *4C6D1E5C03C8_467FCCB101CF_var* //#UC END# *4C6D1E5C03C8_467FCCB101CF_var* begin //#UC START# *4C6D1E5C03C8_467FCCB101CF_impl* f_TagDataProvider := aNode; f_State := aState; inherited Create(aType); //#UC END# *4C6D1E5C03C8_467FCCB101CF_impl* end;//TnsTagNodePrim.Create class function TnsTagNodePrim.MakeNodeTag(const aNode: DocTagNodeType; aState: TnsNodeStates = []): Ik2Tag; //#UC START# *4C6D1E950086_467FCCB101CF_var* var l_Tag : TnsTagNodePrim; l_Type : Tk2Type; //#UC END# *4C6D1E950086_467FCCB101CF_var* begin //#UC START# *4C6D1E950086_467FCCB101CF_impl* if (aNode = nil) then Result := k2NullTag else begin l_Type := k2.TypeTable[aNode.TypeID]; if (l_Type = nil) then Result := k2NullTag else begin l_Tag := Create(l_Type, aNode, aState); try Result := l_Tag; finally FreeAndNil(l_Tag); end;//try..finally end;//l_Type = nil end;//aNode = nil //#UC END# *4C6D1E950086_467FCCB101CF_impl* end;//TnsTagNodePrim.MakeNodeTag function TnsTagNodePrim.HasTagDataProvider: Boolean; //#UC START# *4C6E885102A4_467FCCB101CF_var* //#UC END# *4C6E885102A4_467FCCB101CF_var* begin //#UC START# *4C6E885102A4_467FCCB101CF_impl* Result := (f_TagDataProvider <> nil); //#UC END# *4C6E885102A4_467FCCB101CF_impl* end;//TnsTagNodePrim.HasTagDataProvider procedure TnsTagNodePrim.DoParseStyle; //#UC START# *4C6D1D01003A_467FCCB101CF_var* //#UC END# *4C6D1D01003A_467FCCB101CF_var* begin //#UC START# *4C6D1D01003A_467FCCB101CF_impl* DoDoParseStyle(f_TagDataProvider.Style); //#UC END# *4C6D1D01003A_467FCCB101CF_impl* end;//TnsTagNodePrim.DoParseStyle procedure TnsTagNodePrim.DoSetSubAtom(var aProp: _PropIn_; const aSubAtom); //#UC START# *4C6D1D220147_467FCCB101CF_var* //#UC END# *4C6D1D220147_467FCCB101CF_var* begin //#UC START# *4C6D1D220147_467FCCB101CF_impl* Case aProp{$IfDef XE4}.r_PropInPrim_{$EndIf}.rProp.TagIndex of k2_tiHandle : begin BaseSetSubAtom(aProp, aSubAtom); (* Case aVT of vtInt : f_TagDataProvider.SetNodeId(Integer(aSubAtom)); vtTag : if (Ik2Tag(aSubAtom) = nil) then f_TagDataProvider.SetNodeId(0) else f_TagDataProvider.SetNodeId(Ik2Tag(aSubAtom).AsLong); else Assert(false); end;//Case aVT*) end;//k2_tiHandle else BaseSetSubAtom(aProp, aSubAtom); end;//Case aProp.TagIndex //#UC END# *4C6D1D220147_467FCCB101CF_impl* end;//TnsTagNodePrim.DoSetSubAtom function TnsTagNodePrim.DoGetSubAtom(aProp: Tk2Prop; out Data: Integer): Boolean; //#UC START# *4C6D1D450332_467FCCB101CF_var* //#UC END# *4C6D1D450332_467FCCB101CF_var* begin //#UC START# *4C6D1D450332_467FCCB101CF_impl* Result := true; Case aProp.TagIndex of k2_tiHandle : begin // http://mdp.garant.ru/pages/viewpage.action?pageId=425267808 if Self.InheritsFrom(k2_idBitmapPara) then Result := False else begin if (f_TagDataProvider = nil) then Result := false else begin Data := Integer(f_TagDataProvider.ExternalID); if (Data <> 0) then StoreIntAtom(aProp, Data); end; end; if not Result OR (Data = 0) then begin ParseStyle; Result := BaseGetSubAtom(aProp, Data); end;//not Result OR (Data = 0) end;//k2_tiHandle k2_tiShortName, k2_tiText, k2_tiReqID : begin ParseStyle; Result := BaseGetSubAtom(aProp, Data); if not Result then Result := GetTextAtomFromCaption(aProp, Data); end;//k2_tiShortName k2_tiData : begin ParseStyle; Result := BaseGetSubAtom(aProp, Data); if not Result then begin Assert(false, 'Похоже, что сюда мы уже никогда не попадаем, т.к. получем картинку в TnsBitmapParaPictureGetter.GetPicture, а если так, то это смело можно откручивать с DocumentTextProvoder''а'); // Найдено в результате разборок с http://mdp.garant.ru/pages/viewpage.action?pageId=342866160 // http://mdp.garant.ru/pages/viewpage.action?pageId=342866160&focusedCommentId=342869010&#comment-342869010 //Result := GetStreamAtomFromData(aProp, Data); end;//not Result end;//k2_tiData k2_tiChildren : Result := BaseGetSubAtom(aProp, Data); else begin ParseStyle; Result := BaseGetSubAtom(aProp, Data); end;//else end;//Case aProp.TagIndex //#UC END# *4C6D1D450332_467FCCB101CF_impl* end;//TnsTagNodePrim.DoGetSubAtom procedure TnsTagNodePrim.Cleanup; //#UC START# *479731C50290_467FCCB101CF_var* //#UC END# *479731C50290_467FCCB101CF_var* begin //#UC START# *479731C50290_467FCCB101CF_impl* inherited; f_TagDataProvider := nil; //#UC END# *479731C50290_467FCCB101CF_impl* end;//TnsTagNodePrim.Cleanup {$If not defined(_Box_) AND not defined(k2TagIsAtomic)} function TnsTagNodePrim.GetHasSubAtom(aProp: Tk2Prop): Boolean; //#UC START# *49A544E802B2_467FCCB101CF_var* var l_Stream : IStream; //#UC END# *49A544E802B2_467FCCB101CF_var* begin //#UC START# *49A544E802B2_467FCCB101CF_impl* if (aProp <> nil) then begin Case aProp.TagIndex of k2_tiExternalHandle, k2_tiHandle, k2_tiShortName, k2_tiText, k2_tiAllChildrenCount : Result := true; (* k2_tiData : begin l_Stream := f_TagDataProvider.Data; Result := (l_Stream <> nil); end;//k2_tiData*) else begin ParseStyle; Result := inherited GetHasSubAtom(aProp); end;//else end;//Case aProp.TagIndex end//(aProp <> nil) else Result := inherited GetHasSubAtom(aProp); //#UC END# *49A544E802B2_467FCCB101CF_impl* end;//TnsTagNodePrim.GetHasSubAtom {$IfEnd} //not _Box_ AND not k2TagIsAtomic {$If not defined(_Box_)} function TnsTagNodePrim.GetSubAtom(aProp: Tk2Prop; out Data: Integer): Boolean; //#UC START# *49A54517029C_467FCCB101CF_var* //#UC END# *49A54517029C_467FCCB101CF_var* begin //#UC START# *49A54517029C_467FCCB101CF_impl* Assert(aProp <> nil); (* if (aProp = nil) then Result := BaseGetSubAtom(aProp, Data) else*) Result := DoGetSubAtom(aProp, Data); //#UC END# *49A54517029C_467FCCB101CF_impl* end;//TnsTagNodePrim.GetSubAtom {$IfEnd} //not _Box_ procedure TnsTagNodePrim.IterateProperties(Action: Ik2Tag_IterateProperties_Action; All: Boolean); //#UC START# *49A545D501F6_467FCCB101CF_var* var l_A : Ik2Tag; //#UC END# *49A545D501F6_467FCCB101CF_var* begin //#UC START# *49A545D501F6_467FCCB101CF_impl* if not All then begin ParseStyle; // - чтобы вычитать все свойства из стиля l_A := Attr[k2_tiHandle]; // http://mdp.garant.ru/pages/viewpage.action?pageId=356071766&focusedCommentId=469798191#comment-469798191 // if l_A.IsValid AND (l_A.AsLong <> 0) then // Action(l_A, Tk2Prop(TagType.Prop[k2_tiHandle])); end;//not All inherited; //#UC END# *49A545D501F6_467FCCB101CF_impl* end;//TnsTagNodePrim.IterateProperties function TnsTagNodePrim.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; //#UC START# *4A60B23E00C3_467FCCB101CF_var* //#UC END# *4A60B23E00C3_467FCCB101CF_var* begin //#UC START# *4A60B23E00C3_467FCCB101CF_impl* if IID.EQ(DocTagNodeType) then begin if (f_TagDataProvider = nil) then Result.SetNoInterface else begin Result.SetOk; DocTagNodeType(Obj) := f_TagDataProvider; end;//f_TagDataProvider = nil end//IID.EQ(DocTagNodeType) else if IID.EQ(IDocumentTextProvider) then begin if (f_TagDataProvider = nil) then Result.SetNoInterface else begin Result.SetOk; IDocumentTextProvider(Obj) := f_TagDataProvider.AsDocumentTextProvider; if (IDocumentTextProvider(Obj) <> nil) then Result.SetOk else Result.SetNoInterface; end;//f_TagDataProvider = nil end//IID.EQ(DocTagNodeType) else if IID.SomeOf([INodeBase]) then begin Result.SetNoInterface; Assert(false, 'Устаревший код'); end//IID.SomeOf([INodeBase]) else Result := inherited COMQueryInterface(IID, Obj); //#UC END# *4A60B23E00C3_467FCCB101CF_impl* end;//TnsTagNodePrim.COMQueryInterface procedure TnsTagNodePrim.SetSubAtom(var aProp: _PropIn_; const aSubAtom); //#UC START# *4C6D1C070249_467FCCB101CF_var* //#UC END# *4C6D1C070249_467FCCB101CF_var* begin //#UC START# *4C6D1C070249_467FCCB101CF_impl* if (aProp{$IfDef XE4}.r_PropInPrim_{$EndIf}.rProp = nil) then BaseSetSubAtom(aProp, aSubAtom) else DoSetSubAtom(aProp, aSubAtom); //#UC END# *4C6D1C070249_467FCCB101CF_impl* end;//TnsTagNodePrim.SetSubAtom function TnsTagNodePrim.MarkModified: Boolean; //#UC START# *4C6D1C29031F_467FCCB101CF_var* //#UC END# *4C6D1C29031F_467FCCB101CF_var* begin //#UC START# *4C6D1C29031F_467FCCB101CF_impl* Result := true; //#UC END# *4C6D1C29031F_467FCCB101CF_impl* end;//TnsTagNodePrim.MarkModified procedure TnsTagNodePrim.ClearFields; {-} begin TagDataProvider := nil; inherited; end;//TnsTagNodePrim.ClearFields end.
unit TrackDeviceLastLocationHistoryUnit; interface uses SysUtils, BaseExampleUnit; type TTrackDeviceLastLocationHistory = class(TBaseExample) public procedure Execute(RouteId: String); end; implementation uses EnumsUnit, DataObjectUnit, TrackingHistoryUnit; procedure TTrackDeviceLastLocationHistory.Execute(RouteId: String); var ErrorString: String; Route: TDataObjectRoute; HistoryStep: TTrackingHistory; begin Route := Route4MeManager.Tracking.GetLastLocation(RouteId, ErrorString); try WriteLn(''); if (Route <> nil) then begin WriteLn('TrackDeviceLastLocationHistory executed successfully'); WriteLn(''); WriteLn(Format('Optimization Problem ID: %s', [Route.OptimizationProblemId])); WriteLn(Format('State: %s', [TOptimizationDescription[TOptimizationState(Route.State)]])); WriteLn(''); for HistoryStep in Route.TrackingHistories do begin WriteLn(Format('Speed: %f', [HistoryStep.Speed.Value])); WriteLn(Format('Longitude: %f', [HistoryStep.Longitude.Value])); WriteLn(Format('Latitude: %f', [HistoryStep.Latitude.Value])); WriteLn(Format('Time Stamp: %s', [HistoryStep.TimeStamp.Value])); WriteLn(''); end; end else WriteLn(Format('TrackDeviceLastLocationHistory error: "%s"', [ErrorString])); finally FreeAndNil(Route); end; end; end.
unit DocumentPrintAndExportFontSizeSettingRes; {* Ресурсы для настройки "Использовать для экспорта и печати следующий размер шрифта" } // Модуль: "w:\common\components\SandBox\VCM\View\Document\DocumentPrintAndExportFontSizeSettingRes.pas" // Стереотип: "UtilityPack" // Элемент модели: "DocumentPrintAndExportFontSizeSettingRes" MUID: (F2DB96F6C0D4) {$Include w:\common\components\SandBox\VCM\sbDefine.inc} interface uses l3IntfUses , l3StringIDEx , afwInterfaces , l3Interfaces , l3CProtoObject ; const {* Локализуемые строки PrintAndExportFontSizeName } str_PrintAndExportFontSize: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExportFontSize'; rValue : 'Использовать для экспорта и печати следующий размер шрифта'); {* Использовать для экспорта и печати следующий размер шрифта } pi_Document_PrintAndExportFontSize = 'Документ/Использовать для экспорта и печати следующий размер шрифта'; {* Идентификатор настройки "Использовать для экспорта и печати следующий размер шрифта" } dv_Document_PrintAndExportFontSize = 0; {* Значение по-умолчанию настройки "Использовать для экспорта и печати следующий размер шрифта" } {* Локализуемые строки PrintAndExportFontSizeValues } str_PrintAndExportFontSize_pef8: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExportFontSize_pef8'; rValue : '8'); {* 8 } str_PrintAndExportFontSize_pef9: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExportFontSize_pef9'; rValue : '9'); {* 9 } str_PrintAndExportFontSize_pef10: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExportFontSize_pef10'; rValue : '10'); {* 10 } str_PrintAndExportFontSize_pef11: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExportFontSize_pef11'; rValue : '11'); {* 11 } str_PrintAndExportFontSize_pef12: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExportFontSize_pef12'; rValue : '12'); {* 12 } str_PrintAndExportFontSize_pef14: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExportFontSize_pef14'; rValue : '14'); {* 14 } str_PrintAndExportFontSize_pef16: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExportFontSize_pef16'; rValue : '16'); {* 16 } type PrintAndExportFontSizeEnum = ( {* Ключи для настройки "Использовать для экспорта и печати следующий размер шрифта" } KEY_PrintAndExportFontSize_pef8 {* 8 } , KEY_PrintAndExportFontSize_pef9 {* 9 } , KEY_PrintAndExportFontSize_pef10 {* 10 } , KEY_PrintAndExportFontSize_pef11 {* 11 } , KEY_PrintAndExportFontSize_pef12 {* 12 } , KEY_PrintAndExportFontSize_pef14 {* 14 } , KEY_PrintAndExportFontSize_pef16 {* 16 } );//PrintAndExportFontSizeEnum PrintAndExportFontSizeValuesMapHelper = {final} class {* Утилитный класс для преобразования значений PrintAndExportFontSizeValuesMap } public class procedure FillStrings(const aStrings: IafwStrings); {* Заполнение списка строк значениями } class function DisplayNameToValue(const aDisplayName: Il3CString): PrintAndExportFontSizeEnum; {* Преобразование строкового значения к порядковому } end;//PrintAndExportFontSizeValuesMapHelper TPrintAndExportFontSizeValuesMapImplPrim = {abstract} class(Tl3CProtoObject, Il3IntegerValueMap) {* Класс для реализации мапы для PrintAndExportFontSizeValuesMap } protected function pm_GetMapID: Tl3ValueMapID; procedure GetDisplayNames(const aList: Il3StringsEx); {* заполняет список значениями "UI-строка" } function MapSize: Integer; {* количество элементов в мапе. } function DisplayNameToValue(const aDisplayName: Il3CString): Integer; function ValueToDisplayName(aValue: Integer): Il3CString; public class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TPrintAndExportFontSizeValuesMapImplPrim } end;//TPrintAndExportFontSizeValuesMapImplPrim TPrintAndExportFontSizeValuesMapImpl = {final} class(TPrintAndExportFontSizeValuesMapImplPrim) {* Класс для реализации мапы для PrintAndExportFontSizeValuesMap } public class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TPrintAndExportFontSizeValuesMapImpl } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } end;//TPrintAndExportFontSizeValuesMapImpl const {* Карта преобразования локализованных строк PrintAndExportFontSizeValues } PrintAndExportFontSizeValuesMap: array [PrintAndExportFontSizeEnum] of Pl3StringIDEx = ( @str_PrintAndExportFontSize_pef8 , @str_PrintAndExportFontSize_pef9 , @str_PrintAndExportFontSize_pef10 , @str_PrintAndExportFontSize_pef11 , @str_PrintAndExportFontSize_pef12 , @str_PrintAndExportFontSize_pef14 , @str_PrintAndExportFontSize_pef16 ); implementation uses l3ImplUses , l3MessageID , l3String , SysUtils , l3Base ; var g_TPrintAndExportFontSizeValuesMapImpl: Pointer = nil; {* Экземпляр синглетона TPrintAndExportFontSizeValuesMapImpl } procedure TPrintAndExportFontSizeValuesMapImplFree; {* Метод освобождения экземпляра синглетона TPrintAndExportFontSizeValuesMapImpl } begin IUnknown(g_TPrintAndExportFontSizeValuesMapImpl) := nil; end;//TPrintAndExportFontSizeValuesMapImplFree class procedure PrintAndExportFontSizeValuesMapHelper.FillStrings(const aStrings: IafwStrings); {* Заполнение списка строк значениями } var l_Index: PrintAndExportFontSizeEnum; begin aStrings.Clear; for l_Index := Low(l_Index) to High(l_Index) do aStrings.Add(PrintAndExportFontSizeValuesMap[l_Index].AsCStr); end;//PrintAndExportFontSizeValuesMapHelper.FillStrings class function PrintAndExportFontSizeValuesMapHelper.DisplayNameToValue(const aDisplayName: Il3CString): PrintAndExportFontSizeEnum; {* Преобразование строкового значения к порядковому } var l_Index: PrintAndExportFontSizeEnum; begin for l_Index := Low(l_Index) to High(l_Index) do if l3Same(aDisplayName, PrintAndExportFontSizeValuesMap[l_Index].AsCStr) then begin Result := l_Index; Exit; end;//l3Same.. raise Exception.CreateFmt('Display name "%s" not found in map "PrintAndExportFontSizeValuesMap"', [l3Str(aDisplayName)]); end;//PrintAndExportFontSizeValuesMapHelper.DisplayNameToValue class function TPrintAndExportFontSizeValuesMapImplPrim.Make: Il3IntegerValueMap; {* Фабричный метод для TPrintAndExportFontSizeValuesMapImplPrim } var l_Inst : TPrintAndExportFontSizeValuesMapImplPrim; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TPrintAndExportFontSizeValuesMapImplPrim.Make function TPrintAndExportFontSizeValuesMapImplPrim.pm_GetMapID: Tl3ValueMapID; begin l3FillChar(Result, SizeOf(Result)); Assert(false); end;//TPrintAndExportFontSizeValuesMapImplPrim.pm_GetMapID procedure TPrintAndExportFontSizeValuesMapImplPrim.GetDisplayNames(const aList: Il3StringsEx); {* заполняет список значениями "UI-строка" } begin PrintAndExportFontSizeValuesMapHelper.FillStrings(aList); end;//TPrintAndExportFontSizeValuesMapImplPrim.GetDisplayNames function TPrintAndExportFontSizeValuesMapImplPrim.MapSize: Integer; {* количество элементов в мапе. } begin Result := Ord(High(PrintAndExportFontSizeEnum)) - Ord(Low(PrintAndExportFontSizeEnum)); end;//TPrintAndExportFontSizeValuesMapImplPrim.MapSize function TPrintAndExportFontSizeValuesMapImplPrim.DisplayNameToValue(const aDisplayName: Il3CString): Integer; begin Result := Ord(PrintAndExportFontSizeValuesMapHelper.DisplayNameToValue(aDisplayName)); end;//TPrintAndExportFontSizeValuesMapImplPrim.DisplayNameToValue function TPrintAndExportFontSizeValuesMapImplPrim.ValueToDisplayName(aValue: Integer): Il3CString; begin Assert(aValue >= Ord(Low(PrintAndExportFontSizeEnum))); Assert(aValue <= Ord(High(PrintAndExportFontSizeEnum))); Result := PrintAndExportFontSizeValuesMap[PrintAndExportFontSizeEnum(aValue)].AsCStr; end;//TPrintAndExportFontSizeValuesMapImplPrim.ValueToDisplayName class function TPrintAndExportFontSizeValuesMapImpl.Make: Il3IntegerValueMap; {* Фабричный метод для TPrintAndExportFontSizeValuesMapImpl } begin if (g_TPrintAndExportFontSizeValuesMapImpl = nil) then begin l3System.AddExitProc(TPrintAndExportFontSizeValuesMapImplFree); Il3IntegerValueMap(g_TPrintAndExportFontSizeValuesMapImpl) := inherited Make; end; Result := Il3IntegerValueMap(g_TPrintAndExportFontSizeValuesMapImpl); end;//TPrintAndExportFontSizeValuesMapImpl.Make class function TPrintAndExportFontSizeValuesMapImpl.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TPrintAndExportFontSizeValuesMapImpl <> nil; end;//TPrintAndExportFontSizeValuesMapImpl.Exists initialization str_PrintAndExportFontSize.Init; {* Инициализация str_PrintAndExportFontSize } str_PrintAndExportFontSize_pef8.Init; {* Инициализация str_PrintAndExportFontSize_pef8 } str_PrintAndExportFontSize_pef9.Init; {* Инициализация str_PrintAndExportFontSize_pef9 } str_PrintAndExportFontSize_pef10.Init; {* Инициализация str_PrintAndExportFontSize_pef10 } str_PrintAndExportFontSize_pef11.Init; {* Инициализация str_PrintAndExportFontSize_pef11 } str_PrintAndExportFontSize_pef12.Init; {* Инициализация str_PrintAndExportFontSize_pef12 } str_PrintAndExportFontSize_pef14.Init; {* Инициализация str_PrintAndExportFontSize_pef14 } str_PrintAndExportFontSize_pef16.Init; {* Инициализация str_PrintAndExportFontSize_pef16 } end.