text
stringlengths
14
6.51M
Function nbChildTopLeft(var tab : arr; y, x: Integer) : Integer; Begin nbChildTopLeft := tab[y, x + 1] + tab[y + 1, x] + tab[y + 1, x + 1]; End; Function nbChildTopRight(var tab : arr; y, x : Integer) : Integer; Begin nbChildTopRight := tab[y, x - 1] + tab[y + 1, x] + tab[y + 1, x - 1]; End; Function nbChildTop(var tab : arr; y, x : Integer) : Integer; Begin nbChildTop := tab[y, x -1] + tab[y, x + 1] + tab[y + 1, x] + tab[y + 1, x - 1] + tab[y + 1, x + 1] ; End; Function nbChildBottomLeft(var tab : arr; y, x: Integer) : Integer; Begin nbChildBottomLeft := tab[y, x + 1] + tab[y - 1, x] + tab[y - 1, x + 1]; End; Function nbChildBottomRight(var tab : arr; y, x: Integer) : Integer; Begin nbChildBottomRight := tab[y, x -1] + tab[y - 1, x] + tab[y - 1, x -1]; End; Function nbChildBottom(var tab : arr; y, x: Integer) : Integer; Begin nbChildBottom := tab[y, x - 1] + tab[y, x + 1] + tab[y - 1, x] + tab[y - 1, x - 1] + tab[y -1, x + 1]; End; Function nbChildLeft(var tab : arr; y, x: Integer) : Integer; Begin nbChildLeft := tab[y, x + 1] + tab[y - 1, x] + tab[y - 1, x +1] + tab[y + 1, x] + tab[y + 1, x + 1]; End; Function nbChildRight(var tab : arr; y, x: Integer) : Integer; Begin nbChildRight := tab[y, x - 1] + tab[y - 1, x] + tab[y - 1, x - 1] + tab[y + 1, x] + tab[y + 1, x - 1]; End; Function nbChildNormal(var tab : arr; y, x: Integer) : Integer; Begin nbChildNormal := tab[y, x + 1] + tab[y + 1, x + 1] + tab[y + 1, x] + tab[y + 1, x - 1] + tab[y, x - 1] + tab[y - 1, x - 1] + tab[y - 1, x] + tab[y - 1, x - 1]; End;
{ COUNTERS Auteur : Bacterius. Utilisez les fonctions suivantes pour insérer un ou plusieurs compteurs dans votre application. Ce qu'il faut bien comprendre dans ce compteur, c'est qu'il possède deux états implicites : - l'état "comptant", où il contient les valeurs de départ de l'horloge, qui sont inutilisables. - l'état "compté", où il contient les valeurs exactes de temps entre le départ et la fin. Les différentes fonctions font basculer un compteur dans un de ces états, voici ces états : InitializeCounter : Passe en comptant. ResetCounter : Passe en comptant. ChangePrecision : Passe en comptant. QueryCounter : Passe en compté. ReleaseCounter : N/A. Ainsi, vous ne pourrez utiliser les valeurs du compteur que après un appel à QueryCounter. Attention : QueryCounter ne modifie PAS la valeur du compteur, il renvoie la différence de temps entre l'appel à ResetCounter et entre l'appel à QueryCounter. L'ordre normal des appels aux fonctions serait alors : 1. InitializeCounter 2. QueryCounter | Effectuer le 2. et le 3. autant de fois que nécessaire. 3. ResetCounter | Eventuellement glisser un SwitchMode à la place du 3. 4. ReleaseCounter Remarques : ¤ Le compteur calcule ses temps sur les temps de l'horloge haute précision, les temps sont donc en virgule flottante (comme 454.56 ms, 72837.12 µs ...). En revanche, si vous ne possédez pas d'horloge haute précision, toutes les précisions au-dessus de 1000 donneront 0 et pour la précision 1000 et inférieur (milliseconde et inférieur), QueryCounter renverra un nombre entier. Pour savoir si vous possédez cette horloge, vérifiez que QueryPerformanceCounter renvoie True (ou bien vérifiez que HighResFound de cette unité est bien à True, puisqu'elle se base sur le résultat de QueryPerformanceCounter). ¤ Vous pouvez utiliser un type PCounter ou bien un type Pointer pour utiliser le compteur. Il est plus sûr d'utiliser un type Pointer car cela empêchera des modifications non désirées de la valeur ou de la précision du compteur, et vous devrez utiliser GetCounterPrecision pour récupérer la précision du compteur. Si vous utilisez PCounter, vous pouvez directement accéder aux champs du compteur, mais ne les modifiez pas directement, utilisez les fonctions prévues à cet effet. ¤ Vous pouvez maintenant utiliser la classe TCounter si vous préférez manipuler des objets. } unit Counters; interface uses Windows, SysUtils; const { Des constantes pour savoir ce que le compteur gère } SECONDS = 1; { Le compteur gère les secondes } MILLISECONDS = 1000; { Le compteur gère les millisecondes } MICROSECONDS = 1000000; { Le compteur gère les microsecondes } NANOSECONDS = 1000000000; { Le compteur gère les nanosecondes } type _COUNTER = record { Un compteur - le type objet ne sera pas utilisé } Precision: Longword; { La précision du compteur (1 : secondes, 1000 : ms, 1000000 : µs } Value: Extended; { La valeur actuelle du compteur en millisecondes ou en microsecondes } end; PCounter = ^_COUNTER; { Un pointeur sur un compteur : sera utilisé dans les fonctions } { InitializeCounter va créer un compteur, et appeller ensuite ChangePrecision (qui appelle ResetCounter) } function InitializeCounter(Precision: Longword): PCounter; { ResetCounter va redéfinir les valeurs du compteur à l'horloge actuelle } function ResetCounter(Counter: PCounter): Boolean; { ChangePrecision permet de changer le mode d'un compteur, puis appeller ResetCounter } function ChangePrecision(Counter: PCounter; NewPrec: Longword): Boolean; { QueryCounter va mettre à jour les valeurs du compteur } function QueryCounter(Counter: PCounter): Extended; { Renvoie la précision du compteur - utile si l'on utilise un type Pointer pour le compteur } function GetCounterPrecision(Counter: PCounter): Longword; { ReleaseCounter va libérer un compteur créé avec InitializeCounter } function ReleaseCounter(Counter: PCounter): Boolean; type TCounter = class { Classe TCounter } private FCounter: PCounter; { Champ objet pour le compteur } function GetValue: Extended; { Récupération de la valeur du compteur } function GetPrecision: Longword; { Récupération de la prec. du compteur } procedure SetPrecision(Value: Longword); { Définition de la prec. du compteur } public constructor Create(Precision: Longword); reintroduce; { Création de TCounter } destructor Destroy; override; { Destruction de TCounter } procedure Reset; { Remise à 0 du compteur } property Value: Extended read GetValue; { Propriété Value } property Precision: Longword read GetPrecision write SetPrecision; { Propriété Precision } end; Var HighResFound: Boolean; Tmp: PInt64; implementation function GetTckCount(Precision: Longword): Extended; { Récupère le temps de l'horloge } Var Freq, Bgn: Int64; begin if not HighResFound then begin { En dessous de millisecondes non disponible } Result := 0; if Precision <= 1000 then Result := GetTickCount div Abs(Precision - 999); Exit; { On s'en va } end; QueryPerformanceFrequency(Freq); { On récupère la fréquence de l'horloge } QueryPerformanceCounter(Bgn); { On récupère le temps actuel } Result := Bgn * Precision / Freq; { On le formate pour obtenir le temps en microsecondes } end; { InitializeCounter crée un compteur, puis appelle ResetCounter avec le mode spécifié } function InitializeCounter(Precision: Longword): PCounter; begin New(Result); { Création du pointeur vers le compteur } ChangePrecision(Result, Precision); { Appelle SwitchMode pour définir la précision du compteur } end; { ResetCounter va basculer le compteur en mode comptant } function ResetCounter(Counter: PCounter): Boolean; begin Result := Assigned(Counter); { On vérifie que le compteur soit bien initialisé } if Result then { Si il l'est ... } with Counter^ do Value := GetTckCount(Precision); { On remet la valeur de l'horloge } end; { ChangePrecision va modifier le mode d'un compteur et appeller ResetCounter ensuite } function ChangePrecision(Counter: PCounter; NewPrec: Longword): Boolean; begin Result := False; if Assigned(Counter) then { On vérifie que le compteur soit initialisé } begin if NewPrec = Counter.Precision then Exit; { Si on ne change pas de précision, on s'en va direct } Counter.Precision := NewPrec; { On modifie le mode } Result := ResetCounter(Counter); { Puis on appelle ResetCounter } end; end; { QueryCounter va faire basculer le compteur en mode compté. Vous pourrez alors utiliser ses valeurs selon l'unité de temps choisie (ms ou µs ). } function QueryCounter(Counter: PCounter): Extended; begin Result := 0; { Valeur à 0, en cas de problème } if Assigned(Counter) then { Si le compteur est bien initialisé ... } with Counter^ do Result := GetTckCount(Precision) - Value; { On calcule le temps écoulé } { ... depuis l'appel à ResetCounter } end; { Renvoie la précision du compteur - utile si l'on utilise un type Pointer pour le compteur } function GetCounterPrecision(Counter: PCounter): Longword; begin Result := High(Longword); { Résultat non valable pour commencer } if Assigned(Counter) then Result := Counter.Precision; { On récupère le mode du compteur } end; { ReleaseCounter va libérer un compteur créé avec InitializeCounter} function ReleaseCounter(Counter: PCounter): Boolean; begin Result := Assigned(Counter); { On vérifie que le compteur soit bien initialisé } if Result then Dispose(Counter); { Le cas échéant, on le libère } end; {-------------------------------- TCOUNTER ------------------------------------} constructor TCounter.Create(Precision: Longword); { Création du TCounter } begin inherited Create; { On crée l'objet } FCounter := InitializeCounter(Precision); { On initialise le compteur } end; destructor TCounter.Destroy; { Destruction du TCounter } begin ReleaseCounter(FCounter); { On libère le compteur } inherited Destroy; { On détruit l'objet } end; procedure TCounter.Reset; { Remise à 0 du compteur } begin ResetCounter(FCounter); { On remet à 0 } end; function TCounter.GetValue: Extended; { Récupération de la valeur du compteur } begin Result := QueryCounter(FCounter); { On récupère avec QueryCounter } end; function TCounter.GetPrecision: Longword; { Récupération du mode du compteur } begin Result := GetCounterPrecision(FCounter); { On récupère avec GetCounterPrecision } end; procedure TCounter.SetPrecision(Value: Longword); { Définition du mode du compteur } begin ChangePrecision(FCounter, Value); { On change avec ChangePrecision. Pas besoin de vérifier si l'on met une precision différente, la fonction s'en occupe ! } end; initialization New(Tmp); HighResFound := QueryPerformanceCounter(Tmp^); Dispose(Tmp); { Si QueryPerformanceCounter renvoie True, vous pourrez utiliser toutes les fonctions du compteur. Sinon, vous ne pourrez pas utiliser les très petites précisions et vous aurez une précision moindre sur les millisecondes. Mais rassurez-vous, de nos jours tous les PC ont des horloges haute précision ! :p } end.
unit clPessoaF; interface type TPessoaF = Class(TObject) private function getAlias: String; function getCategoriaCNH: String; function getCNH: String; function getCPF: String; function getDataRG: TDate; function getEstadoCivil: String; function getNaturalidade: String; function getNome: String; function getNomeConjuge: String; function getNomeMae: String; function getNomePai: String; function getNumeroCTPS: String; function getOrgaoRG: String; function getPIS: String; function getRG: String; function getSerieCTPS: String; function getTipoDoc: String; function getUFCTPS: String; function getUFNatural: String; function getUFRG: String; function getValidadeCNH: TDate; procedure setAlias(const Value: String); procedure setCategoriaCNH(const Value: String); procedure setCNH(const Value: String); procedure setCPF(const Value: String); procedure setDataRG(const Value: TDate); procedure setEstadoCivil(const Value: String); procedure setNaturalidade(const Value: String); procedure setNome(const Value: String); procedure setNomeConjuge(const Value: String); procedure setNomeMae(const Value: String); procedure setNomePai(const Value: String); procedure setNumeroCTPS(const Value: String); procedure setOrgaoRG(const Value: String); procedure setPIS(const Value: String); procedure setRG(const Value: String); procedure setSerieCTPS(const Value: String); procedure setTipoDoc(const Value: String); procedure setUFCTPS(const Value: String); procedure setUFNatural(const Value: String); procedure setUFRG(const Value: String); procedure setValidadeCNH(const Value: TDate); function getAgencia: String; function getBanco: String; function getCpfCnpjFavorecido: String; function getFavorecido: String; function getForma: String; function getNumeroConta: String; function getTipoConta: String; procedure setAgencia(const Value: String); procedure setBanco(const Value: String); procedure setCpfCnpjFavorecido(const Value: String); procedure setFavorecido(const Value: String); procedure setForma(const Value: String); procedure setNumeroConta(const Value: String); procedure setTipoConta(const Value: String); function getCNHRegistro: String; procedure setCNHRegistro(const Value: String); function getCNHUF: String; procedure setCNHUF(const Value: String); function getDataPrimeiraCNH: TDate; procedure setDataPrimeiraCN(const Value: TDate); function getDtNascimento: TDate; procedure setDtNascimento(const Value: TDate); function getEmissaoCNH: TDate; procedure setEmissaoCNH(const Value: TDate); function getCodigoCNH: String; procedure setCodigoCNH(const Value: String); protected _cpf: String; _tipodoc: String; _nascimento: TDate; _nome: String; _alias: String; _rg: String; _ufrg: String; _orgaorg: String; _datarg: TDate; _naturalidade: String; _ufnatural: String; _numeroctps: String; _seriectps: String; _ufctps: String; _pis: String; _codcnh: String; _cnh: String; _cnhregistro: String; _categoriacnh: String; _validadecnh: TDate; _emissaoCNH: TDate; _cnhuf: String; _dataprimeiracnh: TDate; _nomepai: String; _nomemae: String; _estadocivil: String; _nomeconjuge: String; _forma: String; _tipoconta: String; _codigobanco: String; _codigoagencia: String; _numeroconta: String; _favorecido: String; _cpfcnpjfavorecido: String; public property CPF: String read getCPF write setCPF; property TipoDoc: String read getTipoDoc write setTipoDoc; property DtNascimento: TDate read getDtNascimento write setDtNascimento; property Nome: String read getNome write setNome; property Alias: String read getAlias write setAlias; property RG: String read getRG write setRG; property UFRG: String read getUFRG write setUFRG; property OrgaoRG: String read getOrgaoRG write setOrgaoRG; property DataRG: TDate read getDataRG write setDataRG; property Naturalidade: String read getNaturalidade write setNaturalidade; property UFNatural: String read getUFNatural write setUFNatural; property NumeroCTPS: String read getNumeroCTPS write setNumeroCTPS; property SerieCTPS: String read getSerieCTPS write setSerieCTPS; property UFCTPS: String read getUFCTPS write setUFCTPS; property PIS: String read getPIS write setPIS; property CNH: String read getCNH write setCNH; property CodigoCNH: String read getCodigoCNH write setCodigoCNH; property CNHRegistro: String read getCNHRegistro write setCNHRegistro; property CategoriaCNH: String read getCategoriaCNH write setCategoriaCNH; property ValidadeCNH: TDate read getValidadeCNH write setValidadeCNH; property EmissaoCNH: TDate read getEmissaoCNH write setEmissaoCNH; property CNHUF: String read getCNHUF write setCNHUF; property DataPrimeiraCNH: TDate read getDataPrimeiraCNH write setDataPrimeiraCN; property NomePai: String read getNomePai write setNomePai; property NomeMae: String read getNomeMae write setNomeMae; property EstadoCivil: String read getEstadoCivil write setEstadoCivil; property NomeConjuge: String read getNomeConjuge write setNomeConjuge; property Forma: String read getForma write setForma; property TipoConta: String read getTipoConta write setTipoConta; property Banco: String read getBanco write setBanco; property Agencia: String read getAgencia write setAgencia; property NumeroConta: String read getNumeroConta write setNumeroConta; property Favorecido: String read getFavorecido write setFavorecido; property CpfCnpjFavorecido: String read getCpfCnpjFavorecido write setCpfCnpjFavorecido; end; implementation { TPessoaF } function TPessoaF.getAgencia: String; begin Result := _codigoagencia; end; function TPessoaF.getAlias: String; begin Result := _alias; end; function TPessoaF.getBanco: String; begin Result := _codigobanco; end; function TPessoaF.getCategoriaCNH: String; begin Result := _categoriacnh; end; function TPessoaF.getCNH: String; begin Result := _cnh; end; function TPessoaF.getCNHRegistro: String; begin Result := _cnhregistro; end; function TPessoaF.getCNHUF: String; begin Result := _cnhuf; end; function TPessoaF.getCodigoCNH: String; begin Result := _codcnh; end; function TPessoaF.getCPF: String; begin Result := _cpf; end; function TPessoaF.getCpfCnpjFavorecido: String; begin Result := _cpfcnpjfavorecido; end; function TPessoaF.getDataPrimeiraCNH: TDate; begin Result := _dataprimeiracnh; end; function TPessoaF.getDataRG: TDate; begin Result := _datarg; end; function TPessoaF.getDtNascimento: TDate; begin Result := _nascimento; end; function TPessoaF.getEmissaoCNH: TDate; begin Result := _emissaoCNH; end; function TPessoaF.getEstadoCivil: String; begin Result := _estadocivil; end; function TPessoaF.getFavorecido: String; begin Result := _favorecido; end; function TPessoaF.getForma: String; begin Result := _forma; end; function TPessoaF.getNaturalidade: String; begin Result := _naturalidade; end; function TPessoaF.getNome: String; begin Result := _nome; end; function TPessoaF.getNomeConjuge: String; begin Result := _nomeconjuge; end; function TPessoaF.getNomeMae: String; begin Result := _nomemae end; function TPessoaF.getNomePai: String; begin Result := _nomepai; end; function TPessoaF.getNumeroConta: String; begin Result := _numeroconta; end; function TPessoaF.getNumeroCTPS: String; begin Result := _numeroctps; end; function TPessoaF.getOrgaoRG: String; begin Result := _orgaorg; end; function TPessoaF.getPIS: String; begin Result := _pis; end; function TPessoaF.getRG: String; begin Result := _rg; end; function TPessoaF.getSerieCTPS: String; begin Result := _seriectps; end; function TPessoaF.getTipoConta: String; begin Result := _tipoconta; end; function TPessoaF.getTipoDoc: String; begin Result := _tipodoc; end; function TPessoaF.getUFCTPS: String; begin Result := _ufctps; end; function TPessoaF.getUFNatural: String; begin Result := _ufnatural; end; function TPessoaF.getUFRG: String; begin Result := _ufrg; end; function TPessoaF.getValidadeCNH: TDate; begin Result := _validadecnh; end; procedure TPessoaF.setAgencia(const Value: String); begin _codigoagencia := Value; end; procedure TPessoaF.setAlias(const Value: String); begin _alias := Value; end; procedure TPessoaF.setBanco(const Value: String); begin _codigobanco := Value; end; procedure TPessoaF.setCategoriaCNH(const Value: String); begin _categoriacnh := Value; end; procedure TPessoaF.setCNH(const Value: String); begin _cnh := Value; end; procedure TPessoaF.setCNHRegistro(const Value: String); begin _cnhregistro := Value; end; procedure TPessoaF.setCNHUF(const Value: String); begin _cnhuf := Value; end; procedure TPessoaF.setCodigoCNH(const Value: String); begin _codcnh := Value; end; procedure TPessoaF.setCPF(const Value: String); begin _cpf := Value; end; procedure TPessoaF.setCpfCnpjFavorecido(const Value: String); begin _cpfcnpjfavorecido := Value; end; procedure TPessoaF.setDataPrimeiraCN(const Value: TDate); begin _dataprimeiracnh := Value; end; procedure TPessoaF.setDataRG(const Value: TDate); begin _datarg := Value; end; procedure TPessoaF.setDtNascimento(const Value: TDate); begin _nascimento := Value; end; procedure TPessoaF.setEmissaoCNH(const Value: TDate); begin _emissaoCNH := value; end; procedure TPessoaF.setEstadoCivil(const Value: String); begin _estadocivil := Value; end; procedure TPessoaF.setFavorecido(const Value: String); begin _favorecido := Value; end; procedure TPessoaF.setForma(const Value: String); begin _forma := Value; end; procedure TPessoaF.setNaturalidade(const Value: String); begin _naturalidade := Value; end; procedure TPessoaF.setNome(const Value: String); begin _nome := Value; end; procedure TPessoaF.setNomeConjuge(const Value: String); begin _nomeconjuge := Value; end; procedure TPessoaF.setNomeMae(const Value: String); begin _nomemae := Value; end; procedure TPessoaF.setNomePai(const Value: String); begin _nomepai := Value; end; procedure TPessoaF.setNumeroConta(const Value: String); begin _numeroconta := Value; end; procedure TPessoaF.setNumeroCTPS(const Value: String); begin _numeroctps := Value; end; procedure TPessoaF.setOrgaoRG(const Value: String); begin _orgaorg := Value; end; procedure TPessoaF.setPIS(const Value: String); begin _pis := Value; end; procedure TPessoaF.setRG(const Value: String); begin _rg := Value; end; procedure TPessoaF.setSerieCTPS(const Value: String); begin _seriectps := Value; end; procedure TPessoaF.setTipoConta(const Value: String); begin _tipoconta := Value; end; procedure TPessoaF.setTipoDoc(const Value: String); begin _tipodoc := Value; end; procedure TPessoaF.setUFCTPS(const Value: String); begin _ufctps := Value; end; procedure TPessoaF.setUFNatural(const Value: String); begin _ufnatural := Value; end; procedure TPessoaF.setUFRG(const Value: String); begin _ufrg := Value; end; procedure TPessoaF.setValidadeCNH(const Value: TDate); begin _validadecnh := Value; end; end.
{==============================================================================| | MicroCoin | | Copyright (c) 2018 MicroCoin Developers | |==============================================================================| | 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 opies 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. | |==============================================================================| | File: MicroCoin.Forms.Common.Settings.pas | | Created at: 2018-09-13 | | Purpose: Form for wallet and miner server configuration | |==============================================================================} unit MicroCoin.Forms.Common.Settings; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, PngBitBtn, ExtCtrls, ComCtrls, MicroCoin.Application.Settings, UCrypto, UITypes, Vcl.Samples.Spin, Vcl.WinXCtrls, Styles, Themes, PngSpeedButton; type TSettingsForm = class(TForm) PageControl1: TPageControl; MiningTab: TTabSheet; NetOptions: TTabSheet; editMinerName: TLabeledEdit; editMinerServerPort: TSpinEdit; Label1: TLabel; Panel1: TPanel; radionewKey: TRadioButton; radioRandomkey: TRadioButton; radiousethiskey: TRadioButton; cbMyKeys: TComboBox; Panel2: TPanel; btnSave: TPngBitBtn; btnCancel: TPngBitBtn; editServerPort: TSpinEdit; Label2: TLabel; checkEnableRPC: TCheckBox; editJSONRPCPort: TSpinEdit; Label3: TLabel; memoAllowedIPs: TMemo; Label4: TLabel; TabSheet1: TTabSheet; Label5: TLabel; cbSkin: TComboBox; swNewTransaction: TToggleSwitch; Label6: TLabel; Label7: TLabel; ToggleSwitch2: TToggleSwitch; Label8: TLabel; ToggleSwitch3: TToggleSwitch; Label9: TLabel; Label10: TLabel; Label11: TLabel; ToggleSwitch4: TToggleSwitch; CheckBox1: TCheckBox; CheckBox2: TCheckBox; Label12: TLabel; PngBitBtn1: TPngBitBtn; procedure radiousethiskeyClick(Sender: TObject); procedure radioRandomkeyClick(Sender: TObject); procedure radionewKeyClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnCancelClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure cbSkinChange(Sender: TObject); procedure FormCreate(Sender: TObject); private FAppSettings: TAppSettings; procedure SetAppParams(const Value: TAppSettings); { Private declarations } public property AppParams : TAppSettings read FAppSettings write SetAppParams; end; var SettingsForm: TSettingsForm; implementation uses MicroCoin.Common.Config, MicroCoin.Node.Node, MicroCoin.Account.AccountKey; resourcestring StrServerPortAndJSONRPCPortEquals = 'Server port and JSON RPC port are equ' + 'al'; {$R *.dfm} procedure TSettingsForm.btnCancelClick(Sender: TObject); begin ModalResult := mrCancel; CloseModal; end; procedure TSettingsForm.btnSaveClick(Sender: TObject); var xMiningMode: integer; begin if editMinerServerPort.Value = editJSONRPCPort.Value then begin MessageDlg(StrServerPortAndJSONRPCPortEquals, mtError, [mbOK], 0); exit; end; xMiningMode := 0; if radiousethiskey.Checked then xMiningMode := 2 else if radioRandomkey.Checked then xMiningMode := 1 else if radionewKey.Checked then xMiningMode := 0; if radiousethiskey.Checked then AppParams.Entries[TAppSettingsEntry.apMinerPrivateKeySelectedPublicKey].SetAsString(TNode.Node.KeyManager[cbMyKeys.ItemIndex].AccountKey.ToRawString ); AppParams.Entries[TAppSettingsEntry.apInternetServerPort].SetAsInteger(editServerPort.Value); AppParams.Entries[TAppSettingsEntry.apMinerPrivateKeyType].SetAsInteger(xMiningMode); AppParams.Entries[TAppSettingsEntry.apJSONRPCMinerServerActive].SetAsBoolean(true); AppParams.Entries[TAppSettingsEntry.apMinerName].SetAsString(editMinerName.Text); AppParams.Entries[TAppSettingsEntry.apJSONRPCMinerServerPort].SetAsInteger(editMinerServerPort.Value); AppParams.Entries[TAppSettingsEntry.apJSONRPCEnabled].SetAsBoolean(checkEnableRPC.Checked); AppParams.Entries[TAppSettingsEntry.apJSONRPCAllowedIPs].SetAsString(memoAllowedIPs.Text); AppParams.Entries[TAppSettingsEntry.apTheme].SetAsString(cbSkin.Text); AppParams.Entries[TAppSettingsEntry.apNotifyOnNewTransaction].SetAsBoolean(swNewTransaction.State = TToggleSwitchState.tssOn); ModalResult := mrOk; CloseModal; end; procedure TSettingsForm.cbSkinChange(Sender: TObject); begin TStylemanager.TrySetStyle(cbSkin.Text); end; procedure TSettingsForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TSettingsForm.FormCreate(Sender: TObject); begin cbSkin.Clear; cbSkin.Items.AddStrings(TStyleManager.StyleNames); end; procedure TSettingsForm.radionewKeyClick(Sender: TObject); begin cbMyKeys.Enabled := radiousethiskey.Checked; end; procedure TSettingsForm.radioRandomkeyClick(Sender: TObject); begin cbMyKeys.Enabled := radiousethiskey.Checked; end; procedure TSettingsForm.radiousethiskeyClick(Sender: TObject); begin cbMyKeys.Enabled := radiousethiskey.Checked; end; procedure TSettingsForm.SetAppParams(const Value: TAppSettings); var i: integer; xSelectedKey: AnsiString; begin FAppSettings := Value; cbSkin.ItemIndex := cbSkin.Items.IndexOf(AppParams.Entries[TAppSettingsEntry.apTheme].GetAsString('MicroCoin Light')); editMinerName.Text := AppParams.Entries[TAppSettingsEntry.apMinerName].GetAsString(''); editMinerServerPort.Value := AppParams.Entries[TAppSettingsEntry.apJSONRPCMinerServerPort].GetAsInteger(cMinerServerPort); checkEnableRPC.Checked := AppParams.Entries[TAppSettingsEntry.apJSONRPCEnabled].GetAsBoolean(false); memoAllowedIPs.Text := AppParams.Entries[TAppSettingsEntry.apJSONRPCAllowedIPs].GetAsString('127.0.0.1;'); editServerPort.Value := AppParams.Entries[TAppSettingsEntry.apInternetServerPort].GetAsInteger(cNetServerPort); if AppParams.Entries[TAppSettingsEntry.apNotifyOnNewTransaction].GetAsBoolean(true) then swNewTransaction.State := TToggleSwitchState.tssOn else swNewTransaction.State := TToggleSwitchState.tssOff; case AppParams.Entries[TAppSettingsEntry.apMinerPrivateKeyType].GetAsInteger(Integer(1)) of 0 : radionewKey.Checked := true; 1 : radioRandomkey.Checked := true; 2 : radiousethiskey.Checked := true; else radioRandomkey.Checked := true; end; xSelectedKey := FAppSettings.Entries[TAppSettingsEntry.apMinerPrivateKeySelectedPublicKey].GetAsString(''); for i := 0 to TNode.Node.KeyManager.Count-1 do begin cbMyKeys.AddItem(TNode.Node.KeyManager[i].Name, TNode.Node.KeyManager[i].PrivateKey); if TNode.Node.KeyManager[i].AccountKey = TAccountKey.FromRawString(xSelectedKey) then cbMyKeys.ItemIndex := i; end; end; end.
{******************************************************************************} { CnPack For Delphi/C++Builder } { 中国人自己的开放源码第三方开发包 } { (C)Copyright 2001-2006 CnPack 开发组 } { ------------------------------------ } { } { 本开发包是开源的自由软件,您可以遵照 CnPack 的发布协议来修 } { 改和重新发布这一程序。 } { } { 发布这一开发包的目的是希望它有用,但没有任何担保。甚至没有 } { 适合特定目的而隐含的担保。更详细的情况请参阅 CnPack 发布协议。 } { } { 您应该已经和开发包一起收到一份 CnPack 发布协议的副本。如果 } { 还没有,可访问我们的网站: } { } { 网站地址:http://www.cnpack.org } { 电子邮件:master@cnpack.org } { } {******************************************************************************} unit ZhIni; {* |<PRE> ================================================================================ * 软件名称:开发包基础库 * 单元名称:扩展的INI访问单元 * 单元作者:周劲羽 (zjy@cnpack.org) * 备 注:该单元编写时参考了 RxLib 2.75 中的 RxIni.pas * 开发平台:PWin2000Pro + Delphi 5.0 * 兼容测试:PWin9X/2000/XP + Delphi 5/6 * 本 地 化:该单元中的字符串均符合本地化处理方式 * 单元标识:$Id: CnIni.pas,v 1.3 2006/01/13 12:41:33 passion Exp $ * 修改记录:2002.10.20 V1.0 * 创建单元 ================================================================================ |</PRE>} interface //{$I CnPack.inc} uses Windows, Classes, SysUtils, Forms, IniFiles, Graphics, ZhIniStrUtils, ZhStream; type //============================================================================== // 扩展的 INI 访问类 //============================================================================== { TCnIniFile } TCnIniFile = class(TCustomIniFile) {* 扩展的 INI 访问类,使用 Wrap 模式对 TCustomIniFile 进行扩展。定义两个构造器 既可当普通的文件型 INI 类操作,又可仅仅作为其它 TCustomIniFile 对象的包装外 壳进行扩展的操作。} private FIni: TCustomIniFile; FOwned: Boolean; function GetFileName: string; protected property Owned: Boolean read FOwned; property Ini: TCustomIniFile read FIni; public constructor Create(AIni: TCustomIniFile; AOwned: Boolean = False); overload; {* 包装构造器,使用该构造器创建实例,对已有的 TCustomIniFile 对象进行功能扩展 对象的所有方法都转到原 INI 对象中执行 |<PRE> AIni: TCustomIniFile - 被包装的 INI 对象 AOwned: Boolean - 在该对象释放时是否同时释放被包装的 INI 对象 |</PRE>} constructor Create(const FileName: string; MemIniFile: Boolean = True); overload; {* 普通 INI 文件构造器,使用该构造器创建实例,将实例当普通的 INI 对象使用。 |<PRE> FileName: string - INI 文件名 MemIniFile: Boolean - 是否使用内存缓冲方式操作 INI,即内部使用 TMemIniFile 对象。 |</PRE>} destructor Destroy; override; function ReadInteger(const Section, Ident: string; Default: Longint): Longint; override; procedure WriteInteger(const Section, Ident: string; Value: Longint); override; function ReadBool(const Section, Ident: string; Default: Boolean): Boolean; override; procedure WriteBool(const Section, Ident: string; Value: Boolean); override; function ReadDate(const Section, Name: string; Default: TDateTime): TDateTime; override; function ReadDateTime(const Section, Name: string; Default: TDateTime): TDateTime; override; function ReadFloat(const Section, Name: string; Default: Double): Double; override; function ReadTime(const Section, Name: string; Default: TDateTime): TDateTime; override; procedure WriteDate(const Section, Name: string; Value: TDateTime); override; procedure WriteDateTime(const Section, Name: string; Value: TDateTime); override; procedure WriteFloat(const Section, Name: string; Value: Double); override; procedure WriteTime(const Section, Name: string; Value: TDateTime); override; function ReadString(const Section, Ident, Default: string): string; override; procedure WriteString(const Section, Ident, Value: String); override; procedure ReadSection(const Section: string; Strings: TStrings); override; procedure ReadSections(Strings: TStrings); override; procedure ReadSectionValues(const Section: string; Strings: TStrings); override; procedure EraseSection(const Section: string); override; procedure DeleteKey(const Section, Ident: String); override; procedure UpdateFile; override; function ReadColor(const Section, Ident: string; Default: TColor): TColor; {* 读取颜色} procedure WriteColor(const Section, Ident: string; Value: TColor); {* 写入颜色} function ReadFont(const Section, Ident: string; Font: TFont): TFont; {* 读取字体} procedure WriteFont(const Section, Ident: string; Font: TFont); {* 写入字体} function ReadRect(const Section, Ident: string; const Default: TRect): TRect; {* 读取 Rect} procedure WriteRect(const Section, Ident: string; const Value: TRect); {* 写入 Rect} function ReadPoint(const Section, Ident: string; const Default: TPoint): TPoint; {* 读取 Point} procedure WritePoint(const Section, Ident: string; const Value: TPoint); {* 写入 Point} function ReadStrings(const Section, Ident: string; Strings: TStrings): TStrings; overload; {* 从一行文本中读取字符串列表} function ReadStrings(const Section: string; Strings: TStrings): TStrings; overload; {* 从单独的节中读取字符串列表} procedure WriteStrings(const Section, Ident: string; Strings: TStrings); overload; {* 写入字符串列表到一行文本中} procedure WriteStrings(const Section: string; Strings: TStrings); overload; {* 写入字符串列表到单独的节中} property FileName: string read GetFileName; {* INI 文件名} end; //============================================================================== // 支持流操作的 IniFile 类 //============================================================================== { TCnStreamIniFile } TCnStreamIniFile = class (TMemIniFile) {* 支持流操作的 IniFile 类,提供了 LoadFromStream、SaveToStream 允许从流中读取 Ini 数据。 } private FFileName: string; protected public constructor Create(const FileName: string = ''); {* 类构造器,参数为 INI 文件名,如果该文件存在则会自动装载文件 } destructor Destroy; override; {* 类析构器 } function LoadFromFile(const FileName: string): Boolean; {* 从文件中装载 INI 数据 } function LoadFromStream(Stream: TStream): Boolean; virtual; {* 从流中装载 INI 数据 } function SaveToFile(const FileName: string): Boolean; {* 保存 INI 数据到文件 } function SaveToStream(Stream: TStream): Boolean; virtual; {* 保存 INI 数据到流 } procedure UpdateFile; override; {* 更新当前 INI 数据到文件 } property FileName: string read FFileName; {* 创建对象时传递的文件名,只读属性 } end; //============================================================================== // 支持内容 Xor 加密及流操作的 IniFile 类 //============================================================================== { TCnXorIniFile } TCnXorIniFile = class (TCnStreamIniFile) {* 支持内容 Xor 加密及流操作的 IniFile 类,允许对 INI 数据进行 Xor 加密。 } private FXorStr: string; protected public constructor Create(const FileName: string; const XorStr: string); {* 类构造器。 |<PRE> FileName: string - INI 文件名,如果文件存在将自动加载 XorStr: string - 用于 Xor 操作的字符串 |</PRE>} function LoadFromStream(Stream: TStream): Boolean; override; {* 从流中装载 INI 数据,流中的数据将用 Xor 解密 } function SaveToStream(Stream: TStream): Boolean; override; {* 保存 INI 数据到流,流中的数据将用 Xor 加密 } end; implementation uses CnCommon; //============================================================================== // 扩展的 INI 访问类 //============================================================================== { TCnIniFile } constructor TCnIniFile.Create(AIni: TCustomIniFile; AOwned: Boolean); begin inherited Create(''); Assert(Assigned(AIni)); FIni := AIni; FOwned := AOwned; end; constructor TCnIniFile.Create(const FileName: string; MemIniFile: Boolean); begin if MemIniFile then Create(TMemIniFile.Create(FileName), True) else Create(TIniFile.Create(FileName), True); end; destructor TCnIniFile.Destroy; begin if FOwned then FreeAndNil(FIni); inherited; end; //------------------------------------------------------------------------------ // 扩展的 INI 访问方法 //------------------------------------------------------------------------------ function TCnIniFile.ReadColor(const Section, Ident: string; Default: TColor): TColor; begin try Result := StringToColor(ReadString(Section, Ident, ColorToString(Default))); except Result := Default; end; end; procedure TCnIniFile.WriteColor(const Section, Ident: string; Value: TColor); begin WriteString(Section, Ident, ColorToString(Value)); end; function TCnIniFile.ReadRect(const Section, Ident: string; const Default: TRect): TRect; begin Result := StrToRect(ReadString(Section, Ident, RectToStr(Default)), Default); end; procedure TCnIniFile.WriteRect(const Section, Ident: string; const Value: TRect); begin WriteString(Section, Ident, RectToStr(Value)); end; function TCnIniFile.ReadPoint(const Section, Ident: string; const Default: TPoint): TPoint; begin Result := StrToPoint(ReadString(Section, Ident, PointToStr(Default)), Default); end; procedure TCnIniFile.WritePoint(const Section, Ident: string; const Value: TPoint); begin WriteString(Section, Ident, PointToStr(Value)); end; function TCnIniFile.ReadFont(const Section, Ident: string; Font: TFont): TFont; begin Result := Font; try StringToFont(ReadString(Section, Ident, FontToString(Font)), Result); except { do nothing, ignore any exceptions } end; end; procedure TCnIniFile.WriteFont(const Section, Ident: string; Font: TFont); begin WriteString(Section, Ident, FontToString(Font)); end; function TCnIniFile.ReadStrings(const Section, Ident: string; Strings: TStrings): TStrings; begin Result := Strings; Strings.Text := StrToLines(ReadString(Section, Ident, LinesToStr(Strings.Text))); end; function TCnIniFile.ReadStrings(const Section: string; Strings: TStrings): TStrings; begin Result := Strings; if SectionExists(Section) then ReadStringsFromIni(Self, Section, Result); end; procedure TCnIniFile.WriteStrings(const Section, Ident: string; Strings: TStrings); begin WriteString(Section, Ident, LinesToStr(Strings.Text)); end; procedure TCnIniFile.WriteStrings(const Section: string; Strings: TStrings); begin WriteStringsToIni(Self, Section, Strings); end; //------------------------------------------------------------------------------ // 调用被包装的 INI 访问方法 //------------------------------------------------------------------------------ procedure TCnIniFile.DeleteKey(const Section, Ident: String); begin Ini.DeleteKey(Section, Ident); end; procedure TCnIniFile.EraseSection(const Section: string); begin Ini.EraseSection(Section); end; function TCnIniFile.GetFileName: string; begin Result := Ini.FileName; end; procedure TCnIniFile.ReadSection(const Section: string; Strings: TStrings); begin Ini.ReadSection(Section, Strings); end; procedure TCnIniFile.ReadSections(Strings: TStrings); begin Ini.ReadSections(Strings); end; procedure TCnIniFile.ReadSectionValues(const Section: string; Strings: TStrings); begin Ini.ReadSectionValues(Section, Strings); end; function TCnIniFile.ReadString(const Section, Ident, Default: string): string; begin Result := Ini.ReadString(Section, Ident, Default); end; procedure TCnIniFile.UpdateFile; begin Ini.UpdateFile; end; procedure TCnIniFile.WriteString(const Section, Ident, Value: String); begin Ini.WriteString(Section, Ident, Value); end; function TCnIniFile.ReadBool(const Section, Ident: string; Default: Boolean): Boolean; begin Result := Ini.ReadBool(Section, Ident, Default); end; function TCnIniFile.ReadDate(const Section, Name: string; Default: TDateTime): TDateTime; begin Result := Ini.ReadDate(Section, Name, Default); end; function TCnIniFile.ReadDateTime(const Section, Name: string; Default: TDateTime): TDateTime; begin Result := Ini.ReadDateTime(Section, Name, Default); end; function TCnIniFile.ReadFloat(const Section, Name: string; Default: Double): Double; begin Result := Ini.ReadFloat(Section, Name, Default); end; function TCnIniFile.ReadInteger(const Section, Ident: string; Default: Integer): Longint; begin Result := Ini.ReadInteger(Section, Ident, Default); end; function TCnIniFile.ReadTime(const Section, Name: string; Default: TDateTime): TDateTime; begin Result := Ini.ReadTime(Section, Name, Default); end; procedure TCnIniFile.WriteBool(const Section, Ident: string; Value: Boolean); begin Ini.WriteBool(Section, Ident, Value); end; procedure TCnIniFile.WriteDate(const Section, Name: string; Value: TDateTime); begin Ini.WriteDate(Section, Name, Value); end; procedure TCnIniFile.WriteDateTime(const Section, Name: string; Value: TDateTime); begin Ini.WriteDateTime(Section, Name, Value); end; procedure TCnIniFile.WriteFloat(const Section, Name: string; Value: Double); begin Ini.WriteFloat(Section, Name, Value); end; procedure TCnIniFile.WriteInteger(const Section, Ident: string; Value: Integer); begin Ini.WriteInteger(Section, Ident, Value); end; procedure TCnIniFile.WriteTime(const Section, Name: string; Value: TDateTime); begin Ini.WriteTime(Section, Name, Value); end; //============================================================================== // 支持流操作的 IniFile 类 //============================================================================== { TCnStreamIniFile } constructor TCnStreamIniFile.Create(const FileName: string); begin inherited Create(''); FFileName := FileName; if FileExists(FFileName) then LoadFromFile(FFileName); end; destructor TCnStreamIniFile.Destroy; begin UpdateFile; inherited; end; function TCnStreamIniFile.LoadFromFile(const FileName: string): Boolean; var Stream: TFileStream; begin try Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try Result := LoadFromStream(Stream); finally Stream.Free; end; except Result := False; end; end; function TCnStreamIniFile.LoadFromStream(Stream: TStream): Boolean; var Strings: TStrings; begin try Strings := TStringList.Create; try Strings.LoadFromStream(Stream); SetStrings(Strings); finally Strings.Free; end; Result := True; except Result := False; end; end; function TCnStreamIniFile.SaveToFile(const FileName: string): Boolean; var Stream: TFileStream; begin try Stream := TFileStream.Create(FileName, fmCreate); try Stream.Size := 0; Result := SaveToStream(Stream); finally Stream.Free; end; except Result := False; end; end; function TCnStreamIniFile.SaveToStream(Stream: TStream): Boolean; var Strings: TStrings; begin try Strings := TStringList.Create; try GetStrings(Strings); Strings.SaveToStream(Stream); finally Strings.Free; end; Result := True; except Result := False; end; end; procedure TCnStreamIniFile.UpdateFile; begin if FileExists(FFileName) then SaveToFile(FFileName); end; //============================================================================== // 支持文本 Xor 加密及流操作的 IniFile 类 //============================================================================== { TCnXorIniFile } constructor TCnXorIniFile.Create(const FileName, XorStr: string); begin inherited Create(FileName); FXorStr := XorStr; end; function TCnXorIniFile.LoadFromStream(Stream: TStream): Boolean; var XorStream: TCnXorStream; begin XorStream := TCnXorStream.Create(Stream, FXorStr); try Result := inherited LoadFromStream(XorStream); finally XorStream.Free; end; end; function TCnXorIniFile.SaveToStream(Stream: TStream): Boolean; var XorStream: TCnXorStream; begin XorStream := TCnXorStream.Create(Stream, FXorStr); try Result := inherited SaveToStream(XorStream); finally XorStream.Free; end; end; end.
unit FrameDataAccessImpl; interface uses Classes,SysUtils,Db,AdoDb,DbClient,CoreImpl; type TFrameDataAccessImpl=class(TObject) public class procedure LoadModuleFromDatabase(AModuleSearcher:TModuleSearcher); class procedure LoadTableFromDatabase(AModuleItem:TModuleItem); class procedure LoadFieldFromDatabase(ATableItem:TTableItem); class procedure AddField(ATableItem:TTableItem; AFieldName:string; ADisplayLabel:string ; ADataType:TDataType; ACalcType:TCalcType; ASize:Integer ; AIsKey:Boolean ; AIsUnique:Boolean ; AIsShow:Boolean ; AIsEdit:Boolean ; AAllowNull:Boolean ; AIsPassword:Boolean ; AColIndex:Integer ; AShowWidth:Integer; AisDefault:Boolean ; ADefaultValue:Variant ; ADisplayFormat:string ; AEditFormat:string ; AFooter:TFooterType ; ATabOrder:Integer; ADictionary:string ; AShowField:string ; ALinkFieldName:string ; AKeyFieldName:string; AIsLinkMaster:boolean ; AMasterField:string );overload ; class procedure AddField(AFieldItems:TFieldItems ; AFieldName: string; ADisplayLabel: string; AIsKey:Boolean ; AIsShow: Boolean; AIsBrowseShow : Boolean; AShowWidth:integer ) ;overload ; class procedure AddField(ATableItem:TTableItem; AFieldName: string; ADisplayLabel: string; AIsKey:Boolean ; AIsShow: Boolean; AColIndex:integer; AShowWidth:integer ) ;overload ; end; implementation uses EnvironmentImpl; { TFrameDataAccessImpl } class procedure TFrameDataAccessImpl.AddField(ATableItem: TTableItem; AFieldName, ADisplayLabel: string; ADataType: TDataType; ACalcType: TCalcType; ASize: Integer; AIsKey,AIsUnique, AIsShow, AIsEdit, AAllowNull, AIsPassword: Boolean; AColIndex, AShowWidth: Integer; AisDefault:Boolean ;ADefaultValue: Variant; ADisplayFormat, AEditFormat: string; AFooter: TFooterType; ATabOrder: Integer; ADictionary, AShowField, ALinkFieldName, AKeyFieldName: string; AIsLinkMaster:boolean ;AMasterField:string); var Item:TFieldItem; begin Item:=ATableItem.CreateFieldItem(ATableItem); Item.Table:=ATableItem.Code ; Item.FieldName:=AFieldName; Item.DisplayLabel:=ADisplayLabel ; Item.DataType:=ADataType; Item.CalcType:=ACalcType; Item.Size:=ASize ; Item.IsKey:=AIsKey ; Item.IsUnique:=AIsUnique ; Item.IsShow:=AIsShow ; Item.IsEdit:=AIsEdit ; Item.AllowNull:=AAllowNull ; Item.IsPassword:=AIsPassword ; Item.ColIndex:=AColIndex ; Item.ShowWidth:=AShowWidth; Item.isDefault:=AisDefault ; Item.DefaultValue:=ADefaultValue ; Item.DisplayFormat:=ADisplayFormat ; Item.EditFormat:=AEditFormat ; Item.Footer:=AFooter ; Item.TabOrder:=ATabOrder ; Item.Dictionary:=ADictionary ; Item.ShowField:=AShowField ; Item.LinkFieldName:=ALinkFieldName ; Item.KeyFieldName:=AKeyFieldName ; Item.IsLinkMaster:= AIsLinkMaster; Item.MasterField:= AMasterField; ATableItem.FieldItems.Add(Item.FieldName,Item.DisplayLabel,Item); end; class procedure TFrameDataAccessImpl.AddField(AFieldItems: TFieldItems; AFieldName, ADisplayLabel: string;AIsKey, AIsShow, AIsBrowseShow: Boolean; AShowWidth: integer); var AFieldItem:TFieldItem ; begin AFieldItem:=TFieldItem.Create ; AFieldItem.FieldName:=AFieldName ; AFieldItem.DisplayLabel:=ADisplayLabel; AFieldItem.IsKey := AIsKey ; AFieldItem.IsShow:=AIsShow; AFieldItem.IsBrowseShow:=AIsBrowseShow ; AFieldItem.ShowWidth :=AShowWidth ; AFieldItem.DataType:=dtString ; try AFieldItems.Add(AFieldItem.FieldName,AFieldItem.DisplayLabel,AFieldItem) ; except on e:exception do begin end ; end; end; class procedure TFrameDataAccessImpl.AddField(ATableItem: TTableItem; AFieldName, ADisplayLabel: string; AIsKey, AIsShow:boolean; AColIndex,AShowWidth: integer); var FieldItem:TFieldItem ; begin FieldItem:=ATableItem.CreateFieldItem(ATableItem); FieldItem.FieldName:=AFieldName ; FieldItem.DisplayLabel:=ADisplayLabel; FieldItem.IsKey := AIsKey ; FieldItem.IsShow:=AIsShow; FieldItem.ColIndex :=AColIndex ; FieldItem.ShowWidth :=AShowWidth ; FieldItem.DataType:=dtString ; ATableItem.FieldItems.Add(FieldItem.FieldName,FieldItem.DisplayLabel,FieldItem); end; class procedure TFrameDataAccessImpl.LoadFieldFromDatabase( ATableItem: TTableItem); const Select_Field_Sql='select vc_fieldcode, vc_tablecode, vc_fieldname, i_resid,' +' ti_datatype, i_fieldsize, vc_describe, ti_decimal, vc_default,' +' b_key, b_unique, b_allownull, b_autoincrement, i_autoincrementstep, ' +' vc_calctype, vc_formula, vc_displayformat, vc_editformat, vc_ctrltype,' +' vc_dictcode, vc_showfield, vc_LinkField, vc_KeyField, b_password, b_showed,' +' b_browseshow, b_edit, b_tabstop, i_taborder, i_foottype, i_row, i_column,' +' i_width, b_standardout, vc_linkmodule,vc_sheet,b_linkmaster,vc_masterfield from us_fields ' +' where vc_tablecode=''%s'''; var Item:TFieldItem; DataSet:TClientDataSet; begin ATableItem.FieldItems.Clear; with _Environment.DataAccess do begin SelectSql(Format(Select_Field_Sql,[ATableItem.Code]),DataSet); try DataSet.First; while not DataSet.Eof do begin Item:=ATableItem.CreateFieldItem(ATableItem); Item.FieldName:=DataSet.FieldByName('vc_fieldname').AsString; Item.Table:=DataSEt.FieldByName('vc_tablecode').AsString; Item.DisplayLabel:=DataSet.FieldByName('vc_DisplayLabel').AsString; Item.ResId:=DataSet.FieldByName('i_resid').AsInteger; Item.DataType:=TDataType(DataSet.FieldByName('ti_datatype').AsInteger); Item.Size:=DataSet.FieldByName('i_fieldsize').AsInteger; Item.Describe:=DataSet.FieldByName('vc_describe').AsString; Item.Decimal:=DataSet.FieldByName('ti_decimal').AsInteger; Item.DefaultValue:=DataSet.FieldByName('vc_default').Value; Item.IsKey:=DataSet.FieldByName('b_key').AsBoolean; Item.IsUnique:=DataSet.FieldByName('b_unique').AsBoolean; Item.AllowNull:=DataSet.FieldByName('b_allownull').AsBoolean; Item.AutoIncrement:=DataSet.FieldByName('b_autoincrement').AsBoolean; Item.AutoIncrementStep:=DataSet.FieldByName('i_autoincrementstep').AsInteger; Item.CtrlType:=TVirtualCtrlType(DataSet.FieldByName('vc_ctrltype').AsInteger); Item.Formula:=DataSet.FieldByName('vc_formula').AsString; Item.CalcType:=TCalcType(DataSet.FieldByName('vc_calctype').asInteger); Item.DisplayFormat:=DataSEt.FieldByName('vc_displayformat').AsString; Item.EditFormat:=dataSEt.FieldByName('vc_editformat').AsString; Item.Dictionary:=DataSet.FieldByName('vc_dictcode').AsString; Item.ShowField:=DataSet.FieldByname('vc_showfield').AsString; Item.LinkFieldName:=DataSet.FieldByName('vc_LinkField').AsString; Item.KeyFieldName:=DataSet.FieldByName('vc_KeyField').AsString; Item.IsPassword:=DataSet.FieldByName('b_password').AsBoolean; Item.IsShow:=DataSet.FieldByName('b_showed').AsBoolean; Item.IsBrowseShow:=DataSet.FieldByName('b_browseshow').AsBoolean; Item.IsEdit:=DataSet.FieldByName('b_edit').AsBoolean; Item.TabStop:=DataSet.FieldByName('b_tabstop').AsBoolean; Item.TabOrder:=DataSet.FieldByName('i_taborder').AsInteger; Item.Footer:=TFooterType(DataSet.FieldByName('i_foottype').AsInteger); Item.RowIndex:=DataSet.FieldByName('i_row').AsInteger; Item.ColIndex:=DataSet.FieldByName('i_column').AsInteger; Item.ShowWidth:=DataSet.FieldByname('i_width').AsInteger; Item.IsStandOut:=DataSet.FieldByName('b_standardout').AsBoolean; Item.LinkModule:=DataSet.FieldByName('vc_linkmodule').AsString; Item.IsLinkMaster:=DataSet.FieldByName('b_linkmaster').AsBoolean; Item.MasterField:=DataSet.FieldByName('vc_masterfield').AsString; ATableItem.FieldItems.Add(Item.FieldName,Item.DisplayLabel,Item); DataSet.Next; end; finally DataSet.Free; end; end; end; class procedure TFrameDataAccessImpl.LoadModuleFromDatabase( AModuleSearcher: TModuleSearcher); const Select_Module_Sql='select vc_modulecode, vc_templetcode, vc_categorycode,' +' vc_factcode, vc_modulename, vc_username2, vc_mnemonic, i_resid, b_isfunction,' +' b_shortcutshow, b_toolbarshow, vc_plugIn, vc_icon, i_program, vc_describe, ' +' vc_version, vc_systemic, bi_funcowner,vc_sheetOrder from us_modules'; var Item:TModuleItem; DataSet:TClientDataSet; begin AModuleSearcher.Clear; with _Environment.DataAccess do begin SelectSql(Select_Module_Sql,DataSet); try DataSet.First; while not DataSet.Eof do begin Item:=TModuleItem.Create; Item.Code:=DataSet.FieldByName('vc_modulecode').AsString; Item.Name:=DataSet.FieldByName('vc_modulename').AsString; Item.Templet:=DataSet.FieldByName('vc_templetcode').AsString; Item.Category:=DataSet.FieldByName('vc_templetcode').AsString; Item.Command:=DataSet.FieldByName('vc_factcode').AsString; Item.Name2:=DataSet.FieldByName('vc_username2').AsString; Item.Mnemonic:=DataSet.FieldByName('vc_mnemonic').AsString; Item.ResId:=DataSet.FieldByName('i_resid').AsInteger; Item.IsFunc:=DataSet.FieldByName('b_isfunction').AsBoolean; Item.IsShowShortCut:=DataSet.FieldByName('b_shortcutshow').AsBoolean; Item.IsToolBar:=DataSet.FieldByName('b_toolbarshow').AsBoolean; Item.AddIn:=DataSet.FieldByName('vc_plugIn').AsString; Item.Icon:=DataSet.FieldByName('vc_icon').AsString; Item.Describe:=DataSet.FieldByName('vc_describe').AsString; Item.Version:=DataSet.FieldByName('vc_version').AsString; Item.BelongSys:=DataSet.FieldByName('i_program').AsInteger; Item.IsSystemic:=DataSet.FieldByName('vc_systemic').AsBoolean; Item.ChildFunc:=DataSet.fieldByname('bi_funcowner').AsInteger; AModuleSearcher.Add(Item.Code,Item.Name,Item); DataSet.Next; end; finally DataSet.Free; end; end; end; class procedure TFrameDataAccessImpl.LoadTableFromDatabase( AModuleItem: TModuleItem); const Select_Table_Sql='select vc_tablecode, vc_factcode, vc_tablename, vc_tabletype, ' +' vc_attribute, vc_describe, vc_adapt, i_resid from us_tables where vc_factcode=''%s'''; var Item:TTableItem; DataSet:TClientDataSet; begin if(AModuleItem.Initialized)then Exit; AModuleItem.TableItems.Clear; with _Environment.DataAccess do begin SelectSql(Format(Select_Table_Sql,[AModuleItem.Command]),DataSet); try DataSet.First; while not DataSet.Eof do begin Item:=AModuleItem.CreateTableItem(AModuleItem); Item.Code:=DataSet.FieldByname('vc_tablecode').AsString; Item.Module:=DataSet.FieldByName('vc_factcode').AsString; Item.Name:=DataSet.FieldByName('vc_tablename').AsString; Item.TableType:=TTableType(DataSet.FieldByName('vc_tabletype').AsInteger); Item.ResId:=DataSet.FieldByName('i_resid').AsInteger; Item.Attribute:=TTableAttribute(DataSet.FieldByName('vc_attribute').AsInteger); Item.Describe:=DataSet.FieldByName('vc_describe').AsString; Item.Condition:=DataSet.FieldByname('vc_adapt').AsString; AModuleItem.TableItems.Add(Item.Code,Item.Name,Item); LoadFieldFromDatabase(Item); AModuleItem.Initialized:=True; DataSet.Next; end; finally DataSet.Free; end; end; end; end.
unit focalLengthCounter; {$mode objfpc}{$H+} interface uses Classes, SysUtils; const //sqrt(sqr(24)+sqr(36)) //referenceDiagonal = 43.2666153056; //diagonal of 35mm full frame sensor referenceDiagonal = sqrt(sqr(24)+sqr(36)); function diagonal(x, y: real): real; //x and y are the sizes of sensor function cropFactor(x, y: real): real; function focalLengthEquivalent(fl: real; cr: real): integer; //https://en.wikipedia.org/wiki/Angle_of_view#Common_lens_angles_of_view function horizontalFOV(width, focalLength: real): real; function verticalFOV(height, focalLength: real): real; function diagonalFOV(diagonal, focalLength: real): real; implementation function diagonal(x, y: real): real; //x and y are the sizes of sensor begin diagonal := Sqrt(sqr(x) + sqr(y)); //diagonal := abs(y)* sqrt(1 + sqr(x/y)); end; function cropFactor(x, y: real): real; var diag: real; begin diag := diagonal(x, y); cropFactor := referenceDiagonal / diag; end; //cropFactor function focalLengthEquivalent(fl: real; cr: real): integer; begin focalLengthEquivalent := round(fl * cr); end; function horizontalFOV(width, focalLength: real): real; begin horizontalFOV := (2 * ArcTan(width/(focalLength * 2))* 180 / Pi); end; function verticalFOV(height, focalLength: real): real; begin verticalFOV := (2 * ArcTan(height/(focalLength * 2))* 180 / Pi); end; function diagonalFOV(diagonal, focalLength: real): real; begin diagonalFOV := (2 * ArcTan(diagonal/(focalLength * 2))* 180 / Pi); end; begin end.
unit EushullyFS; interface uses Classes, SysUtils, EushullyALF, EushullyFile, ComCtrls; type TEushullyFS = class private f_root: string; f_archives_count: UInt32; f_archives: array of TEushullyALF; function getLoaded(): boolean; function getRoot(): string; function getArchive(FileName: string): TEushullyALF; function getMainArchive(): TEushullyALF; procedure onFile(FileIterator: TSearchRec); public destructor Destroy(); override; function load(path: string): boolean; procedure unload(); property Loaded: boolean read getLoaded; property Root: string read getRoot; property Archive[FileName: string]: TEushullyALF read getArchive; property MainArchive: TEushullyALF read getMainArchive; procedure MakeTree(Tree: TTreeView; parent: TTreeNode); function getArchiveByFile(FileName: string): TEushullyALF; function open(FileName: string): TEushullyFile; end; implementation destructor TEushullyFS.Destroy(); begin unload(); end; procedure TEushullyFS.onFile(FileIterator: TSearchRec); begin if (TEushullyALF.isFormat(FileIterator.Name)) then begin SetLength(self.f_archives, f_archives_count + 1); self.f_archives[f_archives_count] := TEushullyALF.Create(); if (not self.f_archives[f_archives_count].LoadFromFile(FileIterator.Name)) then self.f_archives[f_archives_count] := nil; inc(f_archives_count); end; end; function TEushullyFS.load(path: string): boolean; var rec: TSearchRec; begin self.f_root := path; if FindFirst(IncludeTrailingPathDelimiter(path) + '*.*', faAnyFile - faDirectory, rec) = 0 then begin repeat onFile(rec); until FindNext(rec) <> 0; FindClose(rec); end; result := (f_archives_count > 0); end; procedure TEushullyFS.unload(); var i: integer; begin for i := 0 to self.f_archives_count - 1 do self.f_archives[i].Free; SetLength(self.f_archives, 0); self.f_archives_count := 0; end; function TEushullyFS.getLoaded(): boolean; begin result := (f_archives_count > 0); end; function TEushullyFS.getRoot(): string; begin result := self.f_root; end; function TEushullyFS.getArchive(FileName: string): TEushullyALF; var i: integer; begin for i := 0 to self.f_archives_count - 1 do if (self.f_archives[i].isExist(FileName)) then begin result := self.f_archives[i]; Exit; end; result := nil; end; function TEushullyFS.getMainArchive(): TEushullyALF; var i: integer; begin for i := 0 to self.f_archives_count - 1 do if (self.f_archives[i].ArchiveType = ALF_DATA) then begin result := self.f_archives[i]; Exit; end; result := nil; end; procedure TEushullyFS.MakeTree(Tree: TTreeView; parent: TTreeNode); var i, j: integer; alf: TEushullyALF; alf_node: TTreeNode; begin for i := 0 to self.f_archives_count - 1 do begin alf := f_archives[i]; alf_node := Tree.Items.AddChild(parent, ExtractFileName(alf.Name)); alf_node.Data := alf; for j := 0 to alf.FilesCount - 1 do begin if (alf.FileName[j] <> '@') then Tree.Items.AddChild(alf_node, alf.FileName[j]).Data := Pointer(j); end; end; Tree.Selected := parent; end; function TEushullyFS.getArchiveByFile(FileName: string): TEushullyALF; var i: integer; begin for i := 0 to self.f_archives_count - 1 do if (self.f_archives[i].isExist(FileName)) then begin result := f_archives[i]; Exit; end; result := nil; end; function TEushullyFS.open(FileName: string): TEushullyFile; begin result := TEushullyFile.Create(self.Archive[FileName], self.Root, FileName); end; end.
unit ftTypes; interface uses hcTypes ,hcConsts ; type TftTipPercentage = (tpNone,tp5,tp10,tp15,tp20,tp25,tp30); TftComboStudio = class(TObject) Name, GUID :string; Number :Integer; end; TftComboStateProvince = class(TObject) Name, GUID :string; end; TftComboDate = class(TObject) DateValue :TDateTime; DateString :string; end; TftLifeStylePassPaymentType = (ptCreditCard,ptDebitCard,ptOnNextVisit); TftLifeStylePaymentStatus = (psSkipped,psFree,psReturned,psPaid,psUnPaid); TftLifeStylePaymentAction = (paNone,paSkip,paFree,paReturn,paPay,paPayProRate); TftAirMilesAction = (amaResubmit = 1,amaSubmit = 2); TftLampWarningLevel = (lwlNone,lwlOne,lwlTwo); TftEmployeeTransactionType = (ettSales,ettTans); TftPackageKind = (pkMinutes, pkVisits, pkDurational); TftTanType = (ttSpray,ttUV,ttRedLight,ttAirbrush,ttLash); TftBulbType = (btUnKnown, btUV, btRedLight); { Security Levels 1 - Bed Cleaner (can login for timesheet tracking but thats it) 2 - Technician or Part-time CEO (can tan people) 3 - Manager or Full-time CEO (control over financials etc) 4 - Franchisee or Administrator (ie: Fabutan Head Office staff) (God like access) } TftSecurityLevel = (slBedCleaner = 1,slTechnician = 2,slManager = 3,slAdmin = 4); TftLampChangeType = (lcRegular =1,lcFirst=2,lc750Hour=3,lcFull=4); TftGoldCardSelectionType = (stForAddon,stForReinstatement,stForRenewal); TftDiscountType = (dtPercentage,dtDollarAmount); TftGender = (gFemale=1,gMale=2); TftMaritalStatus = (msSingle=1,msMarried=2); TftPaymentMethod = (pmNone,pmCash,pmDebitCard,pmCheque,pmVisa,pmMasterCard,pmAMEX,pmDiscover); TInvoiceStatus = (isOpen, isClosed); TInvoiceItemStatus = (iisActive,iisVoid); TEmployeeStatus = (esHidden, esActive, esInActive); TftPercentRange = 0..100; TftRoomFilter = (rfAll,rfAvailable,rfUnderMaintenance,rfInUse,rfAny,rfSprayOnly,rfUVOnly,rfRedLightOnly,rfAirbrushOnly,rfLashOnly); //filter used for SelectRoom dialog results TftRoomFilterSet = set of TftRoomFilter; //filterset since can include or exclude "Any" in combination with Available, UnderMaintenance, and InUse TftBedStatus = (bsInactive,bsUnderMaintenance,bsActive); TftDynamicKV = array of ThcKeyValuePair; TftCardType = (ctGiftCertificate,ctTransfer); TftTaxRates = record GST, PST, UDT :double; IsHST :boolean; IsPSTonGST :boolean; end; TftReturnInfo = class(TObject) public Description, InvoiceGUID, InvoiceProductGUID, ClientAccountGUID, ProductGUID, OptionGUID, GiftCertificateGUID, CommissionEmployeeGUID, GoldCardGUID :string; CardNumber :string; NegatedOriginalQty :integer; DiscountEach, BasePriceEach, SalePriceEach, PriceEach :Currency; GSTRate, PSTRate, UDTRate :single; IsSale, IsCombo, IsSampleCups, IsVoided :boolean; end; TftSecurityInfoType = (itPassword,itPIN); const STR_RedLight = 'Red Light'; STR_UV = 'UV'; //in the database [fnPrimaryPackageCategory] Kevin calls these Categories but in Fabware it's TanType PackageCategories: array[TftTanType] of string = ( 'Spray' ,'UV' ,'RedLight' ,'Airbrush' ,'Lash' ); SecurityLevelNames :array[TftSecurityLevel] of string = ( 'Bed Cleaner', 'Technician', 'Manager', 'Admin' ); LifeStylePaymentStatusNames :array[TftLifeStylePaymentStatus] of string = ( 'Skipped', 'Free', 'Returned', 'Paid', 'Unpaid' ); LifeStylePaymentActionNames :array[TftLifeStylePaymentAction] of string = ( '', 'Skip', 'Free', 'Return', 'Pay', 'PayProRate' ); PackageKindString : array[TftPackageKind] of string = ('Minutes','Visits','Expiry'); //used by routine to strip out undesired payment methods AmexCode :string = 'A'; DiscoverCode :string = 'S'; ChequeCode :string = 'Q'; CardTypeKV :array[TftCardType] of ThcKeyValuePair = ( ('G','Gift Certificate'), ('T','Transfer Card') ); PaymentMethodKV :array[TftPaymentMethod] of ThcKeyValuePair = ( ('N','None'), ('C','Cash'), ('D','Debit Card'), ('Q','Cheque'), ('V','Visa'), ('M','MasterCard'), ('A','AMEX'), ('S','Discover') ); ReferralSource :array[1..11] of string = ('Radio Advertising','Outdoor Advertising','Flyer/Coupon','Online Advertisement','Online Search','Print Advertisement','Social Media','Friend or Family Referral','Owner/Staff member Referral','Signage','Other'); GenderKV :array[1..3] of ThcKeyValuePair = ( (hcConsts.NullKVKey,'UnSpecified'), ('F','Female'), ('M','Male') ); SalutationKV :array[1..3] of ThcKeyValuePair = //maps a salutation selection into a GenderKV key value ( (hcConsts.NullKVKey,'UnSpecified'), ('F','Ms./Mrs.'), ('M','Mr.') ); MaritalStatusKV :array[1..3] of ThcKeyValuePair = ( (hcConsts.NullKVKey,'UnSpecified'), ('S','Single'), ('M','Married') ); BedBulbTypesKV :array[TftBulbType] of ThcKeyValuePair = ( (hcConsts.NullKVKey,'Not Applicable'), (STR_UV,STR_UV), (STR_RedLight,STR_RedLight) ); BedStatusKV :array[TftBedStatus] of ThcKeyValuePair = ( ('I','Delete'), //bed is "removed" and will nto be displayed in list ('M','Maintenance'), //bed is under maintenance. It is displayed but cannot be used ('A','Active') //Bed is usable ); EmployeeStatusCodes :array[TEmployeeStatus] of string = ('H','A','I'); EmployeeStatusNames :array[TEmployeeStatus] of string = ('Hidden','Active','InActive'); DiscountTypeNames :array[TftDiscountType] of String = ('Percentage (%)','Dollar Amount ($)'); LampChangeTypeNames :array[TftLampChangeType] of string = ( 'Regular', 'First', '750 Hour', 'Full' ); LampChangeTypeDescriptions :array[TftLampChangeType] of string = ( 'A REGULAR Lamp Change is Swapping the TOP Lamps to the BOTTOM, and Replacing the TOP Lamps.', 'A FIRST Lamp Change is Replacing the TOP Lamps, and Leaving the BOTTOM Lamps in place.', 'A 750 Hour Bulb Change Leave TOP Lamps, Swap Stored Lamps to the BOTTOM', 'A FULL Lamp Change means you are Replacing BOTH TOP and BOTTOM Lamps' ); function PaymentKeyToValue(const KeyCode :string) :string; implementation function PaymentKeyToValue(const KeyCode :string) :string; var I :TftPaymentMethod; begin for I := low(TftPaymentMethod) to high(TftPaymentMethod) do begin if (PaymentMethodKV[I,Key] = KeyCode) then begin Result := PaymentMethodKV[I,Value]; break; end; end; end; end.
unit Parmlist; interface uses SysUtils,Classes; const DS_SUCCESS=0; type TDSParameter=class(TStringList) protected function GetParam(ind:integer):string; function GetValue(ind:integer):string; public FindFlag:boolean; function ParamByName(ParamName:string):integer; function StrByName(ParamName:string):string; function IntByName(ParamName:string):longint; function BoolByName(ParamName:string):boolean; procedure AddParamStr(ParamName,Value:string); procedure AddParamInt(ParamName:string;Value:longint); procedure AddParamBool(ParamName:string;Value:boolean); property Params[Index:integer]:string read GetParam; property Values[Index:integer]:string read GetValue; end; implementation function TDSParameter.GetParam(ind:integer):string; var k:integer; begin k:=pos('=',Strings[ind]); if k>0 then GetParam:=Copy(Strings[ind],1,k-1) else GetParam:=Strings[ind] end; function TDSParameter.GetValue(ind:integer):string; var k:integer; begin k:=pos('=',Strings[ind]); if k>0 then GetValue:=Copy(Strings[ind],k+1,length(Strings[ind])-k) else GetValue:='' end; function TDSParameter.ParamByName(ParamName:string):integer; var i:integer; begin FindFlag:=FALSE; ParamByName:=-1; for i:=0 to Count-1 do if UpperCase(Params[i])=UpperCase(ParamName) then begin FindFlag:=TRUE; ParamByName:=i; break end; end; function TDSParameter.StrByName(ParamName:string):string; var k:integer; begin k:=ParamByName(ParamName); if FindFlag then StrByName:=Values[k] else StrByName:='' end; function TDSParameter.IntByName(ParamName:string):longint; var k:integer; begin k:=ParamByName(ParamName); IntByName:=0; if FindFlag then try IntByName:=StrToInt(Values[k]) except end end; function TDSParameter.BoolByName(ParamName:string):boolean; var k:integer; begin k:=ParamByName(ParamName); if FindFlag then BoolByName:=Values[k]='1' else BoolByName:=FALSE end; procedure TDSParameter.AddParamStr(ParamName,Value:string); var k:integer; begin k:=ParamByName(ParamName); if FindFlag then Strings[k]:=ParamName+'='+Value else Add(ParamName+'='+Value) end; procedure TDSParameter.AddParamInt(ParamName:string;Value:longint); begin AddParamStr(ParamName,IntToStr(Value)); end; procedure TDSParameter.AddParamBool(ParamName:string;Value:boolean); var s:string; begin if Value then s:='1' else s:='0'; AddParamStr(ParamName,s); end; end.
program tp1_4; uses Crt; type str20 = string[20]; str8 = string[8]; empleado = record nombre: str20; apellido: str20; edad: integer; dni: longint; n_emp: integer; end; archivo = file of empleado; function menu():integer; var opc: integer; begin writeln('Elige una opción: '); writeln('=================='); writeln('1. Ingresar información'); writeln('2. Ver información'); writeln('3. Borrar'); writeln('4. Exportar'); writeln('0. Salir'); readln(opc); menu:= opc; end; function submenuAgregar():integer; var opc: integer; begin writeln('Ingresar información '); writeln('===================='); writeln('1. Crear archivo e ingresar información'); writeln('2. Ingresar empleados al final del archivo'); writeln('3. Modificar edades'); writeln('0. Volver'); readln(opc); submenuAgregar:= opc; end; function submenuExportar():integer; var opc: integer; begin writeln('Exportar'); writeln('========'); writeln('1. Exportar todos los empleados'); writeln('2. Exportar empleados que no tienen DNI definido'); writeln('0. Volver'); readln(opc); submenuExportar:= opc; end; function submenuBorrar():integer; var opc: integer; begin writeln('Borrar'); writeln('========'); writeln('1. Borrar viendo los empleados de forma secuencial'); writeln('2. Borrar por numero de empleado'); writeln('0. Volver'); readln(opc); submenuBorrar:= opc; end; function submenuMostrar():integer; var opc: integer; begin writeln('Abrir archivo: '); writeln('=================='); writeln('1. Listar en pantalla los datos de empleados que tengan un nombre o apellido determinado.'); writeln('2. Listar en pantalla los empleados de a uno por línea'); writeln('3. Listar en pantalla empleados mayores de 70 años'); writeln('0. Volver'); readln(opc); submenuMostrar:= opc; end; procedure crearEmpleados(archivo: str20; tipo: str8); var empleados: archivo; emp: empleado; cont: integer; begin assign(empleados, 'data/ej1/'+ archivo+'.dat'); case tipo of 'new': begin cont:=1; rewrite(empleados); writeln('Ingrese el apellido del empleado #', cont); readln(emp.apellido); while (emp.apellido <> 'fin') do begin writeln('Ingrese el nombre del empleado #', cont); readln(emp.nombre); writeln('Ingrese la edad del empleado #', cont); readln(emp.edad); writeln('Ingrese el dni del empleado #', cont); readln(emp.dni); writeln('Ingrese el N° de empleado del empleado #', cont); readln(emp.n_emp); write(empleados, emp); cont:= cont+1; writeln('Ingrese el apellido del empleado #', cont); readln(emp.apellido); writeln(); end; close(empleados); end; 'end': begin reset(empleados); cont:=fileSize(empleados)+1; seek(empleados, fileSize(empleados)); writeln('Ingrese el apellido del empleado #', cont); readln(emp.apellido); while (emp.apellido <> 'fin') do begin writeln('Ingrese el nombre del empleado #', cont); readln(emp.nombre); writeln('Ingrese la edad del empleado #', cont); readln(emp.edad); writeln('Ingrese el dni del empleado #', cont); readln(emp.dni); writeln('Ingrese el N° de empleado del empleado #', cont); readln(emp.n_emp); write(empleados, emp); cont:= cont+1; writeln('Ingrese el apellido del empleado #', cont); readln(emp.apellido); writeln(); end; close(empleados); end; end; ClrScr; end; procedure exportar(archivo:str20; tipo: str8); var texto: Text; empleados: archivo; emp: empleado; begin assign(empleados, 'data/ej1/'+ archivo+'.dat'); reset(empleados); case tipo of 'full': begin assign(texto, 'data/ej1/todos_empleados.txt'); rewrite(texto); while(not eof(empleados)) do begin Read(empleados, emp); with emp do writeln(texto, ' ', apellido, ' ', nombre, ' ', dni, ' ', edad, ' ', n_emp); end; end; 'dni': begin assign(texto, 'data/ej1/faltaDNIEmpleado.txt'); rewrite(texto); while(not eof(empleados)) do begin Read(empleados, emp); if(emp.dni=00) then begin With emp do writeln(texto, ' ', apellido, ' ', nombre, ' ', dni, ' ', edad, ' ', n_emp); end; end; end; end; writeln('Archivo exportado correctamente...'); close(empleados); close(texto); end; procedure imprimirEmpleado(emp: empleado); begin writeln('Empleado #', emp.n_emp, ': '); writeln('==============='); writeln('Apellido: '+emp.apellido); writeln('Nombre: '+emp.nombre); writeln('Edad: ',emp.edad); writeln('DNI: ',emp.dni); writeln(); end; procedure modificarEdad(archivo: str20); var empleados: archivo; emp: empleado; opc: str8; edad: longint; begin assign(empleados, 'data/ej1/'+archivo+'.dat'); reset(empleados); while(not eof(empleados)) do begin Read(empleados, emp); imprimirEmpleado(emp); writeln('Desea cambiar la edad de este empleado: (s/n): '); readln(opc); if(opc='s') then begin writeln('Introduzca la nueva edad: '); readln(edad); emp.edad:=edad; seek(empleados, filePos(empleados)-1); write(empleados, emp); writeln('Editado correctamente...'); end; end; close(empleados); end; procedure leerUltimo(var empleados: archivo; var emp: empleado); var pos: integer; begin pos:=filePos(empleados)-1; seek(empleados, fileSize(empleados)-1); read(empleados, emp); seek(empleados, filePos(empleados)-1); Truncate(empleados); reset(empleados); seek(empleados, pos); end; procedure borrar(archivo: str20; tipo: str20); var empleados: archivo; emp, emp_ul: empleado; opc: str8; num: integer; borrado: boolean; begin assign(empleados, 'data/ej1/'+archivo+'.dat'); reset(empleados); case tipo of 'secuencial': begin while(not eof(empleados)) do begin Read(empleados, emp); imprimirEmpleado(emp); writeln('Desea borrar este empleado: (s/n): '); readln(opc); if(opc='s') then begin leerUltimo(empleados, emp_ul); write(empleados, emp_ul); writeln('Borrado correctamente...'); end; end; end; 'numero': begin writeln('Ingrese el numero de empleado que desea borrar: '); readln(num); borrado:=false; while(not eof(empleados)) do begin read(empleados, emp); if(emp.n_emp=num) then begin leerUltimo(empleados, emp_ul); write(empleados, emp_ul); borrado:=true; end; end; if(borrado)then writeln('Borrado correctamente') else writeln('El empleado no existia en base de datos'); end; end; close(empleados); end; procedure listarEmpleados(archivo: str20; tipo: str8); var nombre: str20; empleados: archivo; emp: empleado; cont: integer; begin assign(empleados, 'data/ej1/'+ archivo+'.dat'); reset(empleados); cont:=0; ClrScr; case tipo of 'filter': begin writeln('Ingrese el nombre o apellido a filtrar: '); readln(nombre); while (not eof(empleados)) do begin Read(empleados, emp); if((emp.apellido = nombre) or (emp.nombre = nombre)) then begin imprimirEmpleado(emp); cont:=cont+1; end; end; if (cont = 0) then begin writeln('No hay empleados con nombre o apellido igual a '+nombre); writeln(); end; end; 'full': begin if (eof(empleados)) then begin writeln('No hay empleados en la BD.'); end; while (not eof(empleados)) do begin Read(empleados, emp); imprimirEmpleado(emp); end; end; 'old': begin while (not eof(empleados)) do begin Read(empleados, emp); if (emp.edad >= 70) then begin imprimirEmpleado(emp); cont:= cont + 1; end; end; if (cont = 0) then begin writeln('No hay empleados mayores de 70 años.'); writeln(); end; end; end; end; var archivo_nombre: str20; fin: boolean; opcion, subopc: integer; begin fin:=false; writeln('Ingrese el nombre del archivo a trabajar: '); readln(archivo_nombre); repeat opcion:= menu(); case opcion of 1: begin ClrScr; subopc:= submenuAgregar(); case subopc of 1: crearEmpleados(archivo_nombre, 'new'); 2: crearEmpleados(archivo_nombre, 'end'); 3: modificarEdad(archivo_nombre); end; end; 2: begin ClrScr; subopc:= submenuMostrar(); case subopc of 1: listarEmpleados(archivo_nombre, 'filter'); 2: listarEmpleados(archivo_nombre, 'full'); 3: listarEmpleados(archivo_nombre, 'old'); end; end; 3: begin ClrScr; subopc:= submenuBorrar(); case subopc of 1: borrar(archivo_nombre, 'secuencial'); 2: borrar(archivo_nombre, 'numero'); end; end; 4: begin ClrScr; subopc:= submenuExportar(); case subopc of 1: exportar(archivo_nombre, 'full'); 2: exportar(archivo_nombre, 'dni'); end; end; 0: fin:= true; end; until (fin); end.
unit Universe; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DBObjPas; type { TWorldEntity } TWorldEntity = class(TDataTable) { an object in the universe } private function GetEntities(I: Integer): TWorldEntity; public property Entities[I: Integer]: TWorldEntity read GetEntities; end; { TUniverse } TUniverse = class(TWorldEntity) public constructor Create(AnOwner: TComponent); override; {initializes the global typed constant TheUniverse or replaces the instance, that it points to, because only one global instance may exist} end; const TheUniverse: TUniverse = nil; {initialized by TUniverse.Create The initialization is not done by this unit, because the owner of TheUniverse can depend on the kind of application, that uses it} implementation { TWorldEntity } function TWorldEntity.GetEntities(I: Integer): TWorldEntity; begin TDataRecord(Result) := Items[I] end; { TUniverse } constructor TUniverse.Create(AnOwner: TComponent); begin if Assigned(TheUniverse) then raise Exception.Create('The universe already exists.'); inherited Create(AnOwner); TheUniverse := Self end; end.
unit uMainForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, ComCtrls, Spin, Math, BZMath, BZVectorMath, BZVectorMathUtils, BZColors, BZGraphic, BZBitmap; type { TMainForm } TMainForm = class(TForm) Label1 : TLabel; Label2 : TLabel; Label3 : TLabel; Label4 : TLabel; Label5 : TLabel; Label6 : TLabel; Label7 : TLabel; Label8 : TLabel; Panel1 : TPanel; pnlView : TPanel; RadioButton1 : TRadioButton; RadioButton2 : TRadioButton; speScaleFactor : TSpinEdit; tbValueM : TTrackBar; tbValueA : TTrackBar; tbValueB : TTrackBar; tbValueN1 : TTrackBar; tbValueN2 : TTrackBar; tbValueN3 : TTrackBar; tbNbPoints : TTrackBar; procedure FormClose(Sender : TObject; var CloseAction : TCloseAction); procedure FormCreate(Sender : TObject); procedure FormShow(Sender : TObject); procedure pnlViewPaint(Sender : TObject); procedure HandleParamsChange(Sender : TObject); private FDisplayBuffer : TBZBitmap; public procedure UpdateShape; end; var MainForm : TMainForm; implementation {$R *.lfm} uses BZGeoTools; { TMainForm } procedure TMainForm.FormCreate(Sender : TObject); begin FDisplayBuffer := TBZBitmap.Create(pnlView.Width, pnlView.Height); end; procedure TMainForm.FormShow(Sender : TObject); begin UpdateShape; end; procedure TMainForm.pnlViewPaint(Sender : TObject); begin FDisplayBuffer.DrawToCanvas(pnlView.Canvas, pnlView.ClientRect); end; procedure TMainForm.HandleParamsChange(Sender : TObject); begin UpdateShape; end; procedure TMainForm.FormClose(Sender : TObject; var CloseAction : TCloseAction); begin FreeAndNil(FDisplayBuffer); end; procedure TMainForm.UpdateShape; Var m, a, b, n1, n2, n3, sf : Single; pts : TBZArrayOfFloatPoints; begin sf := speScaleFactor.Value; m := tbValueM.Position; a := tbValueA.Position / 100; b := tbValueB.Position / 100; n1 := tbValueN1.Position / 100; n2 := tbValueN2.Position / 100; n3 := tbValueN3.Position / 100; if RadioButton1.Checked then BuildPolySuperShape(vec2(FDisplayBuffer.CenterX, FDisplayBuffer.CenterY), n1,n2,n3,m,a,b,sf,tbNbPoints.Position,pts) else BuildPolyStar(vec2(FDisplayBuffer.CenterX, FDisplayBuffer.CenterY),tbValueA.Position, tbValueB.Position, tbValueM.Position, pts); FDisplayBuffer.Clear(clrBlack); With FDisplayBuffer.Canvas do begin Pen.Style := ssSolid; Pen.Color := clrWhite; Polygon(pts); end; FreeAndNil(pts); pnlView.Invalidate; end; end.
(* @file UGameplayConstants.pas * @author Willi Schinmeyer * @date 2011-10-27 * * UGameplayConstants Unit * * Contains various constants regarding gameplay. *) unit UGameplayConstants; interface uses crt, UTetrominoShape; const (* @brief Possible Tetromino colors * @note Strictly speaking not gameplay relevant, but it fits here *) TETROMINO_COLORS : array[0..3] of byte = ( RED, GREEN, BLUE, YELLOW ); TETROMINO_SHAPES : array[0..6] of TTetrominoShape = ( //O ( (x:-1; y:-1), (x:-1;y:0), (x:0; y:0), (x:0; y:-1) ), //L ( (x:-1; y:-1), (x:-1;y:0), (x:-1; y:1), (x:0; y:-1) ), //J ( (x:0; y:-1), (x:0;y:0), (x:0; y:1), (x:-1; y:-1) ), //T ( (x:-1; y:0), (x:0;y:0), (x:1; y:0), (x:0; y:-1) ), //I ( (x:0; y:-2), (x:0;y:-1), (x:0; y:0), (x:0; y:1) ), //S ( (x:-1; y:-1), (x:-1;y:0), (x:0; y:0), (x:0; y:1) ), //Z ( (x:-1; y:1), (x:-1;y:0), (x:0; y:0), (x:0; y:-1) ) ); //keep in sync with shape definitions above TETROMINO_MIN_X = -1; TETROMINO_MIN_Y = -2; TETROMINO_MAX_X = 1; TETROMINO_MAX_Y = 1; GAMEFIELD_WIDTH = 10; GAMEFIELD_HEIGHT = 20; //time a tetromino initially needs to drop one step (in ms) TETROMINO_BASE_DROP_TIME : integer = 1000; //factor by which the drop time is multiplied every level TETROMINO_DROP_TIME_FACTOR : real = 0.8; //minimum drop time (0 might cause infinite loops) TETROMINO_MIN_DROP_TIME : integer = 1; //score you get per complete row SCORE_PER_ROW : integer = 10; //bonus score multiplier applied for every row > 1 SCORE_ROW_MULTIPLIER : real = 1.5; //bonus score multiplier applied for every level > 1 SCORE_LEVEL_MULTIPLIER : real = 1.2; //Rows that need to be removed to advance to the next level ROWS_PER_LEVEL : integer = 10; implementation begin end.
unit RRManagerLicenseConditionTreeFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Facade, Dialogs, StdCtrls, ComCtrls, LicenseZone; type TfrmLicenseConditionTree = class(TFrame) gbxSearch: TGroupBox; edtSearch: TEdit; trwConditions: TTreeView; btnNext: TButton; procedure btnNextClick(Sender: TObject); procedure edtSearchChange(Sender: TObject); private { Private declarations } FInitSearch: boolean; function FindItem(ACaption: string; FindFirst: boolean): TTreeNode; function GetActiveLicenseCondition: TLicenseCondition; function GetActiveLicenseKind: TLicenseConditionKind; public { Public declarations } property ActiveLicenseKind: TLicenseConditionKind read GetActiveLicenseKind; property ActiveLicenseCondition: TLicenseCondition read GetActiveLicenseCondition; procedure MakeTree; end; implementation {$R *.dfm} { TfrmLicenseConditionTree } function TfrmLicenseConditionTree.GetActiveLicenseCondition: TLicenseCondition; begin Result := nil; if Assigned(trwConditions.Selected) and (trwConditions.Selected.Level = 1) then Result := TLicenseCondition(trwConditions.Selected.Data); end; function TfrmLicenseConditionTree.GetActiveLicenseKind: TLicenseConditionKind; begin Result := nil; if Assigned(trwConditions.Selected) then begin if trwConditions.Selected.Level = 0 then Result := TLicenseConditionKind(trwConditions.Selected.Data) else Result := TLicenseConditionKind(trwConditions.Selected.Parent.Data); end; end; procedure TfrmLicenseConditionTree.MakeTree; var i, j: integer; Node: TTreeNode; begin Node := nil; for i := 0 to (TMainFacade.GetInstance as TMainFacade).AllLicenseConditionKinds.Count - 1 do begin Node := trwConditions.Items.AddObject(Node, (TMainFacade.GetInstance as TMainFacade).AllLicenseConditionKinds.Items[i].List, (TMainFacade.GetInstance as TMainFacade).AllLicenseConditionKinds.Items[i]); for j := 0 to (TMainFacade.GetInstance as TMainFacade).AllLicenseConditions.Count - 1 do if (TMainFacade.GetInstance as TMainFacade).AllLicenseConditions.Items[j].LicenseConditionKind = (TMainFacade.GetInstance as TMainFacade).AllLicenseConditionKinds.Items[i] then trwConditions.Items.AddChildObject(Node, (TMainFacade.GetInstance as TMainFacade).AllLicenseConditions.Items[j].List, (TMainFacade.GetInstance as TMainFacade).AllLicenseConditions.Items[j]); Node.Expand(true); end; end; procedure TfrmLicenseConditionTree.btnNextClick(Sender: TObject); begin FindItem(edtSearch.Text, not FInitSearch); FInitSearch := true; btnNext.Caption := 'Далее'; end; function TfrmLicenseConditionTree.FindItem(ACaption: string; FindFirst: boolean): TTreeNode; var Node: TTreeNode; begin if FindFirst then Node := trwConditions.Items.GetFirstNode else if Assigned(trwConditions.Selected) then Node := trwConditions.Selected.GetNext; while Assigned(Node) do begin if pos(AnsiUpperCase(ACaption), AnsiUpperCase(Node.Text)) > 0 then begin Node.Selected := true; Result := Node; break; end; Node := Node.GetNext; end; end; procedure TfrmLicenseConditionTree.edtSearchChange(Sender: TObject); begin FInitSearch := false; btnNext.Caption := 'Найти'; end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Janela Cadastro de Pessoas The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije @version 2.0 ******************************************************************************* } unit UPessoa; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UTelaCadastro, Menus, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, Mask, JvExMask, JvToolEdit, JvCombobox, LabeledCtrls, DBCtrls, LabeledDBCtrls, DB, DBClient, StrUtils, Math, VO, PessoaFisicaVO, PessoaJuridicaVO, Generics.Collections, Atributos, Constantes, CheckLst, JvExCheckLst, JvCheckListBox, JvBaseEdits, Controller, Actions, ActnList, RibbonSilverStyleActnCtrls, ActnMan, ToolWin, ActnCtrls, Biblioteca; type [TFormDescription(TConstantes.MODULO_CADASTROS, 'Pessoa')] TFPessoa = class(TFTelaCadastro) ScrollBox: TScrollBox; PageControlDadosPessoa: TPageControl; tsTipoPessoa: TTabSheet; PanelDadosPessoa: TPanel; PageControlTipoPessoa: TPageControl; tsPessoaFisica: TTabSheet; PanelPessoaFisica: TPanel; EditCPF: TLabeledMaskEdit; GroupBoxRG: TGroupBox; EditRGNumero: TLabeledEdit; EditRGEmissao: TLabeledDateEdit; EditRGOrgaoEmissor: TLabeledEdit; EditNascimento: TLabeledDateEdit; RadioGroupSexo: TRadioGroup; LComboBoxEstadoCivil: TLabeledDBLookupComboBox; tsPessoaJuridica: TTabSheet; PanelPessoaJuridica: TPanel; EditFantasia: TLabeledEdit; EditCNPJ: TLabeledMaskEdit; EditInscricaoMunicipal: TLabeledEdit; EditDataConstituicao: TLabeledDateEdit; tsContato: TTabSheet; PanelContatos: TPanel; GridContato: TJvDBUltimGrid; EditNomeMae: TLabeledEdit; EditNaturalidade: TLabeledEdit; EditNacionalidade: TLabeledEdit; ComboBoxRaca: TLabeledComboBox; ComboBoxTipoSangue: TLabeledComboBox; GroupBoxCNH: TGroupBox; EditCNHNumero: TLabeledEdit; EditCNHVencimento: TLabeledDateEdit; ComboBoxCNHCategoria: TLabeledComboBox; GroupBoxTituloEleitoral: TGroupBox; EditTituloNumero: TLabeledEdit; EditTituloZona: TLabeledCalcEdit; EditTituloSecao: TLabeledCalcEdit; EditNomePai: TLabeledEdit; GroupBoxReservista: TGroupBox; EditReservistaNumero: TLabeledEdit; ComboBoxReservistaCategoria: TLabeledComboBox; EditInscricaoEstadual: TLabeledEdit; EditSuframa: TLabeledEdit; ComboBoxTipoRegime: TLabeledComboBox; ComboBoxCRT: TLabeledComboBox; tsEndereco: TTabSheet; PanelEnderecos: TPanel; GridEndereco: TJvDBUltimGrid; PanelPessoaDadosBase: TPanel; EditEmail: TLabeledEdit; EditNome: TLabeledEdit; ComboboxTipoPessoa: TLabeledComboBox; CheckListBoxPessoa: TJvCheckListBox; EditSite: TLabeledEdit; CDSEndereco: TClientDataSet; DSEndereco: TDataSource; CDSContato: TClientDataSet; DSContato: TDataSource; CDSEstadoCivil: TClientDataSet; DSEstadoCivil: TDataSource; ActionToolBar2: TActionToolBar; ActionManager: TActionManager; ActionExcluirContato: TAction; ActionExcluirEndereco: TAction; ActionExcluirTelefone: TAction; ActionToolBar1: TActionToolBar; tsTelefone: TTabSheet; CDSTelefone: TClientDataSet; DSTelefone: TDataSource; PanelTelefones: TPanel; GridTelefone: TJvDBUltimGrid; ActionToolBar3: TActionToolBar; procedure FormCreate(Sender: TObject); procedure ComboboxTipoPessoaChange(Sender: TObject); procedure ActionExcluirContatoExecute(Sender: TObject); procedure ActionExcluirEnderecoExecute(Sender: TObject); procedure ActionExcluirTelefoneExecute(Sender: TObject); procedure ControlaPersistencia(pDataSet: TDataSet); procedure ControlaInsercaoGridInterna(pDataSet: TDataSet; pCampoControle: String); private { Private declarations } IdTipoPessoa: Integer; public { Public declarations } procedure GridParaEdits; override; procedure LimparCampos; override; // Controles CRUD function DoInserir: Boolean; override; function DoEditar: Boolean; override; function DoExcluir: Boolean; override; function DoSalvar: Boolean; override; procedure ExibirDadosTipoPessoa; procedure ConfigurarLayoutTela; procedure PopulaComboEstadoCivil(Sender: TObject); end; var FPessoa: TFPessoa; implementation uses EstadoCivilController, PessoaController, EstadoCivilVO, PessoaVO, PessoaContatoVO, PessoaEnderecoVO, PessoaTelefoneVO; {$R *.dfm} {$Region 'Infra'} procedure TFPessoa.FormCreate(Sender: TObject); var I: Integer; begin ClasseObjetoGridVO := TPessoaVO; ObjetoController := TPessoaController.Create; inherited; PopulaComboEstadoCivil(Self); // Configura a Grid dos Endereços ConfiguraCDSFromVO(CDSEndereco, TPessoaEnderecoVO); ConfiguraGridFromVO(GridEndereco, TPessoaEnderecoVO); // Configura a Grid dos Contatos ConfiguraCDSFromVO(CDSContato, TPessoaContatoVO); ConfiguraGridFromVO(GridContato, TPessoaContatoVO); // Configura a Grid dos Telefones ConfiguraCDSFromVO(CDSTelefone, TPessoaTelefoneVO); ConfiguraGridFromVO(GridTelefone, TPessoaTelefoneVO); end; procedure TFPessoa.ConfigurarLayoutTela; begin PageControlDadosPessoa.ActivePageIndex := 0; PanelEdits.Enabled := True; if StatusTela = stNavegandoEdits then begin PanelDadosPessoa.Enabled := False; PanelContatos.Enabled := False; PanelEnderecos.Enabled := False; PanelPessoaDadosBase.Enabled := False; PanelTelefones.Enabled := False; end else begin PanelDadosPessoa.Enabled := True; PanelContatos.Enabled := True; PanelEnderecos.Enabled := True; PanelTelefones.Enabled := True; PanelPessoaDadosBase.Enabled := True; end; ExibirDadosTipoPessoa; end; procedure TFPessoa.ExibirDadosTipoPessoa; begin case ComboboxTipoPessoa.ItemIndex of 0: begin PanelPessoaFisica.Parent := PanelDadosPessoa; PanelPessoaFisica.Visible := True; PanelPessoaJuridica.Visible := False; end; 1: begin PanelPessoaJuridica.Parent := PanelDadosPessoa; PanelPessoaFisica.Visible := False; PanelPessoaJuridica.Visible := True; end; end; end; procedure TFPessoa.PopulaComboEstadoCivil(Sender: TObject); begin ConfiguraCDSFromVO(CDSEstadoCivil, TEstadoCivilVO); TEstadoCivilController.SetDataSet(CDSEstadoCivil); TController.ExecutarMetodo('EstadoCivilController.TEstadoCivilController', 'Consulta', ['ID>0', '0', False], 'GET', 'Lista'); LComboBoxEstadoCivil.ListField := 'NOME'; LComboBoxEstadoCivil.KeyField := 'ID' end; procedure TFPessoa.LimparCampos; var I: Integer; begin inherited; // Pessoa ComboboxTipoPessoa.ItemIndex := 0; // Pessoa Física RadioGroupSexo.ItemIndex := -1; LComboBoxEstadoCivil.KeyValue := Null; // Contatos CDSContato.EmptyDataSet; // Endereços CDSEndereco.EmptyDataSet; // Telefones CDSTelefone.EmptyDataSet; // CheckListBox for I := 0 to CheckListBoxPessoa.Items.Count - 1 do CheckListBoxPessoa.Checked[I] := False; end; procedure TFPessoa.ComboboxTipoPessoaChange(Sender: TObject); begin ExibirDadosTipoPessoa; end; {$EndRegion 'Infra'} {$REGION 'Controles CRUD'} function TFPessoa.DoInserir: Boolean; begin Result := inherited DoInserir; if Result then begin IdTipoPessoa := 0; EditNome.SetFocus; ComboboxTipoPessoa.Enabled := True; ExibirDadosTipoPessoa; end; end; function TFPessoa.DoEditar: Boolean; begin Result := inherited DoEditar; if Result then begin EditNome.SetFocus; ComboboxTipoPessoa.Enabled := False; end; end; function TFPessoa.DoExcluir: Boolean; begin if inherited DoExcluir then begin try TController.ExecutarMetodo('PessoaController.TPessoaController', 'Exclui', [IdRegistroSelecionado], 'DELETE', 'Boolean'); Result := TController.RetornoBoolean; except Result := False; end; end else begin Result := False; end; if Result then TController.ExecutarMetodo('PessoaController.TPessoaController', 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista'); end; function TFPessoa.DoSalvar: Boolean; begin if EditNome.Text = '' then begin Application.MessageBox('Informe o nome da pessoa.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); EditNome.SetFocus; Exit(False); end else if ComboboxTipoPessoa.ItemIndex = 0 then begin if EditCPF.Text = '' then begin Application.MessageBox('Informe o CPF da pessoa.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); EditCPF.SetFocus; Exit(False); end else if EditNomeMae.Text = '' then begin Application.MessageBox('Informe o nome da mãe.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); EditNomeMae.SetFocus; Exit(False); end else if LComboBoxEstadoCivil.KeyValue = Null then begin Application.MessageBox('Selecione o estado civil.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); LComboBoxEstadoCivil.SetFocus; Exit(False); end end else if ComboboxTipoPessoa.ItemIndex = 1 then begin if EditCNPJ.Text = '' then begin Application.MessageBox('Informe o CNPJ da pessoa.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); EditCNPJ.SetFocus; Exit(False); end; end; Result := inherited DoSalvar; if Result then begin try if not Assigned(ObjetoVO) then ObjetoVO := TPessoaVO.Create; TPessoaVO(ObjetoVO).Nome := EditNome.Text; TPessoaVO(ObjetoVO).Tipo := IfThen(ComboboxTipoPessoa.ItemIndex = 0, 'F', 'J'); TPessoaVO(ObjetoVO).Email := EditEmail.Text; TPessoaVO(ObjetoVO).Site := EditSite.Text; TPessoaVO(ObjetoVO).Cliente := IfThen(CheckListBoxPessoa.Checked[0], 'S', 'N'); TPessoaVO(ObjetoVO).Fornecedor := IfThen(CheckListBoxPessoa.Checked[1], 'S', 'N'); TPessoaVO(ObjetoVO).Colaborador := IfThen(CheckListBoxPessoa.Checked[2], 'S', 'N'); TPessoaVO(ObjetoVO).Transportadora := IfThen(CheckListBoxPessoa.Checked[3], 'S', 'N'); // Tipo de Pessoa if TPessoaVO(ObjetoVO).Tipo = 'F' then begin TPessoaVO(ObjetoVO).PessoaFisicaVO.Id := IdTipoPessoa; TPessoaVO(ObjetoVO).PessoaFisicaVO.IdPessoa := TPessoaVO(ObjetoVO).Id; TPessoaVO(ObjetoVO).PessoaFisicaVO.CPF := EditCPF.Text; TPessoaVO(ObjetoVO).PessoaFisicaVO.DataNascimento := EditNascimento.Date; if LComboBoxEstadoCivil.KeyValue <> Null then TPessoaVO(ObjetoVO).PessoaFisicaVO.IdEstadoCivil := LComboBoxEstadoCivil.KeyValue; TPessoaVO(ObjetoVO).PessoaFisicaVO.Raca := Copy(ComboBoxRaca.Text, 1, 1); TPessoaVO(ObjetoVO).PessoaFisicaVO.TipoSangue := Copy(ComboBoxTipoSangue.Text, 1, 1); TPessoaVO(ObjetoVO).PessoaFisicaVO.Naturalidade := EditNaturalidade.Text; TPessoaVO(ObjetoVO).PessoaFisicaVO.Nacionalidade := EditNacionalidade.Text; TPessoaVO(ObjetoVO).PessoaFisicaVO.NomePai := EditNomePai.Text; TPessoaVO(ObjetoVO).PessoaFisicaVO.NomeMae := EditNomeMae.Text; TPessoaVO(ObjetoVO).PessoaFisicaVO.RG := EditRGNumero.Text; TPessoaVO(ObjetoVO).PessoaFisicaVO.DataEmissaoRg := EditRGEmissao.Date; TPessoaVO(ObjetoVO).PessoaFisicaVO.OrgaoRg := EditRGOrgaoEmissor.Text; TPessoaVO(ObjetoVO).PessoaFisicaVO.ReservistaNumero := EditReservistaNumero.Text; if ComboBoxReservistaCategoria.Text <> '' then TPessoaVO(ObjetoVO).PessoaFisicaVO.ReservistaCategoria := StrToInt(ComboBoxReservistaCategoria.Text); case RadioGroupSexo.ItemIndex of 0: TPessoaVO(ObjetoVO).PessoaFisicaVO.Sexo := 'F'; 1: TPessoaVO(ObjetoVO).PessoaFisicaVO.Sexo := 'M'; else TPessoaVO(ObjetoVO).PessoaFisicaVO.Sexo := ''; end; TPessoaVO(ObjetoVO).PessoaFisicaVO.CnhNumero := EditCNHNumero.Text; TPessoaVO(ObjetoVO).PessoaFisicaVO.CnhVencimento := EditCNHVencimento.Date; TPessoaVO(ObjetoVO).PessoaFisicaVO.CnhCategoria := ComboBoxCNHCategoria.Text; TPessoaVO(ObjetoVO).PessoaFisicaVO.TituloEleitoralNumero := EditTituloNumero.Text; TPessoaVO(ObjetoVO).PessoaFisicaVO.TituloEleitoralZona := EditTituloZona.AsInteger; TPessoaVO(ObjetoVO).PessoaFisicaVO.TituloEleitoralSecao := EditTituloSecao.AsInteger; end else if TPessoaVO(ObjetoVO).Tipo = 'J' then begin TPessoaVO(ObjetoVO).PessoaJuridicaVO.Id := IdTipoPessoa; TPessoaVO(ObjetoVO).PessoaJuridicaVO.IdPessoa := TPessoaVO(ObjetoVO).Id; TPessoaVO(ObjetoVO).PessoaJuridicaVO.Fantasia := EditFantasia.Text; TPessoaVO(ObjetoVO).PessoaJuridicaVO.Cnpj := EditCNPJ.Text; TPessoaVO(ObjetoVO).PessoaJuridicaVO.InscricaoEstadual := EditInscricaoEstadual.Text; TPessoaVO(ObjetoVO).PessoaJuridicaVO.InscricaoMunicipal := EditInscricaoMunicipal.Text; TPessoaVO(ObjetoVO).PessoaJuridicaVO.DataConstituicao := EditDataConstituicao.Date; TPessoaVO(ObjetoVO).PessoaJuridicaVO.Suframa := EditSuframa.Text; TPessoaVO(ObjetoVO).PessoaJuridicaVO.TipoRegime := Copy(ComboBoxTipoRegime.Text, 1, 1); TPessoaVO(ObjetoVO).PessoaJuridicaVO.Crt := Copy(ComboBoxCRT.Text, 1, 1); end; // Contatos TController.PreencherObjectListFromCDS<TPessoaContatoVO>(TPessoaVO(ObjetoVO).ListaPessoaContatoVO, CDSContato); // Endereços TController.PreencherObjectListFromCDS<TPessoaEnderecoVO>(TPessoaVO(ObjetoVO).ListaPessoaEnderecoVO, CDSEndereco); // Telefones TController.PreencherObjectListFromCDS<TPessoaTelefoneVO>(TPessoaVO(ObjetoVO).ListaPessoaTelefoneVO, CDSTelefone); if StatusTela = stInserindo then TController.ExecutarMetodo('PessoaController.TPessoaController', 'Insere', [TPessoaVO(ObjetoVO)], 'PUT', 'Lista') else if StatusTela = stEditando then begin if TPessoaVO(ObjetoVO).ToJSONString <> StringObjetoOld then begin TController.ExecutarMetodo('PessoaController.TPessoaController', 'Altera', [TPessoaVO(ObjetoVO)], 'POST', 'Boolean'); end else Application.MessageBox('Nenhum dado foi alterado.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); end; except Result := False; end; end; end; {$ENDREGION} {$REGION 'Controle de Grids e ClientDataSets'} procedure TFPessoa.GridParaEdits; begin inherited; if not CDSGrid.IsEmpty then begin ObjetoVO := TPessoaVO(TController.BuscarObjeto('PessoaController.TPessoaController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET')); end; if Assigned(ObjetoVO) then begin // Pessoa EditNome.Text := TPessoaVO(ObjetoVO).Nome; ComboboxTipoPessoa.ItemIndex := IfThen(TPessoaVO(ObjetoVO).Tipo = 'F', 0, 1); EditEmail.Text := TPessoaVO(ObjetoVO).Email; EditSite.Text := TPessoaVO(ObjetoVO).Site; if TPessoaVO(ObjetoVO).Cliente = 'S' then CheckListBoxPessoa.Checked[0] := True; if TPessoaVO(ObjetoVO).Fornecedor = 'S' then CheckListBoxPessoa.Checked[1] := True; if TPessoaVO(ObjetoVO).Colaborador = 'S' then CheckListBoxPessoa.Checked[2] := True; if TPessoaVO(ObjetoVO).Transportadora = 'S' then CheckListBoxPessoa.Checked[3] := True; // Tipo Pessoa if (TPessoaVO(ObjetoVO).Tipo = 'F') and (Assigned(TPessoaVO(ObjetoVO).PessoaFisicaVO)) then // Pessoa Física begin IdTipoPessoa := TPessoaVO(ObjetoVO).PessoaFisicaVO.Id; EditCPF.Text := TPessoaVO(ObjetoVO).PessoaFisicaVO.CPF; EditNascimento.Date := TPessoaVO(ObjetoVO).PessoaFisicaVO.DataNascimento; if TPessoaVO(ObjetoVO).PessoaFisicaVO.IdEstadoCivil > 0 then LComboBoxEstadoCivil.KeyValue := TPessoaVO(ObjetoVO).PessoaFisicaVO.IdEstadoCivil; case AnsiIndexStr(TPessoaVO(ObjetoVO).PessoaFisicaVO.Raca, ['B', 'N', 'P', 'I']) of 0: ComboBoxRaca.ItemIndex := 0; 1: ComboBoxRaca.ItemIndex := 1; 2: ComboBoxRaca.ItemIndex := 2; 3: ComboBoxRaca.ItemIndex := 3; else ComboBoxRaca.ItemIndex := -1; end; case AnsiIndexStr(TPessoaVO(ObjetoVO).PessoaFisicaVO.TipoSangue, ['A+', 'A-', 'B+', 'B-', 'O+', 'O-', 'AB+', 'AB-']) of 0: ComboBoxTipoSangue.ItemIndex := 0; 1: ComboBoxTipoSangue.ItemIndex := 1; 2: ComboBoxTipoSangue.ItemIndex := 2; 3: ComboBoxTipoSangue.ItemIndex := 3; 4: ComboBoxTipoSangue.ItemIndex := 4; 5: ComboBoxTipoSangue.ItemIndex := 5; 6: ComboBoxTipoSangue.ItemIndex := 6; 7: ComboBoxTipoSangue.ItemIndex := 7; else ComboBoxTipoSangue.ItemIndex := -1; end; EditNaturalidade.Text := TPessoaVO(ObjetoVO).PessoaFisicaVO.Naturalidade; EditNacionalidade.Text := TPessoaVO(ObjetoVO).PessoaFisicaVO.Nacionalidade; EditNomePai.Text := TPessoaVO(ObjetoVO).PessoaFisicaVO.NomePai; EditNomeMae.Text := TPessoaVO(ObjetoVO).PessoaFisicaVO.NomeMae; EditRGNumero.Text := TPessoaVO(ObjetoVO).PessoaFisicaVO.RG; EditRGEmissao.Date := TPessoaVO(ObjetoVO).PessoaFisicaVO.DataEmissaoRg; EditRGOrgaoEmissor.Text := TPessoaVO(ObjetoVO).PessoaFisicaVO.OrgaoRg; EditReservistaNumero.Text := TPessoaVO(ObjetoVO).PessoaFisicaVO.ReservistaNumero; ComboBoxReservistaCategoria.ItemIndex := TPessoaVO(ObjetoVO).PessoaFisicaVO.ReservistaCategoria - 1; case AnsiIndexStr(TPessoaVO(ObjetoVO).PessoaFisicaVO.Sexo, ['F', 'M']) of 0: RadioGroupSexo.ItemIndex := 0; 1: RadioGroupSexo.ItemIndex := 1; else RadioGroupSexo.ItemIndex := -1; end; EditCNHNumero.Text := TPessoaVO(ObjetoVO).PessoaFisicaVO.CnhNumero; EditCNHVencimento.Date := TPessoaVO(ObjetoVO).PessoaFisicaVO.CnhVencimento; case AnsiIndexStr(TPessoaVO(ObjetoVO).PessoaFisicaVO.CnhCategoria, ['A', 'B', 'C', 'D', 'E']) of 0: ComboBoxCNHCategoria.ItemIndex := 0; 1: ComboBoxCNHCategoria.ItemIndex := 1; 2: ComboBoxCNHCategoria.ItemIndex := 2; 3: ComboBoxCNHCategoria.ItemIndex := 3; 4: ComboBoxCNHCategoria.ItemIndex := 4; else ComboBoxCNHCategoria.ItemIndex := -1; end; EditTituloNumero.Text := TPessoaVO(ObjetoVO).PessoaFisicaVO.TituloEleitoralNumero; EditTituloZona.AsInteger := TPessoaVO(ObjetoVO).PessoaFisicaVO.TituloEleitoralZona; EditTituloSecao.AsInteger := TPessoaVO(ObjetoVO).PessoaFisicaVO.TituloEleitoralSecao; end else if (TPessoaVO(ObjetoVO).Tipo = 'J') and (Assigned(TPessoaVO(ObjetoVO).PessoaJuridicaVO)) then // Pessoa Jurídica begin IdTipoPessoa := TPessoaVO(ObjetoVO).PessoaJuridicaVO.Id; EditFantasia.Text := TPessoaVO(ObjetoVO).PessoaJuridicaVO.Fantasia; EditCNPJ.Text := TPessoaVO(ObjetoVO).PessoaJuridicaVO.Cnpj; EditInscricaoEstadual.Text := TPessoaVO(ObjetoVO).PessoaJuridicaVO.InscricaoEstadual; EditInscricaoMunicipal.Text := TPessoaVO(ObjetoVO).PessoaJuridicaVO.InscricaoMunicipal; EditDataConstituicao.Date := TPessoaVO(ObjetoVO).PessoaJuridicaVO.DataConstituicao; EditSuframa.Text := TPessoaVO(ObjetoVO).PessoaJuridicaVO.Suframa; case AnsiIndexStr(TPessoaVO(ObjetoVO).PessoaJuridicaVO.TipoRegime, ['1', '2', '3']) of 0: ComboBoxTipoRegime.ItemIndex := 0; 1: ComboBoxTipoRegime.ItemIndex := 1; 2: ComboBoxTipoRegime.ItemIndex := 2; else ComboBoxTipoRegime.ItemIndex := -1; end; case AnsiIndexStr(TPessoaVO(ObjetoVO).PessoaJuridicaVO.Crt, ['1', '2', '3']) of 0: ComboBoxCRT.ItemIndex := 0; 1: ComboBoxCRT.ItemIndex := 1; 2: ComboBoxCRT.ItemIndex := 2; else ComboBoxCRT.ItemIndex := -1; end; end; // Preenche as grids internas com os dados das Listas que vieram no objeto TController.TratarRetorno<TPessoaEnderecoVO>(TPessoaVO(ObjetoVO).ListaPessoaEnderecoVO, True, True, CDSEndereco); TController.TratarRetorno<TPessoaContatoVO>(TPessoaVO(ObjetoVO).ListaPessoaContatoVO, True, True, CDSContato); TController.TratarRetorno<TPessoaTelefoneVO>(TPessoaVO(ObjetoVO).ListaPessoaTelefoneVO, True, True, CDSTelefone); // Limpa as listas para comparar posteriormente se houve inclusões/alterações e subir apenas o necessário para o servidor TPessoaVO(ObjetoVO).ListaPessoaEnderecoVO.Clear; TPessoaVO(ObjetoVO).ListaPessoaContatoVO.Clear; TPessoaVO(ObjetoVO).ListaPessoaTelefoneVO.Clear; // Serializa o objeto para consultar posteriormente se houve alterações FormatSettings.DecimalSeparator := '.'; StringObjetoOld := ObjetoVO.ToJSONString; FormatSettings.DecimalSeparator := ','; end; ConfigurarLayoutTela; end; procedure TFPessoa.ControlaInsercaoGridInterna(pDataSet: TDataSet; pCampoControle: String); begin if Trim(pDataSet.FieldByName(pCampoControle).AsString) = '' then pDataSet.Cancel; end; procedure TFPessoa.ControlaPersistencia(pDataSet: TDataSet); begin pDataSet.FieldByName('PERSISTE').AsString := 'S'; end; {$ENDREGION} {$REGION 'Exclusões Internas'} procedure TFPessoa.ActionExcluirContatoExecute(Sender: TObject); begin if not CDSContato.IsEmpty then begin if Application.MessageBox('Tem certeza que deseja excluir o registro selecionado?', 'Pergunta do Sistema', MB_YesNo + MB_IconQuestion) = IdYes then begin if StatusTela = stInserindo then CDSContato.Delete else if StatusTela = stEditando then begin TController.ExecutarMetodo('PessoaController.TPessoaController', 'ExcluiContato', [CDSContato.FieldByName('ID').AsInteger], 'DELETE', 'Boolean'); if TController.RetornoBoolean then CDSContato.Delete; end; end; end else Application.MessageBox('Não existem dados para serem excluídos.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); end; procedure TFPessoa.ActionExcluirEnderecoExecute(Sender: TObject); begin if not CDSEndereco.IsEmpty then begin if Application.MessageBox('Tem certeza que deseja excluir o registro selecionado?', 'Pergunta do Sistema', MB_YesNo + MB_IconQuestion) = IdYes then begin if StatusTela = stInserindo then CDSEndereco.Delete else if StatusTela = stEditando then begin TController.ExecutarMetodo('PessoaController.TPessoaController', 'ExcluiEndereco', [CDSEndereco.FieldByName('ID').AsInteger], 'DELETE', 'Boolean'); if TController.RetornoBoolean then CDSEndereco.Delete; end; end; end else Application.MessageBox('Não existem dados para serem excluídos.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); end; procedure TFPessoa.ActionExcluirTelefoneExecute(Sender: TObject); begin if not CDSTelefone.IsEmpty then begin if Application.MessageBox('Tem certeza que deseja excluir o registro selecionado?', 'Pergunta do Sistema', MB_YesNo + MB_IconQuestion) = IdYes then begin if StatusTela = stInserindo then CDSTelefone.Delete else if StatusTela = stEditando then begin TController.ExecutarMetodo('PessoaController.TPessoaController', 'ExcluiTelefone', [CDSTelefone.FieldByName('ID').AsInteger], 'DELETE', 'Boolean'); if TController.RetornoBoolean then CDSTelefone.Delete; end; end; end else Application.MessageBox('Não existem dados para serem excluídos.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); end; {$EndREGION 'Exclusões Internas'} end.
unit Automobile; interface const RESISTOR_STATE_B = 0; RESISTOR_STATE_C = 1; RESISTOR_STATE_D = 2; type TOnEventChargeLevelChanged = procedure (newLevel: Integer) of object; TOnEventResistorStateChanged = procedure (newState: Integer) of object; TAutomobile = class private FCapacity: Integer; FChargeLevel: Integer; FResistorState: Integer; FChargingAllow: Boolean; FUseFan: Boolean; FAutoMode: Boolean; FOnChargeLevelChanged: TOnEventChargeLevelChanged; FOnResistorStateChanged: TOnEventResistorStateChanged; procedure SetChargeLevel(const Value: Integer); procedure SetResisorState(const Value: Integer); procedure SetChargingAllow(const Value: Boolean); function GetIsFullCharge: Boolean; public constructor Create(Cap: Integer); function ConsumeEnergy(Value: Integer): Integer; procedure SetResistorToInitState; property Capacity: Integer read FCapacity; property ChargeLevel: Integer read FChargeLevel write SetChargeLevel; property ResistorState: Integer read FResistorState write SetResisorState; property ChargingAllow: Boolean read FChargingAllow write SetChargingAllow; property AutoMode: Boolean read FAutoMode write FAutoMode; property IsFullCharge: Boolean read GetIsFullCharge; property OnChargeLevelChanged: TOnEventChargeLevelChanged read FOnChargeLevelChanged write FOnChargeLevelChanged; property OnResistorStateChanged: TOnEventResistorStateChanged read FOnResistorStateChanged write FOnResistorStateChanged; end; implementation { TAutomobile } function TAutomobile.ConsumeEnergy(Value: Integer): Integer; var LeftSpace: Integer; begin LeftSpace := Capacity - ChargeLevel; if Value > LeftSpace then Value := LeftSpace; ChargeLevel := ChargeLevel + Value; if IsFullCharge then ResistorState := RESISTOR_STATE_B; Result := Value; end; constructor TAutomobile.Create(Cap: Integer); begin FCapacity := Cap; FResistorState := RESISTOR_STATE_B; FUseFan := False; FAutoMode := True; FChargingAllow := False; end; function TAutomobile.GetIsFullCharge: Boolean; begin Result := (FChargeLevel >= FCapacity); end; procedure TAutomobile.SetChargeLevel(const Value: Integer); begin if FChargeLevel = Value then Exit; if Value > FCapacity then FChargeLevel := FCapacity else if Value < 0 then FChargeLevel := 0; FChargeLevel := Value; if Assigned(FOnChargeLevelChanged) then FOnChargeLevelChanged(FChargeLevel); end; procedure TAutomobile.SetChargingAllow(const Value: Boolean); begin if(FChargingAllow = Value) then Exit; FChargingAllow := Value; if FChargingAllow then begin if FAutoMode and not IsFullCharge then begin if FUseFan then ResistorState := RESISTOR_STATE_D else ResistorState := RESISTOR_STATE_C; end; end else begin if FAutoMode then ResistorState := RESISTOR_STATE_B; end; end; procedure TAutomobile.SetResisorState(const Value: Integer); begin if FResistorState = Value then Exit; FResistorState := Value; if Assigned(FOnResistorStateChanged) then FOnResistorStateChanged(FResistorState); end; procedure TAutomobile.SetResistorToInitState; begin ResistorState := RESISTOR_STATE_B; FChargingAllow := False; end; end.
{******************************************************************************* 作者: dmzn@163.com 2023-03-21 描述: 防火墙规则 *******************************************************************************} unit UFirewall; interface uses System.SysUtils, System.Variants, System.Classes, ActiveX, ComObj, UFirewallLib; function AddExe2Firewall(nCaption,nExe: string): Boolean; //添加防火墙规则 implementation function AddExe2Firewall(nCaption,nExe: string): Boolean; const cRullName = 'Fihe_NetChecker'; var fwPolicy2 : INetFwPolicy2; RulesObject : OleVariant; RObject : OleVariant; Profile : Integer; NewRule : INetFwRule; begin if nCaption = '' then nCaption := cRullName; //default name CoInitialize(nil); try fwPolicy2 := INetFwPolicy2(CreateOleObject('HNetCfg.FwPolicy2')); Profile := fwPolicy2.CurrentProfileTypes; //Profile := NET_FW_PROFILE2_PRIVATE OR NET_FW_PROFILE2_PUBLIC; RulesObject := fwPolicy2.Rules; NewRule := INetFwRule(CreateOleObject('HNetCfg.FWRule')); NewRule.Name := nCaption; NewRule.Description := nCaption; NewRule.Applicationname := nExe; NewRule.Protocol := NET_FW_IP_PROTOCOL_TCP; NewRule.Direction := NET_FW_RULE_DIR_OUT; NewRule.Enabled := TRUE; NewRule.Profiles := Profile; NewRule.Action := NET_FW_ACTION_ALLOW; RulesObject.Add(NewRule); finally NewRule := nil; RulesObject := Unassigned; end; end; end.
unit Database; interface uses Declarations, System.Generics.Collections, Model.Interfaces; function CreateDatabaseClass: IDatabaseInterface; implementation uses System.IniFiles, System.SysUtils, System.IOUtils; type TDatabase = class(TInterfacedObject, IDatabaseInterface) private const SalesSection = 'Sales'; SalesTotal = 'Total Sales'; var fCustomers: TObjectList<TCustomer>; fItems: TObjectList<TItem>; fFullFileName: string; public constructor Create; destructor Destroy; override; function getTotalSales: Currency; function getCustomerList: TObjectList<TCustomer>; function getItems: TObjectList<TItem>; function getCustomerFromName(const nameStr: string): TCustomer; function getItemFromDescription(const desc: string): TItem; function getItemFromId(const id: Integer): TItem; procedure SaveCurrentSales(const currentSales: Currency); end; constructor TDatabase.Create; var tmpCustomer: TCustomer; tmpItem: TItem; begin inherited; fFullFileName := TPath.Combine(ExtractFilePath(ParamStr(0)), 'POSApp.data'); fCustomers := TObjectList<TCustomer>.Create; //Create mock customers tmpCustomer := TCustomer.Create; tmpCustomer.ID := 1; tmpCustomer.Name := 'John'; tmpCustomer.DiscountRate := 12.50; tmpCustomer.Balance := -Random(5000); fCustomers.Add(tmpCustomer); tmpCustomer := TCustomer.Create; tmpCustomer.ID := 2; tmpCustomer.Name := 'Alex'; tmpCustomer.DiscountRate := 23.00; tmpCustomer.Balance := -Random(2780); fCustomers.Add(tmpCustomer); tmpCustomer := TCustomer.Create; tmpCustomer.ID := 3; tmpCustomer.Name := 'Peter'; tmpCustomer.DiscountRate := 0.0; tmpCustomer.Balance := -Random(9000); fCustomers.Add(tmpCustomer); tmpCustomer := TCustomer.Create; tmpCustomer.ID := 4; tmpCustomer.Name := 'Retail Customer'; tmpCustomer.DiscountRate := 0.0; tmpCustomer.Balance := 0.0; fCustomers.Add(tmpCustomer); fItems := TObjectList<TItem>.Create; //Create mock items to sell tmpItem := TItem.Create; tmpItem.ID := 100; tmpItem.Description := 'T-shirt'; tmpItem.Price := 13.55; fItems.Add(tmpItem); tmpItem := TItem.Create; tmpItem.ID := 200; tmpItem.Description := 'Trousers'; tmpItem.Price := 23.45; fItems.Add(tmpItem); tmpItem := TItem.Create; tmpItem.ID := 300; tmpItem.Description := 'Coat'; tmpItem.Price := 64.00; fItems.Add(tmpItem); tmpItem := TItem.Create; tmpItem.ID := 400; tmpItem.Description := 'Shirt'; tmpItem.Price := 28.00; fItems.Add(tmpItem); end; destructor TDatabase.Destroy; begin fCustomers.Free; fItems.Free; inherited; end; function TDatabase.getCustomerFromName(const nameStr: string): TCustomer; var tmpCustomer: TCustomer; begin if not Assigned(fCustomers) then Exit; result := nil; for tmpCustomer in fCustomers do begin if tmpCustomer.Name = nameStr then begin result := tmpCustomer; Exit; end; end; end; function TDatabase.getCustomerList: TObjectList<TCustomer>; begin result := fCustomers; end; function TDatabase.getItemFromDescription(const desc: string): TItem; var tmpItem: TItem; begin result := nil; if not Assigned(fItems) then Exit; for tmpItem in fItems do begin if tmpItem.Description = desc then begin result := tmpItem; Exit; end; end; end; function TDatabase.getItemFromId(const id: Integer): TItem; var tmpItem: TItem; begin result := nil; if not Assigned(fItems) then Exit; for tmpItem in fItems do begin if tmpItem.ID = id then begin result := tmpItem; Exit; end; end; end; function TDatabase.getItems: TObjectList<TItem>; begin result := fItems; end; function TDatabase.getTotalSales: Currency; var tmpIniFile: TIniFile; amount: Currency; begin amount := 0.00; tmpIniFile := TIniFile.Create(fFullFileName); try amount := tmpIniFile.ReadFloat(SalesSection, SalesTotal, 0.00); finally tmpIniFile.Free; result := amount; end; end; procedure TDatabase.SaveCurrentSales(const currentSales: Currency); var tmpIniFile: TIniFile; begin tmpIniFile := TIniFile.Create(fFullFileName); try tmpIniFile.WriteFloat(SalesSection, SalesTotal, getTotalSales + currentSales); finally tmpIniFile.Free; end; end; function createDatabaseClass: IDatabaseInterface; begin Result := TDatabase.Create; end; end.
unit RRManagerChangeLicenseZoneFundFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, RRManagerBaseGUI, CommonComplexCombo, StdCtrls, RRManagerObjects, RRManagerBaseObjects, BaseObjects; type TfrmChangeLicenseZoneFrame = class(TBaseFrame) //TfrmChangeLicenseZoneFrame = class(TFrame) gbxStatusChange: TGroupBox; cmplxLicenseZoneState: TfrmComplexCombo; lblLicenseZone: TStaticText; private { Private declarations } function GetLicenseZone: TOldLicenseZone; protected procedure FillControls(ABaseObject: TBaseObject); override; procedure ClearControls; override; public { Public declarations } constructor Create(AOwner: TComponent); override; property LicenseZone: TOldLicenseZone read GetLicenseZone; procedure Save; override; end; implementation {$R *.dfm} { TfrmChangeLicenseZoneFrame } procedure TfrmChangeLicenseZoneFrame.ClearControls; begin inherited; end; constructor TfrmChangeLicenseZoneFrame.Create(AOwner: TComponent); begin inherited; EditingClass := TOldLicenseZone; cmplxLicenseZoneState.Caption := 'Статус участка'; cmplxLicenseZoneState.FullLoad := true; cmplxLicenseZoneState.DictName := 'TBL_LICENSE_ZONE_STATE_DICT'; end; procedure TfrmChangeLicenseZoneFrame.FillControls( ABaseObject: TBaseObject); begin inherited; lblLicenseZone.Caption := Format('Вид фонда для лицензионного участка %s, находящегося в фонде %s, будет изменен на ', [(ABaseObject as TOldLicenseZone).List(loFull, false, false), (ABaseObject as TOldLicenseZone).LicenseZoneState]); cmplxLicenseZoneState.AddItem((ABaseObject as TOldLicenseZone).LicenseZoneStateID, (ABaseObject as TOldLicenseZone).LicenseZoneState); end; function TfrmChangeLicenseZoneFrame.GetLicenseZone: TOldLicenseZone; begin Result := nil; if EditingObject is TOldLicenseZone then Result := EditingObject as TOldLicenseZone; end; procedure TfrmChangeLicenseZoneFrame.Save; begin inherited; LicenseZone.LicenseZoneStateID := cmplxLicenseZoneState.SelectedElementID; LicenseZone.LicenseZoneState := cmplxLicenseZoneState.SelectedElementName; end; end.
unit uAquos; interface uses uRS232; type TInputAType = ( iaUnknown, iaTV, iaDTV, iaExt1, iaExt2, iaExt3, iaExt4, iaExt5, iaExt6, iaExt7 ); TInputBType = ( ibUnknown = 0, ibExt1YC = 10, ibExt1CVBS = 11, ibExt1RGB = 12, ibExt2YC = 20, ibExt2CVBS = 21, ibExt2RGB = 22, ibExt3 = 30, ibExt4 = 40, ibExt5 = 50, ibExt6 = 60, ibExt7 = 70 ); { TAquosConnection } TAquosConnection = class(TObject) protected FRS232: TRS232; FCurrentTVChannel: integer; FCurrentDTVChannel: integer; FCurrentVolume: integer; FIsTextmode: boolean; FCurrentTextPage: integer; FCurrentInputA: TInputAType; FCurrentInputB: TInputBType; function WaitForResponse: string; function IsOk( const s: string ): boolean; procedure SendCmd( const s: string ); public property InputA: TInputAType read FCurrentInputA; property InputB: TInputBType read FCurrentInputB; property TVChannel: integer read FCurrentTVChannel; property DTVChannel: integer read FCurrentDTVChannel; property Volume: integer read FCurrentVolume; property TextPage: integer read FCurrentTextPage; property IsTextmode: boolean read FIsTextmode; constructor Create( iPort: integer ); destructor Destroy; override; function IsConnected: boolean; function TurnOff: boolean; function ChangeTVChannel( iChannel: integer ): boolean; function ChangeDTVChannel( iChannel: integer ): boolean; function ChangeVolume( iVolume: integer ): boolean; function SetInputTV: boolean; function SetInputDTV: boolean; function SetInputExt( iExtIndex: integer ): boolean; function ChangeInputB( anInput: TInputBType ): boolean; function SetTextPage( iPage: integer ): boolean; function SetTextPageOn: boolean; function SetTextPageOff: boolean; end; const C_UNKNOWNVAR = -1; implementation uses SysUtils, StrUtils; { TAquosConnection } function TAquosConnection.ChangeDTVChannel(iChannel: integer): boolean; begin SendCmd( 'DTVD' + IntToStr(iChannel) ); Result := IsOk( WaitForResponse ); if Result then begin FCurrentDTVChannel := iChannel; end; end; function TAquosConnection.ChangeInputB(anInput: TInputBType): boolean; begin SendCmd( 'INP' + IntToStr(Ord(anInput)) ); Result := IsOk( WaitForResponse ); if Result then begin FCurrentInputB := anInput; end; end; function TAquosConnection.ChangeTVChannel(iChannel: integer): boolean; begin SendCmd( 'DCCH' + IntToStr(iChannel) ); Result := IsOk( WaitForResponse ); if Result then begin FCurrentTVChannel := iChannel; end; end; function TAquosConnection.ChangeVolume(iVolume: integer): boolean; begin SendCmd( 'VOLM' + IntToStr(iVolume) ); Result := IsOk( WaitForResponse ); if Result then begin FCurrentVolume := iVolume; end; end; constructor TAquosConnection.Create( iPort: integer ); begin FRS232 := TRS232.Create( iPort ); FCurrentTVChannel := C_UNKNOWNVAR; FCurrentDTVChannel := C_UNKNOWNVAR; FCurrentVolume := C_UNKNOWNVAR; FIsTextmode := False; FCurrentTextPage := C_UNKNOWNVAR; FCurrentInputA := iaUnknown; FCurrentInputB := ibUnknown; FRS232.Open; end; destructor TAquosConnection.Destroy; begin FRS232.Free; inherited; end; function TAquosConnection.IsConnected: boolean; begin Result := FRS232.IsConnected; end; function TAquosConnection.IsOk(const s: string): boolean; var s2: string; begin s2 := Trim( s ); Result := SameText( 'OK', s2 ); end; procedure TAquosConnection.SendCmd(const s: string); begin // the spaces aren't really needed, but we'll humor the manual FRS232.Write( s + StringOfChar(' ', 8 - Length(s)) + #$0D ) end; function TAquosConnection.SetInputDTV: boolean; begin SendCmd( 'IDTV' ); Result := IsOk( WaitForResponse ); if Result then begin FCurrentInputA := iaDTV; FCurrentInputB := ibUnknown; FCurrentTVChannel := C_UNKNOWNVAR; FCurrentDTVChannel := C_UNKNOWNVAR; end; end; function TAquosConnection.SetInputExt(iExtIndex: integer): boolean; begin SendCmd( 'IAVD' + IntToStr(iExtIndex) ); Result := IsOk( WaitForResponse ); if Result then begin FCurrentInputA := TInputAType( Ord(iaExt1) + (iExtIndex - 1) ); FCurrentInputB := ibUnknown; FCurrentTVChannel := C_UNKNOWNVAR; FCurrentDTVChannel := C_UNKNOWNVAR; end; end; function TAquosConnection.SetInputTV: boolean; begin SendCmd( 'ITVD' ); Result := IsOk( WaitForResponse ); if Result then begin FCurrentInputA := iaDTV; FCurrentInputB := ibUnknown; FCurrentTVChannel := C_UNKNOWNVAR; FCurrentDTVChannel := C_UNKNOWNVAR; end; end; function TAquosConnection.SetTextPage(iPage: integer): boolean; begin Result := False; if not FIsTextmode then begin SetTextPageOn; end; if FIsTextmode then begin SendCmd( 'DCPG' + IntToStr(iPage) ); Result := IsOk( WaitForResponse ); if Result then begin FCurrentTextPage := iPage; end; end; end; function TAquosConnection.SetTextPageOff: boolean; begin SendCmd( 'TEXT0' ); Result := IsOk( WaitForResponse ); if Result then begin FIsTextmode := False; FCurrentTextPage := C_UNKNOWNVAR; end; end; function TAquosConnection.SetTextPageOn: boolean; begin SendCmd( 'TEXT1' ); Result := IsOk( WaitForResponse ); if Result then begin FIsTextmode := True; FCurrentTextPage := C_UNKNOWNVAR; end; end; function TAquosConnection.TurnOff: boolean; begin SendCmd( 'POWR0' ); Result := IsOk( WaitForResponse ); if Result then begin // you can't switch the tv on anymore now end; end; function TAquosConnection.WaitForResponse: string; begin Result := ''; Result := Result + FRS232.Read; while Pos( #$0D, Result ) <= 0 do begin Result := Result + FRS232.Read; end; end; end.
{ this file is part of Ares Aresgalaxy ( http://aresgalaxy.sourceforge.net ) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. } { Description: various functions related to combo boxes } unit helper_combos; interface uses stdctrls,classes,{tntstdctrls,}registry,const_ares{,tntsysutils}; const HISTORY_GENERAL=0; HISTORY_TITLE=1; HISTORY_AUTHOR=2; HISTORY_ALBUM=3; HISTORY_DATE=4; procedure combo_add_bitrates(combo:tcombobox); procedure combo_add_size(combo:tcombobox); procedure combo_add_resolutions(combo:tcombobox); //procedure combo_add_categories(combo:TtntComboBox; mime:byte); //function add_tntcombo_history(combo:ttntcombobox):boolean; //procedure combo_add_history(combo:ttntcombobox;first:byte;second:byte); procedure combo_add_languages(combo:tcombobox); procedure delete_excedent_history(reg:tregistry;lista:tstringlist); //function combo_to_mimetype(combo:ttntcombobox):byte; function combo_index_to_bitrate(index:integer):integer; //in synch a seconda dell'indice della combo search function combo_index_to_duration(index:integer):integer; //in synch a seconda dell'indice della combo search function combo_index_to_size(index:integer):integer; //in synch a seconda dell'indice della combo search function combo_index_to_resolution(index:integer):integer; //in synch a seconda dell'indice della combo search implementation function combo_index_to_resolution(index:integer):integer; //in synch a seconda dell'indice della combo search begin case index of 0:result:=0; 1:result:=16; 2:result:=32; 3:result:=48; 4:result:=80; 5:result:=160; 6:result:=320; 7:result:=640; 8:result:=720; 9:result:=800; 10:result:=1024; 11:result:=1280; else result:=2048; end; end; function combo_index_to_size(index:integer):integer; //in synch a seconda dell'indice della combo search begin case index of 0:result:=0; 1: result:= GIGABYTE; 2: result:= 500 * MEGABYTE; 3: result:= 200 * MEGABYTE; 4: result:= 100 * MEGABYTE; 5: result:= 50 * MEGABYTE; 6: result:= 20 * MEGABYTE; 7: result:= 10 * MEGABYTE; 8: result:= 5 * MEGABYTE; 9: result:= 2 * MEGABYTE; 10:result:= 1 * MEGABYTE; 11:result:= 500 * KBYTE; 12:result:= 200 * KBYTE; 13:result:= 100 * KBYTE; 14:result:= 50 * KBYTE; 15:result:= 20 * KBYTE else result:= 10 * KBYTE; end; end; procedure combo_add_size(combo:tcombobox); begin with combo.items do begin beginupdate; clear; add(''); add('1 GB'); add('500 MB'); add('200 MB'); add('100 MB'); add('50 MB'); add('20 MB'); add('10 MB'); add('5 MB'); add('2 MB'); add('1 MB'); add('500 KB'); add('200 KB'); add('100 KB'); add('50 KB'); add('20 KB'); add('10 KB'); endupdate; end; end; function combo_index_to_duration(index:integer):integer; //in synch a seconda dell'indice della combo search begin case index of 0:result:=0; 1:result:=10; 2:result:=30; 3:result:=60; 4:result:=120; 5:result:=300; 6:result:=600; 7:result:=1800; 8:result:=3600 else result:=7200; end; end; function combo_index_to_bitrate(index:integer):integer; //in synch a seconda dell'indice della combo search begin case index of 0:result:=0; {1:result:=2000; 2:result:=1200; 3:result:=800; 4:result:=640; 5:result:=480; } 1:result:=320; 2:result:=256; 3:result:=224; 4:result:=192; 5:result:=160; 6:result:=128; 7:result:=112; 8:result:=96; 9:result:=80; 10:result:=64; 11:result:=56; 12:result:=48; 13:result:=40; 14:result:=32; else result:=24; end; end; {function combo_to_mimetype(combo:ttntcombobox):byte; begin result:=0; case combo.itemindex of 0:result:=0; 1:result:=1; 2:result:=5; 3:result:=7; 4:result:=6; 5:result:=3; 6:result:=8; //other 2956+ end; end; } procedure delete_excedent_history(reg:tregistry;lista:tstringlist); begin while lista.count>99 do begin reg.deletevalue(lista.strings[0]); lista.delete(0); end; end; procedure combo_add_languages(combo:tcombobox); begin with combo.items do begin beginupdate; clear; add(''); add('abkhazian'); add('afan'); add('afaraa'); add('afrikaans'); add('albanian'); add('amharic'); add('arabic'); add('armenian'); add('assamese'); add('aymara'); add('azerbaijani'); add('bashkir'); add('basque'); add('bengali'); add('bhutani'); add('bihari'); add('bislama'); add('breton'); add('bulgarian'); add('burmese'); add('byelorussian'); add('cambodian'); add('catalan'); add('chinese'); add('corsican'); add('croatian'); add('czech'); add('danish'); add('dutch'); add('english'); add('esperanto'); add('estonian'); add('faeroese'); add('fiji'); add('finnish'); add('french'); add('frisian'); add('galician'); add('georgian'); add('german'); add('greek'); add('greenlandic'); add('guarani'); add('gujarati'); add('hausa'); add('hebr'); add('hindi'); add('hungarian'); add('icelandic'); add('indonesi'); add('interlingue'); add('inuktit'); add('inupiak'); add('irish'); add('italian'); add('japanese'); add('javanese'); add('kannada'); add('kashmiri'); add('kazakh'); add('kinyarwanda'); add('kirghiz'); add('kirundi'); add('korean'); add('kurdish'); add('laothian'); add('latin'); add('latvian lettish'); add('lingala'); add('lithuanian'); add('macedonian'); add('malagasy'); add('malay'); add('malayalam'); add('maltese'); add('maori'); add('marathi'); add('moldavian'); add('mongolian'); add('nauru'); add('nepali'); add('norwegian'); add('occitan'); add('oriya'); add('pashto pushto'); add('persian'); add('polish'); add('portuguese'); add('punjabi'); add('quechua'); add('rhaeto-romance'); add('romanian'); add('russian'); add('samoan'); add('sangro'); add('sanskrit'); add('scots gaelic'); add('serbian'); add('serbo-croatian'); add('sesotho'); add('setswana'); add('shona'); add('sindhi'); add('singhalese'); add('siswati'); add('slovak'); add('slovenian'); add('somali'); add('spanish'); add('sudanese'); add('swahili'); add('swedish'); add('tagalog'); add('tajik'); add('tamil'); add('tatar'); add('tegulu'); add('thai'); add('tibetan'); add('tigrinya'); add('tonga'); add('tsonga'); add('turkish'); add('turkmen'); add('twi'); add('uigur'); add('ukrainian'); add('urdu'); add('uzbek'); add('vietnamese'); add('volapuk'); add('welch'); add('wolof'); add('xhosa'); add('yiddish'); add('yoruba'); add('zhuang'); add('zulu'); endupdate; end; end; {procedure combo_add_history(combo:ttntcombobox;first:byte;second:byte); var reg:tregistry; lista:tstringlist; str:string; firststr,secondstr:string; begin case first of 0:firststr:='gen'; 1:firststr:='audio'; 3:firststr:='software'; 5:firststr:='video'; 6:firststr:='document'; 7:firststr:='image'; 8:firststr:='other'; end; case second of HISTORY_GENERAL:secondstr:='gen'; HISTORY_TITLE:secondstr:='tit'; HISTORY_AUTHOR:secondstr:='aut'; HISTORY_ALBUM:secondstr:='alb'; HISTORY_DATE:secondstr:='dat'; end; reg:=tregistry.create; try with combo.items do begin beginupdate; clear; reg.openkey(areskey+'Search.History\'+firststr+chr(46)+secondstr,true); lista:=tstringlist.create; reg.getvaluenames(lista); reg.closekey; reg.destroy; while (lista.count>0) do begin str:=hexstr_to_bytestr(lista.strings[0]); lista.delete(0); add(utf8strtowidestr(str)); end; lista.free; if count>0 then begin Insert(0,GetLangStringW(PURGE_SEARCH_STR)); insert(1,''); end else begin add(GetLangStringW(PURGE_SEARCH_STR)); add(''); end; endupdate; end; except end; end;} {function add_tntcombo_history(combo:ttntcombobox):boolean; var i:integer; begin result:=false; for i:=0 to combo.items.count-1 do if Tnt_WideLowerCase(combo.text)=Tnt_WideLowerCase(combo.items.strings[i]) then begin exit; end; combo.items.add(combo.text); result:=true; end; } {procedure combo_add_categories(combo:TtntComboBox; mime:byte); const cat_audio:array[0..147] of widestring= ('acapella','acid','acid jazz','acid punk','acoustic','all','alternative', 'alternrock','ambient','anime','avantgarde','ballad','bass','beat', 'bebob','big band','black metal','bluegrass','blues','booty bass','britpop', 'cabaret','celtic','chamber music','chanson','chorus','christian gangs','christian rap', 'classic rock','classical','club','club-house','comedy','contemporary','country', 'cristian rock','crossover','cult','dance','dance hall','darkwave','death metal', 'disco','dream','drum & bass','drum solo','duet','easy listening','electronic', 'ethnic','eurodance','euro-house','euro-techno','fast fusion','folk','folk/Rock', 'folklore','freestyle','funk','fusion','game','gangsta','goa', 'gospel','gothic','gothic rock','grunge','hard rock','hardcore','heavy metal', 'hip-hop','house','humour','indie','industrial','instrumental','instrumental pop', 'instrumental rock','jazz','jazz/funk','jpop','jungle','latin','lo-fi', 'meditative','merengue','metal','musical','national folk','native american','negerpunk', 'new age','new wave','noise','oldies','opera','other','polka', 'polsk punk','pop','pop/funk','pop/folk','porn groove','power ballad','pranks', 'primus','progressive rock','psychedelic','psychedelic rock','punk','punk rock','r&b', 'rap','rave','reggae','retro','revival','rhythmic soul','rock', 'rock & roll','salsa','satire','showtunes','ska','slow jam','slow rock', 'sonata','soul','sound clip','soundtrack','southern rock','space','speech', 'swing','symphonic rock','symphony','synthpop','tango','techno','techno-industrial', 'terror','thrash metal','top 40','trailer','trance','tribal','trip-hop', 'vocal'); cat_image:array[0..16] of widestring= ('animal & pets','architecture','art','cartoons','celebrity & idols', 'colture & communities','erotica','familty','friends','funny home video', 'history','homes','nature & landscapes','science & technology','sports & outdoors', 'travel & vacations','vehicles & transportation'); cat_video:array[0..25] of widestring= ('action & adventure','anime','cartoon','classic','comedy', 'commercial','documentary','drama','erotica','food', 'horror & suspense','humor','kids & family','motors','music & musicals', 'nature','news','science','science fiction & fantasy','series', 'sports','talkshow','thriller','trailer','travel', 'war'); cat_doc:array[0..63] of widestring= ('adventure','architecture','art','autobiography','biography','biology', 'business','chemistry','children','commerce','computing','cookery', 'doctory','drawing','electronics','engineering','entertainment','erotica', 'essay','fairytale','family','farming','fiction','food','gaming','gardening', 'geography','grammar','guide','health','history','home','horrow','humour', 'internet','language','law','letter','literature','mathematics', 'medicine','memoir','music','mystery','nature','news','occultism', 'parody','parenting','philosophy','physics','poetry','prophesy', 'psychology','reference','religion','romance','science', 'sport','summary','thriller','tourism','travel','tutorial'); cat_soft:array[0..30] of widestring= ('active x','animation','antivirus','browsers','business finance', 'business taxes','cd burners','chat','drivers','file sharing', 'games action','games arcade','games casino','games strategy','html editors', 'image editing','internet','internet tools','java','mp3 & audio', 'mp3 search','palm os','players','pocket pc','screensavers', 'servers','site management','software editors','themes','video', 'wallpaper'); var i:integer; begin with combo.items do begin beginupdate; clear; add(''); case mime of 1:begin //audio for i:=0 to 147 do add(cat_audio[i]); end; 7:begin //image for i:=0 to 16 do add(cat_image[i]); end; 5:begin //video for i:=0 to 25 do add(cat_video[i]); end; 6:begin //dec for i:=0 to 63 do add(cat_doc[i]); end; 3:begin //soft for i:=0 to 30 do add(cat_soft[i]); end; end; endupdate; end; end; } procedure combo_add_resolutions(combo:tcombobox); begin with combo.items do begin beginupdate; clear; add(''); add('16x16'); add('32x32'); add('48x48'); add('80x60'); add('160x120'); add('320x240'); add('640x480'); add('720x480'); add('800x600'); add('1024x768'); add('1280x1024'); add('2048x1536'); endupdate; end; end; procedure combo_add_bitrates(combo:tcombobox); begin with combo.items do begin beginupdate; clear; add(''); { add('2000'); add('1200'); add('800'); add('640'); add('480'); } add('320'); add('256'); add('224'); add('192'); add('160'); add('128'); add('112'); add('96'); add('80'); add('64'); add('56'); add('48'); add('40'); add('32'); add('24'); endupdate; end; end; end.
unit PLAT_HtmlLink; interface uses PLAT_QuickLink,Classes,PLAT_utils,Sysutils; type THtmlLink=class(TQuickLink) private FHref:String; FHead: String; procedure SetHRef(const Value: String); procedure SetHead(const Value: String); procedure WebBrowserDocumentComplete(Sender: TObject; const pDisp: IDispatch; var URL: OleVariant); procedure WebBrowserTitleChange(Sender: TObject; const Text: WideString); procedure WebBrowserBeforeNavigate2(Sender: TObject; const pDisp: IDispatch; var URL, Flags, TargetFrameName, PostData, Headers: OleVariant; var Cancel: WordBool); public procedure Execute;override; procedure LoadFromStream(Stream:TStream);override; procedure SaveToStream(Stream:TStream);override; property HRef:String read FHRef write SetHRef; property Head:String read FHead write SetHead; constructor Create( Head,Href: String); end; implementation uses ShellAPI,Forms,Windows,comctrls,shdocvw,Controls; { THtmlLink } procedure THtmlLink.Execute; var Sheet:TTabSheet; bs:TWebBrowser; begin { Sheet:=TTabSheet.Create (Application.MainForm); Sheet.PageControl :=FormMain.PageControl1; Sheet.Parent:=FormMain.PageControl1; Sheet.Align :=alClient; Sheet.Caption:=Head; } bs:=TWebBrowser.Create(Application.MainForm); Sheet.InsertControl (bs); bs.Align :=alClient; bs.Navigate(WideString(HRef)); bs.OnTitleChange := WebBrowserTitleChange; bs.OnDocumentComplete := WebBrowserDocumentComplete; with (Sheet.Parent as TPageControl) do begin ActivePageIndex :=PageCount -1; end; //ShellExecute( Application.handle,'OPEN',PChar(DocumentName),'','',SW_SHOWMAXIMIZED ); end; procedure THtmlLink.LoadFromStream(Stream:TStream); var szData:String; begin inherited; TUtils.LoadStringFromStream (Stream,szData); //Pub Tutils.LoadStringFromStream (Stream,FCaption); TUtils.LoadStringFromStream(Stream,FDescription); Stream.Read(FLeft,SizeOf(FLeft)); Stream.Read (FTop,SizeOf(FTop)); TUtils.LoadStringFromStream(Stream,FHead); TUtils.LoadStringFromStream(Stream,FHref); end; procedure THtmlLink.SaveToStream(Stream:TStream); var i:Integer; szData:String; begin szData:=self.ClassName ; TUtils.SaveStringToStream (Stream,szData); //pub start Tutils.SaveStringToStream (Stream,FCaption); TUtils.SaveStringToStream(Stream,FDescription); Stream.Write(FLeft,SizeOf(FLeft)); Stream.Write (FTop,SizeOf(FTop)); //pub start TUtils.SaveStringToStream(Stream,FHead); TUtils.SaveStringToStream(Stream,FHref); end; procedure THtmlLink.SetHead(const Value: String); begin FHead := Value; end; procedure THtmlLink.SetHRef(const Value: String); begin FHRef:=Value; end; procedure THtmlLink.WebBrowserDocumentComplete(Sender: TObject; const pDisp: IDispatch; var URL: OleVariant); begin (Sender as TWebBrowser).OnBeforeNavigate2 :=WebBrowserBeforeNavigate2; (Sender as TWebBrowser).OnDocumentComplete:=nil; end; procedure THtmlLink.WebBrowserTitleChange(Sender: TObject; const Text: WideString); begin ((Sender as TWinControl).Parent as TTabSheet).Caption:=Text; end; procedure THtmlLink.WebBrowserBeforeNavigate2(Sender: TObject; const pDisp: IDispatch; var URL, Flags, TargetFrameName, PostData, Headers: OleVariant; var Cancel: WordBool); var htmllink:THtmlLink; begin if uppercase(URL)=uppercase(ExtractFilePath(application.exename)+'Client.htm') then exit; if Pos('GRPREQUEST',Uppercase(URL)) >0then begin //ExecuteGRPRequest(ExtractFileName(URL)); Cancel:=true; end else begin With THtmlLink.Create(Headers,URL) do begin Execute; end; Cancel:=true; end; end; constructor THtmlLink.Create(Head,Href : String); begin self.FHref:=Href; self.FHead :=Head; end; end.
{*******************************************************} { } { ThreadCompare.pas { Copyright @2014/5/12 13:39:10 by 姜梁 { } { 功能描述:获取对比取得相同文件 { 函数说明: {*******************************************************} unit ThreadCompare; interface uses Classes, Messages ,DataModelFileInfo, Windows, MD5_D2009, Generics.Collections, Generics.Defaults; const //查找完一次后触发的消息 WM_IncProgress= WM_USER+200; EndCompareNum = -1; type TThreadCompareFile = class(TThread) private ListDataInfo: TListFileInfo; // function GetSameItem(dataInfo:TFileInfoDataModule): TListFileInfo; // function GetFileInfo(const AFileName: string): string; public MainHandle:Cardinal; ListTotalSameData :TListFileInfo; IsEnd: Boolean; constructor Create(dataList:TListFileInfo);overload; protected procedure Execute; override; end; type TFileDataComparer = class(TComparer<TFileInfoDataModule>) public function Compare(const Left, Right: TFileInfoDataModule): Integer; override; end; implementation uses IdHashMessageDigest, SysUtils; /// <summary> /// 线程开始 ,需要调用resume启动线程 /// </summary> /// <param name="">传入datalist所有文件信息</param> constructor TThreadCompareFile.Create(dataList: TListFileInfo); begin //确定 list已经初始化 if not Assigned(dataList) then raise Exception.Create('dataList没有初始化'); ListDataInfo:= dataList; inherited Create(true); end; /// <summary> /// 线程开始执行 /// </summary> procedure TThreadCompareFile.Execute; var I,groupIndex,beginIndex: Integer; FileDataComparer:TFileDataComparer; FindSame:Boolean; begin FreeOnTerminate:= True; //对列表中文件大小进行排序,小的在前,大的在后 FileDataComparer:= TFileDataComparer.Create; ListDataInfo.Sort(FileDataComparer); //初始化开始索引和相同组序号 beginIndex:=0; groupIndex:=0; while ListDataInfo.Count- 1 <> beginIndex do begin //通知主页面进度条前进 SendMessage(MainHandle,WM_IncProgress,1,0); //如果该开始的item已经被识别为重复,那么不再查找他的重复值 if ListDataInfo[beginIndex].IsSort then begin Inc(beginIndex); Continue; end; //1.从beginindex开始遍历 FindSame:= False; for I := beginIndex +1 to ListDataInfo.Count - 1 do begin //2.如果item已经被识别为重复,那么就不进行判别是否重复处理 if ListDataInfo[I].IsSort then Continue; //3.因为已经对大小排序,如果遍历到大小不同,说明已经把文件大小一样的遍历完 //了,没必要继续遍历,所以退出遍历。 if ListDataInfo[beginIndex].FileSize = ListDataInfo[I].FileSize then begin //4.判断是否文件名相同,相同就加入新的重复表中 //if ListDataInfo[beginIndex].FileName = ListDataInfo[I].FileName then if ListDataInfo[beginIndex].MDString = ListDataInfo[I].MDString then begin //if ListDataInfo[beginIndex].FileName <> ListDataInfo[I].FileName then // begin if not ListDataInfo[beginIndex].ISMD5 then begin ListDataInfo[beginIndex].MDString:= MD5F(ListDataInfo[beginIndex].FilePath +'\'+ListDataInfo[beginIndex].FileName); ListDataInfo[beginIndex].ISMD5:= True; end; if not ListDataInfo[I].ISMD5 then begin ListDataInfo[I].MDString:= MD5F(ListDataInfo[I].FilePath +'\'+ListDataInfo[I].FileName); ListDataInfo[I].ISMD5:= True; end; if ListDataInfo[beginIndex].MDString = ListDataInfo[I].MDString then begin //5.找到重复值,将组名赋值,并将item的issort值为true表明,他已经是重复值 FindSame:= True; ListDataInfo[I].GroupIndex := groupIndex; ListDataInfo[I].IsSort := True; ListTotalSameData.Add(ListDataInfo[I]); end; // end else // begin // //5.找到重复值,将组名赋值,并将item的issort值为true表明,他已经是重复值 // FindSame:= True; // // ListDataInfo[I].GroupIndex := groupIndex; // ListDataInfo[I].IsSort := True; // ListTotalSameData.Add(ListDataInfo[I]); // end; end; end else Break; end; //6. 判断是否找到重复,是的话把beginIndex指的item加入重复文件list中。如果没有 //找到重复的,就释放所指的item的空间, if FindSame then begin ListDataInfo[beginIndex].GroupIndex := groupIndex; ListDataInfo[beginIndex].IsSort := True; ListTotalSameData.Add(ListDataInfo[beginIndex]); Inc(groupIndex); end else begin ListDataInfo[beginIndex].Free end; Inc(beginIndex); end; {$REGION '之前所有算法'} // //遍历所有问价差重 // for I := 0 to ListDataInfo.Count - 1 do // begin // //在遍历中会删除已经找到的重复item,在这里判断是否已经遍历完所有的item。如果 // //是就退出循环 // if I = ListDataInfo.Count then Break; // // //取得本文件相同的文件列表,加入总列表中 // // // templist:= GetSameItem(ListDataInfo[I]); // ListTotalSameData.AddRange(templist); // //通知主窗体进度条走动 // temp:= templist.Count; // if temp =0 then // SendMessage(MainHandle,WM_IncProgress,1,0) // else // begin // SendMessage(MainHandle,WM_IncProgress,temp,0); // end; // // templist.Free; // //主窗体点击取消后,该isend标志值为ture。退出循环。线程结束 // if IsEnd then Break; // end; {$ENDREGION} //通知主窗体结束,主窗体开始吧 ListTotalSameData,绑定到listview SendMessage(MainHandle,WM_IncProgress,EndCompareNum,0); ListDataInfo.Free; FileDataComparer.Free; end; {$REGION '之前所有算法'} { /// <summary> /// 取得相同元素,返回相同所用元素列表 /// </summary> /// <param name="">需要查询的元素</param> function TThreadCompareFile.GetSameItem(dataInfo:TFileInfoDataModule): TListFileInfo; var I: Integer; tempList:TListFileInfo; tempBool:Boolean; tempString:string; tempstringo:string; tempdata:TFileInfoDataModule; begin tempList:= TListFileInfo.Create; tempBool:=False; //tempString:= MD5F(dataInfo.FilePath +'\'+dataInfo.FileName); //tempstringo:=GetFileInfo(dataInfo.FilePath +'\'+dataInfo.FileName); //开始遍历循环查找重复值 //OutputDebugString(PChar(inttostr(ListDataInfo.Count))); for I := 0 to ListDataInfo.Count - 1 do begin //在查找过程中会将list中的重复数据删除,所以这里判断,是否已经遍历完修改后的list if I = ListDataInfo.Count then Break; // OutputDebugString(PChar(inttostr(I))); tempdata:= ListDataInfo[I]; //大小必须一致 if dataInfo.FileSize <> tempdata.FileSize then Continue; //名称必须一致 if dataInfo.FileName <> tempdata.FileName then Continue; //路径不能一致 if dataInfo.FilePath = tempdata.FilePath then Continue; //if tempstringo<>GetFileInfo(ListDataInfo[I].FilePath +'\'+ListDataInfo[I].FileName) then //if tempString = MD5F(ListDataInfo[I].FilePath +'\'+ListDataInfo[I].FileName) then begin //加入到重复表中 tempList.Add(tempdata); tempBool:= True; //在原表中删除 ListDataInfo.Delete(I); end; end; //如果找到重复值,那么将该元素也视为重复元素,添加到重复表中,删除在原表中的该元素 if tempBool then begin tempList.Add(dataInfo); ListDataInfo.Remove(dataInfo); end; Result:= tempList; end; /// <summary> /// 取得文件信息,dll,exe /// </summary> /// <param name="">文件路径</param> /// <returns>文件信息组合字符串</returns> function TThreadCompareFile.GetFileInfo(const AFileName: string): string; var FFile: TFileName; FAvailable:Boolean; FInfoSize, Temp, Len: Cardinal; InfoBuf: Pointer; TranslationLength: Cardinal; TranslationTable: Pointer; LanguageID, CodePage, LookupString: String; Value: PChar; tempString :string; begin FFile := AFileName; //取得信息大小 FInfoSize := GetFileVersionInfoSize(PChar(FFile), Temp); //判断是否是可以读取信息的文件 FAvailable := FInfoSize > 0; if FAvailable then begin //设置根据大小缓冲区,读取具体指 InfoBuf := AllocMem(FInfoSize); try // try //读取值 GetFileVersionInfo(PChar(FFile), 0, FInfoSize, InfoBuf); //查询值 if VerQueryValue( InfoBuf, '\VarFileInfo\Translation', TranslationTable, TranslationLength ) then begin CodePage := Format( '%.4x', [ HiWord( PLongInt( TranslationTable )^ ) ] ); LanguageID := Format( '%.4x', [ LoWord( PLongInt( TranslationTable )^ ) ] ); end; LookupString := 'StringFileInfo\' + LanguageID + CodePage + '\'; // if VerQueryValue( InfoBuf, PChar( LookupString + 'CompanyName' ), Pointer( Value ), Len ) then // tempString:= tempString+Value; // if VerQueryValue( InfoBuf, PChar( LookupString + 'FileDescription' ), Pointer( Value ), Len ) then // tempString:= tempString+Value; // if VerQueryValue( InfoBuf, PChar( LookupString + 'FileVersion' ), Pointer( Value ), Len ) then // tempString:= tempString+Value; // if VerQueryValue( InfoBuf, PChar( LookupString + 'InternalName' ), Pointer( Value ), Len ) then // tempString:= tempString+Value; // if VerQueryValue( InfoBuf, PChar( LookupString + 'LegalCopyright' ), Pointer( Value ), Len ) then // tempString:= tempString+Value; // if VerQueryValue( InfoBuf, PChar( LookupString + 'LegalTrademarks' ), Pointer( Value ), Len ) then // tempString:= tempString+Value; // if VerQueryValue( InfoBuf, PChar( LookupString + 'OriginalFilename' ), Pointer( Value ), Len ) then // tempString:= tempString+Value; // if VerQueryValue( InfoBuf, PChar( LookupString + 'ProductName' ), Pointer( Value ), Len ) then // tempString:= tempString+Value; // if VerQueryValue( InfoBuf, PChar( LookupString + 'ProductVersion' ), Pointer( Value ), Len ) then // tempString:= tempString+Value; // if VerQueryValue( InfoBuf, PChar( LookupString + 'Comments' ), Pointer( Value ), Len ) then // tempString:= tempString+Value; tempString:= LookupString;//+tempString+; finally // wrap up finally FreeMem(InfoBuf, FInfoSize); Result:= tempString; end; // end try finally end; end; } {$ENDREGION} { TFileDataComparer } function TFileDataComparer.Compare(const Left,Right: TFileInfoDataModule): Integer; begin if Left.FileSize >Right.FileSize then Result:= 1 else if Left.FileSize <Right.FileSize then Result:= -1 else Result:=0; end; end.
unit uWebSocketEchoServer; interface uses uOSWebSocket, uOSWebSocketHandler, uOSWebSocketServer, uOSHttpSys2WebSocketServer, dwsHTTPSysServer, dwsWebEnvironment; type TWebSocketEchoServer = class private fEchoWebSocketHandler: TWebSocketHandler; //Handler Control Events procedure OnEchoAcceptConnection(aRequest: TWebRequest; aResponse: TWebResponse; var aAccept: Boolean); procedure OnEchoConnectWebSocket(const aWebSocket: TWebSocketServer); procedure OnEchoDisconnectWebSocket(const aWebSocket: TWebSocketServer); //Handler WebSocket Control Events procedure OnEchoWebSocketCloseBuffer(const aWebSocket: TWebSocketServer; const aStatus: Cardinal; const aReasonBuffer: Pointer; const aReasonBufferSize: Cardinal); //WebSocket Events procedure OnEchoWebSocketOpen(const aWebSocket: TWebSocket); procedure OnEchoWebSocketError(const aWebSocket: TWebSocket); procedure OnEchoWebSocketMessage(const aWebSocket: TWebSocket; const aMessage: TWebSocketMessage); procedure OnEchoWebSocketClose(const aWebSocket: TWebSocket; const aWasClean: Boolean; const aCode: Word; const aReason: UTF8String); protected fServer: THttpApi2WebSocketServer; procedure OnHttpServerRequest(aRequest : TWebRequest; aResponse : TWebResponse); public constructor Create; destructor Destroy; override; procedure CloseWebSocketId(const aId: Integer; const aCode: Integer; const aReason: UTF8String); procedure SendToWebSocketId(const aId: Integer; const aMsg: UTF8String); end; implementation uses SynZip, System.SysUtils; { THttpSys2WebSocketServer } procedure TWebSocketEchoServer.CloseWebSocketId(const aId, aCode: Integer; const aReason: UTF8String); begin fEchoWebSocketHandler.CloseWebSocketId(aId, aCode, aReason); end; constructor TWebSocketEchoServer.Create; begin fEchoWebSocketHandler := TWebSocketHandler.Create; fEchoWebSocketHandler.OnAcceptConnection := OnEchoAcceptConnection; fEchoWebSocketHandler.OnConnectWebSocket := OnEchoConnectWebSocket; fEchoWebSocketHandler.OnDisconnectWebSocket := OnEchoDisconnectWebSocket; fEchoWebSocketHandler.OnWebSocketReceiveCloseBuffer := OnEchoWebSocketCloseBuffer; fServer := THttpApi2WebSocketServer.Create(False, 8, 8); //fServer.AddUrlAuthorize('', 8801, False, '+'); fServer.AddUrl('', 8801, False, '+'); fServer.AddWebSocketUrl(fEchoWebSocketHandler, '/echo/', 8801, False, '+'); fServer.RegisterCompress(CompressDeflate); fServer.OnRequest := OnHttpServerRequest; fServer.MaxConnections := 0; fServer.MaxBandwidth := 0; fServer.MaxInputCountLength := 0; FServer.Clone(8-1); end; destructor TWebSocketEchoServer.Destroy; begin fServer.Free; inherited; end; procedure TWebSocketEchoServer.OnHttpServerRequest(aRequest: TWebRequest; aResponse: TWebResponse); begin aResponse.StatusCode := 404; end; procedure TWebSocketEchoServer.SendToWebSocketId(const aId: Integer; const aMsg: UTF8String); begin fEchoWebSocketHandler.SendToWebSocketId(aId, aMsg); end; procedure TWebSocketEchoServer.OnEchoConnectWebSocket(const aWebSocket: TWebSocketServer); begin WriteLn(Format('OnEchoConnectWebSocket(%d)', [aWebSocket.TransportEndpoint.Id])); aWebSocket.OnOpen := OnEchoWebSocketOpen; aWebSocket.OnError := OnEchoWebSocketError; aWebSocket.OnMessage := OnEchoWebSocketMessage; aWebSocket.OnClose := OnEchoWebSocketClose; end; procedure TWebSocketEchoServer.OnEchoAcceptConnection(aRequest: TWebRequest; aResponse: TWebResponse; var aAccept: Boolean); begin WriteLn(Format('OnEchoAcceptConnection(%d)', [-1])); aAccept := True; end; procedure TWebSocketEchoServer.OnEchoWebSocketClose(const aWebSocket: TWebSocket; const aWasClean: Boolean; const aCode: Word; const aReason: UTF8String); begin WriteLn(Format('OnEchoWebSocketClose(%d): %s, %d, %s', [TWebSocketServer(aWebSocket).TransportEndpoint.Id, BoolToStr(aWasClean, True), aCode, aReason])); end; procedure TWebSocketEchoServer.OnEchoWebSocketCloseBuffer(const aWebSocket: TWebSocketServer; const aStatus: Cardinal; const aReasonBuffer: Pointer; const aReasonBufferSize: Cardinal); var reason: UTF8String; begin reason := aWebSocket.BufferToUTF8(aReasonBuffer, aReasonBufferSize); WriteLn(Format('OnEchoWebSocketCloseBuffer(%d), code:%d, reason: %s', [aWebSocket.TransportEndpoint.Id, aStatus, reason])); aWebSocket.Close(aStatus, 'Server: ' + reason); end; procedure TWebSocketEchoServer.OnEchoDisconnectWebSocket(const aWebSocket: TWebSocketServer); begin WriteLn(Format('OnEchoDisconnectWebSocket(%d)', [aWebSocket.TransportEndpoint.Id])); end; procedure TWebSocketEchoServer.OnEchoWebSocketError(const aWebSocket: TWebSocket); begin WriteLn(Format('OnEchoWebSocketError(%d)', [TWebSocketServer(aWebSocket).TransportEndpoint.Id])); end; procedure TWebSocketEchoServer.OnEchoWebSocketMessage(const aWebSocket: TWebSocket; const aMessage: TWebSocketMessage); begin WriteLn(Format('OnEchoWebSocketMessage(%d): IsUTF8:%s, IsFragment:%s, Size: %d, Data:%s', [TWebSocketServer(aWebSocket).TransportEndpoint.Id, BoolToStr(aMessage.MessageType = mtUTF8, True), BoolToStr(aMessage.IsFragment, True), aMessage.BufferSize, Copy(aMessage.AsUTF8, 1, 100)])); fEchoWebSocketHandler.Broadcast(aMessage); end; procedure TWebSocketEchoServer.OnEchoWebSocketOpen(const aWebSocket: TWebSocket); begin WriteLn(Format('OnEchoWebSocketOpen(%d)', [TWebSocketServer(aWebSocket).TransportEndpoint.Id])); end; end.
unit range_regex; // https://github.com/m-matsubara/range-regex-pas // coding=utf8 // Split range to ranges that has its unique pattern. // Example for 12-345: // // 12- 19: 1[2-9] // 20- 99: [2-9]\d // 100-299: [1-2]\d{2} // 300-339: 3[0-3]\d // 340-345: 34[0-5] interface uses System.Classes , System.Generics.Collections ; function bounded_regex_for_range(min_, max_: Int64; pre0: Boolean = False): String; function regex_for_range(min_, max_: Int64; pre0: Boolean = False): String; function split_to_patterns(min_, max_: Int64): TStrings; function split_to_ranges(min_, max_: Int64): TList<Int64>; function fill_by_nines(integer_, nines_count: Int64): Int64; function fill_by_zeros(integer_, zeros_count: Int64): Int64; function range_to_pattern(start, stop: Int64): String; implementation uses System.SysUtils ; (* def bounded_regex_for_range(min_, max_): return r'\b({})\b'.format(regex_for_range(min_, max_)) *) function bounded_regex_for_range(min_, max_: Int64; pre0: Boolean): String; begin Result := Format('\b(%s)\b', [regex_for_range(min_, max_, pre0)]); end; function regex_for_range(min_, max_: Int64; pre0: Boolean): String; var min__: Int64; max__: Int64; negative_subpatterns: TStrings; positive_subpatterns: TStrings; negative_only_subpatterns: TStrings; positive_only_subpatterns: TStrings; subpatterns: TStrings; val: String; pre0Str: String; begin // matsubara Delphi version original specification if (pre0) then pre0Str := '0*' else pre0Str := ''; negative_subpatterns := nil; positive_subpatterns := nil; negative_only_subpatterns := nil; positive_only_subpatterns := nil; try (* > regex_for_range(12, 345) '1[2-9]|[2-9]\d|[1-2]\d{2}|3[0-3]\d|34[0-5]' *) (* positive_subpatterns = [] negative_subpatterns = [] *) (* if min_ < 0: min__ = 1 if max_ < 0: min__ = abs(max_) max__ = abs(min_) negative_subpatterns = split_to_patterns(min__, max__) min_ = 0 *) if (min_ < 0) then begin min__ := 1; if (max_ < 0) then min__ := abs(max_); max__ := abs(min_); negative_subpatterns := split_to_patterns(min__, max__); min_ := 0; end else negative_subpatterns := TStringList.Create; (* if max_ >= 0: positive_subpatterns = split_to_patterns(min_, max_) *) if (max_ >= 0) then positive_subpatterns := split_to_patterns(min_, max_) else positive_subpatterns := TStringList.Create; //negative_only_subpatterns = ['-' + val for val in negative_subpatterns if val not in positive_subpatterns] negative_only_subpatterns := TStringList.Create; for val in negative_subpatterns do begin if (positive_subpatterns.IndexOf(val) < 0) then negative_only_subpatterns.Add('-' + pre0Str + val); end; //positive_only_subpatterns = [val for val in positive_subpatterns if val not in negative_subpatterns] positive_only_subpatterns := TStringList.Create; for val in positive_subpatterns do begin if (negative_subpatterns.IndexOf(val) < 0) then positive_only_subpatterns.Add(pre0Str + val); end; (* intersected_subpatterns = ['-?' + val for val in negative_subpatterns if val in positive_subpatterns] subpatterns = negative_only_subpatterns + intersected_subpatterns + positive_only_subpatterns *) subpatterns := TStringList.Create; subpatterns.AddStrings(negative_only_subpatterns); for val in negative_subpatterns do begin if (positive_subpatterns.IndexOf(val) >= 0) then subpatterns.Add('-?' + pre0Str + val); end; subpatterns.AddStrings(positive_only_subpatterns); //return '|'.join(subpatterns) subpatterns.Delimiter := '|'; subpatterns.StrictDelimiter := True; Result := subpatterns.DelimitedText; finally FreeAndNil(negative_subpatterns); FreeAndNil(positive_subpatterns); FreeAndNil(negative_only_subpatterns); FreeAndNil(positive_only_subpatterns); end; end; function split_to_patterns(min_, max_: Int64): TStrings; var subpatterns: TStrings; start: Int64; stop: Int64; ranges: TList<Int64>; begin //subpatterns = [] subpatterns := TStringList.Create; //start = min_ start := min_; (* for stop in split_to_ranges(min_, max_): subpatterns.append(range_to_pattern(start, stop)) start = stop + 1 *) ranges := split_to_ranges(min_, max_); try for stop in ranges do begin subpatterns.Add(range_to_pattern(start, stop)); start := stop + 1; end; finally FreeAndNil(ranges); end; //return subpatterns Result := subpatterns; end; function split_to_ranges(min_, max_: Int64): TList<Int64>; var stops: TList<Int64>; nines_count: Int64; stop: Int64; zeros_count: Int64; begin //stops = {max_} stops := TList<Int64>.Create; stops.Add(max_); //nines_count = 1 nines_count := 1; //stop = fill_by_nines(min_, nines_count) stop := fill_by_nines(min_, nines_count); (* while min_ <= stop < max_: stops.add(stop) nines_count += 1 stop = fill_by_nines(min_, nines_count) *) while (min_ <= stop) and (stop < max_) do begin if (stops.Contains(stop) = False) then stops.Add(stop); Inc(nines_count); stop := fill_by_nines(min_, nines_count); end; //zeros_count = 1 zeros_count := 1; //stop = fill_by_zeros(max_ + 1, zeros_count) - 1 stop := fill_by_zeros(max_ + 1, zeros_count) - 1; (* while min_ < stop <= max_: stops.add(stop) zeros_count += 1 stop = fill_by_zeros(max_ + 1, zeros_count) - 1 *) while (min_ < stop) and (stop <= max_) do begin if (stops.Contains(stop) = False) then stops.add(stop); Inc(zeros_count); stop := fill_by_zeros(max_ + 1, zeros_count) - 1; end; //stops = list(stops) //stops.sort() stops.Sort; //return stops Result := stops; end; function fill_by_nines(Integer_, nines_count: Int64): Int64; var str: String; begin //return int(str(Int64_)[:-nines_count] + '9' * nines_count) str := IntToStr(Integer_); Result := StrToInt64( Copy(str, 1, Length(str) - nines_count) + Copy('99999999999999999999', 1, nines_count) ); end; function fill_by_zeros(Integer_, zeros_count: Int64): Int64; var idx: Int64; pow: Int64; begin //return Int64 - Int64 % 10 ** zeros_count pow := 1; for idx := 1 to zeros_count do pow := pow * 10; result := Integer_ - Integer_ mod pow; end; function range_to_pattern(start, stop: Int64): String; var pattern: String; any_digit_count: Int64; start_digit: Char; stop_digit: Char; str_start: String; str_stop: String; idx: Int64; str_start_len: Int64; str_stop_len: Int64; len: Int64; begin //pattern = '' //any_digit_count = 0 pattern := ''; any_digit_count := 0; (* for start_digit, stop_digit in zip(str(start), str(stop)): if start_digit == stop_digit: pattern += start_digit elif start_digit != '0' or stop_digit != '9': pattern += '[{}-{}]'.format(start_digit, stop_digit) else: any_digit_count += 1 *) str_start := IntToStr(start); str_stop := IntToStr(stop); str_start_len := Length(str_start); str_stop_len := Length(str_stop); if (str_start_len < str_stop_len) then len := str_start_len else len := str_stop_len; for idx := 1 to len do begin start_digit := str_start[idx]; stop_digit := str_stop[idx]; if (start_digit = stop_digit) then pattern := pattern + start_digit else if (start_digit <> '0') or (stop_digit <> '9') then pattern := pattern + Format('[%s-%s]', [start_digit, stop_digit]) else Inc(any_digit_count); end; (* if any_digit_count: pattern += r'\d' *) if (any_digit_count > 0) then pattern := pattern + '\d'; (* if any_digit_count > 1: pattern += '{{{}}}'.format(any_digit_count) *) if (any_digit_count > 1) then pattern := pattern + Format('{%d}', [any_digit_count]); //return pattern Result := pattern; end; end.
unit LinkedList.CRGP; interface { Does not compile: "Undeclared identifier: 'TLinkedListItem'" type | TLinkedListItem<T: TLinkedListItem> = class private FNext: T; end; } type TLinkedListItem = class abstract private FNext: TLinkedListItem; end; {type TLinkedListItem<T: TLinkedListItem> = class abstract(TLinkedListItem) end; type Does not compile: "'T' is not compatible with type 'TLinkedListItem'" | TPerson = class(TLinkedListItem<TPerson>) end;} type TLinkedListItem<T: class> = class abstract(TLinkedListItem) private function GetNext: T; inline; public class constructor Create; public property Next: T read GetNext; end; type TLinkedList<T: TLinkedListItem> = class private FHead: T; public procedure Add(const AItem: T); property Head: T read FHead; end; type TPerson = class(TLinkedListItem<TPerson>) private FName: String; public constructor Create(const AName: String); property Name: String read FName; end; procedure TestLinkedListCRGP; implementation uses Utils; procedure TestLinkedListCRGP; begin StartSection; WriteLn('A linked list implementation using CRGP.'); WriteLn('Enumerating person names:'); { NOTE: We are creating memory leaks here. } var List := TLinkedList<TPerson>.Create; List.Add(TPerson.Create('Alice')); List.Add(TPerson.Create('Bob')); List.Add(TPerson.Create('Charlie')); var Person := List.Head; while (Person <> nil) do begin WriteLn('* ', Person.Name); Person := Person.Next; end; end; { TLinkedListItem<T> } class constructor TLinkedListItem<T>.Create; begin Assert(T.InheritsFrom(TLinkedListItem)); end; function TLinkedListItem<T>.GetNext: T; begin Result := T(FNext); end; { TLinkedList<T> } procedure TLinkedList<T>.Add(const AItem: T); begin if (AItem <> nil) then begin AItem.FNext := FHead; FHead := AItem; end; end; { TPerson } constructor TPerson.Create(const AName: String); begin inherited Create; FName := AName; end; end.
unit MainWindow; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Indicator; type TForm1 = class(TForm) Indicator1: TIndicator; Indicator2: TIndicator; Indicator3: TIndicator; Indicator4: TIndicator; Indicator5: TIndicator; Indicator6: TIndicator; Indicator7: TIndicator; Indicator8: TIndicator; Indicator9: TIndicator; Indicator10: TIndicator; Indicator11: TIndicator; Indicator12: TIndicator; GroupBox1: TGroupBox; GroupBox2: TGroupBox; GroupBox3: TGroupBox; GroupBox4: TGroupBox; lblFrontSpeed: TLabel; lblRearSpeed: TLabel; lblAvgSpeed: TLabel; GroupBox5: TGroupBox; lblBoardAdress: TLabel; lblDistanceDetectors1: TLabel; lblDistanceDetectors2: TLabel; lblDistanceDetectors3: TLabel; lblInkerDistance1: TLabel; lblInkerDistance2: TLabel; lblInkerDistance3: TLabel; lblInkerDistance4: TLabel; lblDelay1: TLabel; lblDelay2: TLabel; lblDelay3: TLabel; lblDelay4: TLabel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private mainCycleTimer:TTimer; _indicators:array [0..11] of TIndicator; procedure Cycle(Sender: TObject); procedure ShowIndicators(inputByte: Word); procedure ShowSettings(); procedure ShowCalculatedValues; public { Public declarations } end; var Form1: TForm1; implementation uses {$IFDEF DEBUG} FakeDriver, {$ELSE} P16r16, {$ENDIF} Speedometer,TimeDelayController,Settings; {$R *.dfm} function CalculateDelay(speed:real; distance:integer):integer; begin if(speed=0) then exit(0); Result:=Round(distance/speed); end; { TForm1 } procedure TForm1.Cycle(Sender: TObject); var inputByte,output: Longint; delays:array [0..3] of integer; i: Integer; begin inputByte:=PCI_DI16(baseAdress); MeasuringSpeed(inputByte); for i := 0 to 3 do delays[i]:=CalculateDelay(GetAverageSpeed(), basesOfInker[i]); SetDelays(delays); output:=HandleWithTimeDelay((inputByte shr 4)); PCI_DO16(baseAdress,output); ShowIndicators(inputByte or (output shl 8)); ShowCalculatedValues(); end; procedure TForm1.ShowIndicators(inputByte: Word); var i: Integer; begin for i := 0 to 11 do if (inputByte and (1 shl i)) <> 0 then _indicators[i].SetOn else _indicators[i].SetOff; end; procedure TForm1.ShowSettings; begin lblBoardAdress.Caption:='Адрес платы: '+IntToStr(baseAdress); lblDistanceDetectors1.Caption:='Дистанция между 1-м и 2-м фотодатчиком: '+IntToStr(distanceBetweenDetectors[0]); lblDistanceDetectors2.Caption:='Дистанция между 2-м и 3-м фотодатчиком: '+IntToStr(distanceBetweenDetectors[1]); lblDistanceDetectors3.Caption:='Дистанция между 3-м и 4-м фотодатчиком: '+IntToStr(distanceBetweenDetectors[2]); lblInkerDistance1.Caption:='Расстояние до 1-го краскоотметчика: '+IntToStr(basesOfInker[0]); lblInkerDistance2.Caption:='Расстояние до 2-го краскоотметчика: '+IntToStr(basesOfInker[1]); lblInkerDistance3.Caption:='Расстояние до 3-го краскоотметчика: '+IntToStr(basesOfInker[2]); lblInkerDistance4.Caption:='Расстояние до 4-го краскоотметчика: '+IntToStr(basesOfInker[3]); end; procedure TForm1.ShowCalculatedValues; begin lblFrontSpeed.Caption := 'Скорость по переднему концу = ' + IntToStr(Round(speed * 1000)); lblRearSpeed.Caption := 'Скорость по заднему концу = ' + IntToStr(Round(speed2 * 1000)); lblAvgSpeed.Caption := 'Средняя скорость = ' + IntToStr(Round(GetAverageSpeed * 1000)); lblDelay1.Caption:= 'Задержка 1-го кр-ка:'+IntToStr(delays[0])+ ' мс.'; lblDelay2.Caption:= 'Задержка 2-го кр-ка:'+IntToStr(delays[1])+ ' мс.'; lblDelay3.Caption:= 'Задержка 3-го кр-ка:'+IntToStr(delays[2])+ ' мс.'; lblDelay4.Caption:= 'Задержка 4-го кр-ка:'+IntToStr(delays[3])+ ' мс.'; end; procedure TForm1.FormCreate(Sender: TObject); var rtn:word; totalBoards:word; begin baseAdress:=0; rtn := PCI_DriverInit( totalBoards ); if(rtn<>NoError)then begin ShowMessage('Ошибка при попытке открыть драйвер!'); exit; end; ShowSettings(); _indicators[0]:=Indicator1; _indicators[1]:=Indicator2; _indicators[2]:=Indicator3; _indicators[3]:=Indicator4; _indicators[4]:=Indicator5; _indicators[5]:=Indicator6; _indicators[6]:=Indicator7; _indicators[7]:=Indicator8; _indicators[8]:=Indicator9; _indicators[9]:=Indicator10; _indicators[10]:=Indicator11; _indicators[11]:=Indicator12; mainCycleTimer:=TTimer.Create(self); mainCycleTimer.Interval:=50; mainCycleTimer.OnTimer:=Cycle; mainCycleTimer.Enabled:=true; end; procedure TForm1.FormDestroy(Sender: TObject); begin PCI_DriverClose(); end; end.
unit HistoryOperations; interface uses Windows, Classes, ShellApi, SysUtils, Graphics, Calc_Vars; type THistoryList = class private FSelected: Integer; history: TStringList; file_history: TFileName; function GetCount: Integer; function GetItem(Index: Integer): String; public constructor Create; procedure Load(fn: String = 'history.txt'); procedure Save(); property Count: Integer read GetCount; procedure Add(s: String); function GetExpression: String; function GetResult: String; procedure OpenFile; procedure Clear(); property Items[Index: Integer]: String read GetItem; property Selected: Integer read FSelected write FSelected; end; var HistoryList: THistoryList = nil; implementation var F: Text; { THistoryList } procedure THistoryList.Add(s: String); var Temp: TStringList; i: Integer; F: Text; begin if history.IndexOf(s)>-1 then Exit; if HistoryCount<=history.Count then for i:=0 to history.Count - HistoryCount do history.Delete(0); //if HistoryCount = history.Count then history.Delete(0); history.Add(s); //UpdateHistory; if SaveHistory then begin {$I-} Assign(F, exePath+'History\'+FormatDateTime('dd.mm.yyyy', Now)+'.txt'); Append(F); if IOResult<>0 then Rewrite(F); {$I+} Writeln(F, s); Close(F); Self.Save(); end; end; procedure THistoryList.Clear; var i: integer; begin history.Clear(); Save(); end; constructor THistoryList.Create; begin history := TStringList.Create(); Selected := -1; end; function THistoryList.GetCount: Integer; begin Result := history.Count; end; function THistoryList.GetExpression: String; var P: Integer; S: String; begin Result := ''; if FSelected>-1 then begin S:=history.Strings[FSelected]; P:=Pos('=', S); Result := Trim(Copy(S, 1, P-1)); end; end; function THistoryList.GetResult: String; var P: Integer; S: String; begin Result := ''; if FSelected>-1 then begin S:=History.Strings[FSelected]; P:=Pos('=', S); Result := Trim(Copy(S, P+1, Length(S) - P+1)); end; end; procedure THistoryList.Load(fn: String); begin file_history := exePath+fn; if not FileExists(file_history) then begin Assign(F, file_history); Rewrite(F); Close(F); end; history.LoadFromFile(file_history); end; procedure THistoryList.Save(); begin history.SaveToFile(file_history); end; procedure THistoryList.OpenFile; begin ShellExecute(0, 'open', PChar(file_history), nil, nil, 0); end; function THistoryList.GetItem(Index: Integer): String; begin Result := history.Strings[Index]; end; end.
unit Unit14; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ToolWin, ShlObj, ImgList, Menus, Strutils; type TForm12 = class(TForm) ListBox1: TListBox; function GetIEFavourites(const favpath: string):TStrings; procedure Button1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure ListBox1DblClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form12: TForm12; implementation uses Main; {$R *.dfm} function TForm12.GetIEFavourites(const favpath: string):TStrings; var searchrec:TSearchrec; str:TStrings; path,dir,filename:String; Buffer: array[0..2047] of Char; found:Integer; begin str:=TStringList.Create; try path:=FavPath+'\*.url'; dir:=ExtractFilepath(path) ; found:=FindFirst(path,faAnyFile,searchrec) ; while found=0 do begin SetString(filename, Buffer, GetPrivateProfileString('InternetShortcut', PChar('URL'), NIL, Buffer, SizeOf(Buffer), PChar(dir+searchrec.Name))) ; str.Add(filename) ; found:=FindNext(searchrec) ; end; found:=FindFirst(dir+'\*.*',faAnyFile,searchrec) ; while found=0 do begin if ((searchrec.Attr and faDirectory) > 0) and (searchrec.Name[1]<>'.') then str.AddStrings(GetIEFavourites (dir+'\'+searchrec.name)) ; found:=FindNext(searchrec) ; end; FindClose(searchrec) ; finally Result:=str; end; end; procedure TForm12.Button1Click(Sender: TObject) ; var pidl: PItemIDList; FavPath: array[0..MAX_PATH] of char; begin SHGetSpecialFolderLocation(Handle, CSIDL_FAVORITES, pidl) ; SHGetPathFromIDList(pidl, favpath) ; ListBox1.Items:=GetIEFavourites(StrPas(FavPath)) ; end; procedure TForm12.FormShow(Sender: TObject); begin Button1Click(Self) ; end; procedure TForm12.ListBox1DblClick(Sender: TObject); var s:string; begin s := ListBox1.Items[ListBox1.ItemIndex]; s := AnsiReplaceStr(s, 'http://', ''); s := 'http://' + AnsiReplaceStr(s, StrScan(Pchar(s), '/'), ''); Form1.cbURL.Text := s; Close; end; end.
unit Aurelius.Schema.AbsoluteDB; {$I Aurelius.Inc} interface uses ABSMain, ABSTypes, Aurelius.Drivers.AbsoluteDB, Aurelius.Drivers.Interfaces, Aurelius.Schema.AbstractImporter, Aurelius.Sql.Metadata; type TAbsoluteDBSchemaImporter = class(TAbstractSchemaImporter) strict protected procedure GetDatabaseMetadata(Connection: IDBConnection; Database: TDatabaseMetadata); override; end; TAbsoluteDBSchemaRetriever = class(TSchemaRetriever) strict private FABSTable: TABSTable; function ABSDatabase: TABSDatabase; procedure GetTables; procedure GetColumns; procedure GetKeys; procedure GetFieldDefinition(Column: TColumnMetadata; ADatatype: TABSAdvancedFieldType; ASize: Integer); public constructor Create(AConnection: IDBConnection; ADatabase: TDatabaseMetadata); override; destructor Destroy; override; procedure RetrieveDatabase; override; end; implementation uses DB, Classes, SysUtils, Aurelius.Schema.Register, Aurelius.Schema.Utils; { TAbsoluteDBSchemaImporter } procedure TAbsoluteDBSchemaImporter.GetDatabaseMetadata(Connection: IDBConnection; Database: TDatabaseMetadata); var Retriever: TSchemaRetriever; begin Retriever := TAbsoluteDBSchemaRetriever.Create(Connection, Database); try Retriever.RetrieveDatabase; finally Retriever.Free; end; end; { TAbsoluteDBSchemaRetriever } function TAbsoluteDBSchemaRetriever.ABSDatabase: TABSDatabase; begin Result := (Connection as TAbsoluteDBConnectionAdapter).ABSDatabase; end; constructor TAbsoluteDBSchemaRetriever.Create(AConnection: IDBConnection; ADatabase: TDatabaseMetadata); begin inherited Create(AConnection, ADatabase); FABSTable := TABSTable.Create(nil); FABSTable.DatabaseName := ABSDatabase.DatabaseName; end; destructor TAbsoluteDBSchemaRetriever.Destroy; begin FABSTable.Free; inherited; end; procedure TAbsoluteDBSchemaRetriever.GetColumns; var Table: TTableMetadata; Column: TColumnMetadata; I: integer; begin for Table in Database.Tables do begin FABSTable.Close; FABSTable.TableName := Table.Name; FABSTable.FieldDefs.Update; {Get fields} for I := 0 to FABSTable.AdvFieldDefs.Count - 1 do begin Column := TColumnMetadata.Create(Table); Table.Columns.Add(Column); Column.Name := FABSTable.AdvFieldDefs[I].Name; Column.NotNull := FABSTable.AdvFieldDefs[I].Required; GetFieldDefinition(Column, FABSTable.AdvFieldDefs[I].DataType, FABSTable.AdvFieldDefs[I].Size); Column.AutoGenerated := (Pos('autoinc', Lowercase(Column.DataType)) = 1); end; end; end; procedure TAbsoluteDBSchemaRetriever.GetFieldDefinition(Column: TColumnMetadata; ADatatype: TABSAdvancedFieldType; ASize: Integer); const MapStr: array[TABSAdvancedFieldType] of string = ( {aftUnknown } '', {aftChar } 'Char', {aftString } 'Varchar', {aftWideChar } 'WideString', {aftWideString } 'WideString', {aftShortint } 'SmallInt', {aftSmallint } 'SmallInt', {aftInteger } 'Integer', {aftLargeint } 'LargeInt', {aftByte } 'Byte', {aftWord } 'Word', {aftCardinal } 'Cardinal', {aftAutoInc } 'AutoInc', {aftAutoIncShortint } 'AutoInc(ShortInt)', {aftAutoIncSmallint } 'AutoInc(SmallInt)', {aftAutoIncInteger } 'AutoInc(Integer)', {aftAutoIncLargeint } 'AutoInc(LargeInt)', {aftAutoIncByte } 'AutoInc(Byte)', {aftAutoIncWord } 'AutoInc(Word)', {aftAutoIncCardinal } 'AutoInc(Cardinal)', {aftSingle } 'Single', {aftDouble } 'Float', {aftExtended } 'Extended', {aftBoolean } 'Logical', {aftCurrency } 'Currency', {aftDate } 'Date', {aftTime } 'Time', {aftDateTime } 'DateTime', {aftTimeStamp } 'TimeStamp', {aftBytes } 'Bytes', {aftVarBytes } 'VarBytes', {aftBlob } 'Blob', {aftGraphic } 'Graphic', {aftMemo } 'Memo', {aftFormattedMemo } 'FormattedMemo', {aftWideMemo } 'WideMemo', {aftGuid } 'Guid' ); begin Column.DataType := MapStr[ADataType]; if ADataType in [aftBytes, aftChar, aftString, aftWideChar, aftWideString] then Column.Length := ASize; end; procedure TAbsoluteDBSchemaRetriever.GetKeys; var Table: TTableMetadata; UniqueKey: TUniqueKeyMetadata; FieldNames: TStrings; I, J: integer; begin for Table in Database.Tables do begin FABSTable.Close; FABSTable.TableName := Table.Name; FABSTable.IndexDefs.Update; {Get indexes} for I := 0 to FABSTable.IndexDefs.Count - 1 do begin if ixPrimary in FABSTable.IndexDefs[I].Options then begin FieldNames := TStringList.Create; try GetNamesList(FieldNames, FABSTable.AdvIndexDefs[I].Fields); for J := 0 to FieldNames.Count - 1 do Table.IdColumns.Add(TSchemaUtils.GetColumn(Table, FieldNames[J])); finally FieldNames.Free; end; end else if ixUnique in FABSTable.IndexDefs[I].Options then begin UniqueKey := TUniqueKeyMetadata.Create(Table); Table.UniqueKeys.Add(UniqueKey); UniqueKey.Name := FABSTable.IndexDefs[I].Name; FieldNames := TStringList.Create; try GetNamesList(FieldNames, FABSTable.AdvIndexDefs[I].Fields); for J := 0 to FieldNames.Count - 1 do UniqueKey.Columns.Add(TSchemaUtils.GetColumn(Table, FieldNames[J])); finally FieldNames.Free; end; end; end; end; end; procedure TAbsoluteDBSchemaRetriever.GetTables; var TableNames: TStringList; I: Integer; Table: TTableMetadata; begin TableNames := TStringList.Create; try ABSDatabase.GetTablesList(TableNames); for I := 0 to TableNames.Count - 1 do begin Table := TTableMetadata.Create(Database); Database.Tables.Add(Table); Table.Name := TableNames[I]; end; finally TableNames.Free; end; end; procedure TAbsoluteDBSchemaRetriever.RetrieveDatabase; begin Database.Clear; GetTables; GetColumns; GetKeys; end; initialization TSchemaImporterRegister.GetInstance.RegisterImporter('AbsoluteDB', TAbsoluteDBSchemaImporter.Create); end.
unit UcumTests; // -tests -definitions { Copyright (c) 2017+, Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses SysUtils, Classes, DUnitX.TestFramework, StringSupport, DecimalSupport, AdvObjects, MXML, UcumServices; type UcumTestCaseAttribute = class (CustomTestCaseSourceAttribute) protected function GetCaseInfoArray : TestCaseInfoArray; override; end; [TextFixture] TUcumTests = class (TObject) private procedure findTest(id : String; var foundGroup, foundTest : TMXmlElement); procedure TestValidation(test : TMXmlElement); procedure TestDisplayNameGeneration(test : TMXmlElement); procedure TestConversion(test : TMXmlElement); procedure TestMultiplication(test : TMXmlElement); public [Setup] procedure Setup; [TearDown] procedure TearDown; [UcumTestCase] procedure TestCase(id : String); end; implementation var tests : TMXmlElement; svc : TUcumServices; procedure LoadTests; begin if tests = nil then tests := TMXmlParser.ParseFile('C:\work\fhir.org\Ucum-java\src\test\resources\UcumFunctionalTests.xml', [xpDropWhitespace]); end; { UcumTestCaseAttribute } function UcumTestCaseAttribute.GetCaseInfoArray: TestCaseInfoArray; var group, test : TMXmlElement; i: integer; begin LoadTests; i := 0; for group in tests.document.Children do for test in group.Children do if (test.Name = 'case') and (test.attribute['id'] <> '') then inc(i); setLength(result, i); i := 0; for group in tests.document.Children do for test in group.Children do if (test.Name = 'case') and (test.attribute['id'] <> '') then begin result[i].Name := group.Name+'-'+test.attribute['id']; SetLength(result[i].Values, 1); result[i].Values[0] := test.attribute['id']; inc(i); end; end; { TUcumTests } procedure TUcumTests.findTest(id: String; var foundGroup, foundTest: TMXmlElement); var group, test : TMXmlElement; begin LoadTests; foundGroup := nil; foundTest := nil; for group in tests.document.Children do for test in group.Children do if (test.Name = 'case') and (test.attribute['id'] = id) then begin foundGroup := Group; foundTest := test; exit; end; raise Exception.Create('nout found id = '+id); end; procedure TUcumTests.Setup; begin if (svc = nil) then begin svc := TUcumServices.Create; svc.Import('C:\work\fhir.org\Ucum-java\src\main\resources\ucum-essence.xml'); end; end; procedure TUcumTests.TearDown; begin end; procedure TUcumTests.TestCase(id: String); var group, test : TMXmlElement; begin findTest(id, group, test); if group.name = 'validation' then TestValidation(test) else if group.name = 'displayNameGeneration' then TestDisplayNameGeneration(test) else if group.name = 'conversion' then TestConversion(test) else if group.name = 'multiplication' then TestMultiplication(test) else raise Exception.Create('unknown group '+group.Name); end; procedure TUcumTests.TestValidation(test : TMXmlElement); var units : String; valid : boolean; res, reason : String; begin units := test.attribute['unit']; valid := test.attribute['valid'] = 'true'; reason := test.attribute['reason']; res := svc.validate(units); if valid then Assert.IsEmpty(res, 'Unit "'+units+'" should be valid, but had error: '+res) else Assert.IsNotEmpty(res, 'Unit "'+units+'" should be invalid, but no error'); end; procedure TUcumTests.TestDisplayNameGeneration(test : TMXmlElement); var units, display, res : String; begin units := test.attribute['unit']; display := test.attribute['display']; res := svc.analyse(units); Assert.AreEqual(display, res, 'Display name should have been "'+display+'" but was "'+res+'"'); end; procedure TUcumTests.TestConversion(test : TMXmlElement); var value, srcUnit, dstUnit, outcome : String; d : TSmartDecimal; begin value := test.attribute['value']; srcUnit := test.attribute['srcUnit']; dstUnit := test.attribute['dstUnit']; outcome := test.attribute['outcome']; d := svc.convert(TSmartDecimal.ValueOf(value), srcUnit, dstUnit); Assert.IsTrue(d.Compares(TSmartDecimal.ValueOf(outcome)) = 0, 'Value does not match. expected '+outcome+' but got '+d.AsString); end; procedure TUcumTests.TestMultiplication(test : TMXmlElement); var id, v1, u1, v2, u2, vRes, uRes : String; o1, o2, o3 : TUcumPair; begin id := test.attribute['id']; v1 := test.attribute['v1']; u1 := test.attribute['u1']; v2 := test.attribute['v2']; u2 := test.attribute['u2']; vRes := test.attribute['vRes']; uRes := test.attribute['uRes']; o1 := TUcumPair.Create(TSmartDecimal.ValueOf(v1), u1); try o2 := TUcumPair.Create(TSmartDecimal.ValueOf(v2), u2); try o3 := svc.multiply(o1, o2); try Assert.IsTrue((o3.Value.compares(TSmartDecimal.valueOf(vRes)) = 0) and (o3.UnitCode = uRes)); finally o3.Free; end; finally o2.Free; end; finally o1.Free; end; end; initialization TDUnitX.RegisterTestFixture(TUcumTests); finalization tests.Free; svc.Free; end.
unit SmtpModuleUnit; interface uses System.SysUtils, System.Classes, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdServerIOHandler, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdSMTP, IdBaseComponent, IdComponent, IdCustomTCPServer, IdTCPServer, IdCmdTCPServer, IdSMTPServer, IdUserPassProvider, IdSASL, IdSASLUserPass, IdSASLLogin; type TSmtpSettings = class public ServiceName: string; SslRequired : boolean; ListenIp : string; ListenPort : word; UserName : string; Password : string; RemoteHost : string; RemotePort : word; RemoteSslRequired : boolean; RemoteUserName : string; RemotePassword : string; QueueDirectory : string; end; TSmtpModule = class(TDataModule) MailServer: TIdSMTPServer; MailClient: TIdSMTP; SslHandlerServer: TIdServerIOHandlerSSLOpenSSL; SslHandlerClient: TIdSSLIOHandlerSocketOpenSSL; ServerUserPass: TIdUserPassProvider; procedure MailClientTLSNotAvailable(Asender: TObject; var VContinue: Boolean); procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private { Private declarations } _ReadingSettings : Boolean; _WritingSettings : Boolean; procedure SetSmtpSettings(v: TSmtpSettings); function GetSmtpSettings(): TSmtpSettings; procedure LoadSettingsFromFile(fileName: string); procedure SaveSettingsToFile(fileName: string); public { Public declarations } QueueDirectory : string; property ReadingSettings : Boolean read _ReadingSettings; property WritingSettings : Boolean read _WritingSettings; property SmtpSettings : TSmtpSettings read GetSmtpSettings write SetSmtpSettings; function TestClient(host: string; port: word; ssl: boolean; user: string; password: string; testFrom: string = ''; testTo: string = ''): string; end; var SmtpModule: TSmtpModule; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} uses IdMessage; procedure TSmtpModule.LoadSettingsFromFile(fileName: string); var sl: TStringList; cfg: TSmtpSettings; begin if not FileExists(fileName) then Exit; sl := TStringList.Create(); cfg := TSmtpSettings.Create(); try sl.LoadFromFile(fileName); cfg.ServiceName := sl.Values['ServiceName']; cfg.SslRequired := StrToBool(sl.Values['SslRequired']); cfg.ListenIp := sl.Values['ListenIp']; cfg.ListenPort := StrToInt(sl.Values['ListenPort']); cfg.UserName := sl.Values['UserName']; cfg.Password := sl.Values['Password']; cfg.RemoteHost := sl.Values['RemoteHost']; cfg.RemotePort := StrToInt(sl.Values['RemotePort']); cfg.RemoteSslRequired := StrToBool(sl.Values['RemoteSslRequired']); cfg.RemoteUserName := sl.Values['RemoteUserName']; cfg.RemotePassword := sl.Values['RemotePassword']; cfg.QueueDirectory := sl.Values['QueueDirectory']; SmtpSettings := cfg; finally cfg.Free(); sl.Free(); end; end; procedure TSmtpModule.SaveSettingsToFile(fileName: string); var sl: TStringList; cfg: TSmtpSettings; begin sl := TStringList.Create(); cfg := SmtpSettings; try sl.Values['ServiceName'] := cfg.ServiceName; sl.Values['SslRequired'] := BoolToStr(cfg.SslRequired, True); sl.Values['ListenIp'] := cfg.ListenIp; sl.Values['ListenPort'] := IntToStr(cfg.ListenPort); sl.Values['UserName'] := cfg.UserName; sl.Values['Password'] := cfg.Password; sl.Values['RemoteHost'] := cfg.RemoteHost; sl.Values['RemotePort'] := IntToStr(cfg.RemotePort); sl.Values['RemoteSslRequired'] := BoolToStr(cfg.RemoteSslRequired, True); sl.Values['RemoteUserName'] := cfg.RemoteUserName; sl.Values['RemotePassword'] := cfg.RemotePassword; sl.Values['QueueDirectory'] := cfg.QueueDirectory; sl.SaveToFile(fileName); finally cfg.Free(); sl.Free(); end; end; procedure TSmtpModule.MailClientTLSNotAvailable(Asender: TObject; var VContinue: Boolean); begin case MailClient.UseTLS of utNoTLSSupport, utUseExplicitTLS: VContinue := true; else VContinue := false; end; end; procedure TSmtpModule.DataModuleCreate(Sender: TObject); begin LoadSettingsFromFile('Smtp.conf'); end; procedure TSmtpModule.DataModuleDestroy(Sender: TObject); begin SaveSettingsToFile('Smtp.conf'); end; function TSmtpModule.GetSmtpSettings: TSmtpSettings; begin if (ReadingSettings or WritingSettings) then raise Exception.Create('Please wait for pending operation to finish, before reading SMTP settings!'); _ReadingSettings := true; Result := TSmtpSettings.Create; try // Read listening server settings Result.SslRequired := MailServer.UseTLS = utUseRequireTLS; Result.ListenIp := MailServer.Bindings[0].IP; Result.ListenPort := MailServer.Bindings[0].Port; Result.UserName := ServerUserPass.Username; Result.Password := ServerUserPass.Password; // Read remote server settings Result.RemoteHost := MailClient.Host; Result.RemotePort := MailClient.Port; Result.RemoteSslRequired := MailClient.UseTLS = utUseRequireTLS; Result.ServiceName := MailClient.MailAgent; Result.RemoteUserName := MailClient.Username; Result.RemotePassword := MailClient.Password; Result.QueueDirectory := QueueDirectory; finally _ReadingSettings := false; end; end; procedure TSmtpModule.SetSmtpSettings(v: TSmtpSettings); var backup : TSmtpSettings; begin if (WritingSettings or ReadingSettings) then raise Exception.Create('Please wait for pending operation to finish before writing SMTP settings!'); if (TestClient(v.RemoteHost, v.RemotePort, v.RemoteSslRequired, v.RemoteUserName, v.RemotePassword) <> 'OK') then raise Exception.Create('Client connection test failed!'); // Backup existing configuration backup := SmtpSettings; _WritingSettings := true; try try try // First, close all connections MailServer.Active := false; if MailClient.Connected() then MailClient.Disconnect(true); // Write listening server settings if v.SslRequired then MailServer.UseTLS := utUseRequireTLS else MailServer.UseTLS := utUseExplicitTLS; MailServer.Bindings[0].IP := v.ListenIp; MailServer.Bindings[0].Port := v.ListenPort; ServerUserPass.Username := v.UserName; ServerUserPass.Password := v.Password; // Read remote server settings if v.RemoteSslRequired then MailClient.UseTLS := utUseRequireTLS else MailClient.UseTLS := utUseExplicitTLS; MailClient.Host := v.RemoteHost; MailClient.Port := v.RemotePort; MailClient.Username := v.RemoteUserName; MailClient.Password := v.RemotePassword; MailClient.MailAgent := v.ServiceName; QueueDirectory := v.QueueDirectory; MailServer.Active := true; finally _WritingSettings := false; end; except // Recover from backup SmtpSettings := backup; end; finally backup.Free; end; end; function TSmtpModule.TestClient(host: string; port: word; ssl: boolean; user: string; password: string; testFrom: string = ''; testTo: string = ''): string; var status : (stConnect, stAuthenticate, stTestMail, stDone); cli: TIdSmtp; testMail : TIdMessage; sslHandler : TIdSSLIOHandlerSocketOpenSSL; begin status := stConnect; cli := TIdSMTP.Create(Self); sslHandler := TIdSSLIOHandlerSocketOpenSSL.Create(Self); try try cli.IOHandler := sslHandler; if ssl then cli.UseTLS := utUseRequireTLS else cli.UseTLS := utUseExplicitTLS; cli.Username := user; cli.Password := password; cli.Connect(host, port); if (cli.Connected()) then begin status := stAuthenticate; if (cli.Authenticate()) then begin if (testFrom <> '') then begin status := stTestMail; testMail := TIdMessage.Create(Self); testMail.From.Address := testFrom; testMail.Recipients.Add().Address := testTo; testMail.Subject := 'About test mail'; testMail.Body.Text := 'Test mail sending successful!'; try cli.Send(testMail); except on e: Exception do begin Result := e.Message; raise; end; end; end; status := stDone; end; end; finally if cli.Connected() then cli.Disconnect(true); cli.Free; sslHandler.Free; end; except // Shh! end; case status of stConnect: Result := 'Invalid host address!'; stAuthenticate: Result := 'Invalid user name or password!'; stTestMail: Result := 'Test e-mail sending failed with message: ' + Result; stDone: Result := 'OK'; end; end; end.
{******************************************************************************* Title: T2Ti ERP Description: Unit vinculada à tela Menu da aplicação The MIT License Copyright: Copyright (C) 2015 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (T2Ti.COM) @version 2.0 *******************************************************************************} unit UMenu; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, ComCtrls, StdCtrls, ExtCtrls, ImgList, JvExControls, JvComponent, JvPageList, JvTabBar, RibbonLunaStyleActnCtrls, Ribbon, ToolWin, ActnMan, ActnCtrls, ActnList, RibbonSilverStyleActnCtrls, JvExComCtrls, JvStatusBar, ActnMenus, RibbonActnMenus, JvOutlookBar, JvLookOut, ScreenTips, WideStrings, DB, JvComponentBase, Atributos, Enter, XPMan, ShellApi, IndyPeerImpl, // UPais, UUnidadeProduto, UBase, UBanco, ULogin, UEstadoCivil, UPessoa, UProdutoMarca, USetor, UAgenciaBanco, UProdutoGrupo, UProdutoSubGrupo, UAlmoxarifado, UNcm, UUf, UMunicipio, UTipoRelacionamento, UTipoAdmissao, UNivelFormacao, UCfop, UCbo, UCargo, UAtividadeForCli, USituacaoForCli, Uproduto, UEfdTabela437, UCep, UCheque, UTalonarioCheque, UContaCaixa, UConvenio, UOperadoraCartao, UOperadoraPlanoSaude, USindicato, USituacaoColaborador, UTipoColaborador, USalarioMinimo, UCodigoGps, UTipoDesligamento, USefipCodigoMovimentacao, USefipCodigoRecolhimento, USefipCategoriaTrabalho, UTipoItemSped, UEfdTabela4310, UEfdTabela4313, UEfdTabela4314, UEfdTabela4315, UEfdTabela4316, UEfdTabela439, UEfdTabela436, USituacaoDocumento, UCsosnA, UCsosnB, UCstIcmsA, UCstIcmsB, UCstPis, UCstCofins,UCstIpi, UFeriados, UContador, UColaborador, System.Actions; type [TFormDescription('Menu','Menu')] TFMenu = class(TFBase) //actions (* OBS: O nome da Action deve ser igual ao nome do formulário sem o "TF". Exemplos: TFUnidadeProduto = ActionUnidadeProduto TFBanco = ActionBanco Deve ser dessa forma por conta do Controle de Acessos. *) [TComponentDescription('Acessar Janela',TFUnidadeProduto)] ActionUnidadeProduto: TAction; [TComponentDescription('Acessar Janela',TFBanco)] ActionBanco: TAction; [TComponentDescription('Acessar Janela',TFEstadoCivil)] ActionEstadoCivil: TAction; [TComponentDescription('Acessar Janela',TFPais)] ActionPais: TAction; [TComponentDescription('Acessar Janela',TFProdutoMarca)] [TComponentDescription('Acessar Janela',TFPessoa)] ActionPessoa: TAction; [TComponentDescription('Acessar Janela',TFSetor)] ActionSetor: TAction; [TComponentDescription('Acessar Janela',TFAgenciaBanco)] ActionAgenciaBanco: TAction; [TComponentDescription('Acessar Janela',TFProdutoGrupo)] [TComponentDescription('Acessar Janela',TFProdutoSubGrupo)] [TComponentDescription('Acessar Janela',TFAlmoxarifado)] ActionAlmoxarifado: TAction; [TComponentDescription('Acessar Janela',TFNcm)] ActionNCM: TAction; [TComponentDescription('Acessar Janela',TFUf)] ActionUf: TAction; [TComponentDescription('Acessar Janela',TFMunicipio)] ActionMunicipio: TAction; [TComponentDescription('Acessar Janela',TFTipoRelacionamento)] ActionTipoRelacionamento: TAction; [TComponentDescription('Acessar Janela',TFTipoAdmissao)] ActionTipoAdmissao: TAction; [TComponentDescription('Acessar Janela',TFNivelFormacao)] ActionNivelFormacao: TAction; [TComponentDescription('Acessar Janela',TFCfop)] ActionCfop: TAction; [TComponentDescription('Acessar Janela',TFCbo)] ActionCbo: TAction; [TComponentDescription('Acessar Janela',TFCargo)] ActionCargo: TAction; [TComponentDescription('Acessar Janela',TFAtividadeForCli)] ActionAtividadeForCli: TAction; [TComponentDescription('Acessar Janela',TFSituacaoForCli)] ActionSituacaoForCli: TAction; [TComponentDescription('Acessar Janela',TFProduto)] ActionProduto: TAction; [TComponentDescription('Acessar Janela',TFEfdTabela437)] [TComponentDescription('Acessar Janela',TFCep)] ActionCep: TAction; [TComponentDescription('Acessar Janela',TFCheque)] ActionCheque: TAction; [TComponentDescription('Acessar Janela',TFTalonarioCheque)] ActionTalonarioCheque: TAction; [TComponentDescription('Acessar Janela',TFContaCaixa)] ActionContaCaixa: TAction; [TComponentDescription('Acessar Janela',TFConvenio)] ActionConvenio: TAction; [TComponentDescription('Acessar Janela',TFOperadoraCartao)] ActionOperadoraCartao: TAction; [TComponentDescription('Acessar Janela',TFOperadoraPlanoSaude)] ActionOperadoraPlanoSaude: TAction; [TComponentDescription('Acessar Janela',TFSindicato)] ActionSindicato: TAction; [TComponentDescription('Acessar Janela',TFSituacaoColaborador)] ActionSituacaoColaborador: TAction; [TComponentDescription('Acessar Janela',TFTipoColaborador)] ActionTipoColaborador: TAction; [TComponentDescription('Acessar Janela',TFSalarioMinimo)] ActionSalarioMinimo: TAction; [TComponentDescription('Acessar Janela',TFCodigoGps)] ActionCodigoGps: TAction; [TComponentDescription('Acessar Janela',TFTipoDesligamento)] ActionTipoDesligamento: TAction; [TComponentDescription('Acessar Janela',TFSefipCodigoMovimentacao)] ActionSefipCodigoMovimentacao: TAction; [TComponentDescription('Acessar Janela',TFSefipCodigoRecolhimento)] ActionSefipCodigoRecolhimento: TAction; [TComponentDescription('Acessar Janela',TFSefipCategoriaTrabalho)] ActionSefipCategoriaTrabalho: TAction; [TComponentDescription('Acessar Janela',TFTipoItemSped)] ActionTipoItemSped: TAction; [TComponentDescription('Acessar Janela',TFEfdTabela436)] ActionEfdTabela436: TAction; [TComponentDescription('Acessar Janela',TFSituacaoDocumento)] ActionSituacaoDocumento: TAction; [TComponentDescription('Acessar Janela',TFCsosnA)] ActionCsosnA: TAction; [TComponentDescription('Acessar Janela',TFCsosnB)] ActionCsosnB: TAction; [TComponentDescription('Acessar Janela',TFCstIcmsA)] ActionCstIcmsA: TAction; [TComponentDescription('Acessar Janela',TFCstIcmsB)] ActionCstIcmsB: TAction; [TComponentDescription('Acessar Janela',TFCstPis)] ActionCstPis: TAction; [TComponentDescription('Acessar Janela',TFCstCofins)] ActionCstCofins: TAction; [TComponentDescription('Acessar Janela',TFCstIpi)] ActionCstIpi: TAction; [TComponentDescription('Acessar Janela',TFFeriados)] ActionFeriados: TAction; [TComponentDescription('Acessar Janela',TFPessoa)] ActionCliente: TAction; [TComponentDescription('Acessar Janela',TFPessoa)] ActionFornecedor: TAction; [TComponentDescription('Acessar Janela',TFPessoa)] ActionTransportadora: TAction; [TComponentDescription('Acessar Janela',TFColaborador)] ActionColaborador: TAction; [TComponentDescription('Acessar Janela',TFContador)] ActionContador: TAction; ActionSped: TAction; ActionSefip: TAction; ActionPis: TAction; ActionCst: TAction; ActionEndereco: TAction; ActionSocio: TAction; ActionSair: TAction; // [TComponentDescription('Acesso ao Módulo Vendas')] ActionModuloVendas: TAction; [TComponentDescription('Acesso ao Módulo Compras')] ActionModuloCompras: TAction; // Image16: TImageList; PopupMenu: TPopupMenu; menuFechar: TMenuItem; menuFecharTodasExcetoEssa: TMenuItem; menuSepararAba: TMenuItem; N2: TMenuItem; JvTabBar: TJvTabBar; JvModernTabBarPainter: TJvModernTabBarPainter; JvPageList: TJvPageList; Ribbon: TRibbon; RibbonPagePessoa: TRibbonPage; ActionManager: TActionManager; JvStatusBar1: TJvStatusBar; RibbonGroupDiversos: TRibbonGroup; Image48: TImageList; Image32: TImageList; RibbonApplicationMenuBar1: TRibbonApplicationMenuBar; ScreenTipsManager1: TScreenTipsManager; MREnter: TMREnter; RibbonGroupTabelas: TRibbonGroup; RibbonGroupSairPessoal: TRibbonGroup; RibbonPageTabelas: TRibbonPage; RibbonGroupPessoa: TRibbonGroup; RibbonGroupCliForTra: TRibbonGroup; RibbonGroupColaborador: TRibbonGroup; RibbonPageFinanceiro: TRibbonPage; RibbonPageProduto: TRibbonPage; RibbonGroupProduto: TRibbonGroup; RibbonGroupOutros: TRibbonGroup; RibbonPageDiversos: TRibbonPage; RibbonGroupEndereco: TRibbonGroup; RibbonGroupSairTabelas: TRibbonGroup; RibbonGroupSairFinanceiro: TRibbonGroup; RibbonGroupSairProduto: TRibbonGroup; RibbonGroupSairDiversos: TRibbonGroup; RibbonGroupBanco: TRibbonGroup; ActionEfdTabela437: TAction; procedure menuFecharClick(Sender: TObject); procedure menuFecharTodasExcetoEssaClick(Sender: TObject); procedure menuSepararAbaClick(Sender: TObject); procedure JvPageListChange(Sender: TObject); procedure JvTabBarTabClosing(Sender: TObject; Item: TJvTabBarItem; var AllowClose: Boolean); procedure ActionClienteExecute(Sender: TObject); procedure ActionFornecedorExecute(Sender: TObject); procedure ActionTransportadoraExecute(Sender: TObject); procedure ActionColaboradorExecute(Sender: TObject); procedure ActionAtividadeForCliExecute(Sender: TObject); procedure ActionSituacaoForCliExecute(Sender: TObject); procedure ActionCargoExecute(Sender: TObject); procedure ActionTipoColaboradorExecute(Sender: TObject); procedure ActionNivelFormacaoExecute(Sender: TObject); procedure ActionProdutoExecute(Sender: TObject); procedure ActionProdutoMarcaExecute(Sender: TObject); procedure ActionNCMExecute(Sender: TObject); procedure ActionUnidadeProdutoExecute(Sender: TObject); procedure ActionPaisExecute(Sender: TObject); procedure ActionUfExecute(Sender: TObject); procedure ActionMunicipioExecute(Sender: TObject); procedure ActionCepExecute(Sender: TObject); procedure ActionBancoExecute(Sender: TObject); procedure ActionAgenciaBancoExecute(Sender: TObject); procedure ActionContaCaixaExecute(Sender: TObject); procedure ActionTalonarioChequeExecute(Sender: TObject); procedure ActionChequeExecute(Sender: TObject); procedure ActionConvenioExecute(Sender: TObject); procedure ActionContadorExecute(Sender: TObject); procedure ActionAlmoxarifadoExecute(Sender: TObject); procedure ActionSetorExecute(Sender: TObject); procedure ActionOperadoraCartaoExecute(Sender: TObject); procedure ActionCfopExecute(Sender: TObject); procedure ActionEstadoCivilExecute(Sender: TObject); procedure ActionEnderecoExecute(Sender: TObject); procedure ActionSairExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure JvTabBarTabMoved(Sender: TObject; Item: TJvTabBarItem); procedure JvTabBarTabSelected(Sender: TObject; Item: TJvTabBarItem); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ActionPessoaExecute(Sender: TObject); procedure ActionProdutoGrupoExecute(Sender: TObject); procedure ActionProdutoSubGrupoExecute(Sender: TObject); procedure ActionTipoRelacionamentoExecute(Sender: TObject); procedure ActionTipoAdmissaoExecute(Sender: TObject); procedure ActionCboExecute(Sender: TObject); procedure ActionEfdTabela437Execute(Sender: TObject); procedure ActionOperadoraPlanoSaudeExecute(Sender: TObject); procedure ActionSindicatoExecute(Sender: TObject); procedure ActionSituacaoColaboradorExecute(Sender: TObject); procedure ActionSalarioMinimoExecute(Sender: TObject); procedure ActionCodigoGpsExecute(Sender: TObject); procedure ActionTipoDesligamentoExecute(Sender: TObject); procedure ActionSefipCodigoMovimentacaoExecute(Sender: TObject); procedure ActionSefipCodigoRecolhimentoExecute(Sender: TObject); procedure ActionSefipCategoriaTrabalhoExecute(Sender: TObject); procedure ActionTipoItemSpedExecute(Sender: TObject); procedure ActionEfdTabela4310Execute(Sender: TObject); procedure ActionEfdTabela4313Execute(Sender: TObject); procedure ActionEfdTabela4314Execute(Sender: TObject); procedure ActionEfdTabela4315Execute(Sender: TObject); procedure ActionEfdTabela4316Execute(Sender: TObject); procedure ActionEfdTabela439Execute(Sender: TObject); procedure ActionSpedExecute(Sender: TObject); procedure ActionSefipExecute(Sender: TObject); procedure ActionPisExecute(Sender: TObject); procedure ActionSituacaoDocumentoExecute(Sender: TObject); procedure ActionCsosnAExecute(Sender: TObject); procedure ActionCsosnBExecute(Sender: TObject); procedure ActionCstIcmsAExecute(Sender: TObject); procedure ActionCstIcmsBExecute(Sender: TObject); procedure ActionCstPisExecute(Sender: TObject); procedure ActionCstCofinsExecute(Sender: TObject); procedure ActionCstIpiExecute(Sender: TObject); procedure ActionFeriadosExecute(Sender: TObject); procedure ActionCstExecute(Sender: TObject); procedure ActionEfdTabela436Execute(Sender: TObject); private function doLogin: Boolean; function PodeAbrirFormulario(ClasseForm: TFormClass; var Pagina: TJvCustomPage): Boolean; function TotalFormsAbertos(ClasseForm: TFormClass): Integer; procedure AjustarCaptionAbas(ClasseForm: TFormClass); function ObterAba(Pagina: TJvCustomPage): TJvTabBarItem; function ObterPagina(Aba: TJvTabBarItem): TJvCustomPage; public procedure NovaPagina(ClasseForm: TFormClass; IndiceImagem: Integer); function FecharPagina(Pagina: TJvCustomPage): Boolean; overload; function FecharPagina(Pagina: TJvCustomPage; TodasExcetoEssa: Boolean): Boolean; overload; function FecharPaginas: Boolean; procedure SepararAba(Pagina: TJvCustomPage); end; var FMenu: TFMenu; FormAtivo: String; implementation uses SessaoUsuario; {$R *.dfm} var IdxTabSelected: Integer = -1; {$Region 'Infra'} procedure TFMenu.NovaPagina(ClasseForm: TFormClass; IndiceImagem: Integer); var Aba : TJvTabBarItem; Pagina : TJvCustomPage; Form : TForm; begin //verifica se pode abrir o form if not PodeAbrirFormulario(ClasseForm, Pagina) then begin JvPageList.ActivePage := Pagina; Exit; end; //cria uma nova aba Aba := JvTabBar.AddTab(''); //instancia uma página padrão Pagina := TJvStandardPage.Create(Self); //seta a PageList da nova página para aquela que já está no form principal Pagina.PageList := JvPageList; //cria um form passando a página para o seu construtor, que recebe um TComponent Form := ClasseForm.Create(Pagina); //Propriedades do Form with Form do begin Align := alClient; BorderStyle := bsNone; Parent := Pagina; end; //Propriedades da Aba with Aba do begin Caption := Form.Caption; ImageIndex := IndiceImagem; PopupMenu := Self.PopupMenu; end; //ajusta o título (caption) das abas AjustarCaptionAbas(ClasseForm); //ativa a página JvPageList.ActivePage := Pagina; FormAtivo := Form.Name; //exibe o formulário Form.Show; end; function TFMenu.PodeAbrirFormulario(ClasseForm: TFormClass; var Pagina: TJvCustomPage): Boolean; var I: Integer; begin Result := True; //varre a JvPageList para saber se já existe um Form aberto for I := 0 to JvPageList.PageCount - 1 do //se achou um form if JvPageList.Pages[I].Components[0].ClassType = ClasseForm then begin Pagina := JvPageList.Pages[I]; //permite abrir o form novamente caso a Tag tenha o valor zero Result := (Pagina.Components[0] as TForm).Tag = 0; Break; end; end; //verifica o total de formulários abertos function TFMenu.TotalFormsAbertos(ClasseForm: TFormClass): Integer; var I: Integer; begin Result := 0; for I := 0 to JvPageList.PageCount - 1 do begin if JvPageList.Pages[I].Components[0].ClassType = ClasseForm then Inc(Result); end; end; //ajusta o título (caption) das abas procedure TFMenu.AjustarCaptionAbas(ClasseForm: TFormClass); var I, Indice, TotalForms: Integer; NovoCaption: string; begin TotalForms := TotalFormsAbertos(ClasseForm); if TotalForms > 1 then begin Indice := 1; for I := 0 to JvPageList.PageCount - 1 do begin with JvPageList do begin if Pages[I].Components[0].ClassType = ClasseForm then begin NovoCaption := (Pages[I].Components[0] as TForm).Caption + ' (' + IntToStr(Indice) + ')'; (Pages[I] as TJvStandardPage).Caption := NovoCaption; ObterAba(Pages[I]).Caption := NovoCaption; Inc(Indice); end; end; end; end; end; function TFMenu.doLogin: Boolean; var FormLogin: TFLogin; begin FormLogin := TFLogin.Create(Self); try FormLogin.ShowModal; Result := FormLogin.Logado; finally FormLogin.Free; end; end; //controla o fechamento da página function TFMenu.FecharPagina(Pagina: TJvCustomPage): Boolean; var Form: TForm; PaginaEsquerda: TJvCustomPage; begin PaginaEsquerda := nil; Form := Pagina.Components[0] as TForm; Result := Form.CloseQuery; if Result then begin if Pagina.PageIndex > 0 then begin PaginaEsquerda := JvPageList.Pages[Pagina.PageIndex - 1]; end; Form.Close; ObterAba(Pagina).Free; Pagina.Free; JvPageList.ActivePage := PaginaEsquerda; end; end; //controla o fechamento da página - todas exceto a selecionada function TFMenu.FecharPagina(Pagina: TJvCustomPage; TodasExcetoEssa: Boolean): Boolean; var I: Integer; begin Result := True; for I := JvPageList.PageCount - 1 downto 0 do if JvPageList.Pages[I] <> Pagina then begin Result := FecharPagina(JvPageList.Pages[I]); if not Result then Exit; end; end; function TFMenu.FecharPaginas: Boolean; var I: Integer; begin Result := True; for I := JvPageList.PageCount - 1 downto 0 do begin Result := FecharPagina(JvPageList.Pages[I]); if not Result then Exit; end; end; procedure TFMenu.FormClose(Sender: TObject; var Action: TCloseAction); begin if Application.MessageBox('Deseja Realmente Sair?', 'Sair do Sistema', MB_YesNo + MB_IconQuestion) <> IdYes then Application.Run; Sessao.Free; FecharPaginas; end; procedure TFMenu.FormCreate(Sender: TObject); begin if not doLogin then Application.Terminate else inherited; end; procedure TFMenu.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (shift=[ssCtrl]) and (key=VK_TAB) then begin JvPageList.NextPage; end; if (shift=[ssShift]) and (key=VK_TAB) then begin JvPageList.PrevPage; end; end; //separa a aba (formulário) procedure TFMenu.SepararAba(Pagina: TJvCustomPage); begin with Pagina.Components[0] as TForm do begin Align := alNone; BorderStyle := bsSizeable; Left := (((JvPageList.Width )- Width) div 2)+JvPageList.Left; Top := (((JvPageList.ClientHeight)-Height) div 2 )+(JvPageList.Top)-18; Parent := nil; end; ObterAba(Pagina).Visible := False; end; function TFMenu.ObterAba(Pagina: TJvCustomPage): TJvTabBarItem; var Form: TForm; begin Result := nil; Form := Pagina.Components[0] as TForm; FormAtivo := Form.Name; if Assigned(Pagina) then Result := JvTabBar.Tabs[Pagina.PageIndex]; //força o foco no form Form.Hide; Form.Show; end; procedure TFMenu.JvPageListChange(Sender: TObject); begin ObterAba(JvPageList.ActivePage).Selected := True; end; procedure TFMenu.JvTabBarTabClosing(Sender: TObject; Item: TJvTabBarItem; var AllowClose: Boolean); begin AllowClose := FecharPagina(ObterPagina(Item)); end; procedure TFMenu.JvTabBarTabMoved(Sender: TObject; Item: TJvTabBarItem); begin if IdxTabSelected >= 0 then begin JvPageList.Pages[IdxTabSelected].PageIndex := Item.Index; end; end; procedure TFMenu.JvTabBarTabSelected(Sender: TObject; Item: TJvTabBarItem); begin if Assigned(Item) then IdxTabSelected := Item.Index else IdxTabSelected := -1; end; function TFMenu.ObterPagina(Aba: TJvTabBarItem): TJvCustomPage; begin Result := JvPageList.Pages[Aba.Index]; end; {$ENDREGION} {$Region 'Actions'} procedure TFMenu.ActionClienteExecute(Sender: TObject); begin NovaPagina(TFPessoa, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionFornecedorExecute(Sender: TObject); begin NovaPagina(TFPessoa, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionTransportadoraExecute(Sender: TObject); begin NovaPagina(TFPessoa,(Sender as TAction).ImageIndex); //JvTabBar.Tabs[JvPageList.ActivePage.PageIndex].Caption := 'Transportadora'; end; procedure TFMenu.ActionFeriadosExecute(Sender: TObject); begin NovaPagina(TFFeriados,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionProdutoGrupoExecute(Sender: TObject); begin NovaPagina(TFProdutoGrupo,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionProdutoExecute(Sender: TObject); begin NovaPagina(TFProduto, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionAgenciaBancoExecute(Sender: TObject); begin NovaPagina(TFAgenciaBanco,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionAlmoxarifadoExecute(Sender: TObject); begin NovaPagina(TFAlmoxarifado, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionAtividadeForCliExecute(Sender: TObject); begin NovaPagina(TFAtividadeForCli, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionBancoExecute(Sender: TObject); begin NovaPagina(TFBanco, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionEfdTabela437Execute(Sender: TObject); begin NovaPagina(TFEfdTabela437, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionCargoExecute(Sender: TObject); begin NovaPagina(TFCargo, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionCboExecute(Sender: TObject); begin NovaPagina(TFCbo, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionCepExecute(Sender: TObject); begin NovaPagina(TFCep, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionCfopExecute(Sender: TObject); begin NovaPagina(TFCfop, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionChequeExecute(Sender: TObject); begin NovaPagina(TFCheque, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionCodigoGpsExecute(Sender: TObject); begin NovaPagina(TFCodigoGps,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionColaboradorExecute(Sender: TObject); begin NovaPagina(TFColaborador,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionContadorExecute(Sender: TObject); begin NovaPagina(TFContador,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionContaCaixaExecute(Sender: TObject); begin NovaPagina(TFContaCaixa,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionConvenioExecute(Sender: TObject); begin NovaPagina(TFConvenio,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionCsosnAExecute(Sender: TObject); begin NovaPagina(TFCsosnA,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionCsosnBExecute(Sender: TObject); begin NovaPagina(TFCsosnB,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionCstCofinsExecute(Sender: TObject); begin NovaPagina(TFCstCofins,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionCstExecute(Sender: TObject); begin // end; procedure TFMenu.ActionCstIcmsAExecute(Sender: TObject); begin NovaPagina(TFCstIcmsA,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionCstIcmsBExecute(Sender: TObject); begin NovaPagina(TFCstIcmsB,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionCstIpiExecute(Sender: TObject); begin NovaPagina(TFCstIpi,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionCstPisExecute(Sender: TObject); begin NovaPagina(TFCstPis,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionEnderecoExecute(Sender: TObject); begin // end; procedure TFMenu.ActionEstadoCivilExecute(Sender: TObject); begin NovaPagina(TFEstadoCivil,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionProdutoMarcaExecute(Sender: TObject); begin NovaPagina(TFProdutoMarca, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionMunicipioExecute(Sender: TObject); begin NovaPagina(TFMunicipio, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionNCMExecute(Sender: TObject); begin NovaPagina(TFNcm, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionNivelFormacaoExecute(Sender: TObject); begin NovaPagina(TFNivelFormacao, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionOperadoraCartaoExecute(Sender: TObject); begin NovaPagina(TFOperadoraCartao, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionOperadoraPlanoSaudeExecute(Sender: TObject); begin NovaPagina(TFOperadoraPlanoSaude, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionPaisExecute(Sender: TObject); begin NovaPagina(TFPais, (Sender as TAction).ImageIndex); end; procedure TFMenu.ActionPessoaExecute(Sender: TObject); begin NovaPagina(TFPessoa,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionPisExecute(Sender: TObject); begin // end; procedure TFMenu.ActionSairExecute(Sender: TObject); begin Close; end; procedure TFMenu.ActionSalarioMinimoExecute(Sender: TObject); begin NovaPagina(TFSalarioMinimo,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionSefipCategoriaTrabalhoExecute(Sender: TObject); begin NovaPagina(TFSefipCategoriaTrabalho,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionSefipCodigoMovimentacaoExecute(Sender: TObject); begin NovaPagina(TFSefipCodigoMovimentacao,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionSefipCodigoRecolhimentoExecute(Sender: TObject); begin NovaPagina(TFSefipCodigoRecolhimento,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionSefipExecute(Sender: TObject); begin // end; procedure TFMenu.ActionSetorExecute(Sender: TObject); begin NovaPagina(TFSetor,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionSindicatoExecute(Sender: TObject); begin NovaPagina(TFSindicato,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionSituacaoColaboradorExecute(Sender: TObject); begin NovaPagina(TFSituacaoColaborador,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionSituacaoDocumentoExecute(Sender: TObject); begin NovaPagina(TFSituacaoDocumento,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionSituacaoForCliExecute(Sender: TObject); begin NovaPagina(TFSituacaoForCli,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionSpedExecute(Sender: TObject); begin // end; procedure TFMenu.ActionEfdTabela4310Execute(Sender: TObject); begin NovaPagina(TFEfdTabela4310,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionEfdTabela4313Execute(Sender: TObject); begin NovaPagina(TFEfdTabela4313,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionEfdTabela4314Execute(Sender: TObject); begin NovaPagina(TFEfdTabela4314,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionEfdTabela4315Execute(Sender: TObject); begin NovaPagina(TFEfdTabela4315,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionEfdTabela4316Execute(Sender: TObject); begin NovaPagina(TFEfdTabela4316,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionEfdTabela436Execute(Sender: TObject); begin NovaPagina(TFEfdTabela436,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionEfdTabela439Execute(Sender: TObject); begin NovaPagina(TFEfdTabela439,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionProdutoSubGrupoExecute(Sender: TObject); begin NovaPagina(TFProdutoSubGrupo,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionTalonarioChequeExecute(Sender: TObject); begin NovaPagina(TFTalonarioCheque,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionTipoAdmissaoExecute(Sender: TObject); begin NovaPagina(TFTipoAdmissao,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionTipoColaboradorExecute(Sender: TObject); begin NovaPagina(TFTipoColaborador,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionTipoDesligamentoExecute(Sender: TObject); begin NovaPagina(TFTipoDesligamento,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionTipoItemSpedExecute(Sender: TObject); begin NovaPagina(TFTipoItemSped,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionTipoRelacionamentoExecute(Sender: TObject); begin NovaPagina(TFTipoRelacionamento,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionUfExecute(Sender: TObject); begin NovaPagina(TFUf,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionUnidadeProdutoExecute(Sender: TObject); begin NovaPagina(TFUnidadeProduto,(Sender as TAction).ImageIndex); end; {$EndRegion} {$Region 'PopupMenu'} procedure TFMenu.menuFecharClick(Sender: TObject); begin FecharPagina(JvPageList.ActivePage); end; procedure TFMenu.menuFecharTodasExcetoEssaClick(Sender: TObject); begin FecharPagina(JvPageList.ActivePage, True); end; procedure TFMenu.menuSepararAbaClick(Sender: TObject); begin SepararAba(JvPageList.ActivePage); end; {$EndRegion} end.
unit DBUtils; interface uses Forms, Controls, DB, ADODB; procedure OpenBigDataSet(ds: TCustomADODataSet; SortStr: string = ''); function GetNullField(ds: TCustomADODataSet): Integer; procedure CheckNullField(ds: TCustomADODataSet); procedure ProcessDeleteError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); implementation uses Variants, Dialogs, SysUtils; procedure OpenBigDataSet(ds: TCustomADODataSet; SortStr: string); var Save_Cursor: TCursor; SavedParams: TParams; i: Integer; Bookmark: TBookmarkStr; begin Bookmark := ''; if ds.Active then Bookmark := ds.Bookmark; if SortStr = '' then SortStr := ds.Sort; Save_Cursor := Screen.Cursor; try Screen.Cursor := crHourGlass; if ds is TADOQuery then begin SavedParams := TParams.Create; try SavedParams.Assign(TADOQuery(ds).Parameters); // save parameters values ds.Close; TADOQuery(ds).Parameters.ParseSQL(TADOQuery(ds).SQL.Text, true); for i := 0 to SavedParams.Count - 1 do // restore parameters values TADOQuery(ds).Parameters[i].Value := SavedParams[i].Value; ds.Open; finally SavedParams.Free; end; end else begin ds.Close; ds.Open; end; if SortStr <> '' then ds.Sort := SortStr; if Bookmark <> '' then try ds.Bookmark := Bookmark; except end finally Screen.Cursor := Save_Cursor; end end; function GetNullField(ds: TCustomADODataSet): Integer; var i: Integer; begin Result := -1; for i := 0 to ds.FieldCount - 1 do if ds.Fields[i].Visible and ((ds.Fields[i].Value = Null) or (Trim(ds.Fields[i].Value) = '') ) then begin Result := i; Exit; end; end; procedure CheckNullField(ds: TCustomADODataSet); var i: Integer; begin i := GetNullField(ds); if i >= 0 then begin MessageDlg('Поле "' + ds.Fields[i].DisplayLabel + '" не может быть пустым.', mtError, [mbOK], 0); Abort; end; end; procedure ProcessDeleteError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); begin MessageDlg( 'Ошибка удаления записи, возможно есть подчинённые записи.'+ #13#10 + E.Message, mtError, [mbOK], 0); Action := daAbort; end; end.
unit uSubsystemCalculoLoja; interface type { Subsystem } TSubsystemCalculoLoja = class private function AplicarDesconto(const Fidelidade: integer; const Preco: real): real; function AplicarMargemVenda(const Preco: real): real; public function CalcularPrecoFinal(const Fidelidade: integer; const Preco: real): real; end; implementation { TSubsystemCalculoLoja } function TSubsystemCalculoLoja.AplicarDesconto(const Fidelidade: integer; const Preco: real): real; begin // Aplica o desconto conforme a fidelidade do cliente result := Preco; case Fidelidade of 0: result := Preco - (Preco * 0.02); // Nenhuma - 2% de desconto 1: result := Preco - (Preco * 0.06); // Bronze - 6% de desconto 2: result := Preco - (Preco * 0.1); // Prata - 10% de desconto 3: result := Preco - (Preco * 0.18); // Ouro - 18% de desconto end; end; function TSubsystemCalculoLoja.AplicarMargemVenda(const Preco: real): real; begin // Aplica a margem de venda de 35% result := Preco + (Preco * 0.35); end; function TSubsystemCalculoLoja.CalcularPrecoFinal( const Fidelidade: integer; const Preco: real): real; begin // Operação principal do SubSystem: aplica o desconto e a margem de venda result := AplicarDesconto(Fidelidade, Preco); result := AplicarMargemVenda(result); end; end.
program makelogo; const {*** constants ***} TitleStr = 'MAKELOGO - source file converter - V0.0'; AuthorStr = 'Written by Andy Onions 1992'; maxdefs = 100; {maximum number of #DEFINE's} InExt = 'ANY'; SnasmExt = '68K'; MicrotecExt = 'SRC'; SierraExt = 'S'; space = ' '; period = '.'; hash = '#'; switch = '/'; semicolon = ';'; NOERROR = 0; CMDERROR = -1; MaxLenKnown = 7; CASEASM = 1; ENDCASE = 2; DEFINE = 3; INCLUDE = 4; MaxKnown = 4; ASMERROR = -1; MaxLenAsm = 8; SNASM = 1; MICROTEC = 2; SIERRA = 3; MaxAsm = 3; UNKNOWN = 100; PARAMETER = 101; FILENAME = 102; DEFINERR = 103; type {*** typed variables ***} string80 = string[80]; fullstring = string[255]; KnownWords = array[1..MaxKnown] of string[MaxLenKnown]; Assemblers = array[0..MaxAsm] of string[MaxLenAsm]; var {*** variables ***} StdOut, InFile, IncFile, OutFile : text; TextLine, InName, IncName, OutName : fullstring; KnownWord : KnownWords; Assembler : Assemblers; ErrorType, AsmType, IncLineNo, LineNo, DefQty : integer; EndOfFile, InINCLUDE : boolean; OldString : array[1..maxdefs] of string80; NewString : array[1..maxdefs] of string80; {*** procedures and functions ***} procedure Error(err:integer); begin if err=-1 then begin writeln(StdOut,'Usage:-'); writeln(StdOut,'MAKELOGO /assembler infile[.ANY]'); writeln(StdOut,'where assembler is one of:-'); writeln(StdOut,'SNASM'); writeln(StdOut,'MICROTEC'); writeln(StdOut,'SIERRA'); end; if err=-2 then writeln(StdOut,'Invalid assembler specified.'); if err=-3 then writeln(StdOut,'Input and output cannot have same name.'); if err=-4 then writeln(StdOut,'Cannot open input file.'); if err=-5 then writeln(StdOut,'Cannot open output file.'); if err=-6 then writeln(StdOut,'Cannot open INCLUDE file.'); close(StdOut); halt; end; {error} procedure InitWords; begin KnownWord[caseasm] := 'CASEASM'; KnownWord[endcase] := 'ENDCASE'; KnownWord[define] := 'DEFINE'; KnownWord[include] := 'INCLUDE'; Assembler[snasm] := 'SNASM'; Assembler[microtec] := 'MICROTEC'; Assembler[sierra] := 'SIERRA'; end; procedure GetALine(var ALine:fullstring); var EndOfLine, MakeUpper : boolean; Len : integer; Ch : char; begin {body of getaline} if InINCLUDE then EndOfLine := eoln(IncFile) else EndOfLine := eoln(InFile); if not EndOfLine then begin if InINCLUDE then begin read(IncFile,ALine[1]); EndOfLine := eoln(IncFile); end else begin read(InFile,ALine[1]); EndOfLine := eoln(InFile); end; MakeUpper := ALine[1]=hash; len := 1; while not EndOfLine and (len<255) do begin inc(len); if InINCLUDE then begin read(IncFile,ch); EndOfLine := eoln(IncFile); end else begin read(InFile,ch); EndOfLine := eoln(InFile); end; if ch=space then MakeUpper := false; if MakeUpper then ALine[len] := upcase(ch) else ALine[Len] := ch; end; ALine[0] := char(len); end else ALine[0] := #0; if InINCLUDE then begin readln(IncFile); inc(IncLineNo); if eof(IncFile) then begin close(IncFile); EndOfFile := eof(InFile); InINCLUDE := false; end else EndOfFile := false; end else begin readln(InFile); {possibly discard end of very long line} inc(LineNo); EndOfFile := eof(InFile); end; end; {getaline} function MatchWord(Str:fullstring):integer; var i, KnownLen, LineLen : integer; Found : boolean; begin LineLen := length(Str); i := 0; Found := false; while (i<MaxKnown) and not Found do begin inc(i); knownlen := length(knownword[i]); if (linelen>knownlen) and (knownword[i]=copy(Str,2,knownlen)) then Found := true; end; if Found then MatchWord := i else MatchWord := CMDERROR; {no match} end; function WhatAssembler(Str:fullstring;Pos:integer;ch:char):integer; var i, KnownLen, LineLen : integer; Found : boolean; begin Found := false; LineLen := length(Str); if (Pos<=LineLen) and (Str[Pos]=ch) then begin i := 0; while (i<MaxAsm) and not Found do begin inc(i); knownlen := length(Assembler[i]); if (linelen-Pos>=knownlen) and (Assembler[i]=copy(Str,Pos+1,knownlen)) then Found := true; end; end; if Found then WhatAssembler := i else WhatAssembler := ASMERROR; {no match} end; function GetFileName(Str:fullstring;Pos:integer):fullstring; begin if (length(str)>pos) and (str[pos]=space) then begin delete(Str,1,Pos); assign(IncFile,Str); {$I-} reset(IncFile); if ioresult <>0 then GetFileName := '' else begin IncLineNo := 0; GetFileName := Str; writeln(StdOut,'Including: ',Str); end; {$I+} end else GetFileName := ''; end; {getfilename} procedure AddDefList(Str1,Str2:fullstring); var i : integer; begin if DefQty=0 then begin inc(DefQty); OldString[DefQty] := Str1; NewString[DefQty] := Str2; end else begin i := 1; while (i<=DefQty) and (OldString[i]<>Str1) do inc(i); if i>DefQty then begin inc(DefQty); OldString[i] := Str1; end; NewString[i] := Str2; end; end; function GetDefine(Str:fullstring):integer; var l,i : integer; actual : fullstring; begin l := length(Str); if (l>0) and (Str[1]=space) then begin i := 2; while (i<=l) and (Str[i]<>space) do inc(i); if i>2 then begin actual := copy(Str,2,i-2); if i<=l then begin inc(i); if i<=l then AddDefList(actual,copy(Str,i,l-i+1)); GetDefine := NOERROR; end else GetDefine := DEFINERR; end else GetDefine := DEFINERR; end else GetDefine := DEFINERR; end; procedure OutLine(Str:string); {output a commemt line or blank line as is} {output other lines with DEFINEd substitutions if any exist} {output line as is if no DEFINEs} var first, match, index,i : integer; begin if (DefQty=0) or (Str='') or ((Str<>'') and (Str[1]=';')) then write(OutFile,Str) else repeat first := maxint; for i := 1 to DefQty do begin match := pos(OldString[i],Str); if (match>0) and (match<first) then begin first := match; index := i; end; end; if first=maxint then begin write(OutFile,str); str :=''; end else begin if first>1 then write(OutFile,copy(Str,1,first-1)); write(OutFile,NewString[index]); delete(Str,1,first+length(OldString[index])-1); end; until Str=''; writeln(OutFile); end; function ExtractFile:integer; var InCASE, Echo : boolean; IncFile : fullstring; KeyWord, AType, FatalError : integer; begin LineNo := 0; InCASE := false; Echo := true; InINCLUDE := false; FatalError := NOERROR; EndOfFile := eof(InFile); DefQty := 0; while not EndOfFile and (FatalError=NOERROR) do begin GetALine(TextLine); if (length(TextLine)>0) and (TextLine[1]=hash) then begin KeyWord := MatchWord(TextLine); case KeyWord of CMDERROR: FatalError := UNKNOWN; CASEASM: begin AType := WhatAssembler(TextLine,9,'='); if AType=ASMERROR then FatalError := PARAMETER else begin InCASE := true; Echo := AType=AsmType; end; end; ENDCASE: if not InCASE then FatalError := ENDCASE else begin InCASE := false; Echo := true; end; INCLUDE: if InINCLUDE then FatalError := INCLUDE else begin IncName := GetFileName(TextLine,9); if IncName='' then FatalError := FILENAME else InINCLUDE := true; end; DEFINE: FatalError := GetDefine(copy(TextLine,8,length(TextLine)-7)); end; {case} end else if echo then case AsmType of SNASM: OutLine(TextLine); MICROTEC: OutLine(TextLine); SIERRA: if TextLine[1]<>semicolon then OutLine(TextLine); {strip comment lines} end; {case} end; ExtractFile := FatalError; end; {ExtractFile} function GetParam(param:integer):fullstring; var str : fullstring; i : integer; begin {body of GetParam} str := paramstr(param); for i := 1 to length(str) do str[i] := upcase(str[i]); getparam := str; end; {GetParam} begin {body of makelogo} assign(StdOut,''); rewrite(StdOut); writeln(StdOut,TitleStr); writeln(StdOut,AuthorStr); InitWords; if paramcount<>2 then error(-1); {usage} TextLine := getparam(1); AsmType := WhatAssembler(TextLine,1,switch); if AsmType=ASMERROR then error(-2); {assembler} InName := getparam(2); if pos(period,InName)=0 then InName := InName+Period+InExt; OutName := InName; Delete(OutName,pos(period,OutName)+1,3); case AsmType of SNASM: OutName := OutName+SnasmExt; MICROTEC: OutName := OutName+MicrotecExt; SIERRA: OutName := OutName+SierraExt; end; {case} if InName=OutName then error(-3); {name conflict} assign(InFile,InName); {$I-} reset(InFile); if ioresult <>0 then {can't open input} error(-4); {input} {$I+} assign(OutFile,OutName); {$I-} rewrite(OutFile); if ioresult <>0 then {can't open input} begin close(InFile); error(-5); {output} end; {$I+} ErrorType := ExtractFile; if ErrorType=NOERROR then writeln(StdOut,'Assembler file has been created.') else begin write(StdOut,'FATAL ERROR in line:- '); if InINCLUDE then writeln(StdOut,IncLineNo,' of ',IncName) else writeln(StdOut,LineNo,' of ',InName); writeln(StdOut,TextLine); case ErrorType of UNKNOWN: writeln(StdOut,'Unknown command.'); PARAMETER: writeln(StdOut,'Unknown assembler type.'); ENDCASE: writeln(StdOut,'Not in a CASE structure.'); FILENAME: writeln(StdOut,'Cannot find INCLUDE file.'); DEFINERR: writeln(StdOut,'Invalid parameters in DEFINE'); end; {case} end; if InINCLUDE then close(IncFile); close(InFile); close(OutFile); close(StdOut); end. {makelogo} 
unit PtObjectClone; // tnx to: //http://www.yanniel.info/2012/02/deep-copy-clone-object-delphi.html //https://delphihaven.wordpress.com/2011/06/09/object-cloning-using-rtti/ interface type TObjectClone = class public class function FromRtti<T: class>(ASourceObj: T): T; static; class function FromMarshal<T: class>(ASourceObj: T): T; static; end; implementation uses SysUtils, Classes, TypInfo, RTTI, VCL.Controls, DBXJSON, DBXJSONReflect, System.JSON; class function TObjectClone.FromRtti<T>(ASourceObj: T): T; var Context: TRttiContext; IsComponent, LookOutForNameProp: Boolean; RttiType: TRttiType; Method: TRttiMethod; MinVisibility: TMemberVisibility; Params: TArray<TRttiParameter>; Prop: TRttiProperty; SourceAsPointer, ResultAsPointer: Pointer; begin RttiType := Context.GetType(ASourceObj.ClassType); // find a suitable constructor, though treat components specially IsComponent := (ASourceObj is TComponent); for Method in RttiType.GetMethods do if Method.IsConstructor then begin Params := Method.GetParameters; if Params = nil then Break; if (Length(Params) = 1) and IsComponent and (Params[0].ParamType is TRttiInstanceType) and SameText(Method.Name, 'Create') then Break; end; if Params = nil then Result := Method.Invoke(ASourceObj.ClassType, []).AsType<T> else Result := Method.Invoke(ASourceObj.ClassType, [TComponent(ASourceObj).Owner]).AsType<T>; try // many VCL control properties require the Parent property to be set first if ASourceObj is TControl then TControl(Result).Parent := TControl(ASourceObj).Parent; // loop through the props, copying values across for ones that are read/write Move(ASourceObj, SourceAsPointer, SizeOf(Pointer)); Move(Result, ResultAsPointer, SizeOf(Pointer)); LookOutForNameProp := IsComponent and (TComponent(ASourceObj).Owner <> nil); if IsComponent then MinVisibility := mvPublished // an alternative is to build an exception list else MinVisibility := mvPublic; for Prop in RttiType.GetProperties do if (Prop.Visibility >= MinVisibility) and Prop.IsReadable and Prop.IsWritable then if LookOutForNameProp and (Prop.Name = 'Name') and (Prop.PropertyType is TRttiStringType) then LookOutForNameProp := False else Prop.SetValue(ResultAsPointer, Prop.GetValue(SourceAsPointer)); except Result.Free; raise; end; end; class function TObjectClone.FromMarshal<T>(ASourceObj: T): T; var MarshalObj: TJSONMarshal; UnMarshalObj: TJSONUnMarshal; JSONValue: TJSONValue; begin Result:= nil; MarshalObj := TJSONMarshal.Create; UnMarshalObj := TJSONUnMarshal.Create; try JSONValue := MarshalObj.Marshal(ASourceObj); try if Assigned(JSONValue) then Result:= UnMarshalObj.Unmarshal(JSONValue) as T; // safe as-cast finally FreeAndNil(JSONValue); end; finally FreeAndNil(UnMarshalObj); FreeAndNil(MarshalObj); end; end; end.
{ 功能: 音频连接 音频合成 } unit AudioSlideDecoder; interface uses Windows, DecoderParam, AudioSlideParams; type HAUDIODECODER = pointer; PSHORT = ^SHORT; // 创建SlideShow音频解码器 // HAUDIODECODER __stdcall SDAudioCreate(const AudioSlideParam* ); function SDAudioCreate(const pParam : PAudioSlideParam) : HAUDIODECODER; stdcall; // 销毁SlideShow音频解码器 // void __stdcall SDAudioDestroy(HAUDIODECODER hAudio); procedure SDAudioDestroy(hAudio : HAUDIODECODER); stdcall; // 置入一个音频源及其处理参数,多次调用即可置入多个音频源,szSrcAudio为音频源文件路径 // BOOL __stdcall SDAddAudioSource(HAUDIODECODER hAudio, const wchar_t* szSrcAudioFile, const AudioProcessParam* pParam); function SDAddAudioSource(hAudio : HAUDIODECODER; const szSrcAudioFile : PWideChar; const pParam : PAudioProcessParam) : BOOL; stdcall; //double __stdcall SDSeek(HAUDIODECODER hAudio, double time); // 定位到指定时间 //function SDSeek(hAudio: HAUDIODECODER; time: double): double; stdcall; //int __stdcall SDGetNextSamples(HAUDIODECODER hAudio, short * buffer, int n_samples); // 取得下n_samples个sample数据 n_samples应该为声道数量的整数倍 //function SDGetNextSamples(hAudio: HAUDIODECODER; buffer: PSHORT; n_samples: Integer): Integer; stdcall; //double __stdcall SDGetOffset(HAUDIODECODER hAudio); // 返回当前时间 //function SDGetOffset(hAudio: HAUDIODECODER): double; stdcall; //const AudioInfo* __stdcall SDGetAudioInfo(HAUDIODECODER hAudio); // 取得音频信息 //function SDGetAudioInfo(hAudio: HAUDIODECODER): PAudioInfo; stdcall; implementation const DLLNAME = 'WS_SlideDecoder.dll'; function SDAudioCreate ; external DLLNAME Name 'SDAudioCreate'; procedure SDAudioDestroy ; external DLLNAME Name 'SDAudioDestroy'; function SDAddAudioSource ; external DLLNAME Name 'SDAddAudioSource'; //新的接口没有提供这些函数 //function SDSeek ; external DLLNAME Name 'SDSeek'; //function SDGetNextSamples ; external DLLNAME Name 'SDGetNextSamples'; //function SDGetOffset ; external DLLNAME Name 'SDGetOffset'; //function SDGetAudioInfo ; external DLLNAME Name 'SDGetAudioInfo'; end.
unit UDmMain; interface uses SysUtils, Classes, dxSkinsCore, dxSkinsDefaultPainters, cxLookAndFeels, dxSkinsForm, dxSkinsdxStatusBarPainter, dxSkinsdxBarPainter, cxClasses, cxLocalization; type TDmMain = class(TDataModule) dxskncntrlrSkinSys: TdxSkinController; cxLocalizer1: TcxLocalizer; private public procedure LoadSysSkin(SkinFile: string); procedure LoadLocalizer(AFileName: string); end; var DmMain: TDmMain; implementation {$R *.dfm} { TDmMain } procedure TDmMain.LoadLocalizer(AFileName: string); begin cxLocalizer1.StorageType := lstIni; cxLocalizer1.FileName := AFileName; cxLocalizer1.Active := True; cxLocalizer1.Locale := 2052; end; procedure TDmMain.LoadSysSkin(SkinFile: string); begin if not FileExists(SkinFile) then Exit; with Self.dxskncntrlrSkinSys do begin SkinName := 'UserSkin'; dxSkinsUserSkinLoadFromFile(SkinFile); NativeStyle := False; UseSkins := True; end; end; end.
unit DevMax.ViewItem.ListBoxItem; interface uses DevMax.View.Types, DevMax.View.Factory, System.Classes, FMX.Types, FMX.ListBox, FMX.StdCtrls; type TListBoxItemTitleImage = class(TListBoxItem, IViewItem) private function GetDataControls: TViewItemDataControls; function GetControlEvents: TViewItemControlEvents; public constructor Create(AOwner: TComponent); override; end; TListBoxItemRightText = class(TListBoxItem, IViewItem) private FLabel: TLabel; function GetDataControls: TViewItemDataControls; function GetControlEvents: TViewItemControlEvents; public constructor Create(AOwner: TComponent); override; end; implementation { TListBoxItemTitleImage } constructor TListBoxItemTitleImage.Create(AOwner: TComponent); begin inherited; Text := 'Text'; end; function TListBoxItemTitleImage.GetDataControls: TViewItemDataControls; begin Result := [ TViewItemDataControl.Create('ItemText', Self, 'Text') ]; end; function TListBoxItemTitleImage.GetControlEvents: TViewItemControlEvents; begin end; { TListBoxItemRightText } constructor TListBoxItemRightText.Create(AOwner: TComponent); begin inherited; Text := 'Text'; FLabel := TLabel.Create(Self); FLabel.Parent := Self; FLabel.Align := TAlignLayout.Client; FLabel.Margins.Left := 100; FLabel.Margins.Right := 4; FLabel.Text := 'Label'; FLabel.TextSettings.HorzAlign := TTextAlign.Trailing; end; function TListBoxItemRightText.GetDataControls: TViewItemDataControls; begin Result := [ TViewItemDataControl.Create('ItemText', Self, 'Text'), TViewItemDataControl.Create('ItemDetail', FLabel, 'Text') ]; end; function TListBoxItemRightText.GetControlEvents: TViewItemControlEvents; begin end; initialization TViewItemFactory.Instance.Regist('ListBoxItemRightText.Image', TListBoxItemTitleImage); TViewItemFactory.Instance.Regist('ListBoxItemRightText.RightText', TListBoxItemRightText); end.
unit iaDemo.ExampleThread; interface uses iaRTL.Threading.LoggedWorker; type TSimpleExample = class(TiaLoggedWorkerThread) protected procedure Run; override; end; implementation uses System.SysUtils; // repeatedly do some work that eats time.. // WorkerThreads can use Log or ReportProgress methods depending on how worker updates are desired procedure TSimpleExample.Run; var TempWorkVar:Extended; SleepTime:Integer; begin TempWorkVar := 0; Log(Format('%s - work loop in process [%d]', [ThreadNameForDebugger, GetTickCount])); while (not ShouldWorkTerminate) do // Check to see if something outside this thread has requested us to terminate begin TempWorkVar := Cos(TempWorkVar); // simulate some work if (Random(100) mod 4 = 0) then begin SleepTime := Random(10000); Log(Format('%s - random extra sleep %dms [%d]', [ThreadNameForDebugger, SleepTime, GetTickCount])); // simulate occasional wait on Input/Output //if ShouldWorkTerminate(SleepTime) then // Similar outcome to next line if not self.Sleep(SleepTime) then begin Log(Format('%s - Aborted sleep to exit [%d]', [ThreadNameForDebugger, GetTickCount])); //Examine logs to see how fast this is received Exit; end; end; if (Random(100) mod 7 = 0) then begin // We're in a worker thread execution loop (until ShouldWorkTerminate) // We'll exit this Run, but look in the logs for this thread to be restarted after PauseBetweenWorkMS Log(Format('%s - random early work exit [%d]', [ThreadNameForDebugger, GetTickCount])); Break; end; end; end; initialization Randomize; end.
unit IdSoapMime; {$I IdSoapDefines.inc} interface uses Classes, Contnrs, IdHeaderList, {$IFDEF INDY_V10} IdGlobalProtocols, {$ENDIF} IdSoapClasses, IdSoapDebug; type TIdSoapMimeBase = class (TIdBaseObject) private FHeaders: TIdHeaderList; procedure ReadHeaders(AStream : TStream); procedure WriteHeaders(AStream : TStream); public constructor create; destructor Destroy; override; property Headers : TIdHeaderList read FHeaders; end; TIdSoapMimePart = class (TIdSoapMimeBase) private FOwnsContent: Boolean; FContent: TStream; FId : string; procedure SetContent(const AValue: TStream); procedure DecodeContent; procedure ReadFromStream(AStream : TStream; ABoundary : AnsiString); procedure WriteToStream(AStream : TStream); function GetMediaType: String; function GetTransferEncoding: String; procedure SetMediaType(const AValue: String); procedure SetTransferEncoding(const AValue: String); procedure SetId(const AValue: String); function GetContentDisposition: String; procedure SetContentDisposition(const sValue: String); public constructor create; destructor Destroy; override; property Content : TStream read FContent write SetContent; property OwnsContent : Boolean read FOwnsContent write FOwnsContent; property Id : String read FId write SetId; property MediaType : String read GetMediaType write SetMediaType; property ContentDisposition : String read GetContentDisposition write SetContentDisposition; property TransferEncoding : String read GetTransferEncoding write SetTransferEncoding; function ParamName : String; end; TIdSoapMimePartList = class (TObjectList) private function GetPartByIndex(i: integer): TIdSoapMimePart; function GetPart(AName : String): TIdSoapMimePart; function CommaList: String; public property PartByIndex[i : integer] : TIdSoapMimePart read GetPartByIndex; property Part[AName : String] : TIdSoapMimePart read GetPart; default; function AddPart(AId : String) : TIdSoapMimePart; end; TIdSoapMimeMessage = class (TIdSoapMimeBase) private FParts: TIdSoapMimePartList; FBoundary : Ansistring; FStart : String; FMainType : String; procedure AnalyseContentType(AContent : String); function GetMainPart: TIdSoapMimePart; procedure Validate; public constructor create; destructor Destroy; override; property Parts : TIdSoapMimePartList read FParts; property MainPart : TIdSoapMimePart read GetMainPart; property Boundary : ansistring read FBoundary write FBoundary; property Start : String read FStart write FStart; property MainType : String read FMainType write FMainType; // for multi-part forms function getparam(name : String) : TIdSoapMimePart; function hasParam(name : String) : Boolean; procedure ReadFromStream(AStream : TStream); overload; procedure ReadFromStream(AStream : TStream; AContentType : String); overload; // headers are not part of the stream function GetContentTypeHeader : String; procedure WriteToStream(AStream : TStream; AHeaders : boolean); end; implementation uses IdGlobal, IdSoapBase64, IdSoapConsts, idSoapUtilities, SysUtils; const ASSERT_UNIT = 'IdSoapMime'; { Stream Readers } function ReadToValue(AStream : TStream; AValue : AnsiString):AnsiString; const ASSERT_LOCATION = ASSERT_UNIT+'.ReadToValue'; var c : AnsiChar; begin result := ''; while copy(result, length(result)-length(AValue)+1, length(AValue)) <> AValue do begin IdRequire(AStream.Size - AStream.Position <> 0, ASSERT_LOCATION+': Premature termination of stream looking for value "'+string(AValue)+'"'); AStream.Read(c, 1); result := result + c; end; delete(result, length(result)-length(AValue)+1, length(AValue)); end; function ReadBytes(AStream : TStream; AByteCount : Integer):AnsiString; const ASSERT_LOCATION = ASSERT_UNIT+'.ReadBytes'; begin IdRequire(AStream.Size - AStream.Position >= AByteCount, ASSERT_LOCATION+': Premature termination of stream reading "'+inttostr(AByteCount)+'" bytes'); SetLength(result, AByteCount); if AByteCount > 0 then begin AStream.Read(result[1], AByteCount); end; end; { Stream Writers } procedure WriteString(AStream : TStream; Const AStr : AnsiString); begin If AStr <> '' then begin AStream.Write(AStr[1], length(AStr)); end; end; { TIdSoapMimeBase } constructor TIdSoapMimeBase.create; begin inherited; FHeaders := TIdHeaderList.create{$IFDEF INDY_V10}(QuotePlain{?}){$ENDIF}; end; destructor TIdSoapMimeBase.destroy; const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimeBase.destroy'; begin FreeAndNil(FHeaders); inherited; end; procedure TIdSoapMimeBase.ReadHeaders(AStream: TStream); const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimeBase.ReadHeaders'; var LHeader : AnsiString; LFound : Boolean; begin assert(Self.TestValid(TIdSoapMimeBase), ASSERT_LOCATION+': self is not valid'); assert(Assigned(AStream), ASSERT_LOCATION+': Stream is not valid'); LFound := false; repeat LHeader := ReadToValue(AStream, EOL); if LHeader <> '' then begin LFound := true; FHeaders.Add(string(LHeader)); end until LFound and (LHeader = ''); end; procedure TIdSoapMimeBase.WriteHeaders(AStream: TStream); const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimeBase.WriteHeaders'; var i : integer; begin assert(assigned(AStream), ASSERT_LOCATION+': stream is not valid'); For i := 0 to FHeaders.Count - 1 do begin WriteString(AStream, ansiString(FHeaders[i])+EOL); end; WriteString(AStream, EOL); end; { TIdSoapMimePart } constructor TIdSoapMimePart.create; begin inherited; FContent := TIdMemoryStream.create; FOwnsContent := true; end; destructor TIdSoapMimePart.destroy; const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimePart.destroy'; begin if FOwnsContent then begin FreeAndNil(FContent); end; inherited; end; procedure TIdSoapMimePart.DecodeContent; const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimePart.DecodeContent'; var LCnt : String; begin assert(self.TestValid(TIdSoapMimePart), ASSERT_LOCATION+': self is not valid'); LCnt := FHeaders.Values[ID_SOAP_MIME_TRANSFERENCODING]; // possible values (rfc 2045): // "7bit" / "8bit" / "binary" / "quoted-printable" / "base64" // and extendible with ietf-token / x-token // we only process base64. everything else is considered to be binary // (this is not an email processor). Where this is a problem, notify // the indysoap team *with an example*, and this will be extended if AnsiSameText(LCnt, 'base64') then begin Content := IdSoapBase64Decode(Content); end else begin // well, we leave the content unchanged end; end; procedure TIdSoapMimePart.ReadFromStream(AStream: TStream; ABoundary: AnsiString); const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimePart.ReadFromStream'; var LBuffer : pansichar; LEnd : word; LComp0 : Pointer; LComp1 : Pointer; LCompLen : Word; const BUF_LEN = 1024; begin assert(self.TestValid(TIdSoapMimePart), ASSERT_LOCATION+': self is not valid'); assert(Assigned(AStream), ASSERT_LOCATION+': stream is not valid'); assert(ABoundary <> '', ASSERT_LOCATION+': Boundary is not valid'); ReadHeaders(AStream); FId := FHeaders.Values[ID_SOAP_MIME_ID]; if (FId <> '') and (FId[1] = '<') then delete(FId, 1, 1); if (FId <> '') and (FId[length(fId)] = '>') then delete(FId, length(FId), 1); // do this fast GetMem(LBuffer, BUF_LEN); try FillChar(LBuffer^, BUF_LEN, 0); LEnd := 0; LCompLen := length(ABoundary); LComp1 := pAnsichar(ABoundary); assert(LCompLen < BUF_LEN + 10, ASSERT_LOCATION+': Buffer length is not long enough ('+inttostr(BUF_LEN)+' / '+inttostr(LCompLen)+')'); while true do begin if LEnd = BUF_LEN-1 then begin FContent.Write(LBuffer^, LEnd - LCompLen); move(LBuffer[LEnd - LCompLen], LBuffer[0], LCompLen); LEnd := LCompLen; FillChar(LBuffer[LEnd], BUF_LEN - LEnd, 0); end else begin AStream.Read(LBuffer[LEnd], 1); inc(LEnd); end; LComp0 := pointer(NativeUInt(LBuffer)+LEnd-LCompLen); if (LEnd >= LCompLen) and CompareMem(LComp0, LComp1, LCompLen) then begin FContent.Write(LBuffer^, LEnd - (LCompLen + 2 + 2)); // -2 for the EOL, +2 for the other EOL break; end; end; finally FreeMem(LBuffer); end; FContent.Position := 0; DecodeContent; end; procedure TIdSoapMimePart.SetContent(const AValue: TStream); const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimePart.SetContent'; begin assert(self.TestValid(TIdSoapMimePart), ASSERT_LOCATION+': self is not valid'); if FOwnsContent then begin FreeAndNil(FContent); end; FContent := AValue; end; procedure TIdSoapMimePart.WriteToStream(AStream: TStream); const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimePart.WriteToStream'; var LOldPosition : integer; LTemp : AnsiString; begin assert(self.TestValid(TIdSoapMimePart), ASSERT_LOCATION+': self is not valid'); assert(Assigned(AStream), ASSERT_LOCATION+': stream is not valid'); LOldPosition := FContent.Position; WriteHeaders(AStream); if FHeaders.Values[ID_SOAP_MIME_TRANSFERENCODING] = 'base64' then begin WriteString(AStream, IdSoapBase64EncodeAnsi(FContent, true)+EOL_WINDOWS); end else begin AStream.CopyFrom(FContent, (FContent.Size - FContent.Position)-2); if FContent.Size - FContent.Position >= 2 then LTemp := ReadBytes(FContent, 2) else LTemp := ''; WriteString(AStream, LTemp); if LTemp <> EOL_WINDOWS then begin WriteString(AStream, EOL_WINDOWS); end; end; FContent.Position := LOldPosition; end; function TIdSoapMimePart.GetMediaType: String; const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimePart.GetMediaType'; begin assert(self.TestValid(TIdSoapMimePart), ASSERT_LOCATION+': self is not valid'); result := FHeaders.Values[ID_SOAP_CONTENT_TYPE]; end; function TIdSoapMimePart.GetTransferEncoding: String; const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimePart.GetTransferEncoding'; begin assert(self.TestValid(TIdSoapMimePart), ASSERT_LOCATION+': self is not valid'); result := FHeaders.Values[ID_SOAP_MIME_TRANSFERENCODING]; end; Function StringSplit(Const sValue, sDelimiter : String; Var sLeft, sRight: String) : Boolean; Var iIndex : Integer; sA, sB : String; Begin // Find the delimiter within the source string iIndex := Pos(sDelimiter, sValue); Result := iIndex <> 0; If Not Result Then Begin sA := sValue; sB := ''; End Else Begin sA := Copy(sValue, 1, iIndex - 1); sB := Copy(sValue, iIndex + Length(sDelimiter), MaxInt); End; sLeft := sA; sRight := sB; End; function StartsWith(s, test : String):Boolean; begin result := lowercase(copy(s, 1, length(test))) = lowercase(test); end; function TIdSoapMimePart.ParamName: String; var s : String; begin s := Headers.Values['Content-Disposition']; StringSplit(s, ';', s, result); if (s = 'form-data') and StartsWith(trim(result), 'name="') then begin result := copy(result, 8, $FFFF); result := copy(result, 1, pos('"', result)-1); end else result := ''; end; procedure TIdSoapMimePart.SetMediaType(const AValue: String); const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimePart.SetMediaType'; begin assert(self.TestValid(TIdSoapMimePart), ASSERT_LOCATION+': self is not valid'); FHeaders.Values[ID_SOAP_CONTENT_TYPE] := AValue; end; procedure TIdSoapMimePart.SetTransferEncoding(const AValue: String); const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimePart.SetTransferEncoding'; begin assert(self.TestValid(TIdSoapMimePart), ASSERT_LOCATION+': self is not valid'); FHeaders.Values[ID_SOAP_MIME_TRANSFERENCODING] := AValue; end; procedure TIdSoapMimePart.SetId(const AValue: String); const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimePart.SetId'; begin assert(self.TestValid(TIdSoapMimePart), ASSERT_LOCATION+': self is not valid'); FId := AValue; FHeaders.Values[ID_SOAP_MIME_ID] := '<'+AValue+'>'; end; function TIdSoapMimePart.GetContentDisposition: String; const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimePart.GetContentDisposition'; begin assert(self.TestValid(TIdSoapMimePart), ASSERT_LOCATION+': self is not valid'); result := FHeaders.Values[ID_SOAP_CONTENT_DISPOSITION]; end; procedure TIdSoapMimePart.SetContentDisposition(const sValue: String); begin FHeaders.Values[ID_SOAP_CONTENT_DISPOSITION] := sValue; end; { TIdSoapMimePartList } function TIdSoapMimePartList.GetPartByIndex(i: integer): TIdSoapMimePart; const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimePartList.GetPart'; begin assert((i >= 0) and (i < Count), ASSERT_LOCATION+': i is out of range ('+inttostr(i)+' of '+inttostr(Count)+')'); result := Items[i] as TIdSoapMimePart; end; function TIdSoapMimePartList.GetPart(AName : String): TIdSoapMimePart; const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimePartList.GetPart'; var i : integer; s : String; begin if (AName <> '') and (AName[1] = '<') then System.delete(AName, 1, 1); if (AName <> '') and (AName[length(AName)] = '>') then System.delete(AName, length(AName), 1); result := nil; for i := 0 to Count - 1 do begin s := (Items[i] as TIdSoapMimePart).Id; if s = AName then begin result := Items[i] as TIdSoapMimePart; exit; end end; IdRequire(False, ASSERT_LOCATION+': Part "'+AName+'" not found in parts '+CommaList); end; function TIdSoapMimePartList.CommaList: String; const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimePartList.CommaList'; var i : integer; begin result := ''; for i := 0 to Count -1 do begin result := CommaAdd(result, (Items[i] as TIdSoapMimePart).Id); end; end; function TIdSoapMimePartList.AddPart(AId: String): TIdSoapMimePart; const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimePartList.Add'; begin assert(assigned(self), ASSERT_LOCATION+': self is not valid'); assert(AId <> '', ASSERT_LOCATION+': id is not valid'); result := TIdSoapMimePart.create; result.Id := AId; add(result); end; { TIdSoapMimeMessage } function IdAnsiSameText(const S1, S2: ansistring): Boolean; begin Result := AnsiCompareText(String(S1), String(S2)) = 0; end; procedure TIdSoapMimeMessage.AnalyseContentType(AContent: String); const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimeMessage.AnalyseContentType'; var s, l, r, id : AnsiString; begin // this parser is weak - and needs review SplitString(AnsiString(Trim(AContent)), ';',l, s); IdRequire(IdAnsiSameText(l, ID_SOAP_MULTIPART_RELATED) or IdAnsiSameText(l, ID_SOAP_MULTIPART_FORMDATA), ASSERT_LOCATION+': attempt to read content as Mime, but the content-Type is "'+String(l)+'", not "'+String(ID_SOAP_MULTIPART_RELATED)+'" or "'+String(ID_SOAP_MULTIPART_FORMDATA)+'" in header '+String(AContent)); while s <> '' do begin SplitString(s, ';',l, s); SplitString(AnsiString(trim(String(l))), '=', l, r); idRequire(l <> '', ASSERT_LOCATION+': Unnamed part in Content_type header '+AContent); idRequire(r <> '', ASSERT_LOCATION+': Unvalued part in Content_type header '+AContent); if r[1] = '"' then begin delete(r, 1, 1); end; if r[length(r)] = '"' then begin delete(r, length(r), 1); end; if IdAnsiSameText(l, ID_SOAP_MIME_BOUNDARY) then begin FBoundary := r; end else if IdAnsiSameText(l, ID_SOAP_MIME_START) then begin id := r; if (id <> '') and (id[1] = '<') then delete(id, 1, 1); if (id <> '') and (id[length(id)] = '>') then delete(id, length(id), 1); FStart := string(id); end else if IdAnsiSameText(l, ID_SOAP_MIME_TYPE) then begin FMainType := String(r); end; end; end; constructor TIdSoapMimeMessage.create; begin inherited create; FParts := TIdSoapMimePartList.create(true); end; destructor TIdSoapMimeMessage.destroy; const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimeMessage.destroy'; begin assert(self.TestValid(TIdSoapMimeMessage), ASSERT_LOCATION+': self is not valid'); FreeAndNil(FParts); inherited; end; procedure TIdSoapMimeMessage.ReadFromStream(AStream: TStream); const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimeMessage.ReadFromStream'; var LHeader : String; begin assert(self.TestValid(TIdSoapMimeMessage), ASSERT_LOCATION+': self is not valid'); ReadHeaders(AStream); LHeader := FHeaders.Values[ID_SOAP_CONTENT_TYPE]; IdRequire(LHeader <> '', ASSERT_LOCATION+': '+ID_SOAP_CONTENT_TYPE+' header not found in '+FHeaders.CommaText); ReadFromStream(AStream, LHeader); end; function TIdSoapMimeMessage.GetMainPart: TIdSoapMimePart; const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimeMessage.GetMainPart'; begin assert(self.TestValid(TIdSoapMimeMessage), ASSERT_LOCATION+': self is not valid'); IdRequire(FStart <> '', ASSERT_LOCATION+': Start header not valid'); result := FParts[FStart]; end; function TIdSoapMimeMessage.getparam(name: String): TIdSoapMimePart; var i: Integer; begin result := nil; for i := 0 to Parts.Count - 1 do if Parts.PartByIndex[i].ParamName = name then begin result := Parts.PartByIndex[i]; exit; end; end; function TIdSoapMimeMessage.hasParam(name: String): Boolean; var i: Integer; begin result := false; for i := 0 to Parts.Count - 1 do result := result or (Parts.PartByIndex[i].ParamName = name); end; procedure TIdSoapMimeMessage.ReadFromStream(AStream: TStream; AContentType: String); const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimeMessage.ReadFromStream'; var LTemp : AnsiString; LPart : TIdSoapMimePart; begin assert(self.TestValid(TIdSoapMimeMessage), ASSERT_LOCATION+': self is not valid'); IdRequire(AContentType <> '', ASSERT_LOCATION+': Content-Type header not valid'); AnalyseContentType(AContentType); LTemp := ReadToValue(AStream, FBoundary); // that was getting going. usually LTemp would be empty, but we will throw it away repeat LTemp := ReadBytes(AStream, 2); if LTemp = EOL then begin LPart := TIdSoapMimePart.create; try LPart.ReadFromStream(AStream, FBoundary); except FreeAndNil(LPart); raise; end; LPart.FContent.Position := 0; FParts.Add(LPart); end until LTemp = '--'; end; function TIdSoapMimeMessage.GetContentTypeHeader: String; const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimeMessage.GetContentTypeHeader'; begin assert(self.TestValid(TIdSoapMimeMessage), ASSERT_LOCATION+': self is not valid'); result := String(ID_SOAP_MULTIPART_RELATED)+'; type="application/xop+xml"; '+String(ID_SOAP_MIME_START)+'="'+FStart+'"; start-info="application/soap+xml"; '+String(ID_SOAP_MIME_BOUNDARY)+'="'+String(FBoundary)+'"; action="urn:ihe:iti:2007:ProvideAndRegisterDocumentSet-b"'; if FMainType <> '' then begin result := result + '; '+String(ID_SOAP_MIME_TYPE)+'="'+FMainType+'"'; end; // oracle Content-Type: multipart/related; type="application/xop+xml"; start="<rootpart@soapui.org>"; start-info="application/soap+xml"; action="ProvideAndRegisterDocumentSet-b"; boundary="----=_Part_2_2098391526.1311207545005" end; procedure TIdSoapMimeMessage.Validate; const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimeMessage.Validate'; var i, j : integer; LFound : boolean; begin assert(self.TestValid(TIdSoapMimeMessage), ASSERT_LOCATION+': self is not valid'); IdRequire(FBoundary <> '', ASSERT_LOCATION+': Boundary is not valid'); IdRequire(FStart <> '', ASSERT_LOCATION+': Start is not valid'); LFound := false; for i := 0 to FParts.Count - 1 do begin IdRequire(FParts.PartByIndex[i].TestValid(TIdSoapMimePart), ASSERT_LOCATION+': Part['+inttostr(i)+'] is not valid'); IdRequire(FParts.PartByIndex[i].Id <> '', ASSERT_LOCATION+': Part['+inttostr(i)+'].Id is not valid'); LFound := LFound or (FParts.PartByIndex[i].Id = FStart); for j := 0 to i - 1 do begin IdRequire(FParts.PartByIndex[i].Id <> FParts.PartByIndex[j].Id, ASSERT_LOCATION+': Part['+inttostr(i)+'].Id is a duplicate of Part['+inttostr(j)+'].Id ("'+FParts.PartByIndex[i].Id+'")'); end; end; IdRequire(LFound, ASSERT_LOCATION+': The Start Part "'+FStart+'" was not found in the parts '+FParts.CommaList); end; procedure TIdSoapMimeMessage.WriteToStream(AStream: TStream; AHeaders: boolean); const ASSERT_LOCATION = ASSERT_UNIT+'.TIdSoapMimeMessage.WriteToStream'; var i : integer; begin assert(self.TestValid(TIdSoapMimeMessage), ASSERT_LOCATION+': self is not valid'); assert(Assigned(AStream), ASSERT_LOCATION+': stream is not valid'); Validate; if AHeaders then begin WriteHeaders(AStream); end; for i := 0 to FParts.Count - 1 do begin WriteString(AStream, '--'+FBoundary+EOL); FParts.PartByIndex[i].WriteToStream(AStream); end; WriteString(AStream, '--'+FBoundary+'--'); end; end.
unit TestPhisicsControllerUnit; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, PhisicsControllerUnit, ControllersUnit, Test1LoggingUnit, System.Generics.Collections, Dialogs, MainUnit, SysUtils, MenuLoggingUnit, stdCtrls, TestsUnit; type // Test methods for class PhisicsController TestPhisicsController = class(TTestCase) strict private FPhisicsController: PhisicsController; public procedure SetUp; override; procedure TearDown; override; published procedure TestsetTest; procedure TestgetMenu; procedure TestgetQuest; procedure TestgetAnswer; procedure TestgetCorrect; end; implementation procedure TestPhisicsController.SetUp; begin FPhisicsController := PhisicsController.Create; end; procedure TestPhisicsController.TearDown; begin FPhisicsController.Free; FPhisicsController := nil; end; procedure TestPhisicsController.TestsetTest; var caption: string; begin // TODO: Setup method call parameters caption:=FPhisicsController.getMenu.Items[1]; FPhisicsController.setTest(caption); CheckEquals(caption, 'Типы и структуры данных'); CheckNotEquals(caption, 'Теоретические основы баз данных'); // TODO: Validate method results end; procedure TestPhisicsController.TestgetMenu; var ReturnValue: TList<string>; begin ReturnValue := FPhisicsController.getMenu; CheckNotEquals(ReturnValue.Items[1],'Ответ'); CheckEquals(ReturnValue.Items[0], 'Теоретические основы баз данных'); CheckNotEquals(ReturnValue.First, '11'); // TODO: Validate method results end; procedure TestPhisicsController.TestgetQuest; var ReturnValue: TList<string>; begin FPhisicsController.setTest('Типы и структуры данных'); ReturnValue := FPhisicsController.getQuest; CheckNotEquals(ReturnValue.Items[4],'1111'); CheckEquals(ReturnValue.Count, 5); // TODO: Validate method results end; procedure TestPhisicsController.TestgetAnswer; var ReturnValue: TList<string>; begin FPhisicsController.setTest('Типы и структуры данных'); ReturnValue := FPhisicsController.getAnswer; CheckEquals(ReturnValue.Items[1],'Тип данных, конструируемый пользователем для решения конкретных задач.'); CheckTrue(ReturnValue.Items[3]<>'sss'); CheckNotEquals(ReturnValue.Items[1],'Ответ'); CheckEquals(ReturnValue.Count, 5); // TODO: Validate method results end; procedure TestPhisicsController.TestgetCorrect; var ReturnValue: TDictionary<integer,integer>; begin FPhisicsController.setTest('Типы и структуры данных'); ReturnValue := FPhisicsController.getCorrect; CheckEquals(ReturnValue.Items[2], 2); CheckNotEquals(ReturnValue.Items[3], 11); // TODO: Validate method results end; initialization // Register any test cases with the test runner RegisterTest(TestPhisicsController.Suite); end.
unit Controller.ApuracaoICMSST; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, biblKhronos,DateUtils, FireDAC.Comp.Client,Data.DB; type TControllerApuracaoICMSST = class private FView : TForm; FModel : TDataModule; FMensagem : String; FQry : TFDQuery; procedure SetMensagem(const Value: String); function GetMensagem : String; procedure GeraRegistro10(pMes,pAno : String; pFinalidadeSintegra: TFinalidadeSintegra); procedure GerarRegistro88STES(pCNPJ,pDatInv,pDatIni,pDatFin : String); procedure GerarRegistro88STITNF(pCNPJ,pDatIni,pDatFin : String); procedure GeraRegistro11; public function ValidadoDadosBasicos:Boolean; function GerarSintegra(pFinalidadeSintegra: TFinalidadeSintegra) : Boolean; function GerarArquivoSEF : Boolean; procedure ProcessarSintegra(pFinalidadeSintegra : TFinalidadeSintegra); procedure DefineNomeArqSint(pCNPJ,pMes,pAno : String); constructor create(pView: TForm; pModel : TDataModule); property Mensagem : String read GetMensagem write SetMensagem; end; implementation { TControllerApuracaoICMSST } Uses uApuracaoICMSST, uDMApuracaoICMSST,uDMBase,uMensagem,ACBrSintegra; constructor TControllerApuracaoICMSST.create(pView: TForm; pModel : TDataModule); begin inherited create; FView := pView; FModel := pModel; end; procedure TControllerApuracaoICMSST.DefineNomeArqSint(pCNPJ,pMes,pAno : String); Const PreFixoArq = '\Sint_'; var vDir : String; begin vDir := dmPrincipal.DirRaizApp + 'Sintegra'; if not DirectoryExists(vDir) then ForceDirectories(vDir); TFrmApuracao(FView).ACBrSintegra.FileName := vDir + PreFixoArq + pCNPJ + '_' + pMes + pAno + '.txt'; end; function TControllerApuracaoICMSST.GerarArquivoSEF : Boolean; const PreFixoArq = '\SEF_'; cDelimit = '|'; var vLstSEF : TStringList; vDirSaveArq : String; vLinha : String; vCNPJ : String; vMes : String; vAno : String; vDir : String; vQryST : TFDMemTable; vSQL : String; vDatIni : String; vDatFin : String; vCab : String; procedure AddLinhaMontada(pTexto : String); begin vLstSEF.Add(pTexto); end; procedure MontaLinha; begin vLinha := IntToStr(vQryST.FieldByName('ID_SPED').AsInteger) + cDelimit + vQryST.FieldByName('NCM').AsString + cDelimit + vQryST.FieldByName('COD_EAN').AsString + cDelimit + vQryST.FieldByName('DESCR_ITEM').AsString + cDelimit + vQryST.FieldByName('UNID').AsString + cDelimit + '0.00' + cDelimit + //FloatToStr(vQryST.FieldByName('VI.QTDE').AsFloat) + cDelimit + '0.00' + cDelimit +//FloatToStr(vQryST.FieldByName('VL_ICMS_ST_ENT').AsFloat)+ cDelimit + '0.00' + cDelimit + '0.00' + cDelimit +//FloatToStr(vQryST.FieldByName('VI.QTDE').AsFloat) + cDelimit + '0.00' + cDelimit +//FloatToStr(vQryST.FieldByName('VL_ICMS_ST_ENT').AsFloat)+ cDelimit + '0.00' + cDelimit; //vLinha := vLinha + pTexto + cDelimit; //vLinha := vLinha + cDelimit; end; procedure CriaArqSEF; begin vLstSEF.SaveToFile(vDirSaveArq); end; begin try result := False; vLstSEF := TStringList.Create; vCNPJ := TFrmApuracao(FView).EdtCodPart.Text; vMes := TFrmApuracao(FView).cmbMes.Text; vAno := TFrmApuracao(FView).CmbAno.Text; vDir := dmPrincipal.DirRaizApp + 'SEF'; vDirSaveArq := vDir + PreFixoArq + vCNPJ + '_' + vMes + vAno + '.txt'; vDatIni := DateToStr(StartOfAMonth(vAno.ToInteger,vMes.ToInteger)); vDatFin := DateToStr(EndOfTheMonth(StrToDate(vDatIni))); try vSQL := TDmApuracaoICMSST(FModel).GetSEF(vDatIni, vDatFin, vCNPJ); vQryST := TDmApuracaoICMSST(FModel).GetQryTemp; dmPrincipal.BancoExec.ExecSQL(vSQL,TDataSet(vQryST)); if vQryST.IsEmpty then exit; vCab := 'CD_SPED|CD_NCM|CD_EAN13|DS_PRODMERC|TP_UNIDADE|QT_PROD_ST_COMP|' + 'VR_ICMS_ST_COMP|VR_FEM_ST_COMP|QT_PROD_ST_REST|VR_ICMS_ST_REST|' + 'VR_FEM_ST_REST|'; vLstSEF.Add(vCab); vQryST.First; while not vQryST.Eof do begin MontaLinha; AddLinhaMontada(vLinha); vQryST.Next; end; CriaArqSEF; Mensagem := 'Arquivo SEF : ' + vDirSaveArq + ' gerado com sucesso.'; result := true; except raise; end; finally FreeAndNil(vLstSEF); end; end; procedure TControllerApuracaoICMSST.GerarRegistro88STES(pCNPJ,pDatInv,pDatIni,pDatFin : String); var vReg88STES : TRegistro88STES; vQryInventario : TFDMemTable; vSQL : String; begin {Estoques de Produtos ao Regime de Substituição Tributária} try vSQL := TDmApuracaoICMSST(FModel).GetSQL88STES(pDatIni,pDatFin,pCNPJ); vQryInventario := TDmApuracaoICMSST(FModel).GetQryTemp; dmPrincipal.BancoExec.ExecSQL(vSQL,TDataSet(vQryInventario)); if vQryInventario.IsEmpty then exit; vQryInventario.DisableControls; vQryInventario.First; while not vQryInventario.Eof do begin vReg88STES := TRegistro88STES.Create; with vReg88STES do begin CNPJ := pCNPJ; DataInventario := StrToDate(pDatInv); CodigoProduto := vQryInventario.FieldByName('COD_ITEM').AsString; Quantidade := vQryInventario.FieldByName('QTDE').AsFloat; VlrICMSST := vQryInventario.FieldByName('VLRICMSST').AsFloat; VlrICMSOP := vQryInventario.FieldByName('VLRICMSOP').AsFloat; end; TFrmApuracao(FView).ACBrSintegra.Registros88STES.Add(vReg88STES); vQryInventario.Next; end; vQryInventario.EnableControls; except raise; end; end; procedure TControllerApuracaoICMSST.GerarRegistro88STITNF(pCNPJ,pDatIni,pDatFin : String); var vReg88STITNF : TRegistro88STITNF; vQryNF : TFDMemTable; vSQL : String; begin {Itens das Notas Fiscais Relativas à Entrada de Produtos Sujeitos a Substituição Tributária} try vSQL := TDmApuracaoICMSST(FModel).GetSQL88STITNF(pDatIni,pDatFin,pCNPJ); vQryNF := TDmApuracaoICMSST(FModel).GetQryTemp; dmPrincipal.BancoExec.ExecSQL(vSQL,TDataSet(vQryNF)); if vQryNF.IsEmpty then exit; vQryNF.DisableControls; vQryNF.First; while not vQryNF.Eof do begin vReg88STITNF := TRegistro88STITNF.Create; with vReg88STITNF do begin CNPJ := vQryNF.FieldByName('COD_PART').AsString; Modelo := vQryNF.FieldByName('COD_MOD').AsString; Serie := vQryNF.FieldByName('SER').AsString; Numero := vQryNF.FieldByName('NUM_DOC').AsString; CFOP := vQryNF.FieldByName('CFOP').AsString; CST := vQryNF.FieldByName('CST').AsString; NumeroItem := vQryNF.FieldByName('NUM_ITEM').AsInteger; DataEntrada := vQryNF.FieldByName('DT_E_ES').AsDateTime; CodigoProduto := vQryNF.FieldByName('COD_ITEM').AsString; Quantidade := vQryNF.FieldByName('QTDE').AsFloat; VlrProduto := vQryNF.FieldByName('VL_ITEM').AsFloat; ValorDesconto := vQryNF.FieldByName('VL_DESC').AsFloat; BaseICMSOP := vQryNF.FieldByName('VL_BC_ICMS').AsFloat; BaseICMSST := vQryNF.FieldByName('VL_BC_ICMS_ST').AsFloat; AliquotaICMSOP := vQryNF.FieldByName('ALIQ_ICMS').AsFloat; AliquotaICMSST := vQryNF.FieldByName('ALIQ_ST').AsFloat; VlrIPI := vQryNF.FieldByName('VL_IPI').AsFloat; ChaveNFE := vQryNF.FieldByName('CHV_NFE').AsString; end; TFrmApuracao(FView).ACBrSintegra.Registros88STITNF.Add(vReg88STITNF); vQryNF.Next; end; vQryNF.EnableControls; except raise; end; end; function TControllerApuracaoICMSST.GerarSintegra(pFinalidadeSintegra: TFinalidadeSintegra) : Boolean; var vCNPJ : String; vMes : String; vAno : String; vDatInv : String; vDatIniInv : String; vDatIni : String; vDatFin : String; procedure GerarArquivoSintegra; begin TFrmApuracao(FView).ACBrSintegra.GeraArquivo; end; begin result := false; try FQry := TFDQuery.Create(nil); vCNPJ := TFrmApuracao(FView).EdtCodPart.Text; vMes := TFrmApuracao(FView).cmbMes.Text; vAno := TFrmApuracao(FView).CmbAno.Text; vDatIniInv := DateToStr(StartOfTheMonth(StartOfAMonth(vAno.ToInteger,vMes.ToInteger)-1)); vDatIni := DateToStr(StartOfAMonth(vAno.ToInteger,vMes.ToInteger)); vDatInv := DateToStr((StrToDate(vDatIni))-1); vDatFin := DateToStr(EndOfTheMonth(StrToDate(vDatIni))); try if not TDmApuracaoICMSST(FModel).GetContribuinte(vCNPJ) then begin Mensagem := 'Contribuinte não possui cadastro!'; exit; end; DefineNomeArqSint(vCNPJ,vMes,vAno); GeraRegistro10(vMes,vAno,pFinalidadeSintegra); GeraRegistro11; GerarRegistro88STES(vCNPJ,vDatInv,vDatIniInv,vDatInv); GerarRegistro88STITNF(vCNPJ,vDatIni,vDatFin); GerarArquivoSintegra; Mensagem := 'Sintegra :' + TFrmApuracao(FView).ACBrSintegra.FileName + ' gerado com sucesso.'; result := true; except On e: exception do Mensagem := 'Erro : ' + e.Message + ' ao tentar gerar sintegra.'; end; finally FreeAndNil(FQry); end; end; function TControllerApuracaoICMSST.GetMensagem: String; begin result := FMensagem; FMensagem := ''; end; procedure TControllerApuracaoICMSST.ProcessarSintegra( pFinalidadeSintegra: TFinalidadeSintegra); begin if not ValidadoDadosBasicos then begin FrmMensagem.Informacao(Mensagem); exit; end; if not GerarSintegra(pFinalidadeSintegra) then begin FrmMensagem.Informacao(Mensagem); exit; end; FrmMensagem.Informacao(Mensagem); end; procedure TControllerApuracaoICMSST.SetMensagem(const Value: String); begin FMensagem := Value; end; function TControllerApuracaoICMSST.ValidadoDadosBasicos: Boolean; begin result := false; if TFrmApuracao(FView).ChkXML.Checked then begin if TFrmApuracao(FView).cxGridDBTVNF.DataController.DataSource.DataSet.IsEmpty then begin FMensagem := 'Dados dos XML(s) não encontrado(s).'; exit; end; end; if TFrmApuracao(FView).ChkSPED.Checked then begin if TFrmApuracao(FView).cxGridDBTVW0200.DataController.DataSource.DataSet.IsEmpty then begin FMensagem := 'Dados do SPED não encontrado.'; exit; end; end; result := true; end; procedure TControllerApuracaoICMSST.GeraRegistro10(pMes,pAno : String; pFinalidadeSintegra: TFinalidadeSintegra); var vQryContrib : TFDQuery; function ConvFinalidadeSintStr:String; begin result := iif(pFinalidadeSintegra = fsNormal,'1','2'); end; begin vQryContrib := TDmApuracaoICMSST(FModel).GetQry; with TFrmApuracao(FView).ACBrSintegra.Registro10 do begin CNPJ := vQryContrib.FieldByName('CNPJ').AsString; Inscricao := vQryContrib.FieldByName('IE').AsString; RazaoSocial := vQryContrib.FieldByName('RAZAOSOCIAL').AsString; Cidade := vQryContrib.FieldByName('MUNICIPIO').AsString; Estado := vQryContrib.FieldByName('UF').AsString; Telefone := vQryContrib.FieldByName('TELEFONE').AsString; DataInicial := StartOfaMonth(pAno.ToInteger,pMes.ToInteger); DataFinal := EndOfaMonth(pAno.ToInteger,pMes.ToInteger); CodigoConvenio := '1'; NaturezaInformacoes := '1'; FinalidadeArquivo := ConvFinalidadeSintStr; end; end; procedure TControllerApuracaoICMSST.GeraRegistro11; var vQryEndContrib : TFDQuery; begin vQryEndContrib := TDmApuracaoICMSST(FModel).GetQry; with TFrmApuracao(FView).ACBrSintegra.Registro11 do begin Endereco := vQryEndContrib.FieldByName('LOGRADOURO').AsString; Numero := vQryEndContrib.FieldByName('NUMERO').AsString; Bairro := vQryEndContrib.FieldByName('BAIRRO').AsString; Cep := vQryEndContrib.FieldByName('CEP').AsString; Responsavel := ''; Telefone := vQryEndContrib.FieldByName('TELEFONE').AsString; end; end; end.
(* * Copyright (c) 2009, Ciobanu Alexandru * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) {$I ../Library/src/DeHL.Defines.inc} unit Tests.Converter; interface uses SysUtils, Variants, Math, Character, Tests.Utils, TestFramework, DeHL.Base, DeHL.Exceptions, DeHL.Types, DeHL.Conversion, DeHL.Box, DeHL.Math.BigCardinal, DeHL.Math.BigInteger, DeHL.DateTime; type TTestConverter = class(TDeHLTestCase) published procedure TestTConverter; procedure TestClone; procedure TestClone2; procedure Test_Case_0(); procedure Test_Case_1(); procedure Test_Case_2_ClassClass(); procedure Test_Case_2_ClassIntf(); procedure Test_Case_2_ClassRefClassRef(); procedure Test_Case_2_IntfIntf(); procedure Test_Case_3(); procedure Test_Case_4(); procedure Test_Case_5_0(); procedure Test_Case_5_1(); procedure Test_Case_6(); procedure Test_Case_7(); procedure Test_Method(); end; implementation { TTestConverter } procedure TTestConverter.TestClone; var LConv, LCopy: TConverter<Integer, Integer>; begin LConv := TConverter<Integer, Integer>.Create(); LCopy := LConv.Clone as TConverter<Integer, Integer>; CheckEquals(1, LCopy.Convert(1), 'Types not copied properly'); CheckEquals(-1, LCopy.Convert(-1), 'Types not copied properly'); LConv.Free; LCopy.Free; end; procedure TTestConverter.TestClone2; var LConv, LCopy: TConverter<string, string>; LIntf: IType<string>; begin LIntf := TExType<string>.Create(); LConv := TConverter<string, string>.Create(LIntf, TType<string>.Default); LCopy := LConv.Clone as TConverter<string, string>; CheckEquals('>>1', LCopy.Convert('1'), 'From type not copied properly'); LConv.Free; LCopy.Free; end; procedure TTestConverter.TestTConverter; var ConvIS: IConverter<Integer, String>; ConvBI: IConverter<Boolean, Integer>; ConvDD: IConverter<Double, Double>; DoubleConst: Double; begin { Test ctors } CheckException(ENilArgumentException, procedure begin TConverter<Integer, Integer>.Create(nil, TType<Integer>.Default); end, 'ENilArgumentException not thrown in Create (nil type 1)'); CheckException(ENilArgumentException, procedure begin TConverter<Integer, Integer>.Create(TType<Integer>.Default, nil); end, 'ENilArgumentException not thrown in Create (nil type 2)'); { Set up all converters } ConvIS := TConverter<Integer, String>.Create(TType<Integer>.Default, TType<String>.Default); ConvBI := TConverter<Boolean, Integer>.Create(); ConvDD := TConverter<Double, Double>.Create(); { Int/String } Check(ConvIS.Convert(1) = '1', '(Int/Str) Expected conversion to be equal to "1"'); Check(ConvIS.Convert(-78) = '-78', '(Int/Str) Expected conversion to be equal to "-78"'); Check(ConvIS.Convert(0) = '0', '(Int/Str) Expected conversion to be equal to "0"'); { Boolean/Int } Check(ConvBI.Convert(true) <> 0, '(Bool/Int) Expected conversion to not be equal to "0"'); Check(ConvBI.Convert(false) = 0, '(Bool/Int) Expected conversion to be equal to "0"'); { Double/Double } DoubleConst := 1; Check(ConvDD.Convert(DoubleConst)= DoubleConst, '(Double/Double) Expected conversion to not be equal to "1"'); DoubleConst := 1.1; Check(ConvDD.Convert(DoubleConst) = DoubleConst, '(Double/Double) Expected conversion to be equal to "1.1"'); DoubleConst := -4.155555; Check(ConvDD.Convert(DoubleConst) = DoubleConst, '(Double/Double) Expected conversion to be equal to "-4.155555"'); end; procedure TTestConverter.Test_Case_0; var LConv: IConverter<Integer, Integer>; begin LConv := TConverter<Integer, Integer>.Create; CheckEquals(MaxInt, LConv.Convert(MaxInt), 'Case 0/0'); CheckEquals(0, LConv.Convert(0), 'Case 0/0'); CheckEquals(-1, LConv.Convert(-1), 'Case 0/0'); end; procedure TTestConverter.Test_Case_1; var LConv: IConverter<Byte, UInt64>; begin LConv := TConverter<Byte, UInt64>.Create; CheckEquals(0, LConv.Convert(0), 'Case 1'); CheckEquals(255, LConv.Convert(255), 'Case 1'); end; procedure TTestConverter.Test_Case_2_ClassClass; var LConv: IConverter<TObject, TInterfacedObject>; LObj: TObject; LRes: TInterfacedObject; begin LConv := TConverter<TObject, TInterfacedObject>.Create; LObj := TObject.Create; CheckFalse(LConv.TryConvert(LObj, LRes), 'Case 2/0 (f)'); LObj.Free; LObj := TInterfacedObject.Create; CheckTrue(LConv.TryConvert(LObj, LRes), 'Case 2/0 (f)'); CheckTrue(LObj = LRes, 'Case 2 (r)'); LObj.Free; LObj := TRefCountedObject.Create; CheckTrue(LConv.TryConvert(LObj, LRes), 'Case 2/0 (f)'); CheckTrue(LObj = LRes, 'Case 2 (r)'); LObj.Free; end; procedure TTestConverter.Test_Case_2_ClassIntf; var LConv: IConverter<TObject, IInterface>; LObj: TObject; LRes: IInterface; begin LConv := TConverter<TObject, IInterface>.Create; LObj := TObject.Create; CheckFalse(LConv.TryConvert(LObj, LRes), 'Case 2/1 (f)'); LObj.Free; LObj := TInterfacedObject.Create; CheckTrue(LConv.TryConvert(LObj, LRes), 'Case 2/1 (f)'); CheckTrue((LRes as TInterfacedObject) = LObj, 'Case 2/1 (r)'); end; procedure TTestConverter.Test_Case_2_ClassRefClassRef; var LConv: IConverter<TClass, TInterfacedClass>; LObj: TClass; LRes: TInterfacedClass; begin LConv := TConverter<TClass, TInterfacedClass>.Create; LObj := TObject; CheckFalse(LConv.TryConvert(LObj, LRes), 'Case 2/2 (f)'); LObj := TInterfacedObject; CheckTrue(LConv.TryConvert(LObj, LRes), 'Case 2/2 (f)'); CheckTrue(LRes = LObj, 'Case 2/2 (r)'); LObj := TRefCountedObject; CheckTrue(LConv.TryConvert(LObj, LRes), 'Case 2/2 (f)'); CheckTrue(LObj = LRes, 'Case 2/2 (r)'); end; type IMyCoolIntf = interface ['{075828A0-9F21-4905-A7C6-5163D7BB5341}'] end; TMyCoolObj = class(TInterfacedObject, IMyCoolIntf); procedure TTestConverter.Test_Case_2_IntfIntf; var LConv: IConverter<IInterface, IMyCoolIntf>; LObj: IInterface; LRes: IMyCoolIntf; begin LConv := TConverter<IInterface, IMyCoolIntf>.Create; LObj := TInterfacedObject.Create; CheckFalse(LConv.TryConvert(LObj, LRes), 'Case 2/3 (f)'); LObj := TMyCoolObj.Create; CheckTrue(LConv.TryConvert(LObj, LRes), 'Case 2/3 (f)'); CheckTrue((LRes as TMyCoolObj) = (LRes as TMyCoolObj), 'Case 2/3 (r)'); end; type TMySpecialInt0 = type Integer; TMySpecialInt1 = type Integer; TMySpecialByte0 = type Byte; procedure TTestConverter.Test_Case_3; var LConv: IConverter<TMySpecialInt0, Int64>; begin LConv := TConverter<TMySpecialInt0, Int64>.Create; CheckEquals(MaxInt, LConv.Convert(MaxInt), 'Case 3'); CheckEquals(0, LConv.Convert(0), 'Case 3'); end; procedure TTestConverter.Test_Case_4; var LConv: IConverter<Byte, TMySpecialInt0>; begin LConv := TConverter<Byte, TMySpecialInt0>.Create; CheckEquals(255, LConv.Convert(255), 'Case 4'); CheckEquals(0, LConv.Convert(0), 'Case 4'); end; procedure TTestConverter.Test_Case_5_0; var LConv: IConverter<TMySpecialInt0, TMySpecialInt1>; begin LConv := TConverter<TMySpecialInt0, TMySpecialInt1>.Create; CheckEquals(MaxInt, LConv.Convert(MaxInt), 'Case 5/0'); CheckEquals(0, LConv.Convert(0), 'Case 5/0'); CheckEquals(-1, LConv.Convert(-1), 'Case 5/0'); end; procedure TTestConverter.Test_Case_5_1; var LConv: IConverter<TMySpecialByte0, TMySpecialInt1>; begin LConv := TConverter<TMySpecialByte0, TMySpecialInt1>.Create; CheckEquals(255, LConv.Convert(255), 'Case 5/1'); CheckEquals(0, LConv.Convert(0), 'Case 5/1'); end; procedure TTestConverter.Test_Case_6; var LConv: IConverter<TMySpecialByte0, Variant>; begin LConv := TConverter<TMySpecialByte0, Variant>.Create; CheckEquals(255, LConv.Convert(255), 'Case 6'); CheckEquals(0, LConv.Convert(0), 'Case 6'); end; procedure TTestConverter.Test_Case_7; var LConv: IConverter<Variant, TMySpecialByte0>; begin LConv := TConverter<Variant, TMySpecialByte0>.Create; CheckEquals(255, LConv.Convert(255), 'Case 7'); CheckEquals(0, LConv.Convert(0), 'Case 7'); end; function AsIntf(const AAnonMethod): IInterface; begin Pointer(Result) := Pointer(AAnonMethod); end; type TXAnon = class(TInterfacedObject, TConvertProc<TMySpecialInt0, TMySpecialInt1>) public function Invoke(const AIn: TMySpecialInt0; out AOut: TMySpecialInt1): Boolean; end; { TXAnon } function TXAnon.Invoke(const AIn: TMySpecialInt0; out AOut: TMySpecialInt1): Boolean; begin AOut := AIn + 1; Exit(true); end; procedure TTestConverter.Test_Method; var LConv: IConverter<TMySpecialInt0, TMySpecialInt1>; LMethod, LMethodOf: TConvertProc<TMySpecialInt0, TMySpecialInt1>; LAnon: TXAnon; begin { Check the initial = nil } CheckTrue(TConverter<TMySpecialInt0, TMySpecialInt1>.Method = nil, 'Expected NIL for (sp0, sp1)'); { Use a sentinel interface to check if the anon method lives or dies } LAnon := TXAnon.Create(); LMethod := LAnon; { Register a converter } TConverter<TMySpecialInt0, TMySpecialInt1>.Method := LMethod; CheckEquals(2, LAnon.RefCount, 'LMethod ref count <> 2!'); { Check the initial <> nil } LMethodOf := TConverter<TMySpecialInt0, TMySpecialInt1>.Method; CheckTrue(AsIntf(LMethodOf) = AsIntf(LMethod), 'Expected LMethod for (sp0, sp1)'); LMethod := nil; // Kill local ref (-1) LMethodOf := nil; CheckEquals(1, LAnon.RefCount, 'LMethod was destroyed!'); { Test our new converter } LConv := TConverter<TMySpecialInt0, TMySpecialInt1>.Create; CheckEquals(255, LConv.Convert(254), '+1 failed'); CheckEquals(1, LConv.Convert(0), '+1 failed'); { Now let's release the converter } TConverter<TMySpecialInt0, TMySpecialInt1>.Method := nil; CheckTrue(TConverter<TMySpecialInt0, TMySpecialInt1>.Method = nil, 'Expected NIL for (sp0, sp1)'); CheckEquals(1, LAnon.RefCount, 'LMethod was not destroyed!'); { Re-Test the converter } LConv := TConverter<TMySpecialInt0, TMySpecialInt1>.Create; CheckEquals(254, LConv.Convert(254), '=0 failed'); CheckEquals(0, LConv.Convert(0), '=0 failed'); end; initialization TestFramework.RegisterTest(TTestConverter.Suite); end.
unit Helper.TJSONObject; interface uses System.JSON, System.Variants; type THelperJSONObject = class helper for TJSONObject private function GetValuesEx(const Name: string): Variant; procedure SetValuesEx(const Name: string; Value: Variant); public function FieldHasNotNullValue(const fieldName: string): Boolean; function FieldGetIsoDateUtc(const Name: string): TDateTime; function FieldIsValidIsoDateUtc(const Name: string): Boolean; { TODO 99: Add XML Documentation summary at least } property ValuesEx[const Name: string]: Variant read GetValuesEx write SetValuesEx; end; implementation uses System.SysUtils, System.DateUtils; // ---------------------------------------------------------- // // Function checks is TJsonObject has field and this field has not null value // function THelperJSONObject.FieldHasNotNullValue(const fieldName: string) : Boolean; begin Result := Assigned(self.Values[fieldName]) and not self.Values [fieldName].Null; end; function THelperJSONObject.GetValuesEx(const Name: string): Variant; var jsValue: TJSONValue; begin jsValue := self.Values[Name]; if Assigned(jsValue) and not(jsValue.Null) then Result := jsValue.Value else Result := Null; end; procedure THelperJSONObject.SetValuesEx(const Name: string; Value: Variant); begin { TODO 99: Not implemented yet. Implement as fast as it will be possible } raise Exception.Create('Internal developer error. Not implemented yet'); end; function THelperJSONObject.FieldIsValidIsoDateUtc(const Name: string): Boolean; begin try System.DateUtils.ISO8601ToDate(self.Values[Name].Value, False); Result := True; except on E: Exception do Result := False; end end; function THelperJSONObject.FieldGetIsoDateUtc(const Name: string): TDateTime; begin Result := System.DateUtils.ISO8601ToDate(self.Values[Name].Value, False); end; end.
namespace Sugar.Test; interface uses Sugar, Sugar.Xml, Sugar.TestFramework; type ProcessingInstructionTest = public class (Testcase) private Doc: XmlDocument; Data: XmlProcessingInstruction; public method Setup; override; method Value; method TestData; method Target; method NodeType; end; implementation method ProcessingInstructionTest.Setup; begin Doc := XmlDocument.FromString(XmlTestData.PIXml); Assert.IsNotNull(Doc); Data := Doc.ChildNodes[0] as XmlProcessingInstruction; Assert.IsNotNull(Data); end; method ProcessingInstructionTest.Value; begin Assert.IsNotNull(Data.Value); Assert.CheckString("type=""text/xsl"" href=""test""", Data.Value); Data.Value := "type=""text/xsl"""; Assert.CheckString("type=""text/xsl""", Data.Value); Assert.IsException(->begin Data.Value := nil; end); Data := Doc.ChildNodes[1] as XmlProcessingInstruction; Assert.CheckString("", Data.Value); end; method ProcessingInstructionTest.Target; begin Assert.IsNotNull(Data.Target); Assert.CheckString("xml-stylesheet", Data.Target); Data := Doc.ChildNodes[1] as XmlProcessingInstruction; Assert.CheckString("custom", Data.Target); end; method ProcessingInstructionTest.TestData; begin //Data is the same thing as Value Assert.IsNotNull(Data.Data); Assert.CheckString("type=""text/xsl"" href=""test""", Data.Data); Data.Data := "type=""text/xsl"""; Assert.CheckString("type=""text/xsl""", Data.Data); Assert.IsException(->begin Data.Data := nil; end); Data := Doc.ChildNodes[1] as XmlProcessingInstruction; Assert.CheckString("", Data.Data); end; method ProcessingInstructionTest.NodeType; begin Assert.CheckBool(true, Data.NodeType = XmlNodeType.ProcessingInstruction); end; end.
unit Aurelius.Criteria.Projections; {$I Aurelius.inc} interface uses Aurelius.Criteria.Base; type TProjections = class sealed public class function Sum(APropName: string): TSimpleProjection; overload; class function Sum(AProjection: TSimpleProjection): TSimpleProjection; overload; class function Max(APropName: string): TSimpleProjection; overload; class function Max(AProjection: TSimpleProjection): TSimpleProjection; overload; class function Min(APropName: string): TSimpleProjection; overload; class function Min(AProjection: TSimpleProjection): TSimpleProjection; overload; class function Avg(APropName: string): TSimpleProjection; overload; class function Avg(AProjection: TSimpleProjection): TSimpleProjection; overload; class function Count(APropName: string): TSimpleProjection; overload; class function Count(AProjection: TSimpleProjection): TSimpleProjection; overload; class function Prop(APropName: string): TSimpleProjection; class function Group(APropName: string): TSimpleProjection; overload; class function Group(AProjection: TSimpleProjection): TSimpleProjection; overload; class function Condition(ACondition: TCustomCriterion; AWhenTrue, AWhenFalse: TSimpleProjection): TSimpleProjection; class function Value<T>(const AValue: T): TSimpleProjection; class function Literal<T>(const AValue: T): TSimpleProjection; class function ProjectionList: TProjectionList; overload; class function Alias(AProjection: TSimpleProjection; AProjectionAlias: string): TAliasedProjection; class function Sql<TResult>(ASQL: string): TSimpleProjection; end; implementation { TProjections } class function TProjections.Alias(AProjection: TSimpleProjection; AProjectionAlias: string): TAliasedProjection; begin Result := TAliasedProjection.Create(AProjection, AProjectionAlias); end; class function TProjections.Avg(AProjection: TSimpleProjection): TSimpleProjection; begin Result := TAggregateProjection.Create('avg', AProjection); end; class function TProjections.Avg(APropName: string): TSimpleProjection; begin Result := TAggregateProjection.Create('avg', Prop(APropName)); end; class function TProjections.Count(APropName: string): TSimpleProjection; begin Result := TAggregateProjection.Create('count', Prop(APropName)); end; class function TProjections.Condition(ACondition: TCustomCriterion; AWhenTrue, AWhenFalse: TSimpleProjection): TSimpleProjection; begin Result := TConditionalProjection.Create(ACondition, AWhenTrue, AWhenFalse); end; class function TProjections.Count(AProjection: TSimpleProjection): TSimpleProjection; begin Result := TAggregateProjection.Create('count', AProjection); end; class function TProjections.Group(APropName: string): TSimpleProjection; begin Result := TGroupProjection.Create(Prop(APropName)); end; class function TProjections.Group(AProjection: TSimpleProjection): TSimpleProjection; begin Result := TGroupProjection.Create(AProjection); end; class function TProjections.Literal<T>(const AValue: T): TSimpleProjection; begin Result := TConstantProjection<T>.Create(AValue, True); end; class function TProjections.Max(APropName: string): TSimpleProjection; begin Result := TAggregateProjection.Create('max', Prop(APropName)); end; class function TProjections.Max(AProjection: TSimpleProjection): TSimpleProjection; begin Result := TAggregateProjection.Create('max', AProjection); end; class function TProjections.Min(AProjection: TSimpleProjection): TSimpleProjection; begin Result := TAggregateProjection.Create('min', AProjection); end; class function TProjections.ProjectionList: TProjectionList; begin Result := TProjectionList.Create; end; class function TProjections.Prop(APropName: string): TSimpleProjection; begin Result := TPropertyProjection.Create(APropName); end; class function TProjections.Min(APropName: string): TSimpleProjection; begin Result := TAggregateProjection.Create('min', Prop(APropName)); end; class function TProjections.Sql<TResult>(ASQL: string): TSimpleProjection; begin Result := TSqlProjection.Create(ASQL, TypeInfo(TResult)); end; class function TProjections.Sum(AProjection: TSimpleProjection): TSimpleProjection; begin Result := TAggregateProjection.Create('sum', AProjection); end; class function TProjections.Value<T>(const AValue: T): TSimpleProjection; begin Result := TConstantProjection<T>.Create(AValue); end; class function TProjections.Sum(APropName: string): TSimpleProjection; begin Result := TAggregateProjection.Create('sum', Prop(APropName)); end; end.
{#Author fmarakasov@ugtu.net} unit CoreInterfaces; interface uses Classes, ActnList; type // Объекты, которые поддерживают режим просмотра // Вызов Preview должен регистрировать объект как "просмативаемый" // Вызов CloasePreview должен перевести статус объекта в начальное состояние IViewableObject = interface ['{F1D638A8-D95C-4742-A037-06F71D10B57B}'] procedure Preview; procedure ClosePreview; end; // Объекты, которые поддерживают транзакционное редактирование // Вызов Open должен зарегистрировать объект как "находится на редактировании" // Вызов Save должен принять все изменения объекта и перевести статус объекта в начальное состояние // Вызов Cancel должен перевести статус объекта в начальное состояние // Вызов Reload должен обновить состояние объекта IEditableObject = interface ['{D6D4A26F-B06C-4fa6-9842-8792C037B581}'] procedure Open; procedure Save; procedure Cancel; procedure Reload; procedure Delete; end; // Интерфейс описания промежутка времени ITimeSpan = interface (IInterface) ['{F3895D71-7D2A-4587-9FF8-A622E79ACF1A}'] function GetTotalHours : Double; function GetTotalDays : Double; function GetWholeDays : Integer; function GetWholeYears : Integer; function GetWholeMonthes : Integer; function GetWholeWeeks : Integer; property TotalHours : Double read GetTotalHours; property TotalDays : Double read GetTotalDays; property WholeDays : Integer read GetWholeDays; property WholeYears : Integer read GetWholeYears; property WholeMonthes : Integer read GetWholeMonthes; property WholeWeeks : Integer read GetWholeWeeks; end; // Интерфейс даты и времени IDateTime = interface (IInterface) ['{C1B846A1-549E-4f71-B336-A75B5960B0C2}'] function GetValue : TDateTime; function GetYear : Word; function GetMonth : Word; function GetDay : Word; function GetDayOfWeek : Word; function GetHour : Word; function GetMinute : Word; function GetSecond : Word; function GetMillisecond : Word; function GetYearLength : Word; function GetMonthLength : Word; function AddDays(Days : Double) : IDateTime; function AddMonthes(Monthes : Integer) : IDateTime; function AddWeeks(Weeks : Integer) : IDateTime; function AddYears (Years : Integer) : IDateTime; function Parse(const DateTimeString : string) : IDateTime; function EncodeDate(Year, Month, Day : Word) : IDateTime; function EncodeDateTime(Year, Month, Day, Hour, Minute, Second, MSecond : Word) : IDateTime; function Substract(const firstDateTime : IDateTime; const secondDateTime : IDateTime) : ITimeSpan; function Now : IDateTime; function Today : IDateTime; function IsLeapYear : Boolean; function GetLongDateString : String; function GetShortDateString : String; function GetLongTimeString : String; function GetFormatedDateTimeString ( const FormatString : String ) : String; function Between(DateTime1, DateTime2 : IDateTime): Boolean; function StrictBetween(DateTime1, DateTime2 : IDateTime): Boolean; property Year : Word read GetYear; property Month : Word read GetMonth; property Day : Word read GetDay; property DayOfWeek : Word read GetDayOfWeek; property Hour : Word read GetHour; property Minute : Word read GetMinute; property Second : Word read GetSecond; property Millisecond : Word read GetMillisecond; property Value : TDateTime read GetValue; property YearLength : Word read GetYearLength; property MonthLength : Word read GetMonthLength; end; INull = interface (IInterface) ['{17998808-10E3-4B54-9ACB-349B10C58167}'] function IsNull : Boolean; end; ILogger = interface ['{19EE60DB-C03B-4f5f-BA53-7A6A64C97F2C}'] procedure LogMessage(const Message : String); end; IUIComponent = interface (IInterface) ['{C80293FE-32D0-413a-8D3F-3E91BD672755}'] function GetUICaption : String; property UICaption : String read GetUICaption; end; /// /// Интерфейс для отправки сообщений через шлюз электронной почты /// IMail = interface ['{37AD942A-1729-441b-BF72-39B38B74F366}'] procedure SendMail(Subject : String; Body : String; FromAddress : String; ToAddress : String); end; /// /// Интерфейс провайдера подключения /// ILoginProvider = interface ['{101FEFE0-8F45-4056-ACD9-7C4F89C6D592}'] function Connect(const Login, Password : String) : Boolean; end; /// /// Интерфейс запроса имени пользователя и пароля /// ILoginQuery = interface ['{4D53AA63-2D54-4c75-BC15-7A223E5E08D7}'] /// /// Вызывает запрос параметров подключения, передавая в качестве /// аргумента объект интерфейса, который будет обеспечивать /// проверку аргументов подключения /// Возвращает истина, если подключение прошло успешно. /// Во всех остальных ситуациях возвращается ложь. function QueryCredentails(LoginProvider : ILoginProvider) : Boolean; end; /// /// Интерфейс запроса строки подключения /// ISIDProvider = interface ['{0AC49413-1495-446c-9A53-CCFA33E26D94}'] function GetSID:String; end; /// /// /// Интерфейс конфигурации OPC сервера /// IOPCServerConfig = interface ['{E428802A-F13F-47d5-AFE9-958ACEE856BB}'] function GetOPCHostName:String; function GetOPCServerName:String; procedure SetOPCServerName(Value : String); procedure SetOPCHostName(Value : String); /// /// Получает или устанавливает имя хоста, где размещается OPC сервер /// property OPCHostName:String read GetOPCHostName write SetOPCHostName; /// /// Получает или устанавливает имя OPC сервера к которому производится подключение /// property OPCServerName:String read GetOPCServerName write SetOPCServerName; end; POPCRecordData = ^TOPCRecordData; /// /// Запись OPC HDA /// TOPCRecordData = record /// /// Значение элемента /// Value : Variant; /// /// Метка времени /// TimeStamp : TDateTime; /// /// Маска качества сигнала /// Quality : Integer; /// /// Индекс элемента /// RecordIndex : Integer; /// /// Истина, если сигнал качественный /// IsQualityRaw : Boolean; end; IOPCTagInfo = interface ['{DE3CEE05-F30F-4DFC-BE26-037B4502BBB8}'] function GetTagName : String; procedure SetTagName(const Value : String); function GetTagDescription : String; function GetPCU: string; function GetRealTagName: string; /// /// Получить имя PCU /// property PCU: string read GetPCU; /// /// Получить имя реального тэга OPC /// property RealTag: string read GetRealTagName; /// /// Получить или установить имя тэга, которое используется в /// качестве ключа в интерфейса IOPCHDAHistoryProvider /// property TagName:String read GetTagName write SetTagName; /// /// Описание тэга /// property Description:String read GetTagDescription; end; /// /// Интерфейс поддержки графического интерфейса выбора OPC HDA тега /// IOPCHDABrowserUI = interface ['{7BC36481-E90B-4062-BD37-4AABBBDB39B2}'] /// /// Устанавливает в графическом интерфейсе текущий элемент /// procedure SetSelected(const Value : String); /// Открывает графическое представление для навигации по тэгам. /// возвращает интерфейс описания тега, выбранного пользователем или /// nil в случае отказа от выбора function Select : IOPCTagInfo; end; /// /// Провайдер получения доступных имён тэгов OPC HDA /// IOPCHDATagsProvider = interface ['{8DF99812-1465-44C2-BAA9-1DBA9CFBE91D}'] /// /// Возвращает список тэгов OPC HDA /// function GetOPCHDATags : TStrings; property OPCHDATags : TStrings read GetOPCHDATags; end; /// /// /// Провайдер действий. Обеспечивает информацией компоненты типа TActionPanel /// о поддерживаемом классом списке действий и категориях действий /// IActionsProvider = interface ['{EA49C564-6E1B-45cf-A2A6-61EE78C77C23}'] function GetMyActions : TActionList; function GetMyCategories : TStrings; /// /// Список поддерживаемых объектом действий /// property MyActions : TActionList read GetMyActions; /// /// Список поддерживаемых объектом категорий /// Если список категорий пуст или nil, то считается, что поддерживаются /// все категории /// property MyCategories : TStrings read GetMyCategories; end; implementation end.
// Copyright Cheat Engine. All Rights Reserved. unit frmSourceDisplayUnit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ComCtrls, ExtCtrls, Menus, SynEdit, SynEditMarks, SynHighlighterCpp, disassembler, MemoryBrowserFormUnit, tcclib, betterControls, SynGutterBase, debugeventhandler, BreakpointTypeDef; type { TfrmSourceDisplay } TfrmSourceDisplay = class(TForm) itInfo: TIdleTimer; ilDebug: TImageList; MenuItem1: TMenuItem; MenuItem2: TMenuItem; MenuItem3: TMenuItem; MenuItem4: TMenuItem; MenuItem5: TMenuItem; MenuItem6: TMenuItem; MenuItem7: TMenuItem; N1: TMenuItem; PopupMenu1: TPopupMenu; seSource: TSynEdit; SynCppSyn1: TSynCppSyn; tbDebug: TToolBar; tbRun: TToolButton; tbRunTill: TToolButton; tbSeparator1: TToolButton; tbSeparator2: TToolButton; tbSeparator3: TToolButton; tbStepInto: TToolButton; tbStepOut: TToolButton; tbStepOver: TToolButton; tbToggleBreakpoint: TToolButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure itInfoTimer(Sender: TObject); procedure MenuItem1Click(Sender: TObject); procedure seSourceGutterClick(Sender: TObject; X, Y, Line: integer; mark: TSynEditMark); procedure seSourceMouseEnter(Sender: TObject); procedure seSourceMouseLeave(Sender: TObject); procedure seSourceMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure tbRunClick(Sender: TObject); procedure tbRunTillClick(Sender: TObject); procedure tbStepIntoClick(Sender: TObject); procedure tbStepOutClick(Sender: TObject); procedure tbStepOverClick(Sender: TObject); procedure tbToggleBreakpointClick(Sender: TObject); private hintwindow:THintWindow; LoadedPosition: boolean; SourceCodeInfo: TSourceCodeInfo; d: TDisassembler; stepIntoThread: TDebugThreadHandler; stepIntoCountdown: integer; //counter to make sure it doesn't step too long (15 instructions max) function StepIntoHandler(sender: TDebugThreadHandler; bp: PBreakpoint): boolean; public function updateMarks:boolean; //returns true if the current breakpoint matches a line in this source end; function getSourceViewForm(lni: PLineNumberInfo): TfrmSourceDisplay; //creates or shows an existing sourcedisplay form procedure ApplySourceCodeDebugUpdate; //called by memoryview when a breakpoint is triggered and causes a break implementation uses maps, debughelper, cedebugger, CEFuncProc, SynHighlighterAA, debuggertypedefinitions, sourcecodehandler, ProcessHandlerUnit, byteinterpreter, commonTypeDefs, NewKernelHandler, globals; { TfrmSourceDisplay } var sourceDisplayForms: TMap; //searchable by sourcefile strings object function getSourceViewForm(lni: PLineNumberInfo): TfrmSourceDisplay; var sc: tstringlist; begin if lni=nil then exit(nil); if sourceDisplayForms=nil then sourceDisplayForms:=tmap.Create(ituPtrSize,sizeof(TfrmSourceDisplay)); if sourcedisplayforms.GetData(ptruint(lni^.sourcefile), result)=false then begin //create a new form result:=TfrmSourceDisplay.Create(Application); sourceDisplayForms.Add(lni^.sourcefile, result); //load the source result.seSource.Lines.Assign(lni^.sourcefile); result.Tag:=ptruint(lni^.sourcefile); result.updateMarks; //the sourcefilename is in the first line of sourcecode sc:=tstringlist.create; sc.text:=lni^.sourcecode; result.caption:=sc[0].Split([':'])[0]; sc.free; end; result.seSource.CaretY:=lni^.linenr; result.SourceCodeInfo:=SourceCodeInfoCollection.getSourceCodeInfo(lni^.functionaddress); if result.SourceCodeInfo<>nil then result.SourceCodeInfo.parseFullStabData; end; procedure ApplySourceCodeDebugUpdate; var mi: TMapIterator; f: TfrmSourceDisplay; hasbroken: boolean; begin if sourceDisplayForms<>nil then begin hasbroken:=(debuggerthread<>nil) and (debuggerthread.CurrentThread<>nil); mi:=TMapIterator.Create(sourceDisplayForms); try while not mi.EOM do begin mi.GetData(f); f.tbDebug.BeginUpdate; f.tbRun.enabled:=hasbroken; f.tbStepInto.enabled:=hasbroken; f.tbStepOver.enabled:=hasbroken; f.tbStepOut.enabled:=hasbroken; f.tbRunTill.enabled:=hasbroken; f.tbDebug.EndUpdate; if f.updateMarks then f.show; mi.Next; end; finally mi.free; end; end; end; function TfrmSourceDisplay.updateMarks: boolean; var mark: TSynEditMark; ml: TSynEditMarkLine; i: integer; a: ptruint; hasrip: boolean; begin //mark the lines with addresses and breakpoints result:=false; for i:=0 to seSource.Lines.Count-1 do begin a:=ptruint(sesource.Lines.Objects[i]); ml:=sesource.Marks.Line[i+1]; if ml<>nil then ml.Clear(true); if seSource.Lines.Objects[i]<>nil then begin mark:=TSynEditMark.Create(seSource); mark.line:=i+1; mark.ImageList:=ilDebug; if (debuggerthread<>nil) and (debuggerthread.CurrentThread<>nil) and (a=debuggerthread.CurrentThread.context^.{$ifdef CPU64}rip{$else}eip{$endif}) then begin mark.imageindex:=2; sesource.CaretY:=i+1; hasrip:=true; result:=true; end else hasrip:=false; if (debuggerthread<>nil) and (debuggerthread.isBreakpoint(a)<>nil) then begin //2(bp, no rip), or 3(bp, rip) if hasrip=false then mark.ImageIndex:=2 else mark.ImageIndex:=3; end else begin //0(no rip) or 1(rip) if hasrip=false then mark.ImageIndex:=0 else mark.ImageIndex:=1; end; mark.Visible:=true; seSource.Marks.Add(mark); end; end; end; procedure TfrmSourceDisplay.FormCreate(Sender: TObject); begin SynCppSyn1.loadFromRegistryDefault; seSource.Color:=colorset.TextBackground; seSource.Font.color:=colorset.FontColor; seSource.Gutter.Color:=clBtnFace; seSource.Gutter.LineNumberPart.MarkupInfo.Background:=clBtnFace; seSource.Gutter.SeparatorPart.MarkupInfo.Background:=clBtnFace; seSource.LineHighlightColor.Background:=ColorToRGB(seSource.Color) xor $212121; LoadedPosition:=LoadFormPosition(self); if overridefont<>nil then seSource.Font.size:=overridefont.size else seSource.Font.Size:=10; end; procedure TfrmSourceDisplay.FormDestroy(Sender: TObject); var l: TList; i: integer; begin SaveFormPosition(self); itInfo.AutoEnabled:=false; itInfo.Enabled:=false; itinfo.free; itinfo:=nil; if sourceDisplayForms<>nil then //delete this form from the map sourceDisplayForms.Delete(tag); if d<>nil then freeandnil(d); if stepIntoThread<>nil then //it still has an onhandlebreak set begin //first make sure that the stepIntoThread is still alive if debuggerthread<>nil then begin l:=debuggerthread.lockThreadlist; if l.IndexOf(stepIntoThread)<>-1 then //still alive stepIntoThread.OnHandleBreakAsync:=nil; debuggerthread.unlockThreadlist; end; end; end; procedure TfrmSourceDisplay.FormShow(Sender: TObject); begin if loadedposition=false then begin width:=(Screen.PixelsPerInch div 96)*800; height:=(Screen.PixelsPerInch div 96)*600; end; end; procedure TfrmSourceDisplay.itInfoTimer(Sender: TObject); var p,p2,p3: tpoint; token: string; varinfo: TLocalVariableInfo; address,ptr: ptruint; ln: integer; i: integer; l1,l2: integer; str: string; offsettext: string; value: string; br: ptruint; r: trect; begin //get the token under the mouse cursor and look it up itInfo.Enabled:=false; itInfo.AutoEnabled:=false; if hintwindow<>nil then hintwindow.hide; //if not Active then exit; str:=''; p:=mouse.cursorpos; p2:=seSource.ScreenToClient(p); if (p2.x<0) or (p2.x>sesource.ClientWidth) or (p2.y<0) or (p2.y>sesource.ClientWidth) then exit; if p2.x<seSource.Gutter.Width then exit; //gutter stuff p3:=seSource.PixelsToLogicalPos(p2); token:=sesource.GetWordAtRowCol(p3); if trim(token)='' then exit; if SourceCodeInfo<>nil then begin ln:=p3.y-1; if (debuggerthread<>nil) and (debuggerthread.CurrentThread<>nil) then begin address:=debuggerthread.CurrentThread.context^.{$ifdef cpu64}Rip{$else}eip{$endif}; if SourceCodeInfo.getVariableInfo(token, address, varinfo) then begin address:=debuggerthread.CurrentThread.context^.{$ifdef cpu64}Rbp{$else}ebp{$endif}+varinfo.offset; str:=varinfo.name+' at '+inttohex(address,8); if varinfo.ispointer then begin ptr:=0; if ReadProcessMemory(processhandle, pointer(address), @ptr,processhandler.pointersize,br) then begin address:=ptr; str:=str+'->'+inttohex(address,8); end else begin address:=0; str:=str+'->???'; end; end; if address<>0 then begin value:=''; case varinfo.vartype of 1: value:=readAndParseAddress(address, vtDword,nil,false,true); //integer 2: value:=readAndParseAddress(address,vtByte, nil,false,true); //char {$ifdef windows} 3: value:=readAndParseAddress(address,vtDword, nil,false,true); //long. 4 byte on PE, 8 byte on elf when in 64-bit. {$else} 3: if processhandler.is64Bit then value:=readAndParseAddress(address, vtQword, nil,false,true) else value:=readAndParseAddress(address, vtDword, nil,false,true); {$endif} 4: value:=readAndParseAddress(address, vtDword,nil,false,false); //unsigned integer {$ifdef windows} 5: value:=readAndParseAddress(address,vtDword, nil,false,false); //long unsigned {$else} 5: if processhandler.is64Bit then value:=readAndParseAddress(address, vtQword, nil,false,false) else value:=readAndParseAddress(address, vtDword, nil,false,false); {$endif} 6,8: value:=readAndParseAddress(address,vtQword, nil,false,true); //int64 7,9: value:=readAndParseAddress(address,vtQword, nil,false,false); //uint64 10: value:=readAndParseAddress(address,vtWord, nil,false,true); //signed word 11: value:=readAndParseAddress(address,vtWord, nil,false,false); //unsigned word 12: value:=readAndParseAddress(address,vtByte, nil,false,true); //signed byte 13: value:=readAndParseAddress(address,vtByte, nil,false,false); //unsigned byte 14,17: value:=readAndParseAddress(address,vtSingle, nil,false,false); //float 15,18: value:=readAndParseAddress(address,vtDouble, nil,false,false); //double 16: value:=readAndParseAddress(address,vtDouble, nil,false,false); //meh 25: value:=readAndParseAddress(address,vtByte, nil,false,false); //unsigned char 26: value:=readAndParseAddress(address,vtByte, nil,false,false); //bool 27: value:='<void>'; end; if value<>'' then str:=str+' value='+value; end; end else exit; end else begin address:=ptruint(seSource.Lines.Objects[ln]); //get basic info like the offset and type if address=0 then //look around begin i:=1; while i<25 do begin l1:=ln-i; l2:=ln+i; if (l1>0) and (l1<sesource.lines.count-1) and (ptruint(seSource.Lines.Objects[l1])<>0) then begin address:=ptruint(seSource.Lines.Objects[l1]); break; end; if (l2>0) and (l2<sesource.lines.count-1) and (ptruint(seSource.Lines.Objects[l2])<>0) then begin address:=ptruint(seSource.Lines.Objects[l2]); break; end; inc(i); end; end; if address=0 then exit; if SourceCodeInfo.getVariableInfo(token, address, varinfo) then begin //show basic info if varinfo.offset<0 then offsettext:='-'+IntToHex(-varinfo.offset,2) else offsettext:='+'+IntToHex(varinfo.offset,2); if processhandler.is64Bit then offsettext:='RBP'+offsettext else offsettext:='EBP'+offsettext; str:=varinfo.name+' at '+offsettext; end else exit; end; if str<>'' then begin if hintwindow=nil then hintwindow:=THintWindow.Create(self); r:=hintwindow.CalcHintRect(sesource.width, str, nil); r.Top:=r.top+p.y; r.Left:=r.left+p.x; r.Right:=r.right+p.x; r.Bottom:=r.Bottom+p.y; hintwindow.ActivateHint(r, str); end; end; end; procedure TfrmSourceDisplay.MenuItem1Click(Sender: TObject); begin MemoryBrowser.disassemblerview.SelectedAddress:=ptruint(seSource.Lines.Objects[seSource.CaretY-1]); ; MemoryBrowser.show; end; procedure TfrmSourceDisplay.seSourceGutterClick(Sender: TObject; X, Y, Line: integer; mark: TSynEditMark); var address: ptruint; bp: PBreakpoint; seml: TSynEditMarkLine; i: integer; begin address:=ptruint(seSource.Lines.Objects[line-1]); if address=0 then exit; seml:=seSource.Marks.Line[line]; for i:=0 to seml.count-1 do begin if seml[i].IsBookmark then continue; mark:=seml[i]; end; if (mark<>nil) then begin if mark.ImageIndex in [0,1] then begin //set breakpoint try if startdebuggerifneeded(true) then begin DebuggerThread.SetOnExecuteBreakpoint(address); MemoryBrowser.disassemblerview.Update; updateMarks; end; except on e:exception do MessageDlg(e.message,mtError,[mbok],0); end; end else begin //remove breakpoint if DebuggerThread<>nil then begin debuggerthread.lockbplist; bp:=DebuggerThread.isBreakpoint(address); if bp<>nil then debuggerthread.RemoveBreakpoint(bp); DebuggerThread.unlockbplist; end; updateMarks; end; end; end; procedure TfrmSourceDisplay.seSourceMouseEnter(Sender: TObject); begin itInfo.enabled:=false; itInfo.AutoEnabled:=true; end; procedure TfrmSourceDisplay.seSourceMouseLeave(Sender: TObject); begin itInfo.enabled:=false; itInfo.AutoEnabled:=false; end; procedure TfrmSourceDisplay.seSourceMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin itInfo.Enabled:=false; itInfo.AutoEnabled:=true; if hintwindow<>nil then hintwindow.hide; end; procedure TfrmSourceDisplay.tbRunClick(Sender: TObject); begin MemoryBrowser.miDebugRun.Click; end; procedure TfrmSourceDisplay.tbRunTillClick(Sender: TObject); var address: ptruint; begin address:=ptruint(seSource.Lines.Objects[seSource.CaretY-1]); if address=0 then begin errorbeep; exit; end; if debuggerthread<>nil then begin debuggerthread.ContinueDebugging(co_runtill, address); MemoryBrowser.OnMemoryViewerRunning; end; end; function TfrmSourceDisplay.StepIntoHandler(sender: TDebugThreadHandler; bp: PBreakpoint): boolean; var a: ptruint; sci: TSourceCodeInfo; begin if stepintocountdown>0 then begin if bp<>nil then //nil when single stepping begin //a normal bp got hit, stop the stepping sender.OnHandleBreakAsync:=nil; stepIntoThread:=nil; stepIntoCountdown:=0; exit(false); end; //check if this is a call or ret, if so, set the stepintocountdown to 1 and set stepFinished:=true; if d=nil then d:=TDisassembler.Create; //even though this is async, it's still only 1 single thread, so this is safe a:=sender.context^.{$ifdef cpu64}rip{$else}eip{$endif}; sci:=SourceCodeInfoCollection.getSourceCodeInfo(a); if (sci<>nil) and (sci.getLineInfo(a)<>nil) then begin //found a sourcecode line sender.OnHandleBreakAsync:=nil; stepIntoThread:=nil; stepIntoCountdown:=0; exit(false); //do an actual break end; d.disassemble(a); if d.LastDisassembleData.iscall or d.LastDisassembleData.isret then begin sender.OnHandleBreakAsync:=nil; stepIntoThread:=nil; stepIntoCountdown:=0; //followed by a single step end; dec(stepIntoCountdown); sender.continueDebugging(co_stepinto); exit(true);// handled end else begin sender.OnHandleBreakAsync:=nil; stepIntoThread:=nil; stepIntoCountdown:=0; sender.continueDebugging(co_run); //screw this , abandoning this stepping session exit(true); end; end; procedure TfrmSourceDisplay.tbStepIntoClick(Sender: TObject); begin stepIntoCountdown:=15; stepIntoThread:=debuggerthread.CurrentThread; debuggerthread.CurrentThread.OnHandleBreakAsync:=@StepIntoHandler; debuggerthread.ContinueDebugging(co_stepinto); memorybrowser.OnMemoryViewerRunning; end; procedure TfrmSourceDisplay.tbStepOutClick(Sender: TObject); begin memorybrowser.miDebugExecuteTillReturn.Click; end; procedure TfrmSourceDisplay.tbStepOverClick(Sender: TObject); var i,linestart: integer; currentaddress,nextaddress: ptruint; sci: TSourceCodeInfo; lni, lni2: PLineNumberInfo; begin if (debuggerthread<>nil) and (debuggerthread.CurrentThread<>nil) then begin currentaddress:=debuggerthread.CurrentThread.context^.{$ifdef CPU64}rip{$else}eip{$endif}; sci:=SourceCodeInfoCollection.getSourceCodeInfo(currentaddress); if sci<>nil then begin lni:=sci.getLineInfo(currentaddress); if lni<>nil then begin linestart:=lni^.sourcefile.IndexOfObject(tobject(currentaddress)); if linestart=-1 then exit; //never nextaddress:=0; for i:=linestart+1 to lni^.sourcefile.Count-1 do begin nextaddress:=ptruint(sesource.lines.Objects[i]); if nextaddress<>0 then begin lni2:=sci.getLineInfo(nextaddress); if lni2<>nil then //never begin if lni^.functionaddress<>lni2^.functionaddress then break; //different function. So return debuggerthread.ContinueDebugging(co_runtill, nextaddress); memorybrowser.OnMemoryViewerRunning; exit; end; //still here, so not possible to do a step over break; end; end; end; //still here, so no next address, do a step tbStepIntoClick(tbStepInto); end; end; end; procedure TfrmSourceDisplay.tbToggleBreakpointClick(Sender: TObject); begin seSourceGutterClick(seSource,0,0,seSource.CaretY,nil); end; initialization {$I frmsourcedisplayunit.lrs} end.
unit BaseGrid; interface uses syForm, cxSchedulerCustomControls, cxSchedulerStorage, cxGridDBTableView, AstaClientDataset, rsStorage, rsXmlData, Classes; type TpCercaReferto = (tpcrTrovato, tpcrNonTrovato, tpcrStorico, tpcrFiltrato); TFBaseGrid = class(TsyForm) rsStorage1: TrsStorage; rsXMLData1: TrsXMLData; private { Private declarations } protected FCustomized: Boolean; procedure InsertOperazione(md,dd: TcxGridDBTableView; pk: Integer; pdett: boolean; xRefreshDettagli: TAstaClientDataSet); overload; virtual; procedure InsertOperazione(md,dd: TcxGridDBTableView; pk: Integer); overload; virtual; procedure DeleteOperazione(md,dd: TcxGridDBTableView; pk: Integer; pdett: boolean); overload; virtual; procedure DeleteOperazione(md,dd: TcxGridDBTableView; pk: Integer); overload; virtual; procedure RefreshOperazione(md,dd: TcxGridDBTableView; pk: Integer; pdett: boolean; xRefreshDettagli: TAstaClientDataSet); overload; virtual; procedure RefreshOperazione(md,dd: TcxGridDBTableView; pk: Integer); overload; virtual; function CercaReferto: TpCercaReferto; virtual; procedure rsXMLData1LoadFromStream(Sender: TObject; Stream: TStream; var DoStandard: Boolean); procedure rsXMLData1SaveToStream(Sender: TObject; Stream: TStream; var DoStandard: Boolean); procedure Loaded; override; public { Public declarations } function GetResourceByResourceID(AScheduler: TcxCustomScheduler; AResourceID: Variant): TcxSchedulerStorageResourceItem; procedure SendPortDataToForm(const s: string; lungh: integer); override; end; var FBaseGrid: TFBaseGrid; implementation uses cxVariants, AstaDBTypes, DMCommon; {$R *.dfm} function TFBaseGrid.CercaReferto: TpCercaReferto; begin result := tpcrNonTrovato; end; procedure TFBaseGrid.SendPortDataToForm(const s: string; lungh: integer); begin end; function TFBaseGrid.GetResourceByResourceID(AScheduler: TcxCustomScheduler; AResourceID: Variant): TcxSchedulerStorageResourceItem; var I: Integer; begin Result := nil; if AScheduler.Storage = nil then Exit; with AScheduler.Storage do for I := 0 to ResourceCount - 1 do if VarEquals(Resources.ResourceItems[I].ResourceID, AResourceID) then begin Result := Resources.ResourceItems[I]; Break; end; end; procedure TFBaseGrid.InsertOperazione(md,dd: TcxGridDBTableView; pk: Integer); begin InsertOperazione(md,dd,pk,false,nil); end; procedure TFBaseGrid.InsertOperazione(md,dd: TcxGridDBTableView; pk: Integer; pdett: boolean; xRefreshDettagli: TAstaClientDataSet); var TempMs: TAstaUpdateMethod; TempDt: TAstaUpdateMethod; ms,dt: TAstaClientDataSet; begin md.DataController.BeginFullUpdate; dd.DataController.BeginFullUpdate; ms := TAstaClientDataSet(md.DataController.DataSet); dt := TAstaClientDataSet(dd.DataController.DataSet); ms.DisableControls; dt.DisableControls; TempMs := ms.UpdateMethod; TempDt := dt.UpdateMethod; ms.UpdateMethod := umManual; dt.UpdateMethod := umManual; try ms.InsertRefresh(pk); if pdett then begin // xRefreshDettagli.Parambyname('TRIAGE_FK').AsInteger := pk; xRefreshDettagli.Params[0].AsInteger := pk; xRefreshDettagli.syRefresh; dt.DataTransfer(xRefreshDettagli,true,true); end; finally ms.UpdateMethod := TempMs; dt.UpdateMethod := TempDt; dt.EnableControls; ms.EnableControls; md.DataController.EndFullUpdate; dd.DataController.EndFullUpdate; end; end; procedure TFBaseGrid.DeleteOperazione(md,dd: TcxGridDBTableView; pk: Integer); begin DeleteOperazione(md,dd,pk,false); end; procedure TFBaseGrid.DeleteOperazione(md,dd: TcxGridDBTableView; pk: Integer; pdett: boolean); var TempMs: TAstaUpdateMethod; TempDt: TAstaUpdateMethod; ms,dt: TAstaClientDataSet; begin ms := TAstaClientDataSet(md.DataController.DataSet); dt := TAstaClientDataSet(dd.DataController.DataSet); if not ms.IsEmpty then begin md.DataController.BeginFullUpdate; dd.DataController.BeginFullUpdate; ms.DisableControls; dt.DisableControls; try TempMs := ms.UpdateMethod; TempDt := dt.UpdateMethod; ms.UpdateMethod := umManual; dt.UpdateMethod := umManual; try if pdett then begin dt.CancelRange; dt.SetRange([pk],[pk]); while not dt.IsEmpty do dt.Delete; dt.CancelRange; end; ms.Delete; finally ms.UpdateMethod := TempMs; dt.UpdateMethod := TempDt; end; finally dt.EnableControls; ms.EnableControls; md.DataController.EndFullUpdate; dd.DataController.EndFullUpdate; end; end; end; procedure TFBaseGrid.RefreshOperazione(md,dd: TcxGridDBTableView; pk: Integer); begin RefreshOperazione(md,dd,pk,false,nil); end; procedure TFBaseGrid.RefreshOperazione(md,dd: TcxGridDBTableView; pk: Integer; pdett: boolean; xRefreshDettagli: TAstaClientDataSet); var ms,dt: TAstaClientDataSet; begin md.DataController.BeginFullUpdate; dd.DataController.BeginFullUpdate; ms := TAstaClientDataSet(md.DataController.DataSet); dt := TAstaClientDataSet(dd.DataController.DataSet); ms.DisableControls; dt.DisableControls; try ms.RefreshRecord; if pdett then begin dt.CancelRange; dt.SetRange([pk],[pk]); while not dt.IsEmpty do dt.Delete; xRefreshDettagli.Params[0].AsInteger := pk; xRefreshDettagli.syRefresh; dt.DataTransfer(xRefreshDettagli,true,true); dt.CancelRange; end; finally dt.EnableControls; ms.EnableControls; md.DataController.EndFullUpdate; dd.DataController.EndFullUpdate; end; end; procedure TFBaseGrid.rsXMLData1LoadFromStream(Sender: TObject; Stream: TStream; var DoStandard: Boolean); begin FDMCommon.CaricaLayout(Name,Stream); DoStandard := false; end; procedure TFBaseGrid.rsXMLData1SaveToStream(Sender: TObject; Stream: TStream; var DoStandard: Boolean); begin FDMCommon.SalvaPersonalizza(Name, Stream, gblCodUtente); DoStandard := false; end; procedure TFBaseGrid.Loaded; begin inherited; rsStorage1.rootSection := Name; rsXMLData1.OnLoadFromStream := rsXMLData1LoadFromStream; rsXMLData1.OnSaveToStream := rsXMLData1SaveToStream; end; end.
unit dbview; {* Temporary window for displaying the contents of the database *} {$O+,D-} interface uses Overlay, Objects, Drivers, Views, Menus, App, expconst; type PDbViewer = ^TDbViewer; TDbViewer = object(TWindow) constructor Init(Bounds: TRect; WinTitle: String; WindowNo: Word; DataBaseData : DbDataType; Num : Integer); procedure HandleEvent(var Event : TEvent); virtual; end; PInterior = ^TInterior; TInterior = object(TView) DbData : DbDataType; DbItemNum : Integer; constructor Init(var Bounds: TRect); procedure Draw; virtual; procedure HandleEvent(var Event : TEvent); virtual; end; implementation { TInterior } constructor TInterior.Init(var Bounds: TRect); begin TView.Init(Bounds); GrowMode := gfGrowHiX + gfGrowHiY; Options := Options or ofFramed; end; procedure TInterior.HandleEvent(var Event : TEvent); begin TView.HandleEvent(Event); if (Event.What = evBroadcast) and (Event.Command = cmDummy) then ClearEvent(Event); end; procedure TInterior.Draw; var Color: Byte; X: Integer; B: TDrawBuffer; begin TView.Draw; Color := 2; for X := 0 to DbItemNum-1 do begin WriteStr(1, X, 'Identifier ', Color); WriteStr(12, X, DbData[X].Identifier, Color); WriteStr(30, X, 'Value ', Color); WriteStr(36, X, DbData[X].Value, Color); end; end; { TDemoWindow } constructor TDbViewer.Init(Bounds: TRect; WinTitle: String; WindowNo: Word; DataBaseData : DbDataType; Num : Integer); var S: string[3]; Interior: PInterior; begin Str(WindowNo, S); TWindow.Init(Bounds, 'DataBase Viewer', wnNoNumber); GetClipRect(Bounds); Bounds.Grow(-1, -1); Interior := New(PInterior, Init(Bounds)); Interior^.DbData := DataBaseData; Interior^.DbItemNum := Num; Insert(Interior); end; procedure TDbViewer.HandleEvent(var Event : TEvent); begin TWindow.HandleEvent(Event); if (Event.What = evBroadcast) and (Event.Command = cmDummy) then ClearEvent(Event); end; end. { dbview }
unit IocpDsServer; {$define __IOCP_DATASNAP__} interface uses {$ifdef __IOCP_DATASNAP__} Iocp.DSHTTPWebBroker {$else} IdHTTPWebBrokerBridge {$endif}; type TDataSnapServer = class private {$ifdef __IOCP_DATASNAP__} class var FServer: TIocpWebBrokerBridge; {$else} class var FServer: TIdHTTPWebBrokerBridge; {$endif} class function GetActive: Boolean; static; class procedure SetActive(const Value: Boolean); static; public class procedure StartServer(Port: Word); class procedure StopServer; class property Active: Boolean read GetActive write SetActive; end; implementation uses Datasnap.DSSession; { TDataSnapServer } class function TDataSnapServer.GetActive: Boolean; begin Result := FServer.Active; end; class procedure TDataSnapServer.SetActive(const Value: Boolean); begin FServer.Active := Value; end; class procedure TDataSnapServer.StartServer(Port: Word); begin if not FServer.Active then begin {$ifdef __IOCP_DATASNAP__} FServer.Port := Port; {$else} FServer.Bindings.Clear; FServer.DefaultPort := Port; {$endif} FServer.Active := True; end; end; class procedure TDataSnapServer.StopServer; begin if (TDSSessionManager.Instance <> nil) then TDSSessionManager.Instance.TerminateAllSessions; if FServer.Active then begin FServer.Active := False; end; end; initialization {$ifdef __IOCP_DATASNAP__} TDataSnapServer.FServer := TIocpWebBrokerBridge.Create(nil); {$else} TDataSnapServer.FServer := TIdHTTPWebBrokerBridge.Create(nil); {$endif} finalization TDataSnapServer.FServer.Free; end.
function fac(n:integer):longint; begin if n=0 then fac:=1 else fac:=n*fac(n-1); end; var k:integer; begin writeln('Enter number '); readln(k); writeln('Factorial from ',k,' is ',fac(k)); end.
unit ServerSentEvent; interface type HCkString = Pointer; HCkServerSentEvent = Pointer; function CkServerSentEvent_Create: HCkServerSentEvent; stdcall; procedure CkServerSentEvent_Dispose(handle: HCkServerSentEvent); stdcall; procedure CkServerSentEvent_getData(objHandle: HCkServerSentEvent; outPropVal: HCkString); stdcall; function CkServerSentEvent__data(objHandle: HCkServerSentEvent): PWideChar; stdcall; procedure CkServerSentEvent_getEventName(objHandle: HCkServerSentEvent; outPropVal: HCkString); stdcall; function CkServerSentEvent__eventName(objHandle: HCkServerSentEvent): PWideChar; stdcall; procedure CkServerSentEvent_getLastEventId(objHandle: HCkServerSentEvent; outPropVal: HCkString); stdcall; function CkServerSentEvent__lastEventId(objHandle: HCkServerSentEvent): PWideChar; stdcall; function CkServerSentEvent_getLastMethodSuccess(objHandle: HCkServerSentEvent): wordbool; stdcall; procedure CkServerSentEvent_putLastMethodSuccess(objHandle: HCkServerSentEvent; newPropVal: wordbool); stdcall; function CkServerSentEvent_getRetry(objHandle: HCkServerSentEvent): Integer; stdcall; function CkServerSentEvent_LoadEvent(objHandle: HCkServerSentEvent; eventText: PWideChar): wordbool; stdcall; implementation {$Include chilkatDllPath.inc} function CkServerSentEvent_Create; external DLLName; procedure CkServerSentEvent_Dispose; external DLLName; procedure CkServerSentEvent_getData; external DLLName; function CkServerSentEvent__data; external DLLName; procedure CkServerSentEvent_getEventName; external DLLName; function CkServerSentEvent__eventName; external DLLName; procedure CkServerSentEvent_getLastEventId; external DLLName; function CkServerSentEvent__lastEventId; external DLLName; function CkServerSentEvent_getLastMethodSuccess; external DLLName; procedure CkServerSentEvent_putLastMethodSuccess; external DLLName; function CkServerSentEvent_getRetry; external DLLName; function CkServerSentEvent_LoadEvent; external DLLName; end.
unit List_EventServiceItem; interface {$I InfraCommon.Inc} uses {$IFDEF USE_GXDEBUG}DBugIntf, {$ENDIF} Contnrs, InfraCommonIntf, InfraCommon; type {.$DEFINE EQUAL_INDEX_DEFAULT Implementing Here} {$DEFINE EQUAL_VALUE_DEFAULT} {.$DEFINE INVALID_INDEX_DEFAULT Implementing Here} {$DEFINE INVALID_VALUE_DEFAULT} _ITERABLELIST_BASE_ = TBaseElement;// List's Class Base _ITERABLELIST_INTF_ = IInfraEventServiceItems; // List's Interface Implementing _ITERATOR_INTF_ = IInterface; // List's Interface Implementing _INDEX_ = TGUID; // List's Item Index ===>>> TGUID _VALUE_ = IInfraEventServiceItem; // List's Item Valeu {$I ..\Templates\InfraTempl_ListDynIndex.inc} function IsIndexEqual(Index1, Index2: _INDEX_): boolean; function InvalidIndex: _INDEX_; end; TInfraEventServiceItems = class(_ITERABLELIST_); implementation uses SysUtils, InfraConsts; { TInfraEventServiceItems } {$I ..\Templates\InfraTempl_ListDynIndex.inc} function _ITERABLELIST_.IsIndexEqual(Index1, Index2: _INDEX_): boolean; begin Result := IsEqualGUID(Index1, Index2); end; function _ITERABLELIST_.InvalidIndex: _INDEX_; begin Result := NullGuid; end; destructor _ITERABLELIST_.Destroy; begin FreeAndNil(FItems); inherited; end; end.
unit uMRGroupReport; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, uModApp, uUnit; type TModMRGroupReport = class; TModMRItemReport = class(TModApp) private FGroupReport: TModMRGroupReport; FKode: string; FNama: string; FUnitUsaha: TModUnit; protected public class function GetTableName: string; override; published [AttributeOfForeign] property GroupReport: TModMRGroupReport read FGroupReport write FGroupReport; property Kode: string read FKode write FKode; property Nama: string read FNama write FNama; [AttributeOfForeign] property UnitUsaha: TModUnit read FUnitUsaha write FUnitUsaha; end; TModMRGroupReport = class(TModApp) private FKode: string; FNama: string; public class function GetTableName: string; override; published [AttributeOfCode] property Kode: string read FKode write FKode; property Nama: string read FNama write FNama; end; implementation { TModMRGroupReport } { ****************************************************** TModMRGroupReport ****************************************************** } class function TModMRGroupReport.GetTableName: string; begin Result := 'TMRGroupReport'; end; { TModMRItemReport } { ****************************************************** TModMRItemReport ****************************************************** } class function TModMRItemReport.GetTableName: string; begin Result := 'TMRItemReport'; end; initialization TModMRGroupReport.RegisterRTTI; TModMRItemReport.RegisterRTTI; end.
unit SimpleLogTextFormat; {$mode objfpc}{$H+} interface uses Classes, SysUtils, StringFeatures, LogItem, LogFormat, LogTextFormat; type { TSimpleTextLogFormat } TSimpleTextLogFormat = class(TComponent, ILogTextFormat) public constructor Create(const aOwner: TComponent); reintroduce; public type TTimeToStr = function(ADate: TDateTime): string; public const NumberHere = 'NUMBER'; TimeHere = 'TIME'; TagHere = 'TAG'; ObjectHere = 'OBJECT'; TextHere = 'TEXT'; LineEndingHere = '\n'; DefaultFormat = 'NUMBER # TIME [TAG]\nOBJECT: TEXT'; DefaultZeroLength = 6; private FFormatStr: string; FTimeToStr: TTimeToStr; FZeroLength: integer; protected procedure Initialize; procedure Replace(var AText: string; const AOldPattern, ANewPattern: string); public property TimeToStr: TTimeToStr read FTimeToStr write FTimeToStr; function DefaultTimeToStr: TTimeToStr; property FormatStr: string read FFormatStr write FFormatStr; property ZeroLength: integer read FZeroLength write FZeroLength; function Format(const aItem: PLogItem): string; end; implementation { TSimpleTextLogFormat } constructor TSimpleTextLogFormat.Create(const aOwner: TComponent); begin inherited Create(aOwner); Initialize; end; procedure TSimpleTextLogFormat.Initialize; begin FormatStr := DefaultFormat; TimeToStr := DefaultTimeToStr; ZeroLength := DefaultZeroLength; end; procedure TSimpleTextLogFormat.Replace(var AText: string; const AOldPattern, ANewPattern: string); begin AText := StringReplace(AText, AOldPattern, ANewPattern, [rfReplaceAll]); end; function TSimpleTextLogFormat.DefaultTimeToStr: TTimeToStr; begin result := @SysUtils.DateTimeToStr; end; function TSimpleTextLogFormat.Format(const aItem: PLogItem): string; begin result := FormatStr; Replace(result, LineEndingHere, LineEnding); Replace(result, NumberHere, ZeroToStr(aItem^.Number, ZeroLength)); if pos(TimeHere, result) > 0 then begin if TimeToStr = nil then raise ELogFormat.Create('Can not format message: no TimeToStr function'); Replace(result, TimeHere, self.TimeToStr(aItem^.Time)); end; Replace(result, TagHere, aItem^.Tag); Replace(result, ObjectHere, aItem^.ObjectName); Replace(result, TextHere, aItem^.Text); end; end.
(* Copyright 2016 Michael Justin 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 SimpleLoggerTests; interface uses {$IFDEF FPC} fpcunit,testregistry {$ELSE} TestFramework {$ENDIF}; type { TSimpleLoggerTests } TSimpleLoggerTests = class(TTestCase) published procedure CreateLogger; procedure TestConfig; procedure TestConfigShowDateTime; procedure TestDebug; procedure TestInfo; end; implementation uses djLogAPI, SimpleLogger, Classes, SysUtils; { TSimpleLoggerTests } procedure TSimpleLoggerTests.CreateLogger; var LoggerFactory: ILoggerFactory; Logger: ILogger; begin LoggerFactory := TSimpleLoggerFactory.Create; Logger := LoggerFactory.GetLogger('simple'); CheckEquals('simple', Logger.Name); end; procedure TSimpleLoggerTests.TestConfig; var S: TStrings; LoggerFactory: ILoggerFactory; Logger: ILogger; begin LoggerFactory := TSimpleLoggerFactory.Create; // configure with TStrings S := TStringList.Create; try S.Values['defaultLogLevel'] := 'debug'; SimpleLogger.Configure(S); finally S.Free; end; Logger := LoggerFactory.GetLogger('simple'); CheckFalse(Logger.IsTraceEnabled, 'trace'); CheckTrue(Logger.IsDebugEnabled, 'debug'); CheckTrue(Logger.IsInfoEnabled, 'info'); CheckTrue(Logger.IsWarnEnabled, 'warn'); CheckTrue(Logger.IsErrorEnabled, 'error'); // configure key-value pair SimpleLogger.Configure('defaultLogLevel', 'info'); Logger := LoggerFactory.GetLogger('simple'); CheckFalse(Logger.IsTraceEnabled, 'trace 2'); CheckFalse(Logger.IsDebugEnabled, 'debug 2'); CheckTrue(Logger.IsInfoEnabled, 'info 2'); CheckTrue(Logger.IsWarnEnabled, 'warn 2'); CheckTrue(Logger.IsErrorEnabled, 'error 2'); end; procedure TSimpleLoggerTests.TestConfigShowDateTime; var LoggerFactory: ILoggerFactory; Logger: ILogger; begin SimpleLogger.Configure('showDateTime', 'true'); // SimpleLogger.Configure('dateTimeFormat', 'hh:nn:ss.zzz'); LoggerFactory := TSimpleLoggerFactory.Create; Logger := LoggerFactory.GetLogger('dateTime on'); Logger.Info('testShowDateTime 1'); SimpleLogger.Configure('showDateTime', 'false'); Logger := LoggerFactory.GetLogger('dateTime off'); Logger.Info('testShowDateTime 2'); end; procedure TSimpleLoggerTests.TestDebug; var LoggerFactory: ILoggerFactory; Logger: ILogger; E: EAbort; begin LoggerFactory := TSimpleLoggerFactory.Create; SimpleLogger.Configure('defaultLogLevel', 'debug'); Logger := LoggerFactory.GetLogger('simple'); Logger.Trace('simple trace msg'); Logger.Debug('simple debug msg'); Logger.Info('simple info msg'); E := EAbort.Create('simple example exception'); Logger.Debug('simple msg', E); E.Free; end; procedure TSimpleLoggerTests.TestInfo; var LoggerFactory: ILoggerFactory; Logger: ILogger; E: EAbort; begin LoggerFactory := TSimpleLoggerFactory.Create; SimpleLogger.Configure('defaultLogLevel', 'info'); Logger := LoggerFactory.GetLogger('simple'); Logger.Trace('simple trace msg'); Logger.Debug('simple debug msg'); Logger.Info('simple info msg'); E := EAbort.Create('simple example exception'); Logger.Info('simple msg', E); E.Free; end; end.
unit test_state; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testutils, testregistry, state; type { TStateTester } TStateTester= class(TTestCase) protected AState : TState; procedure SetUp; override; procedure TearDown; override; published procedure TestHookUp; procedure TestSetName; end; implementation procedure TStateTester.TestHookUp; begin Fail('Write your own test'); end; procedure TStateTester.TestSetName; begin AState.Name := 'Test State Name'; AssertEquals('Test State Name', AState.Name); end; procedure TStateTester.SetUp; begin AState := TState.Create; end; procedure TStateTester.TearDown; begin FreeAndNil(AState); end; initialization RegisterTest(TStateTester); end.
unit USplitBibleVerses; interface uses Classes, SysUtils, UUtilsStrings, USlideLayout; type TSplitOption = (soNumbers, soLineBreaks); TSplitOptions = set of TSplitOption; function SplitBibleVerses(strLine: String; iMaxLineLength: integer; content: TLayoutItem; splitOptions: TSplitOptions): TArrayOfString; implementation uses RegExpr; function SplitBibleVerses(strLine: String; iMaxLineLength: integer; content: TLayoutItem; splitOptions: TSplitOptions): TArrayOfString; var iBestFind: integer; function MatchRegex(strLine, strRegEx: string; iMaxLineLength: integer): integer; var iOccurences, i: integer; regex: TRegExpr; begin Result := -1; iOccurences := 0; regex := TRegExpr.Create; try regex.ModifierM := True; regex.Expression := strRegEx; if regex.Exec(strLine) then begin repeat if regex.MatchPos[0] < iMaxLineLength then begin Result := regex.MatchPos[0]; end else break; until not regex.ExecNext; end; finally regex.Free; end; end; function GetBestFind(strLine: string; iMaxLineLength: integer; content: TLayoutItem): integer; var iTextMaxLineLength, iNextBreak, iNextBestBreak: integer; begin iTextMaxLineLength := iMaxLineLength; Result := -1; while (iTextMaxLineLength > 100) and (Result = -1) do begin // does it fit anyway? if (Length(strLine) < iTextMaxLineLength) then begin if content.TextFit(strLine) then begin Result := -1; Exit; end; end; // first only find the max line length if Assigned(content) then begin while (iTextMaxLineLength > 100) do begin if not content.TextFit(copy(strLine, 1, iTextMaxLineLength)) then begin dec(iTextMaxLineLength, 10); end else break; end; end; iNextBestBreak := -1; // empty line wins iNextBreak := MatchRegex(strLine, '(\r\n){2,}', iTextMaxLineLength); if iNextBreak <> -1 then begin if iNextBestBreak < iNextBreak then iNextBestBreak := iNextBreak; if (iNextBreak / iTextMaxLineLength > 0.5) then Result := iNextBreak; end; if soNumbers in splitOptions then begin if Result = -1 then begin iNextBreak := MatchRegex(strLine, '\d+', iTextMaxLineLength); if iNextBreak <> -1 then begin if iNextBestBreak < iNextBreak then iNextBestBreak := iNextBreak; if (iNextBreak / iTextMaxLineLength > 0.6) then Result := iNextBreak; end; end; end; if soLineBreaks in splitOptions then begin if Result = -1 then begin iNextBreak := MatchRegex(strLine, '\r\n+', iTextMaxLineLength); if iNextBreak <> -1 then begin if iNextBestBreak < iNextBreak then iNextBestBreak := iNextBreak; if (iNextBreak / iTextMaxLineLength > 0.7) then Result := iNextBreak; end; end; end; if Result = -1 then begin iNextBreak := MatchRegex(strLine, '\w+', iTextMaxLineLength); if iNextBreak <> -1 then begin if iNextBestBreak < iNextBreak then iNextBestBreak := iNextBreak; end; end; if Result = -1 then begin if iNextBestBreak > 0 then Result := iNextBestBreak; end; // does the result fit in content? if Assigned(content) and (Result <> -1) then begin if not content.TextFit(copy(strLine, 1, Result-1)) then begin iTextMaxLineLength := Result -1; Result := -1; end; end else begin // never loop with less space Exit; end; end; end; begin SetLength(Result, 0); while Length(strLine) > 0 do begin iBestFind := GetBestFind(strLine, iMaxLineLength, content); if iBestFind = -1 then begin break; end; SetLength(Result, Length(Result) + 1); Result[High(Result)] := copy(strLine, 1, iBestFind-1); strLine := trim(copy(strLine, iBestFind, MaxInt)); end; // add all that was left SetLength(Result, Length(Result) + 1); Result[High(Result)] := copy(strLine, 1, MaxInt); end; end.
unit Minerva.Treinamento.Generic; interface type TClasseGenerica<T> = class private FCodigo: integer; FDescricao: string; FObjeto: T; published property Codigo: integer read FCodigo write FCodigo; property Descricao: string read FDescricao write FDescricao; property Objeto: T read FObjeto write FObjeto; end; TUtils = class class function IIf<T>(pCondicao: Boolean; T1,T2:T):T; end; implementation { TUtils } class function TUtils.IIf<T>(pCondicao: Boolean; T1, T2: T): T; begin if pCondicao then Result := T1 else Result := T2; end; end.
unit Dao.Persistencia; interface uses Rtti, StrUtils, System.Variants, Classes, System.SysUtils, Vcl.Forms, System.TypInfo, Data.DB, Dao.DB, Dao.Atributo, FireDAC.Comp.Client, FireDAC.VCLUI.Wait, FireDAC.DApt; type TPersistencia = class strict private FSQL: string; function GetNomedaTabela: string; function GetCampoChavePrimaria: string; public property SQL: string read FSQL write FSQL; property NomedaTabela: string read GetNomedaTabela; property NomeCampoChavePrimaria: string read GetCampoChavePrimaria; function Inserir: Boolean; virtual; function Alterar: Boolean; virtual; function Excluir: Boolean; virtual; function Carregar(const AValor: Int64): Boolean; overload; virtual; abstract; function Carregar: Boolean; overload; end; implementation function TPersistencia.Alterar: Boolean; var AContexto: TRttiContext; ATipo: TRttiType; APropriedade: TRttiProperty; AAtributo: TCustomAttribute; ANomeTabela, ACampo, ASql, AWhere: string; Parametros, ParametrosPK: array of TParametroQuery; Parametro, ParametroPK: TParametroQuery; QueryTmp: TFDQuery; begin Result := False; ACampo := NullAsStringValue; setLength(Parametros,0); setLength(ParametrosPK,0); AContexto := TRttiContext.Create; try ATipo := AContexto.GetType(ClassType); for AAtributo in ATipo.GetAttributes do begin if AAtributo is Tabela then begin ANomeTabela := Tabela(AAtributo).Nome; Break; end; end; for APropriedade in ATipo.GetProperties do begin for AAtributo in APropriedade.GetAttributes do begin if AAtributo is Campo then begin ACampo := ACampo + ' ' + Campo(AAtributo).Nome + ',' + sLineBreak; if APropriedade.GetValue(Self).AsVariant <> Null then begin if (Campo(AAtributo).ChavePrimaria) then begin SetLength(ParametrosPK, Length(ParametrosPK)+1); ParametrosPK[high(ParametrosPK)].Name := Campo(AAtributo).Nome; ParametrosPK[high(ParametrosPK)].Value := APropriedade.GetValue(Self).AsVariant; end else begin SetLength(Parametros, Length(Parametros)+1); Parametros[high(Parametros)].Name := Campo(AAtributo).Nome; Parametros[high(Parametros)].Value := APropriedade.GetValue(Self).AsVariant; end; end end; end; end; AWhere := NullAsStringValue; for ParametroPK in ParametrosPK do begin if AWhere = NullAsStringValue then AWhere := AWhere + 'WHERE ' else AWhere := AWhere + ' AND '; AWhere := AWhere + '(' + ParametroPK.Name + ' = :' + ParametroPK.Name + ')'; end; ACampo := Trim(ACampo); ACampo := Copy(ACampo, 1, ACampo.Length - 1); ASql := 'SELECT ' + ACampo + sLineBreak + ' FROM ' + ANomeTabela + sLineBreak + ' ' + AWhere; QueryTmp := TConexao.GetInstancia.CriaQuery(ASql, ParametrosPK); try QueryTmp.Edit; for Parametro in Parametros do begin if VarToStrDef(Parametro.Value,NullAsStringValue) = NullAsStringValue then QueryTmp.FieldByName(Parametro.Name).Clear else if QueryTmp.FieldByName(Parametro.Name) is TBlobField then raise Exception.Create('Implementar Persistencia TBlobField') //TBlobField(QueryTmp.FieldByName(Parametro.Name)).LoadFromStream(Parametro.Value) else QueryTmp.FieldByName(Parametro.Name).Value := Parametro.Value; end; QueryTmp.Post; for APropriedade in ATipo.GetProperties do begin for AAtributo in APropriedade.GetAttributes do begin if (AAtributo is Campo) then APropriedade.SetValue(Self, Tvalue.FromVariant(QueryTmp.FieldByName(Campo(AAtributo).Nome).Value)); end; end; QueryTmp.Close; Result := True; finally FreeAndNil(QueryTmp); end; finally AContexto.Free; end; end; function TPersistencia.Carregar: Boolean; var AContexto: TRttiContext; ATipo: TRttiType; APropriedade: TRttiProperty; AAtributo: TCustomAttribute; ANomeTabela, AWhere, ACampo, ASql: string; ParametrosPK: array of TParametroQuery; ParametroPK: TParametroQuery; QueryTmp: TFDQuery; begin Result := False; setLength(ParametrosPK,0); AContexto := TRttiContext.Create; try ATipo := AContexto.GetType(ClassType); for AAtributo in ATipo.GetAttributes do begin if AAtributo is Tabela then begin ANomeTabela := Tabela(AAtributo).Nome; Break; end; end; for APropriedade in ATipo.GetProperties do begin for AAtributo in APropriedade.GetAttributes do begin if AAtributo is Campo then begin ACampo := ACampo + ' ' + Campo(AAtributo).Nome + ',' + sLineBreak; if APropriedade.GetValue(Self).AsVariant <> Null then begin if (Campo(AAtributo).ChavePrimaria) then begin SetLength(ParametrosPK, Length(ParametrosPK)+1); ParametrosPK[high(ParametrosPK)].Name := Campo(AAtributo).Nome; ParametrosPK[high(ParametrosPK)].Value := APropriedade.GetValue(Self).AsVariant; end end end; end; end; AWhere := NullAsStringValue; for ParametroPK in ParametrosPK do begin if AWhere = NullAsStringValue then AWhere := AWhere + 'WHERE ' else AWhere := AWhere + ' AND '; AWhere := AWhere + '(' + ParametroPK.Name + ' = :' + ParametroPK.Name + ')'; end; ACampo := Trim(ACampo); ACampo := Copy(ACampo, 1, ACampo.Length - 1); ASql := 'SELECT ' + ACampo + sLineBreak + ' FROM ' + ANomeTabela + sLineBreak + ' ' + AWhere; QueryTmp := TConexao.GetInstancia.CriaQuery(ASql, ParametrosPK); try for APropriedade in ATipo.GetProperties do begin for AAtributo in APropriedade.GetAttributes do begin if (AAtributo is Campo) then APropriedade.SetValue(Self, Tvalue.FromVariant(QueryTmp.FieldByName(Campo(AAtributo).Nome).Value)); end; end; QueryTmp.Close; Result := True; finally FreeAndNil(QueryTmp); end; finally QueryTmp.Free; AContexto.Free; end; end; function TPersistencia.Excluir: Boolean; var AContexto: TRttiContext; ATipo: TRttiType; APropriedade: TRttiProperty; AAtributo: TCustomAttribute; ANomeTabela, ACampo, AWhere, ASql: string; ParametrosPK: array of TParametroQuery; ParametroPK: TParametroQuery; QueryTmp: TFDQuery; begin Result := False; setLength(ParametrosPK,0); AContexto := TRttiContext.Create; try ATipo := AContexto.GetType(ClassType); for AAtributo in ATipo.GetAttributes do begin if AAtributo is Tabela then begin ANomeTabela := Tabela(AAtributo).Nome; Break; end; end; for APropriedade in ATipo.GetProperties do begin for AAtributo in APropriedade.GetAttributes do begin if AAtributo is Campo then begin if APropriedade.GetValue(Self).AsVariant <> Null then begin if (Campo(AAtributo).ChavePrimaria) then begin ACampo := ACampo + ' ' + Campo(AAtributo).Nome + ',' + sLineBreak; SetLength(ParametrosPK, Length(ParametrosPK)+1); ParametrosPK[high(ParametrosPK)].Name := Campo(AAtributo).Nome; ParametrosPK[high(ParametrosPK)].Value := APropriedade.GetValue(Self).AsVariant; end end end; end; end; AWhere := NullAsStringValue; for ParametroPK in ParametrosPK do begin if AWhere = NullAsStringValue then AWhere := AWhere + 'WHERE ' else AWhere := AWhere + ' AND '; AWhere := AWhere + '(' + ParametroPK.Name + ' = :' + ParametroPK.Name + ')'; end; ACampo := Trim(ACampo); ACampo := Copy(ACampo, 1, ACampo.Length - 1); ASql := 'SELECT ' + ACampo + sLineBreak + ' FROM ' + ANomeTabela + sLineBreak + ' ' + AWhere; QueryTmp := TConexao.GetInstancia.CriaQuery(ASql, ParametrosPK); try QueryTmp.Delete; for APropriedade in ATipo.GetProperties do begin for AAtributo in APropriedade.GetAttributes do begin if (AAtributo is Campo) then APropriedade.SetValue(Self, Tvalue.FromVariant(Null)); end; end; QueryTmp.Close; Result := True; finally FreeAndNil(QueryTmp); end; finally AContexto.Free; end; end; function TPersistencia.GetCampoChavePrimaria: string; var AContexto: TRttiContext; ATipo: TRttiType; APropriedade: TRttiProperty; AAtributo: TCustomAttribute; begin Result := NullAsStringValue; AContexto := TRttiContext.Create; try ATipo := AContexto.GetType(ClassType); for APropriedade in ATipo.GetProperties do begin for AAtributo in APropriedade.GetAttributes do begin if AAtributo is Campo then begin if Campo(AAtributo).ChavePrimaria then Result := Campo(AAtributo).Nome; end; end; end; finally AContexto.Free; end; end; function TPersistencia.GetNomedaTabela: string; var AContexto: TRttiContext; ATipo: TRttiType; AAtributo: TCustomAttribute; begin Result := NullAsStringValue; AContexto := TRttiContext.Create; try ATipo := AContexto.GetType(ClassType); for AAtributo in ATipo.GetAttributes do begin if AAtributo is Tabela then Result := Tabela(AAtributo).Nome; end; finally AContexto.Free; end; end; function TPersistencia.Inserir: Boolean; var AContexto: TRttiContext; ATipo: TRttiType; APropriedade: TRttiProperty; AAtributo: TCustomAttribute; ANomeTabela, ACampo, ASql: string; Parametros: array of TParametroQuery; Parametro: TParametroQuery; QueryTmp: TFDQuery; begin Result := False; ACampo := NullAsStringValue; setLength(Parametros,0); AContexto := TRttiContext.Create; try ATipo := AContexto.GetType(ClassType); for AAtributo in ATipo.GetAttributes do begin if AAtributo is Tabela then begin ANomeTabela := Tabela(AAtributo).Nome; Break; end; end; for APropriedade in ATipo.GetProperties do begin for AAtributo in APropriedade.GetAttributes do begin if AAtributo is Campo then begin ACampo := ACampo + ' ' + Campo(AAtributo).Nome + ',' + sLineBreak; if APropriedade.GetValue(Self).AsVariant <> Null then begin if not (Campo(AAtributo).ChavePrimaria) then begin SetLength(Parametros, Length(Parametros)+1); Parametros[high(Parametros)].Name := Campo(AAtributo).Nome; Parametros[high(Parametros)].Value := APropriedade.GetValue(Self).AsVariant; end; end end; end; end; ACampo := Trim(ACampo); ACampo := Copy(ACampo, 1, ACampo.Length - 1); ASql := 'SELECT ' + ACampo + sLineBreak + ' FROM ' + ANomeTabela + sLineBreak + ' WHERE 1=2'; QueryTmp := TConexao.GetInstancia.CriaQuery(ASql, []); try QueryTmp.Insert; for Parametro in Parametros do begin if VarToStrDef(Parametro.Value,NullAsStringValue) = NullAsStringValue then QueryTmp.FieldByName(Parametro.Name).Clear else if QueryTmp.FieldByName(Parametro.Name) is TBlobField then raise Exception.Create('Implementar Persistencia TBlobField') //TBlobField(QueryTmp.FieldByName(Parametro.Name)).LoadFromStream(Parametro.Value) else QueryTmp.FieldByName(Parametro.Name).Value := Parametro.Value; end; QueryTmp.Post; for APropriedade in ATipo.GetProperties do begin for AAtributo in APropriedade.GetAttributes do begin if (AAtributo is Campo) then APropriedade.SetValue(Self, Tvalue.FromVariant(QueryTmp.FieldByName(Campo(AAtributo).Nome).Value)); end; end; QueryTmp.Close; Result := True; finally FreeAndNil(QueryTmp); end; finally AContexto.Free; end; end; end.
unit ACBrRFDDll; {$mode delphi} interface uses Classes, ACBrRFD, SysUtils; { Ponteiros de função para uso nos eventos} type TCalcEADCallback = procedure(Arquivo: PChar); cdecl; type TCalcHashLogCallback = function(const Linha: PChar) : PChar; cdecl; type TChaveCallback = function () : PChar; {Classe que armazena os EventHandlers para o componente ACBr} type TEventHandlersRFD = class OnCalcEADCallback : TCalcEADCallback; OnCalcHashLogCallback : TCalcHashLogCallback; OnGetKeyHashLogCallback : TChaveCallback; OnGetKeyRSACallback : TChaveCallback; procedure OnCalcEAD(Arquivo: String); procedure OnCalcHashLog(const Linha: String; var Hash: String); procedure OnGetKeyHashLog(var Chave: String); procedure OnGetKeyRSA(var Chave: AnsiString); end; {Handle para o componente TACBrValidador} type TRFDHandle = record UltimoErro : String; RFD : TACBrRFD; EventHandlers : TEventHandlersRFD; end; {Ponteiro para o Handle } type PRFDHandle = ^TRFDHandle; implementation uses ACBrECFDll; {%region Create/Destroy/Erro} { PADRONIZAÇÃO DAS FUNÇÕES: PARÂMETROS: Todas as funções recebem o parâmetro "handle" que é o ponteiro para o componente instanciado; Este ponteiro deve ser armazenado pela aplicação que utiliza a DLL; RETORNO: Todas as funções da biblioteca retornam um Integer com as possíveis Respostas: MAIOR OU IGUAL A ZERO: SUCESSO Outos retornos maior que zero indicam sucesso, com valor específico de cada função. MENOR QUE ZERO: ERROS -1 : Erro ao executar; Vide UltimoErro -2 : ACBr não inicializado. Outros retornos negativos indicam erro específico de cada função; A função "UltimoErro" retornará a mensagem da última exception disparada pelo componente. } { CRIA um novo componente TACBrRFD retornando o ponteiro para o objeto criado. Este ponteiro deve ser armazenado pela aplicação que utiliza a DLL e informado em todas as chamadas de função relativas ao TACBrRFD. } Function RFD_Create(var rfdHandle: PRFDHandle): Integer; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin try New(rfdHandle); rfdHandle^.RFD := TACBrRFD.Create(nil); rfdHandle^.EventHandlers := TEventHandlersRFD.Create(); rfdHandle^.UltimoErro:= ''; Result := 0; except on exception : Exception do begin Result := -1; rfdHandle^.UltimoErro := exception.Message; end end; end; { DESTRÓI o objeto TACBrRFD e libera a memória utilizada. Esta função deve SEMPRE ser chamada pela aplicação que utiliza a DLL quando o componente não mais for utilizado. } Function RFD_Destroy(rfdHandle: PRFDHandle): Integer; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.Destroy(); rfdHandle^.RFD := nil; Dispose(rfdHandle); rfdHandle := nil; Result := 0; except on exception : Exception do begin Result := -1; rfdHandle^.UltimoErro := exception.Message; end end; end; Function RFD_GetUltimoErro(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin try StrPLCopy(Buffer, rfdHandle^.UltimoErro, BufferLen); Result := length(rfdHandle^.UltimoErro); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; {%endregion} {%region Funções mapeando as propriedades do componente } Function RFD_GetDirRFD(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.DirRFD; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetDirRFD(const rfdHandle: PRFDHandle; const Dir : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.DirRFD := Dir; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetSH_CNPJ(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.SH_CNPJ; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetSH_CNPJ(const rfdHandle: PRFDHandle; const SH_CNPJ : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.SH_CNPJ := SH_CNPJ; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetSH_COO(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.SH_COO; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetSH_COO(const rfdHandle: PRFDHandle; const SH_COO : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.SH_COO := SH_COO; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetSH_IE(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.SH_IE; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetSH_IE(const rfdHandle: PRFDHandle; const SH_IE : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.SH_IE := SH_IE; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetSH_IM(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.SH_IM; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetSH_IM(const rfdHandle: PRFDHandle; const SH_IM : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.SH_IM := SH_IM; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetSH_Linha1(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.SH_Linha1; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetSH_Linha1(const rfdHandle: PRFDHandle; const SH_Linha1 : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.SH_Linha1 := SH_Linha1; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetSH_Linha2(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.SH_Linha2; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetSH_Linha2(const rfdHandle: PRFDHandle; const SH_Linha2 : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.SH_Linha2 := SH_Linha2; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetSH_NomeAplicativo(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.SH_NomeAplicativo; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetSH_NomeAplicativo(const rfdHandle: PRFDHandle; const SH_NomeAplicativo : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.SH_NomeAplicativo := SH_NomeAplicativo; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetSH_VersaoAplicativo(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.SH_VersaoAplicativo; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetSH_VersaoAplicativo(const rfdHandle: PRFDHandle; const SH_VersaoAplicativo : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.SH_VersaoAplicativo := SH_VersaoAplicativo; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetSH_NumeroAplicativo(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.SH_NumeroAplicativo; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetSH_NumeroAplicativo(const rfdHandle: PRFDHandle; const SH_NumeroAplicativo : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.SH_NumeroAplicativo := SH_NumeroAplicativo; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetIgnoraEcfMfd(const rfdHandle: PRFDHandle) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try if rfdHandle^.RFD.IgnoraEcfMfd then Result := 1 else Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetIgnoraEcfMfd(const rfdHandle: PRFDHandle; const IgnoraEcfMfd : Boolean) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.IgnoraEcfMfd := IgnoraEcfMfd; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; {%endregion} {%region Funções mapeando as propriedades do componente não visiveis} Function RFD_GetAtivo(const rfdHandle: PRFDHandle) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try if rfdHandle^.RFD.Ativo then Result := 1 else Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetAtivo(const rfdHandle: PRFDHandle; const Ativo : Boolean) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.Ativo := Ativo; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetDiaMov(const rfdHandle: PRFDHandle; var value : Double) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try value := rfdHandle^.RFD.DiaMov; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetDirECF(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.DirECF; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetDirECFLog(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.DirECFLog; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetDirECFMes(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.DirECFMes; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetArqRFDID(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.ArqRFDID; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetArqRFD(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.ArqRFD; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetArqReducaoZ(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.ArqReducaoZ; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetArqINI(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.ArqINI; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetECF_CROAtual(const rfdHandle: PRFDHandle) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try Result := rfdHandle^.RFD.ECF_CROAtual; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetECF_CROAtual(const rfdHandle: PRFDHandle; const value : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.ECF_CROAtual := value; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetECF_RFDID(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.ECF_RFDID; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetECF_RFDID(const rfdHandle: PRFDHandle; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.ECF_RFDID := value; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetECF_DataHoraSwBasico(const rfdHandle: PRFDHandle; var value : Double) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try value := rfdHandle^.RFD.ECF_DataHoraSwBasico; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetECF_DataHoraSwBasico(const rfdHandle: PRFDHandle; const value : Double) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.ECF_DataHoraSwBasico := value; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetAtoCotepe(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.AtoCotepe; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetAtoCotepe(const rfdHandle: PRFDHandle; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.AtoCotepe := value; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetCONT_CNPJ(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.CONT_CNPJ; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetCONT_CNPJ(const rfdHandle: PRFDHandle; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.CONT_CNPJ := value; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetCONT_IE(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.CONT_IE; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetCONT_IE(const rfdHandle: PRFDHandle; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.CONT_IE := value; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetCONT_NumUsuario(const rfdHandle: PRFDHandle; var value : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try value := rfdHandle^.RFD.CONT_NumUsuario; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetCONT_NumUsuario(const rfdHandle: PRFDHandle; const value : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.CONT_NumUsuario := value; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetCONT_RazaoSocial(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.CONT_RazaoSocial; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetCONT_RazaoSocial(const rfdHandle: PRFDHandle; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.CONT_RazaoSocial := value; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetCONT_Endereco(const rfdHandle: PRFDHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.CONT_Endereco; StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetCONT_Endereco(const rfdHandle: PRFDHandle; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.CONT_Endereco := value; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetCONT_DataHoraCadastro(const rfdHandle: PRFDHandle; var value : Double) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try value := rfdHandle^.RFD.CONT_DataHoraCadastro; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetCONT_DataHoraCadastro(const rfdHandle: PRFDHandle; const value : Double) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.CONT_DataHoraCadastro := value; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetCONT_CROCadastro(const rfdHandle: PRFDHandle; var value : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try value := rfdHandle^.RFD.CONT_CROCadastro; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetCONT_CROCadastro(const rfdHandle: PRFDHandle; const value : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.CONT_CROCadastro := value; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GetCONT_GTCadastro(const rfdHandle: PRFDHandle; var value : Double) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try value := rfdHandle^.RFD.CONT_GTCadastro; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetCONT_GTCadastro(const rfdHandle: PRFDHandle; const value : Double) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.CONT_GTCadastro := value; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; {%endregion} {%region Componente ACBr} Function RFD_SetECF(const rfdHandle: PRFDHandle; const ecfHandle : PECFHandle) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try if (ecfHandle = nil) then begin rfdHandle^.RFD.ECF := nil; Result := 0; end else begin rfdHandle^.RFD.ECF := ecfHandle^.ECF; Result := 0; end; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; {%endregion} {%region Metodos} Function RFD_Ativar(const rfdHandle: PRFDHandle) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.Ativar; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_Desativar(const rfdHandle: PRFDHandle) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.Desativar; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_VerificaParametros(const rfdHandle: PRFDHandle) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.VerificaParametros; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_AchaRFDID(const rfdHandle: PRFDHandle; const value : pChar; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.AchaRFDID(value); StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_LerINI(const rfdHandle: PRFDHandle) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.LerINI; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_GravarINI(const rfdHandle: PRFDHandle) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.GravarINI; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_CriarArqRFDID(const rfdHandle: PRFDHandle; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.CriarArqRFDID(value); Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_NomeArqRFD(const rfdHandle: PRFDHandle; const value : Double; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; var StrTmp : String; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try StrTmp := rfdHandle^.RFD.NomeArqRFD(value); StrPLCopy(Buffer, StrTmp, BufferLen); Result := length(StrTmp); except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_AbreCupom(const rfdHandle: PRFDHandle) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.AbreCupom; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_VendeItem(const rfdHandle: PRFDHandle; const Codigo, Descricao: pChar; const Qtd, ValorUnitario: Double; const Unidade: pChar; const ValorDescAcres: Double; Aliquota: pChar ) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.VendeItem(Codigo, Descricao, Qtd, ValorUnitario, Unidade, ValorDescAcres, Aliquota); Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SubTotalizaCupom(const rfdHandle: PRFDHandle; const DescontoAcrescimo: Double) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.SubTotalizaCupom(DescontoAcrescimo); Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_FechaCupom(const rfdHandle: PRFDHandle) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.FechaCupom; Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_CancelaCupom(const rfdHandle: PRFDHandle; const value : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.CancelaCupom(value); Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_CancelaItemVendido(const rfdHandle: PRFDHandle; const value : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.CancelaItemVendido(value); Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_ReducaoZ(const rfdHandle: PRFDHandle; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.ReducaoZ(value); Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_Documento(const rfdHandle: PRFDHandle; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.Documento(value); Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_EfetuaPagamento(const rfdHandle: PRFDHandle; const value : pChar; const valor : Double) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try rfdHandle^.RFD.EfetuaPagamento(value, valor); Result := 0; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; {%endregion} {%region HandlerEventos} procedure TEventHandlersRFD.OnCalcEAD(Arquivo: String); begin OnCalcEADCallback(PChar(Arquivo)); end; procedure TEventHandlersRFD.OnCalcHashLog(const Linha: String; var Hash: String); begin Hash := OnCalcHashLogCallback(PChar(Linha)); end; procedure TEventHandlersRFD.OnGetKeyHashLog(var Chave: String); begin Chave := OnGetKeyHashLogCallback(); end; procedure TEventHandlersRFD.OnGetKeyRSA(var Chave: String); begin Chave := OnGetKeyRSACallback(); end; {%endregion} {%region Eventos} Function RFD_SetOnCalcEAD(const rfdHandle: PRFDHandle; const method : TCalcEADCallback) : Integer; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try if Assigned(method) then begin rfdHandle^.RFD.OnCalcEAD := rfdHandle^.EventHandlers.OnCalcEAD; rfdHandle^.EventHandlers.OnCalcEADCallback := method; Result := 0; end else begin rfdHandle^.RFD.OnCalcEAD := nil; rfdHandle^.EventHandlers.OnCalcEADCallback := nil; Result := 0; end; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetOnCalcHashLog(const rfdHandle: PRFDHandle; const method : TCalcHashLogCallback) : Integer; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try if Assigned(method) then begin rfdHandle^.RFD.OnCalcHashLog := rfdHandle^.EventHandlers.OnCalcHashLog; rfdHandle^.EventHandlers.OnCalcHashLogCallback := method; Result := 0; end else begin rfdHandle^.RFD.OnCalcHashLog := nil; rfdHandle^.EventHandlers.OnCalcHashLogCallback := nil; Result := 0; end; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetOnGetKeyHashLog(const rfdHandle: PRFDHandle; const method : TChaveCallback) : Integer; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try if Assigned(method) then begin rfdHandle^.RFD.OnGetKeyHashLog := rfdHandle^.EventHandlers.OnGetKeyHashLog; rfdHandle^.EventHandlers.OnGetKeyHashLogCallback := method; Result := 0; end else begin rfdHandle^.RFD.OnGetKeyHashLog := nil; rfdHandle^.EventHandlers.OnGetKeyHashLogCallback := nil; Result := 0; end; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; Function RFD_SetOnGetKeyRSA(const rfdHandle: PRFDHandle; const method : TChaveCallback) : Integer; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export; begin if (rfdHandle = nil) then begin Result := -2; Exit; end; try if Assigned(method) then begin rfdHandle^.RFD.OnGetKeyRSA := rfdHandle^.EventHandlers.OnGetKeyRSA; rfdHandle^.EventHandlers.OnGetKeyRSACallback := method; Result := 0; end else begin rfdHandle^.RFD.OnGetKeyRSA := nil; rfdHandle^.EventHandlers.OnGetKeyRSACallback := nil; Result := 0; end; except on exception : Exception do begin rfdHandle^.UltimoErro := exception.Message; Result := -1; end end; end; {%endregion} exports { Funções } RFD_Create, RFD_Destroy, RFD_GetUltimoErro, { Funções mapeando as propriedades do componente } RFD_GetDirRFD, RFD_SetDirRFD, RFD_GetSH_CNPJ, RFD_SetSH_CNPJ, RFD_GetSH_COO, RFD_SetSH_COO, RFD_GetSH_IE, RFD_SetSH_IE, RFD_GetSH_IM, RFD_SetSH_IM, RFD_GetSH_Linha1, RFD_SetSH_Linha1, RFD_GetSH_Linha2, RFD_SetSH_Linha2, RFD_GetSH_NomeAplicativo, RFD_SetSH_NomeAplicativo, RFD_GetSH_VersaoAplicativo, RFD_SetSH_VersaoAplicativo, RFD_GetSH_NumeroAplicativo, RFD_SetSH_NumeroAplicativo, RFD_GetIgnoraEcfMfd, RFD_SetIgnoraEcfMfd, { Funções mapeando as propriedades do componente não visiveis} RFD_GetAtivo, RFD_SetAtivo, RFD_GetDiaMov, RFD_GetDirECF, RFD_GetDirECFLog, RFD_GetDirECFMes, RFD_GetArqRFDID, RFD_GetArqRFD, RFD_GetArqReducaoZ, RFD_GetArqINI, RFD_GetECF_CROAtual, RFD_SetECF_CROAtual, RFD_GetECF_RFDID, RFD_SetECF_RFDID, RFD_GetECF_DataHoraSwBasico, RFD_SetECF_DataHoraSwBasico, RFD_GetAtoCotepe, RFD_SetAtoCotepe, RFD_GetCONT_CNPJ, RFD_SetCONT_CNPJ, RFD_GetCONT_IE, RFD_SetCONT_IE, RFD_GetCONT_NumUsuario, RFD_SetCONT_NumUsuario, RFD_GetCONT_RazaoSocial, RFD_SetCONT_RazaoSocial, RFD_GetCONT_Endereco, RFD_SetCONT_Endereco, RFD_GetCONT_DataHoraCadastro, RFD_SetCONT_DataHoraCadastro, RFD_GetCONT_CROCadastro, RFD_SetCONT_CROCadastro, RFD_GetCONT_GTCadastro, RFD_SetCONT_GTCadastro, { Componente ACBr } RFD_SetECF, { Metodos } RFD_Ativar, RFD_Desativar, RFD_VerificaParametros, RFD_AchaRFDID, RFD_LerINI, RFD_GravarINI, RFD_CriarArqRFDID, RFD_NomeArqRFD, RFD_AbreCupom, RFD_VendeItem, RFD_SubTotalizaCupom, RFD_FechaCupom, RFD_CancelaCupom, RFD_CancelaItemVendido, RFD_ReducaoZ, RFD_Documento, RFD_EfetuaPagamento, { Eventos } RFD_SetOnCalcEAD, RFD_SetOnCalcHashLog, RFD_SetOnGetKeyHashLog, RFD_SetOnGetKeyRSA; end.
unit LblEdtDt; interface Uses SysUtils,StdCtrls,Classes,Buttons,Controls,ExtCtrls,Menus, Messages,EditDate,SQLCtrls,DBTables,TSQLCls,WinProcs; Type TLabelEditDate=class(TSQLControl) protected BackUp,fDateFormat:string; procedure WriteCaption(s:string); Function ReadCaption:String; procedure WriteText(s:string); Function ReadText:String; procedure WritePC(s:boolean); Function ReadPC:boolean; procedure WriteRO(s:boolean); Function ReadRO:boolean; procedure WriteML(s:integer); Function ReadML:integer; procedure EditOnKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditOnEnter(Sender: TObject); procedure EditOnClick(Sender: TObject); public Data:longint; Lbl:TLabel; EditDate:TEditDate; constructor Create(AOwner:TComponent); override; destructor Destroy; override; procedure WMSize(var Msg:TMessage); message WM_SIZE; function GetHeight:integer; procedure Value(sl:TStringList); override; procedure SetValue(var q:TQuery); override; function GetDateTime:TDateTime; function OptimalWidth:integer; published property Caption:String read ReadCaption write WriteCaption; property DateFormat:String read fDateFormat write fDateFormat; property Text:String read ReadText write WriteText; property ParentColor:boolean read ReadPC write WritePC; property ReadOnly:boolean read ReadRO write WriteRO; property MaxLength:integer read ReadML write WriteML; property Align; property DragCursor; property DragMode; property Enabled; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; end; procedure Register; implementation Uses WinTypes; function TLabelEditDate.OptimalWidth:integer; var dc:HDC; sz:TSIZE; begin dc:=GetDC(EditDate.Handle); GetTextExtentPoint(DC,'99.99.9999',11,sz); ReleaseDC(EditDate.Handle,dc); OptimalWidth:=sz.cx end; function TLabelEditDate.GetHeight:integer; begin GetHeight:=-EditDate.Font.Height+13-Lbl.Font.Height end; destructor TLabelEditDate.Destroy; begin Lbl.Free; EditDate.Free; inherited Destroy; end; constructor TLabelEditDate.Create(AOwner:TComponent); begin inherited create(AOwner); Lbl:=TLabel.Create(self); EditDate:=TEditDate.Create(self); Lbl.Parent:=self; EditDate.Parent:=self; DateFormat:='yyyy-mm-dd'; Lbl.Left:=0; Lbl.Top:=0; EditDate.Left:=0; EditDate.OnKeyUp:=EditOnKeyUp; EditDate.OnEnter:=EditOnEnter; EditDate.OnClick:=EditonClick; end; procedure TLabelEditDate.Value(sl:TStringList); begin if Assigned(fValueEvent) then fValueEvent(self,sl) else if (not Visible) or (Text='') or (Text=' . . ') then sl.Add('NULL') else sl.Add(sql.ConvertToDate2(sql.MakeStr( FormatDateTime(DateFormat,StrToDateTime(Text))))); end; procedure TLabelEditDate.SetValue(var q:TQuery); begin if Assigned(fSetValueEvent) then fSetValueEvent(self,q) else try if q.FieldByName(fFieldName).IsNull then Text:=' . . ' else Text:=DateToStr(q.FieldByName(fFieldName).AsDateTime); except end; end; procedure TLabelEditDate.WMSize(var Msg:TMessage); begin Lbl.Height:=-Lbl.Font.Height+3; Lbl.Width:=Msg.LParamLo; EditDate.Top:=Lbl.Height; EditDate.Height:=-EditDate.Font.Height+10; EditDate.Width:=Msg.LParamLo; Height:=EditDate.Height+Lbl.Height; Width:=Msg.LParamLo; end; procedure TLabelEditDate.WriteCaption(s:String); begin Lbl.Caption:=s end; function TLabelEditDate.ReadCaption:String; begin ReadCaption:=Lbl.Caption end; procedure TLabelEditDate.WritePC(s:boolean); begin EditDate.ParentColor:=s end; function TLabelEditDate.ReadPC:boolean; begin ReadPC:=EditDate.ParentColor end; procedure TLabelEditDate.WriteRO(s:boolean); begin EditDate.ReadOnly:=s end; function TLabelEditDate.ReadRO:boolean; begin ReadRO:=EditDate.ReadOnly end; procedure TLabelEditDate.WriteML(s:integer); begin EditDate.MaxLength:=s end; function TLabelEditDate.ReadML:integer; begin ReadML:=EditDate.MaxLength end; procedure TLabelEditDate.WriteText(s:String); begin EditDate.Text:=s end; function TLabelEditDate.ReadText:String; begin ReadText:=EditDate.Text end; procedure Register; begin RegisterComponents('MyOwn',[TLabelEditDate]) end; procedure TLabelEditDate.EditOnKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key=VK_ESCAPE then EditDate.Text:=BackUp end; procedure TLabelEditDate.EditOnEnter(Sender: TObject); begin EditDate.SetFocus; BackUp:=EditDate.Text end; procedure TLabelEditDate.EditOnClick(Sender: TObject); begin if EditDate.Text=' . . ' then begin EditDate.SelStart:=0; EditDate.SelLength:=0; end; end; function TLabelEditDate.GetDateTime:TDateTime; begin if (not Visible) or (Text='') or (Text=' . . ') then GetDateTime:=0 else GetDateTime:=StrToDateTime(Text) end; end.
{ Este exemplo foi baixado no site www.andrecelestino.com Passe por lá a qualquer momento para conferir os novos artigos! :) contato@andrecelestino.com } unit untThread; interface uses classes, SysUtils, Windows, ComCtrls; type TMinhaThread = class(TThread) private FTempo: integer; FProgressBar: TProgressBar; public constructor Create; overload; procedure Progress; procedure Execute; override; property Tempo: Integer read FTempo write FTempo; property ProgressBar: TProgressBar read FProgressBar write FProgressBar; end; implementation constructor TMinhaThread.Create; begin inherited Create(True); end; procedure TMinhaThread.Execute; begin // loop infinito while True do begin Sleep(FTempo); Synchronize(Progress); end; end; procedure TMinhaThread.Progress; begin // atualiza a ProgressBar a cada iteração do método 'Execute' FProgressBar.StepIt; end; end.
{ ID: a_zaky01 PROG: starry LANG: PASCAL } type cluster=record star:array[0..101,0..101] of boolean; size,w,h:longint; end; var w,h,i,j,k,now:longint; input:string; new:boolean; temp:cluster; a,stat:array[0..101,0..101] of boolean; ans:array[0..101,0..101] of byte; seen:array[1..26] of cluster; fin,fout:text; function gen(i,j:integer):cluster; var i0,j0,minh,maxh,minw,maxw:integer; procedure fill(i,j:integer); var i1,j1:integer; begin stat[i,j]:=true; inc(gen.size); if i<minh then minh:=i; if i>maxh then maxh:=i; if j<minw then minw:=j; if j>maxw then maxw:=j; for i1:=i-1 to i+1 do for j1:=j-1 to j+1 do if not ((i1=1) and (j1=j)) then if a[i1,j1] and not stat[i1,j1] then fill(i1,j1); end; begin with gen do begin size:=0; fillchar(star,sizeof(star),false); end; minh:=i; maxh:=i; minw:=j; maxw:=j; fill(i,j); dec(minh); dec(minw); gen.h:=maxh-minh; gen.w:=maxw-minw; for i0:=1 to gen.h do for j0:=1 to gen.w do if stat[i0+minh,j0+minw] and (ans[i0+minh,j0+minw]=0) then gen.star[i0,j0]:=true; end; procedure fill(i,j,k:integer); var i1,j1:integer; begin ans[i,j]:=k; for i1:=i-1 to i+1 do for j1:=j-1 to j+1 do if not ((i1=1) and (j1=j)) then if a[i1,j1] and (ans[i1,j1]<>k) then fill(i1,j1,k); end; function match(cl1,cl2:cluster):boolean; var i,j:integer; temp:cluster; function check:boolean; var i,j,h0,w0:integer; function same:boolean; var i,j:integer; begin for i:=1 to h0 do for j:=1 to w0 do if cl1.star[i,j] xor cl2.star[i,j] then exit(false); exit(true); end; procedure swap(var a,b:boolean); var temp:boolean; begin temp:=a; a:=b; b:=temp; end; begin if cl1.h<>cl2.h then exit(false); h0:=cl1.h; w0:=cl1.w; if same then exit(true); for i:=1 to h0 do for j:=1 to w0 div 2 do swap(cl1.star[i,j],cl1.star[i,w0-j+1]); if same then exit(true); for i:=1 to h0 div 2 do for j:=1 to w0 do swap(cl1.star[i,j],cl1.star[h0-i+1,j]); if same then exit(true); for i:=1 to h0 do for j:=1 to w0 div 2 do swap(cl1.star[i,j],cl1.star[i,w0-j+1]); if same then exit(true); exit(false); end; begin if cl1.size<>cl2.size then exit(false); if cl1.w*cl1.h<>cl2.w*cl2.h then exit(false); if (cl1.w<>cl2.w) and (cl1.w<>cl2.h) then exit(false); if check then exit(true); temp:=cl1; for i:=1 to cl1.w do for j:=1 to cl1.h do temp.star[i,j]:=cl1.star[j,i]; temp.w:=cl1.h; temp.h:=cl1.w; cl1:=temp; if check then exit(true); exit(false); end; begin assign(fin,'starry.in'); assign(fout,'starry.out'); reset(fin); rewrite(fout); readln(fin,w,h); for i:=1 to h do begin readln(fin,input); for j:=1 to w do if input[j]='1' then a[i,j]:=true; end; now:=0; for i:=1 to h do for j:=1 to w do if a[i,j] and not stat[i,j] then begin temp:=gen(i,j); new:=true; for k:=1 to now do if match(temp,seen[k]) then begin fill(i,j,k); new:=false; break; end; if new then begin inc(now); fill(i,j,now); seen[now]:=temp; end; end; for i:=1 to h do begin for j:=1 to w do if ans[i,j]=0 then write(fout,0) else write(fout,chr(ans[i,j]+96)); writeln(fout); end; close(fin); close(fout); end.
unit USort; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, DBCtrls, TeEngine, Series, TeeProcs, Chart, ComCtrls; const N = 13; //количество элементов в демонстрационном массиве для сортировки ssleep = 700; //задержка в мс tab = ' '; //отступ type TIndex = 1..N; //тип-индексы массива TElem = Integer; //тип-элемент массива TMas = array[TIndex] of TElem; //тип-массив procedure RandomFill(var mas: TMas); //заполнение массива случайными числами function ToString(mas: TMas): string; //возвращат массив в виде строки procedure ShellSort(var mas: TMas; var lb: TListBox); //сортировка шелла с выводом процесса на listbox implementation //заполнение массива случайными числами (в диапазоне 1-99) procedure RandomFill(var mas: TMas); var i: Integer; begin Randomize; for i:= 1 to N do mas[i]:= 1 + Random(99); end; //возвращат массив в виде строки function ToString(mas: TMas): string; var i: Integer; begin Result:= ''; for i:= 1 to N do Result:= Result + IntToStr(mas[i]) + ' '; end; //сдвигает i-ю строку на lb на отступ tab procedure Move(var lb: TListBox; i: Integer); var s: string; begin s:= tab + Trim(lb.Items[i-1]); lb.Items[i-1]:= s; end; //удаляет отступ i-й строки на lb procedure MoveBack(var lb: TListBox; i: Integer); var s: string; begin s:= Trim(lb.Items[i-1]); lb.Items[i-1]:= s; end; //меняет местами i-ю и j-ю строки на lb procedure Swap(var lb: TListBox; i,j: Integer); var s: string; begin s:= lb.Items[i-1]; lb.Items[i-1]:= lb.Items[j-1]; lb.Items[j-1]:= s; end; procedure ShellSort(var mas: TMas; var lb: TListBox); function CountStep(k: integer): integer; //ф-я для вычисления шага (3^k-1)/2 var i: integer; begin Result:= 1; for i:= 1 to k do Result:= 3 * Result; Result:= (Result - 1) div 2; end; var i, k, step, p, l, T: integer; el: TElem; begin T:= Trunc(Ln(n) / Ln(3)); // определяем количество шагов for k:= T downto 1 do begin step:= CountStep(k); //вычисляем очередной шаг for p := 1 to step do //применяем сортировку вставками для всех групп begin i:= step + p; while i <= N do begin el:= mas[i]; l:= i - step; //действия с listbox Move(lb,i); Move(lb,l); Application.ProcessMessages; //чтобы на listbox применились изменения sleep(ssleep); while (l >= 1) and (el < mas[l]) do begin //действия с listbox Move(lb,l); Application.ProcessMessages; if (l < i - step) then sleep(ssleep); mas[l + step]:= mas[l]; //действия с listbox Swap(lb,l+step,l); Application.ProcessMessages; sleep(ssleep); //действия с listbox MoveBack(lb,l+step); Application.ProcessMessages; l:= l - step; end; if (l < i - step) then begin mas[l + step]:= el; //действия с listbox MoveBack(lb,l+step); end else begin //действия с listbox MoveBack(lb,i); MoveBack(lb,l); end; //действия с listbox Application.ProcessMessages; sleep(ssleep); i:= i + step; end; end; end; end; end.
unit RipRelativeScanner; { This class will scan a given module and return the rip relative instructions } {$mode delphi} interface uses {$ifdef darwin} macport, {$endif} {$ifdef windows} Windows, {$endif} Classes, SysUtils, disassembler, symbolhandler, symbolhandlerstructs, processhandlerunit, NewKernelHandler, CEFuncProc; type TRIPRelativeScanner=class private modulebase: ptruint; modulesize: dword; executablelist: array of record base: ptruint; size: dword; end; addresslist: array of ptruint; valuelist: array of ptruint; addresslistpos: integer; addresslistsize: integer; function getAddress(i: integer): ptruint; procedure scan(startaddress, stopaddress: ptruint; includeLongJumpsAndCalls: boolean; modulebase: ptruint=0; modulesize: ptruint=0); public constructor create(startaddress, stopaddress: ptruint; includeLongJumpsAndCalls: boolean); overload; constructor create(modulename: string; includeLongJumpsAndCalls: boolean); overload; property Address[i: integer]: ptruint read getAddress; published property Count: integer read addresslistpos; end; implementation function TRIPRelativeScanner.getAddress(i: integer): ptruint; begin result:=0; if (i<0) or (i>=addresslistpos) then exit; result:=addresslist[i]; end; procedure TRIPRelativeScanner.scan(startaddress, stopaddress: ptruint; includeLongJumpsAndCalls: boolean; modulebase: ptruint=0; modulesize: ptruint=0); var currentbase: ptruint; mbi: TMemoryBasicInformation; d: TDisassembler; a: ptruint; stop: ptruint; i: integer; desc: string; begin //querry the executable memory regions currentbase:=startaddress; zeromemory(@mbi, sizeof(mbi)); while (currentbase<stopaddress) and (VirtualQueryEx(processhandle, pointer(currentbase), mbi, sizeof(mbi))=sizeof(mbi)) do begin if (mbi.Protect and (PAGE_EXECUTE or PAGE_EXECUTE_READ or PAGE_EXECUTE_READWRITE or PAGE_EXECUTE_WRITECOPY))<>0 then begin setlength(executablelist, length(executablelist)+1); executablelist[length(executablelist)-1].base:=ptruint(mbi.BaseAddress); executablelist[length(executablelist)-1].size:=mbi.RegionSize; end; currentbase:=ptruint(mbi.BaseAddress)+mbi.RegionSize; end; setlength(addresslist, 512); addresslistsize:=512; addresslistpos:=0; d:=TDisassembler.Create; d.dataOnly:=true; d.MarkIPRelativeInstructions:=includeLongJumpsAndCalls; try for i:=0 to length(executablelist)-1 do begin a:=maxx(startaddress, executablelist[i].base); stop:=MinX(stopaddress, executablelist[i].base+executablelist[i].size); while a<stop do begin d.disassemble(a, desc); if not ((length(d.LastDisassembleData.Bytes)=2) and ((d.LastDisassembleData.Bytes[0]=0) and (d.LastDisassembleData.Bytes[1]=0))) then begin if (d.LastDisassembleData.riprelative>0) and ((modulebase=0) or InRangeX(d.LastDisassembleData.modrmValue, modulebase, modulebase+modulesize)) then begin //found one addresslist[addresslistpos]:=d.LastDisassembleData.address+d.LastDisassembleData.riprelative; inc(addresslistpos); if addresslistpos>=addresslistsize then begin addresslistsize:=addresslistsize*2; setlength(addresslist, addresslistsize); end; end; end else inc(a, 8-(a mod 8)); //this can cause an alignment issue end; end; finally d.free; end; end; constructor TRIPRelativeScanner.create(startaddress, stopaddress: ptruint; includeLongJumpsAndCalls: boolean); begin scan(startaddress, stopaddress, includeLongJumpsAndCalls); end; constructor TRIPRelativeScanner.create(modulename: string; includeLongJumpsAndCalls: boolean); var mi: TModuleInfo; begin if (includeLongJumpsAndCalls or processhandler.is64bit) and symhandler.getmodulebyname(modulename, mi) then begin modulebase:=mi.baseaddress; modulesize:=mi.basesize; scan(modulebase, modulebase+modulesize, includeLongJumpsAndCalls, modulebase, modulesize); end; end; end.
unit Visao.CadastroBomba; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Visao.FormPadrao, Vcl.StdCtrls, Vcl.ExtCtrls, Controle.CadastroBomba; type TFrmCadastroBomba = class(TFrmPadrao) procedure btnNovoClick(Sender: TObject); procedure btnGravarClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure edtCodigoKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } end; var FrmCadastroBomba: TFrmCadastroBomba; Controle: TControleBomba; implementation uses uTipos, Classes.Funcoes; {$R *.dfm} procedure TFrmCadastroBomba.btnGravarClick(Sender: TObject); begin inherited; with Controle.Bomba do begin Codigo := StrToIntDef(edtCodigo.Text, 1); Descricao := edtDescricao.Text; end; Controle.SalvarBomba(Evento); end; procedure TFrmCadastroBomba.btnNovoClick(Sender: TObject); var vCodigoBomba: Integer; begin inherited; vCodigoBomba := Controle.ObtemNumeroVago; Inc(vCodigoBomba); edtCodigo.Text := IntToStr(vCodigoBomba); end; procedure TFrmCadastroBomba.edtCodigoKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key = #13 then begin with Controle do begin if CarregaBomba(edtCodigo.Text) then begin edtDescricao.Text := Bomba.Descricao; Evento := teNavegacao; AlteraBotoes(4); end; end; end; end; procedure TFrmCadastroBomba.FormCreate(Sender: TObject); begin inherited; if not Assigned(Controle) then Controle := TControleBomba.Create; end; procedure TFrmCadastroBomba.FormDestroy(Sender: TObject); begin inherited; if Assigned(Controle) then FreeAndNil(Controle); end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Janela Cadastro de Endereços do WMS The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije @version 2.0 ******************************************************************************* } unit UWmsEndereco; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UTelaCadastro, Vcl.Menus, Vcl.StdCtrls, Vcl.ExtCtrls, LabeledCtrls, Vcl.Buttons, Vcl.Grids, Vcl.DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, Vcl.ComCtrls, JvToolEdit, Vcl.Mask, JvExMask, JvBaseEdits, System.Actions, Vcl.ActnList, Vcl.ToolWin, Vcl.ActnMan, Vcl.ActnCtrls, Vcl.PlatformDefaultStyleActnCtrls, Data.DB, Datasnap.DBClient, System.Generics.Collections, UDataModule, Biblioteca, Controller; type TFWmsEndereco = class(TFTelaCadastro) ScrollBox: TScrollBox; EditQuantidadeEstante: TLabeledCalcEdit; Bevel1: TBevel; PageControl1: TPageControl; TabSheet1: TTabSheet; Panel1: TPanel; DSEstantes: TDataSource; CDSEstantes: TClientDataSet; ActionManager: TActionManager; ActionAdicionarEstante: TAction; ActionRemoverEstante: TAction; ActionAdicionarCaixa: TAction; ActionRemoverCaixa: TAction; CDSCaixas: TClientDataSet; DSCaixas: TDataSource; EditCodigo: TLabeledEdit; EditNome: TLabeledEdit; Panel2: TPanel; GridEstantes: TJvDBUltimGrid; ActionToolBarServicos: TActionToolBar; Panel3: TPanel; ActionToolBarItens: TActionToolBar; GridCaixas: TJvDBUltimGrid; procedure FormCreate(Sender: TObject); procedure ActionRemoverEstanteExecute(Sender: TObject); procedure ControlaPersistencia(pDataSet: TDataSet); procedure ActionAdicionarEstanteExecute(Sender: TObject); procedure ActionRemoverCaixaExecute(Sender: TObject); procedure ActionAdicionarCaixaExecute(Sender: TObject); private function DoInserir: Boolean; override; function DoEditar: Boolean; override; function DoExcluir: Boolean; override; function DoSalvar: Boolean; override; procedure GridParaEdits; override; procedure LimparCampos; override; public end; var FWmsEndereco: TFWmsEndereco; implementation {$R *.dfm} uses WmsEstanteVO, WmsCaixaVO, WmsRuaVO, WmsRuaController, WmsCaixaController; {$REGION 'Infra'} procedure TFWmsEndereco.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TWmsRuaVO; ObjetoController := TWmsRuaController.Create; inherited; // Configura as Grids de detalhes ConfiguraCDSFromVO(CDSEstantes, TWmsEstanteVO); ConfiguraGridFromVO(GridEstantes, TWmsEstanteVO); ConfiguraCDSFromVO(CDSCaixas, TWmsCaixaVO); ConfiguraGridFromVO(GridCaixas, TWmsCaixaVO); end; procedure TFWmsEndereco.LimparCampos; begin inherited; CDSEstantes.EmptyDataSet; CDSCaixas.EmptyDataSet; end; {$ENDREGION} {$REGION 'Controles CRUD'} function TFWmsEndereco.DoInserir: Boolean; begin Result := inherited DoInserir; if Result then begin EditCodigo.SetFocus; end; end; function TFWmsEndereco.DoEditar: Boolean; begin Result := inherited DoEditar; if Result then begin EditCodigo.SetFocus; end; end; function TFWmsEndereco.DoExcluir: Boolean; begin if inherited DoExcluir then begin try TController.ExecutarMetodo('WmsRuaController.TWmsRuaController', 'Exclui', [IdRegistroSelecionado], 'DELETE', 'Boolean'); Result := TController.RetornoBoolean; except Result := False; end; end else begin Result := False; end; if Result then TController.ExecutarMetodo('WmsRuaController.TWmsRuaController', 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista'); end; function TFWmsEndereco.DoSalvar: Boolean; var WmsEstante: TWmsEstanteVO; WmsCaixa: TWmsCaixaVO; begin Result := inherited DoSalvar; if Result then begin try if not Assigned(ObjetoVO) then ObjetoVO := TWmsRuaVO.Create; TWmsRuaVO(ObjetoVO).Codigo := EditCodigo.Text; TWmsRuaVO(ObjetoVO).Nome := EditNome.Text; TWmsRuaVO(ObjetoVO).QuantidadeEstante := EditQuantidadeEstante.AsInteger; /// EXERCICIO - TENTE IMPLEMENTAR OS DADOS DA LISTA DE DETALHES DE ACORDO COM O MODELO PROPOSTO NA INFRA // Estantes CDSEstantes.DisableControls; CDSEstantes.First; while not CDSEstantes.Eof do begin if (CDSEstantes.FieldByName('PERSISTE').AsString = 'S') or (CDSEstantes.FieldByName('ID').AsInteger = 0) then begin WmsEstante := TWmsEstanteVO.Create; WmsEstante.Id := CDSEstantes.FieldByName('ID').AsInteger; WmsEstante.IdWmsRua := TWmsRuaVO(ObjetoVO).Id; WmsEstante.Codigo := CDSEstantes.FieldByName('CODIGO').AsString; WmsEstante.QuantidadeCaixa := CDSEstantes.FieldByName('QUANTIDADE_CAIXA').AsInteger; TWmsRuaVO(ObjetoVO).ListaWmsEstanteVO.Add(WmsEstante); end; CDSEstantes.Next; end; CDSEstantes.First; CDSEstantes.EnableControls; // Caixas /// EXERCICIO /// As caixas são filhas das estantes. Como implementar esse código? CDSCaixas.DisableControls; CDSCaixas.First; while not CDSCaixas.Eof do begin if (CDSCaixas.FieldByName('PERSISTE').AsString = 'S') or (CDSCaixas.FieldByName('ID').AsInteger = 0) then begin WmsCaixa := TWmsCaixaVO.Create; WmsCaixa.Id := CDSCaixas.FieldByName('ID').AsInteger; WmsCaixa.IdWmsEstante := TWmsRuaVO(ObjetoVO).Id; TWmsRuaVO(ObjetoVO).ListaWmsEstanteVO[0].ListaWmsCaixaVO.Add(WmsCaixa); end; CDSCaixas.Next; end; CDSCaixas.First; CDSCaixas.EnableControls; if StatusTela = stInserindo then begin TController.ExecutarMetodo('WmsRuaController.TWmsRuaController', 'Insere', [TWmsRuaVO(ObjetoVO)], 'PUT', 'Lista'); end else if StatusTela = stEditando then begin if TWmsRuaVO(ObjetoVO).ToJSONString <> StringObjetoOld then begin TController.ExecutarMetodo('WmsRuaController.TWmsRuaController', 'Altera', [TWmsRuaVO(ObjetoVO)], 'POST', 'Boolean'); end else Application.MessageBox('Nenhum dado foi alterado.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); end; except Result := False; end; end; end; {$ENDREGION} {$REGION 'Controle de Grid e Edits'} procedure TFWmsEndereco.GridParaEdits; begin inherited; if not CDSGrid.IsEmpty then begin ObjetoVO := TWmsRuaVO(TController.BuscarObjeto('WmsRuaController.TWmsRuaController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET')); end; if Assigned(ObjetoVO) then begin EditCodigo.Text := TWmsRuaVO(ObjetoVO).Codigo; EditNome.Text := TWmsRuaVO(ObjetoVO).Nome; EditQuantidadeEstante.AsInteger := TWmsRuaVO(ObjetoVO).QuantidadeEstante; TController.TratarRetorno<TWmsEstanteVO>(TWmsRuaVO(ObjetoVO).ListaWmsEstanteVO, True, True, CDSEstantes); /// EXERCICIO /// Como carregar os dados das caixas vinculadas às estantes? TWmsCaixaController.SetDataSet(CDSCaixas); TController.ExecutarMetodo('WmsCaixaController.TWmsCaixaController', 'Consulta', ['ID>0', '0', False], 'GET', 'Lista'); // Serializa o objeto para consultar posteriormente se houve alterações FormatSettings.DecimalSeparator := '.'; StringObjetoOld := ObjetoVO.ToJSONString; FormatSettings.DecimalSeparator := ','; end; end; {$ENDREGION} {$REGION 'Actions'} procedure TFWmsEndereco.ActionAdicionarCaixaExecute(Sender: TObject); begin inherited; /// EXERCICIO /// Implemente o procedimento end; procedure TFWmsEndereco.ActionAdicionarEstanteExecute(Sender: TObject); begin inherited; /// EXERCICIO /// Implemente o procedimento end; {$ENDREGION} {$REGION 'Exclusões Internas'} procedure TFWmsEndereco.ActionRemoverEstanteExecute(Sender: TObject); begin if Application.MessageBox('Tem certeza que deseja remover a Estante?', 'Pergunta do Sistema', MB_YesNo + MB_IconQuestion) = IdYes then begin if StatusTela = stInserindo then CDSEstantes.Delete else if StatusTela = stEditando then begin TController.ExecutarMetodo('WmsRuaController.TWmsRuaController', 'ExcluiItem', [CDSEstantes.FieldByName('ID').AsInteger], 'DELETE', 'Boolean'); if TController.RetornoBoolean then CDSEstantes.Delete; end; end; end; procedure TFWmsEndereco.ActionRemoverCaixaExecute(Sender: TObject); begin if Application.MessageBox('Tem certeza que deseja remover a Caixa?', 'Pergunta do Sistema', MB_YesNo + MB_IconQuestion) = IdYes then begin if StatusTela = stInserindo then CDSCaixas.Delete else if StatusTela = stEditando then begin TController.ExecutarMetodo('WmsRuaController.TWmsRuaController', 'ExcluiServico', [CDSCaixas.FieldByName('ID').AsInteger], 'DELETE', 'Boolean'); if TController.RetornoBoolean then CDSCaixas.Delete; end; end; end; procedure TFWmsEndereco.ControlaPersistencia(pDataSet: TDataSet); begin pDataSet.FieldByName('PERSISTE').AsString := 'S'; end; {$ENDREGION} /// EXERCICIO /// Implemente o mestre/detalhe entre os clientdatasets end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, LCLType, Grids, Windows, math , NPCs; type { TForm1 } TForm1 = class(TForm) Image1: TImage; Player: TPLAYER; Shape2: TShape; Timer1: TTimer; killanimation_timer: TTimer; procedure FormCreate(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word); procedure FormKeyUp(Sender: TObject; var Key: Word); procedure Image1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure Timer1Timer(Sender: TObject); procedure killtimer(Sender: TObject); private public end; var Form1: TForm1; implementation var upp,downp,leftp,rightp:boolean; shoot:boolean; //player controls paralyzed:boolean; paralyzetimer: 0..5; enemy:array of NPC; play_bullets: array [0..15] of strela; enem_bullets:array [0..100] of strela; play_health: TPlayerHealthbar; cooldown:integer = 0; //player shoot cooldown healthpoints, maxhealthpoints:integer; bullplay,bullenem:integer; //počíta, kam dať ďalší náboj level: 1..25; levelcleared:array [1..25] of boolean; gotkey:boolean; killcount,enemies:integer; timer:integer; //animation_timer_delay:boolean; //niečo ako delay() {$R *.lfm} {$I levels.inc} procedure TForm1.FormCreate(Sender: TObject); var i:integer; begin randomize; level:=1; timer:=0; for i:=1 to 25 do levelcleared[i]:=false; paralyzed:=false; gotkey:=false; bullplay:=0; bullenem:=16; healthpoints:=400; maxhealthpoints:=400; play_health:=TPlayerHealthbar.create(nil); with play_health do begin Parent:=Form1; left:=50; top:=640; paint(healthpoints,maxhealthpoints); end; for i:=0 to length(play_bullets)-1 do begin play_bullets[i]:=strela.create(nil); with play_bullets[i] do begin parent:=Form1; shape:=playstrela2; top:=-50; left:=-50; idle:=true; paint; end; end; for i:=0 to length(enem_bullets)-1 do begin enem_bullets[i]:=strela.Create(nil); with enem_bullets[i] do begin parent:=Form1; top:=-50; left:=-50; idle:=true; paint; end; end; Player:=TPLAYER.Create(Form1); Player.Width:=50; Player.Height:=50; Player.top:=350; Player.left:=700; Player.Parent:=Form1; Player.paint; changelevel; end; procedure proshoot; begin if bullplay>length(play_bullets)-2 then bullplay:=0 else bullplay:=bullplay+1; with play_bullets[bullplay] do begin vx:=Form1.Player.aimx; vy:=Form1.Player.aimy; x:=Form1.Player.left+Form1.Player.width div 2+round(Form1.Player.aimx*15)-4; y:=Form1.Player.top+Form1.Player.height div 2+round(Form1.Player.aimy*15)-4; top:=round(y)-height div 2; left:=round(x)-width div 2; idle:=false; end; end; function fuhol(x,y:real;var tempc:real):real; var tempa,tempb:integer; begin tempa:=Form1.Player.left+Form1.Player.width div 2-round(x); tempb:=Form1.Player.top+Form1.Player.height div 2-round(y); tempc:=sqrt(sqr(tempa)+sqr(tempb)); if tempc<>0 then fuhol:=arcsin(tempa/tempc); if tempb<0 then fuhol:=pi()-fuhol; end; procedure enemshoot(iter:NPC); var i:integer; uhol,tempc:real; begin if bullenem>length(enem_bullets)-6 then bullenem:=0; if iter<>nil then begin bullenem:=bullenem+1; uhol:=fuhol(iter.x,iter.y,tempc); case iter.enemytype of mage: with enem_bullets[bullenem] do begin uhol:=uhol+random(1000)/5000-0.1; shape:=enemstrela2; vx:=sin(uhol); vy:=cos(uhol); iter.vx:=sin(uhol); iter.vy:=cos(uhol); iter.Top:=iter.top+60; iter.Top:=iter.top-60; x:=iter.left+iter.width div 2; y:=iter.top+iter.height div 2; top:=round(y)-4; left:=round(x)-4; idle:=false; end; sorcerer: for i:=1 to 3 do begin with enem_bullets[bullenem] do begin shape:=enemstrela3; vx:=sin(uhol-i*0.2+0.4); vy:=cos(uhol-i*0.2+0.4); iter.vx:=sin(uhol); iter.vy:=cos(uhol); x:=iter.left+iter.width div 2; y:=iter.top+iter.height div 2; top:=round(y)-4; left:=round(x)-4; idle:=false; end; bullenem+=1; iter.Top:=iter.top+60; iter.Top:=iter.top-60; end; turret: begin if iter.shoottimer mod 4=1 then uhol+=pi/4; for i:=1 to 4 do begin with enem_bullets[bullenem] do begin shape:=enemstrela1; vx:=sin(uhol+i*pi/2); vy:=cos(uhol+i*pi/2); x:=iter.left+iter.width div 2; y:=iter.top+iter.height div 2; top:=round(y)-4; left:=round(x)-4; idle:=false; end; bullenem+=1; iter.Top:=iter.top+60; iter.Top:=iter.top-60; end; end; cannon: begin with enem_bullets[bullenem] do begin shape:=mina; vx:=sin(uhol); vy:=cos(uhol); iter.vx:=sin(uhol); iter.vy:=cos(uhol); iter.Top:=iter.top+60; iter.Top:=iter.top-60; x:=iter.left+iter.width div 2; y:=iter.top+iter.height div 2; top:=round(y)-4; left:=round(x)-4; idle:=false; end; end; end; end; end; procedure TForm1.killtimer(Sender: TObject); var i:integer; begin for i:=0 to length(enemy)-1 do if enemy[i]<>nil then if enemy[i].ded then with enemy[i] do begin top:=top+60; top:=top-60; //kvôli paint funkcií health:=health-1; if health=-14 then begin form1.killanimation_timer.Enabled:=false; Freeandnil(enemy[i]); killcount+=1; if killcount=enemies then begin levelcleared[level]:=true; changelevel; end; Freeandnil(killanimation_timer); end; end; end; procedure Do_killanimation(iter:NPC); begin if iter.health<1 then with iter do begin ded:=True; health:=-10; //podľa hodnoty robí animáciu end; form1.killanimation_timer:=TTimer.Create(Form1); with form1.killanimation_timer do //timer begin interval:=60; OnTimer:=@form1.killtimer; enabled:=true; end; end; procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word); begin case Key of VK_W:upp:=true; VK_S:downp:=true; VK_A:leftp:=true; VK_D:rightp:=true; VK_SPACE:shoot:=true; end; end; procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word); begin case Key of VK_W:upp:=false; VK_S:downp:=false; VK_A:leftp:=false; VK_D:rightp:=false; VK_SPACE:shoot:=false; end; end; procedure TForm1.Image1MouseMove(Sender: TObject; Shift: TShiftState; X,Y: Integer); var tempc:real; tempx,tempy:integer; begin tempx:=X-form1.left; tempy:=Y-form1.Top; tempc:=sqrt(sqr(tempx-Player.Left-Player.width div 2)+sqr(tempy-Player.top-Player.height div 2)); Player.aimx:=(tempx-Player.Left-Player.width div 2)/tempc; Player.aimy:=(tempy-Player.top-Player.height div 2)/tempc; end; procedure timer2; var i:integer; //enemy timer begin if paralyzed then paralyzetimer+=1; if paralyzetimer=5 then paralyzed:=false; for i:=0 to length(enemy)-1 do if enemy[i]<>nil then begin enemy[i].incshoottimer; case enemy[i].enemytype of mage: if enemy[i].shoottimer<10 then begin enemshoot(enemy[i]); enemy[i].movable:=false; end else enemy[i].movable:=true; sorcerer: if enemy[i].shoottimer=1 then enemshoot(enemy[i]); turret: if enemy[i].shoottimer=1 then enemshoot(enemy[i]); cannon: if enemy[i].shoottimer=1 then begin enemshoot(enemy[i]); enemy[i].movable:=false; end else if enemy[i].shoottimer=7 then enemy[i].movable:=true; end; if (enemy[i].health<1) and (not enemy[i].ded) then begin Do_killanimation(enemy[i]); end; end; play_health.paint(healthpoints, maxhealthpoints); end; procedure TForm1.Timer1Timer(Sender: TObject); var i,j:integer; uhol,tempc:real; begin form1.Canvas.Changing; if healthpoints < 0 then //smrť begin timer1.enabled:=false; ShowMessage('GAMEOVER'); end; if GetAsynckeystate(MK_LBUTTON)<>0 then shoot:=true else shoot:=false; image1mousemove(nil,[],mouse.CursorPos.X,mouse.CursorPos.Y); if cooldown<50 then cooldown:=cooldown+1; if upp and (image1.Canvas.Pixels[Player.left,Player.top-4]=clgray) and not paralyzed then Player.top:=Player.top-4; if downp and (image1.Canvas.Pixels[Player.left,Player.top+Player.height+4]=clgray) and not paralyzed then Player.top:=Player.top+4; if leftp and (image1.Canvas.Pixels[Player.left-4,Player.top]=clgray) and not paralyzed then Player.left:=Player.left-4; if rightp and (image1.Canvas.Pixels[Player.left+Player.width+4,Player.top]=clgray) and not paralyzed then Player.left:=Player.left+4; Player.Top:=player.top+60; Player.Top:=player.top-60; if shoot and (cooldown>20) then //fire rate begin proshoot; cooldown:=0; end; if Player.left<5 then //prechod do levelov begin level+=1; Player.left:=form1.width-Player.width-100; changelevel; end; if Player.top<5 then begin level+=5; Player.top:=form1.height-Player.Height-100; changelevel; end; if Player.left>995-Player.width then //prechod do levelov begin level-=1; Player.left:=100; changelevel; end; if Player.top>695-Player.height then begin level-=5; Player.top:=100; changelevel; end; for i:=0 to length(play_bullets)-1 do //pohyb hráčových nábojov begin if not play_bullets[i].idle then with play_bullets[i] do begin moving; if (x+width div 2>image1.Width-100) or (x+width div 2<100) or (y+height div 2>image1.height-100) or (y+height div 2<100) then begin x:=0; y:=0; vx:=0; vy:=0; top:=-50; left:=-50; idle:=true; end else for j:=0 to length(enemy)-1 do if (enemy[j]<>nil) and (enemy[j].enemytype<>key) then if (x+hitboxwidth>enemy[j].x-enemy[j].hitboxwidth) and (x-hitboxwidth<enemy[j].x+enemy[j].hitboxwidth) and (y+hitboxheight>enemy[j].y-enemy[j].hitboxheight) and (y-hitboxheight<enemy[j].y+enemy[j].hitboxheight) then begin begin x:=0; y:=0; vx:=0; vy:=0; top:=-50; left:=-50; idle:=true; end; if enemy[j].health>1 then enemy[j].health:=enemy[j].health-damage; end; end; end; for i:=0 to length(enem_bullets)-1 do //pohyb ostatných nábojov if not enem_bullets[i].idle then with enem_bullets[i] do begin moving; if (shape=mina) then begin if damage=-2 then begin fuhol(x,y,tempc); if tempc<96 then healthpoints-=90; end; if damage=-16 then begin x:=0; y:=0; vx:=0; vy:=0; top:=-50; left:=-50; damage:=0; idle:=true; end; end; if (x+width div 2>image1.Width-100) or (x-width div 2<100) or (y+height div 2>image1.height-100) or (y-height div 2<100) then if enem_bullets[i].shape=mina then enem_bullets[i].v:=0 else begin x:=0; y:=0; vx:=0; vy:=0; top:=-50; left:=-50; idle:=true; end else if (x+hitboxwidth>Player.left) and (x-hitboxwidth<Player.left+Player.width) and (y+hitboxheight>Player.top) and (y-hitboxheight<Player.top+Player.height) and (enem_bullets[i].shape<>mina) then begin healthpoints-=enem_bullets[i].damage; play_health.paint(healthpoints,maxhealthpoints); begin x:=0; y:=0; vx:=0; vy:=0; top:=-50; left:=-50; idle:=true; end; end; end; for i:=0 to length(enemy)-1 do if (enemy[i]<>nil) and enemy[i].movable then begin uhol:=fuhol(enemy[i].x,enemy[i].y,tempc); if (enemy[i].enemytype=paralyzer) and (tempc<40) then begin paralyzed:=true; paralyzetimer:=0; end; if (enemy[i].enemytype=key) and (tempc<20) and (enemy[i].health>0) then begin gotkey:=true; enemy[i].health:=-2; Do_killanimation(enemy[i]); continue; end; enemy[i].vx:=sin(uhol); enemy[i].vy:=cos(uhol); enemy[i].moving; end; timer+=1; if timer=14 then begin timer2; timer:=0; end; form1.canvas.Changed; end; end.
{$include kode.inc} unit kode_isaac; // http://www.wolfgang-ehrhardt.de/misc_en.html { TODO: check, double-check, triple-check see also: http://sebsauvage.net/isaac/ } //{$define CONST} {const in proc declaration} //{$define V7PLUS} {TP7 or higher} //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- type Ptr2Inc = pByte; KIsaac = class private FRandMem : array[0..255] of longint; // the internal state FRandRes : array[0..255] of longint; // the results given to the user FRandA : longint; // accumulator FRandB : longint; // the last result FRandC : longint; // counter, guarantees cycle >= 2^40 FNextRes : longint; // the next result FRandIdx : word; // the index in FRandRes[] private procedure generate; procedure internal_init(flag:boolean); public procedure init (seed:longint); procedure init0; procedure inita(const key:array of longint; klen:integer); procedure next; procedure read(dest:pointer; len:longint); public function getLong : longint; function getDword : longint; function getWord : word; function getDouble : double; function getDouble53 : double; //function selftest: boolean; end; (* isaac_ctx = record // context of random number generator FRandMem : array[0..255] of longint; // the internal state FRandRes : array[0..255] of longint; // the results given to the user FRandA : longint; // accumulator FRandB : longint; // the last result FRandC : longint; // counter, guarantees cycle >= 2^40 FNextRes : longint; // the next result FRandIdx : word; // the index in FRandRes[] end; // Type cast to increment untyped pointer Ptr2Inc = pByte; //---------- // Init context from FRandRes[0]=seed, FRandRes[i]=0 otherwise procedure isaac_init (var ctx: isaac_ctx; seed: longint); // Init context from randseed procedure isaac_init0(var ctx: isaac_ctx); // Init all context variables with separate seeds, klen: number of seeds procedure isaac_inita(var ctx: isaac_ctx; const key: array of longint; klen: integer); // Next step of PRNG procedure isaac_next(var ctx: isaac_ctx); // Read len bytes from the PRNG to dest procedure isaac_read(var ctx: isaac_ctx; dest: pointer; len: longint); // Next random positive longint function isaac_long(var ctx: isaac_ctx): longint; // Next 32 bit random dword (cardinal or longint) function isaac_dword(var ctx: isaac_ctx): longint; // Next random word function isaac_word(var ctx: isaac_ctx): word; // Next random double [0..1) with 32 bit precision function isaac_double(var ctx: isaac_ctx): double; // Next random double in [0..1) with full double 53 bit precision function isaac_double53(var ctx: isaac_ctx): double; // Simple self-test of ISAAC PRNG //function isaac_selftest: boolean; *) //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- // generate next 256 result values, ie refill FRandRes procedure KIsaac.generate; var x,y : longint; xi : integer absolute x; {better performance for BIT16} i : integer; begin inc(FRandC); inc(FRandB,FRandC); for i := 0 to 255 do begin case i and 3 of 0 : FRandA := FRandA xor (FRandA shl 13); 1 : FRandA := FRandA xor (FRandA shr 6); 2 : FRandA := FRandA xor (FRandA shl 2); 3 : FRandA := FRandA xor (FRandA shr 16); end; x := FRandMem[i]; inc(FRandA,FRandMem[(i+128) and 255]); y := FRandMem[(xi shr 2) and 255] + FRandA + FRandB; FRandMem[i] := y; FRandB := FRandMem[(y shr 10) and 255] + x; FRandRes[i] := FRandB; end; // reset result index FRandIdx := 0; end; //---------- // Init state, use FRandRes if flag=true procedure KIsaac.internal_init(flag: boolean); var i,j : integer; m : array[0..7] of longint; // mix the array procedure Mix; begin m[0] := m[0] xor (m[1] shl 11); inc(m[3], m[0]); inc(m[1], m[2]); m[1] := m[1] xor (m[2] shr 2); inc(m[4], m[1]); inc(m[2], m[3]); m[2] := m[2] xor (m[3] shl 8); inc(m[5], m[2]); inc(m[3], m[4]); m[3] := m[3] xor (m[4] shr 16); inc(m[6], m[3]); inc(m[4], m[5]); m[4] := m[4] xor (m[5] shl 10); inc(m[7], m[4]); inc(m[5], m[6]); m[5] := m[5] xor (m[6] shr 4); inc(m[0], m[5]); inc(m[6], m[7]); m[6] := m[6] xor (m[7] shl 8); inc(m[1], m[6]); inc(m[7], m[0]); m[7] := m[7] xor (m[0] shr 9); inc(m[2], m[7]); inc(m[0], m[1]); end; begin FRandA := 0; FRandB := 0; FRandC := 0; for i := 0 to 7 do m[i] := longint($9e3779b9); {the golden ratio} for i := 0 to 3 do Mix; i := 0; while i < 256 do begin // fill in FRandMem[] with messy stuff if flag then begin // use all the information in the seed for j := 0 to 7 do inc(m[j], FRandRes[i+j]); end; Mix; move(m,FRandMem[i],sizeof(m)); inc(i,8); end; if flag then begin // do a second pass to make all of the seed affect all of FRandMem i := 0; while i < 256 do begin for j := 0 to 7 do inc(m[j], FRandMem[i+j]); Mix; move(m, FRandMem[i], sizeof(m)); inc(i,8); end; end; // generate first set of results generate; // prepare to use the first set of results FRandIdx := 0; end; //---------------------------------------------------------------------- // //---------------------------------------------------------------------- // Init context from FRandRes[0] = seed, FRandRes[i] = 0 otherwise procedure KIsaac.init(seed: longint); begin fillchar(FRandRes, sizeof(FRandRes),0); FRandRes[0] := seed; internal_init(true); end; //---------- // Init context from randseed and FRandRes[i]:=random procedure KIsaac.init0; var i,j : integer; tl : longint; ta : packed array[0..3] of byte absolute tl; begin for i := 0 to 255 do begin for j := 0 to 3 do ta[j] := byte(random(256)); FRandRes[i] := tl; end; internal_init(true); end; //---------- // Init all context variables with separate seeds, klen: number of seeds procedure KIsaac.inita(const key:array of longint; klen:integer); var i : integer; begin for i := 0 to 255 do begin if i < klen then FRandRes[i] := key[i] else FRandRes[i] := 0; end; internal_init(true); end; //---------- // Next step of PRNG procedure KIsaac.next; begin if FRandIdx > 255 then generate; FNextRes := FRandRes[FRandIdx]; inc(FRandIdx); end; //---------- // Read len bytes from the PRNG to dest procedure KIsaac.read(dest:pointer; len:longint); type plong = ^longint; begin // not optimized next; plong(dest)^ := FNextRes; inc(Ptr2Inc(dest),4); dec(len, 4); if len > 0 then begin next; move(FNextRes, dest^, len and 3); end; end; //---------------------------------------------------------------------- // Next random positive longint function KIsaac.getLong : longint; begin next; result := FNextRes shr 1; end; //---------- // Next 32 bit random dword (cardinal or longint) function KIsaac.getDword : longint; begin next; result := FNextRes; end; //---------- // Next random word function KIsaac.getWord : word; type TwoWords = packed record L,H : word end; begin next; result := TwoWords(FNextRes).H; end; //---------- // Next random double [0..1) with 32 bit precision function KIsaac.getDouble : double; begin next; result := (FNextRes + 2147483648.0) / 4294967296.0; end; //---------- // Next random double in [0..1) with full double 53 bit precision function KIsaac.getDouble53 : double; var hb,lb : longint; begin next; hb := FNextRes shr 5; next; lb := FNextRes shr 6; result := (hb * 67108864.0 + lb) / 9007199254740992.0; end; //---------- // Simple self-test of ISAAC PRNG (* function KIsaac.isaac_selftest: boolean; var ctx: isaac_ctx; begin fillchar(ctx,sizeof(ctx),0); internal_init(ctx, true); isaac_generate(ctx); // check first and last longint of randvec.txt if ctx.FRandRes[0]<>longint($f650e4c8) then begin isaac_selftest := false; exit; end; isaac_generate(ctx); isaac_selftest := ctx.FRandRes[255] = longint($4bb5af29); end; *) //---------------------------------------------------------------------- end.
unit ucap_basevars; {##################################################################################} (*!*EXTENDED COMMENT SYNTAX !*) (** This unit uses extended syntax for comments **) (** You don't need to support this, but it's more likely to be readable **) (** if you do **) (** If your IDE is using SynEdit, you may find a SynHighlighterPas.pp-file here: **) (** https://github.com/Life4YourGames/IDE-Extensions **) (** You have to set the colors yourself in your IDEs setting **) (** Afaik: Lazarus and CodeTyphon automatically detect those new attributes **) (** Also: The comments are all valid fpc-comments, you don't have to worry **) (** Syntax-description: **) (*- Divider **) (* Native AnsiComment / Cathegory **) (*! Warning, pay attention !*) (* TODO **) (* DONE **) { native bor comment } //Native double-slash comment (*! End of comment syntax info **) {##################################################################################} {$mode objfpc}{$H+} interface uses Classes, SysUtils (** JSONs*), fpjson ; const (*- Constants used for JSON-Operations -*) CCAP_JSONKey_Type: ShortString = 'type'; CCAP_JSONKey_ID: ShortString = 'cap_name'; CCAP_JSONVal_permType_Single: ShortString = 'cap_permsingle'; CCAP_JSONVal_permType_Ref: ShortString = 'cap_permref'; CCAP_JSONKey_permRefs: ShortString = 'cap_permref'; CCAP_JSONVal_UType: ShortString = 'cap_user'; CCAP_JSONKey_User: ShortString = 'cap_user'; CCAP_JSONKey_UAttributes: ShortString = 'cap_user_attributes'; CCAP_JSONKey_UOptionIDs: ShortString = 'cap_user_optionids'; CCAP_JSONKey_UOptionVals: ShortString = 'cap_user_optionvals'; CCAP_JSONKey_UGroups: ShortString = 'cap_user_groups'; CCAP_JSONVal_GType: ShortString = 'cap_group'; CCAP_JSONKey_Group: ShortString = 'cap_group'; CCAP_JSONKey_GAttributes: ShortString = 'cap_group_attributes'; CCAP_JSONKey_GOptionIDs: ShortString = 'cap_group_optionids'; CCAP_JSONKey_GOptionVals: ShortString = 'cap_group_optionvals'; CCAP_JSONKey_GUsers: ShortString = 'cap_group_users'; CCAP_JSONKey_MgmtPermissions: ShortString = 'cap_mgmt_perms'; CCAP_JSONKey_MgmtUsers: ShortString = 'cap_mgmt_users'; CCAP_JSONKey_MgmtGroups: ShortString = 'cap_mgmt_group'; CCAP_JSONKey_MgmtSettings: ShortString = 'cap_mgmt_settings'; (*- Defaults -*) CCAP_DefaultCompare: ShortString = '>'; CCAP_DefaultJSONFormat = [foSingleLineObject, foSingleLineArray]; CCAP_DefUser: ShortString = 'u_default'; CCAP_DefGroup: ShortString = 'g_default'; (*- Constants used by "uCAP_Mgmt" -*) (** Note: Those can be overriden by customizing the settings-file or the object in runtime *) (** "%.%" is representing the Head-dir "FSavePath" in the object *) CCAP_Mgmt_DirStruc_Users: ShortString = '%.%/users'; CCAP_Mgmt_DirStruc_Groups: ShortString = '%.%/groups'; CCAP_Mgmt_DirStruc_Settings: ShortString = '%.%/settings'; var (*- Variables used by "uCAP_Mgmt" -*) (** This is for you, if you want other internal aliases (e.g. if you need those strings to be in your filenames, whyever you would want that) *) (*! A standart I use in my projects: Path-Aliases are always replaced !without! trailing PathDelim !*) (** This counts also for Returned paths: WITHOUT trailing PathDelim *) CCAP_Mgmt_DirAlias_Permissions: ShortString = '%perms%'; CCAP_Mgmt_DirAlias_Users: ShortString = '%usrs%'; CCAP_Mgmt_DirAlias_Groups: ShortString = '%grps%'; CCAP_Mgmt_DirAlias_head: ShortString = '%.%'; CCAP_Mgmt_DirAlias_Settings: ShortString = '%sttg%'; CCAP_Mgmt_Sttg_HeadDir: ShortString = 'mgmt_sttg_headdir'; CCAP_Mgmt_Sttg_UserDir: ShortString = 'mgmt_sttg_userdir'; CCAP_Mgmt_Sttg_GroupDir: ShortString = 'mgmt_sttg_groupdir'; CCAP_Mgmt_Sttg_SttgDir: ShortString = 'mgmt_sttg_sttgdir'; CCAP_Mgmt_Sttg_FilePrefix: ShortString = 'mgmt_sttg_fileprefix'; CCAP_Mgmt_Sttg_FileSuffix: ShortString = 'mgmt_sttg_filesuffix'; (** Yes, these are also used in ex-/import *) CCAP_Mgmt_Index_Settings: ShortString = 'cap_mgmt_settings'; CCAP_Mgmt_Index_Permissions: ShortString = 'cap_mgmt_perms'; CCAP_Mgmt_Index_Users: ShortString = 'cap_mgmt_users'; CCAP_Mgmt_Index_Groups: ShortString = 'cap_mgmt_groups'; CCAP_Mgmt_Index_AliasIndexes: ShortString = 'cap_mgmt_aliasids'; CCAP_Mgmt_Index_AliasValues: ShortString = 'cap_mgmt_aliasvals'; (* Some more Aliases *) CCAP_Alias_ID: ShortString = '%Ident%'; CCAP_Alias_ObjectID: ShortString = '%ObjectID%'; CCAP_Alias_Time: ShortString ='%time%'; CCAP_Alias_Date: ShortString = '%date%'; type ECustomAPError = class(Exception); const (*! Error-Codes and corresponding names! You will need them to debug !*) (*- Errors -*) (** Errors are always using this scheme <error>:(<error_2>:...<error_n>):<reason>:adit *) (** If you find EC and not ERC, it's still an Errorcode *) (** I know this looks stupid, but e.g. an exception could be caused by another error or could result in another error *) //This is a warning witch CAN be very important, but doesn't have to => you CAN ignore it, if you want to EC_CAP_E_000: ShortString = 'CAP_EC_000_'; EN_CAP_E_000: ShortString = 'Explicit_Warning:'; //This is most commonly followed by "E.ClassName + ':' + E.Message" EC_CAP_E_001: ShortString = 'CAP_EC_001:'; EN_CAP_E_001: ShortString = 'An_exception_occured:'; //Commonly followed by the reason EC_CAP_E_002: ShortString = 'CAP_EC_002:'; EN_CAP_E_002: ShortString = 'Unable_to_import:'; //Commonly followed by the reason EC_CAP_E_003: ShortString = 'CAP_EC_003:'; EN_CAP_E_003: ShortString = 'Unable_to_open_file:'; (*- Reasons -*) //Commonly followed by nothing, a warning AND/OR a debug hint ERC_CAP_E_201: ShortString = 'CAP_ERC_201:'; ERN_CAP_E_201: ShortString = 'Invalid_datatype:'; //Commonly followed by nothing, a warning AND/OR a debug hint ERC_CAP_E_202: ShortString = 'CAP_ERC_202:'; ERN_CAP_E_202: ShortString = 'No_Data:'; //Commonly followed by nothing, a warning AND/OR a debug hint ERC_CAP_E_203: ShortString = 'CAP_ERC_203:'; ERN_CAP_E_203: ShortString = 'Insufficient_Data:'; //Commonly followed by nothing, a warning AND/OR a debug hint ERC_CAP_E_204: ShortString = 'CAP_ERC_204:'; ERN_CAP_E_204: ShortString = 'Invalid_value:'; (*! Some information on compiler options *) (** Use CAP_DisableAbstract to "remove" abstract method - warnings (Note: Enabled by default in package-settings) *) (** Use CAP_UseInt64 to enable Int64 Support for permissions-values *) (** Use CAP_StrictSeperations to seperate TBaseObject.GetName(nil) to TBaseObject.GetIdent to avoid confusion *) implementation end.
unit ArrayBld; //////////////////////////////////////////////////////////////////////////////// // // Author: Jaap Baak // https://github.com/transportmodelling/Utils // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// interface //////////////////////////////////////////////////////////////////////////////// Type TArrayBuilder<T> = record private FValues: TArray<T>; Function GetValues(Index: Integer): T; inline; public Class Operator Implicit(const Values: array of T): TArrayBuilder<T>; Class Operator Implicit(const Builder: TArrayBuilder<T>): TArray<T>; Class Operator Add(const A: TArrayBuilder<T>; const B: array of T): TArrayBuilder<T>; Class Operator Add(const A: TArrayBuilder<T>; const B: TArrayBuilder<T>): TArrayBuilder<T>; Class Function Concat(const A: array of T; const B: array of T): TArray<T>; overload; static; Class Function Concat(const A: array of T; const B: array of T; const C: array of T): TArray<T>; overload; static; public Constructor Create(const Values: array of T); overload; Constructor Create(const Values: array of T; const First,count: Integer); overload; Constructor Create(const Length: Integer; const Values: T); overload; Constructor Create(const Length: Integer); overload; Function Length: Integer; inline; Procedure Append(const Values: array of T); overload; Procedure Append(const Values: array of T; const First,Count: Integer); overload; Procedure Clear; public Property AsArray: TArray<T> read FValues; Property Values[Index: Integer]: T read GetValues; default; end; TIntArrayBuilder = TArrayBuilder<Integer>; TFloatArrayBuilder = TArrayBuilder<Float64>; TFloat32ArrayBuilder = TArrayBuilder<Float32>; TStringArrayBuilder = TArrayBuilder<String>; TCharArrayBuilder = TArrayBuilder<Char>; //////////////////////////////////////////////////////////////////////////////// implementation //////////////////////////////////////////////////////////////////////////////// Class Operator TArrayBuilder<T>.Implicit(const Values: array of T): TArrayBuilder<T>; begin Result := TArrayBuilder<T>.Create(Values); end; Class Operator TArrayBuilder<T>.Implicit(const Builder: TArrayBuilder<T>): TArray<T>; begin Result := Builder.AsArray; end; Class Operator TArrayBuilder<T>.Add(const A: TArrayBuilder<T>; const B: array of T): TArrayBuilder<T>; begin Result.Append(A.FValues); Result.Append(B); end; Class Operator TArrayBuilder<T>.Add(const A: TArrayBuilder<T>; const B: TArrayBuilder<T>): TArrayBuilder<T>; begin Result.Append(A.FValues); Result.Append(B.FValues); end; Class Function TArrayBuilder<T>.Concat(const A: array of T; const B: array of T): TArray<T>; var Builder: TArrayBuilder<T>; begin Builder.Append(A); Builder.Append(B); Result := Builder; end; Class Function TArrayBuilder<T>.Concat(const A: array of T; const B: array of T; const C: array of T): TArray<T>; var Builder: TArrayBuilder<T>; begin Builder.Append(A); Builder.Append(B); Builder.Append(C); Result := Builder; end; Constructor TArrayBuilder<T>.Create(const Values: array of T); begin Finalize(FValues); Append(Values); end; Constructor TArrayBuilder<T>.Create(const Values: array of T; const First,count: Integer); begin Finalize(FValues); Append(Values,First,Count); end; Constructor TArrayBuilder<T>.Create(const Length: Integer; const Values: T); begin SetLength(FValues,Length); for var Index := 0 to Length-1 do FValues[Index] := Values; end; Constructor TArrayBuilder<T>.Create(const Length: Integer); begin SetLength(FValues,Length); end; Function TArrayBuilder<T>.GetValues(Index: Integer): T; begin Result := FValues[Index]; end; Function TArrayBuilder<T>.Length: Integer; begin Result := System.Length(FValues); end; Procedure TArrayBuilder<T>.Append(const Values: array of T); begin Append(Values,low(Values),System.Length(Values)); end; Procedure TArrayBuilder<T>.Append(const Values: array of T; const First,Count: Integer); begin var Offset := Length; SetLength(FValues,Offset+Count); for var Index := 0 to Count-1 do FValues[Index+Offset] := Values[First+Index]; end; Procedure TArrayBuilder<T>.Clear; begin FValues := nil; end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: VO relacionado ą tabela [Transportadora] The MIT License Copyright: Copyright (C) 2015 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije @version 2.0 ******************************************************************************* } unit UTransportadora; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UTelaCadastro, Menus, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, Mask, JvExMask, JvToolEdit, JvCombobox, LabeledCtrls, DBCtrls, LabeledDBCtrls, DB, DBClient, StrUtils, Math, JSonVO, Generics.Collections, Atributos, Constantes, CheckLst, JvExCheckLst, JvCheckListBox, JvBaseEdits, ULookup, PessoaVO, PessoaController; type [TFormDescription(TConstantes.MODULO_CADASTROS, 'Transportadora')] TFTransportadora = class(TFTelaCadastro) ScrollBox: TScrollBox; BevelEdits: TBevel; EditIdContabilConta: TLabeledCalcEdit; EditContabilConta: TLabeledEdit; EditNomePessoa: TLabeledEdit; EditIdPessoa: TLabeledCalcEdit; MemoObservacao: TLabeledMemo; procedure FormCreate(Sender: TObject); procedure EditIdPessoaExit(Sender: TObject); procedure EditIdPessoaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditIdPessoaKeyPress(Sender: TObject; var Key: Char); procedure EditIdContabilContaExit(Sender: TObject); procedure EditIdContabilContaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditIdContabilContaKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } procedure GridParaEdits; override; // Controles CRUD function DoInserir: Boolean; override; function DoEditar: Boolean; override; function DoExcluir: Boolean; override; function DoSalvar: Boolean; override; end; var FTransportadora: TFTransportadora; implementation uses Biblioteca, TransportadoraVO, TransportadoraController, UDataModule, ContabilContaVO, ContabilContaController; {$R *.dfm} {$REGION 'Infra'} procedure TFTransportadora.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TTransportadoraVO; ObjetoController := TTransportadoraController.Create; inherited; end; {$ENDREGION} {$REGION 'Controles CRUD'} function TFTransportadora.DoInserir: Boolean; begin Result := inherited DoInserir; if Result then begin EditIdPessoa.SetFocus; end; end; function TFTransportadora.DoEditar: Boolean; begin Result := inherited DoEditar; if Result then begin EditIdPessoa.SetFocus; end; end; function TFTransportadora.DoExcluir: Boolean; begin if inherited DoExcluir then begin try Result := TPessoaController(ObjetoController).Exclui(IdRegistroSelecionado); except Result := False; end; end else begin Result := False; end; if Result then TTransportadoraController(ObjetoController).Consulta(Filtro, Pagina); end; function TFTransportadora.DoSalvar: Boolean; begin if EditIdPessoa.Text = '' then begin Application.MessageBox('Informe o Código da Pessoa.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); EditIdPessoa.SetFocus; Exit(False); end; Result := inherited DoSalvar; if Result then begin try if not Assigned(ObjetoVO) then ObjetoVO := TTransportadoraVO.Create; TTransportadoraVO(ObjetoVO).DataCadastro := Date(); TTransportadoraVO(ObjetoVO).IdPessoa := EditIdPessoa.AsInteger; TTransportadoraVO(ObjetoVO).PessoaNome := EditNomePessoa.Text; TTransportadoraVO(ObjetoVO).IdContabilConta := EditIdContabilConta.AsInteger; TTransportadoraVO(ObjetoVO).ContabilContaClassificacao := EditContabilConta.Text; TTransportadoraVO(ObjetoVO).Observacao := MemoObservacao.Text; if StatusTela = stInserindo then Result := TTransportadoraController(ObjetoController).Insere(TTransportadoraVO(ObjetoVO)) else if StatusTela = stEditando then begin if TTransportadoraVO(ObjetoVO).ToJSONString <> TTransportadoraVO(ObjetoOldVO).ToJSONString then begin TTransportadoraVO(ObjetoVO).Id := IdRegistroSelecionado; Result := TTransportadoraController(ObjetoController).Altera(TTransportadoraVO(ObjetoVO), TTransportadoraVO(ObjetoOldVO)); end else Application.MessageBox('Nenhum dado foi alterado.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); end; except Result := False; end; end; end; {$ENDREGION} {$REGION 'Campos Transientes'} procedure TFTransportadora.EditIdContabilContaExit(Sender: TObject); var Filtro: String; begin if EditIdContabilConta.Value <> 0 then begin try Filtro := 'ID = ' + EditIdContabilConta.Text; EditIdContabilConta.Clear; EditContabilConta.Clear; if not PopulaCamposTransientes(Filtro, TContabilContaVO, TContabilContaController) then PopulaCamposTransientesLookup(TContabilContaVO, TContabilContaController); if CDSTransiente.RecordCount > 0 then begin EditIdContabilConta.Text := CDSTransiente.FieldByName('ID').AsString; EditContabilConta.Text := CDSTransiente.FieldByName('CLASSIFICACAO').AsString; end else begin Exit; EditIdContabilConta.SetFocus; end; finally CDSTransiente.Close; end; end else begin EditContabilConta.Clear; end; end; procedure TFTransportadora.EditIdContabilContaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_F1 then begin EditIdContabilConta.Value := -1; MemoObservacao.SetFocus; end; end; procedure TFTransportadora.EditIdContabilContaKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin Key := #0; MemoObservacao.SetFocus; end; end; procedure TFTransportadora.EditIdPessoaExit(Sender: TObject); var Filtro: String; begin if EditIdPessoa.Value <> 0 then begin try Filtro := 'ID = ' + EditIdPessoa.Text; EditIdPessoa.Clear; EditNomePessoa.Clear; if not PopulaCamposTransientes(Filtro, TPessoaVO, TPessoaController) then PopulaCamposTransientesLookup(TPessoaVO, TPessoaController); if CDSTransiente.RecordCount > 0 then begin EditIdPessoa.Text := CDSTransiente.FieldByName('ID').AsString; EditNomePessoa.Text := CDSTransiente.FieldByName('NOME').AsString; end else begin Exit; EditIdPessoa.SetFocus; end; finally CDSTransiente.Close; end; end else begin EditNomePessoa.Clear; end; end; procedure TFTransportadora.EditIdPessoaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_F1 then begin EditIdPessoa.Value := -1; EditIdContabilConta.SetFocus; end; end; procedure TFTransportadora.EditIdPessoaKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin Key := #0; EditIdContabilConta.SetFocus; end; end; {$ENDREGION} {$REGION 'Controle de Grid'} procedure TFTransportadora.GridParaEdits; begin inherited; if not CDSGrid.IsEmpty then begin ObjetoVO := ObjetoController.VO<TTransportadoraVO>(IdRegistroSelecionado); if StatusTela = stEditando then ObjetoOldVO := ObjetoVO.Clone; end; if Assigned(ObjetoVO) then begin // Transportadora EditIdPessoa.AsInteger := TTransportadoraVO(ObjetoVO).IdPessoa; EditNomePessoa.Text := TTransportadoraVO(ObjetoVO).PessoaNome; EditIdContabilConta.AsInteger := TTransportadoraVO(ObjetoVO).IdContabilConta; EditContabilConta.Text := TTransportadoraVO(ObjetoVO).ContabilContaClassificacao; MemoObservacao.Text := TTransportadoraVO(ObjetoVO).Observacao; end; end; {$ENDREGION} end.
unit uKeys; interface type TKeys = class // ветка текущего приложения class function Home: string; // ветка настроек приложения class function Main:string; // ветка подключений class function Connections:string; class function Connection(aConnectionName:string):string; // ветка пространства имён class function NameSpace(aConnectionName:string):string; // ветка справочников class function References(aConnectionName:string):string; end; implementation uses System.SysUtils, Forms; { TKeys } class function TKeys.Connection(aConnectionName: string): string; begin Result := TKeys.Connections + '\' + aConnectionName; end; class function TKeys.Connections: string; begin Result := TKeys.Home+'\Connection'; end; class function TKeys.Home: string; var fn:string; begin fn := ExtractFileName(Application.ExeName); fn := ChangeFileExt(fn,''); Result := '\Software\Monitoring\'+fn; end; class function TKeys.Main: string; begin Result := TKeys.Home+'\Main'; end; class function TKeys.NameSpace(aConnectionName: string): string; begin Result := Format('%s\%s\NameSpace', [TKeys.Connections, aConnectionName]); end; class function TKeys.References(aConnectionName: string): string; begin Result := Format('%s\%s\References', [TKeys.Connections, aConnectionName]); end; end.
unit Marvin.Core.IA.Connectionist.Classifier; { MIT License Copyright (c) 2018-2019 Marcus Vinicius D. B. Braga 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. } interface uses { marvin } Marvin.Core.InterfacedList, Marvin.Core.IA.Connectionist.Activation, Marvin.Core.IA.Connectionist.LayerInitInfo; type TDoubleArray = array of Double; TDoubleMatrix = array of TDoubleArray; THelperDoubleArray = record helper for TDoubleArray function Clone: TDoubleArray; function IsMaxValue(const AValue: Double): Double; function ToBinaryValue: TDoubleArray; function ToString: string; function IsEquals(const AValue: TDoubleArray): Boolean; end; IClassifier = interface ['{FF28CF74-02E0-437A-96A7-F45B404E8439}'] function ConfigureClassifier: IClassifier; function SetHiddenLayerSizes(const AHiddenLayersInfo: TLayerInitInfoArray): IClassifier; function SetLearningFile(const ALearningFile: string): IClassifier; function SetLearning(const ALearning: Double): IClassifier; function SetMaxIter(const AMaxIter: Integer): IClassifier; function SetMomentum(const AMomentum: Double): IClassifier; function Cost: Double; function Epochs: Integer; function EpochsCovered: Integer; { treino } function Fit(const ATrainDataInputs: TDoubleArray; const ATrainDataOutputs: TDoubleArray): IClassifier; overload; function Fit(const ATrainDataInputs: IList<TDoubleArray>; const ATrainDataOutputs: IList<TDoubleArray>): IClassifier; overload; function Fit(const ATrainDataInputs: IList<IList<Double>>; const ATrainDataOutputs: IList<IList<Double>>): IClassifier; overload; { teste } function Predict(const ATestDataInputs: TDoubleArray; out APredictedDataOutputs: TDoubleArray): IClassifier; overload; function Predict(const ATestDataInputs: IList<TDoubleArray>; out APredictedDataOutputs: IList<TDoubleArray>): IClassifier; overload; function Predict(const ATestDataInputs: IList<IList<Double>>; out APredictedDataOutputs: IList<IList<Double>>): IClassifier; overload; end; implementation uses { embarcadero } System.Math, System.SysUtils; { THelperDoubleArray } function THelperDoubleArray.Clone: TDoubleArray; var LIndex: Integer; begin Result := nil; SetLength(Result, Length(Self)); for LIndex := Low(Self) to High(Self) do begin Result[LIndex] := Self[LIndex]; end; end; function THelperDoubleArray.IsEquals(const AValue: TDoubleArray): Boolean; var LResult: Boolean; LIndex: Integer; begin LResult := (Length(Self) = Length(AValue)); if LResult then begin for LIndex := Low(Self) to High(Self) do begin if (Self[LIndex] <> AValue[LIndex]) then begin LResult := False; Break; end; end; end; Result := LResult; end; function THelperDoubleArray.IsMaxValue(const AValue: Double): Double; begin Result := 0; if MaxValue(Self) = AValue then begin Result := 1; end; end; function THelperDoubleArray.ToBinaryValue: TDoubleArray; procedure LToBinary(const AMax, AMin: Double); var LIndex: Integer; begin for LIndex := Low(Self) to High(Self) do begin if Self[LIndex] = MaxValue(Self) then Self[LIndex] := AMax else Self[LIndex] := AMin; end; end; begin Result := Self; LToBinary(MaxDouble, MinDouble); LToBinary(1, 0); end; function THelperDoubleArray.ToString: string; var LIndex: Integer; begin Result := EmptyStr; for LIndex := Low(Self) to High(Self) do begin Result := Result + Self[LIndex].ToString + ', '; end; Result := Result.Trim; Delete(Result, Length(Result), 1); Result := Format('[%s]', [Result]); end; end.
namespace Sugar.TestFramework; interface type {$IF ECHOES} List<T> = public class mapped to System.Collections.Generic.List<T> public method &Add(Item: T); mapped to &Add(Item); method AddRange(Items: List<T>); mapped to AddRange(Items); method ToArray: array of T; mapped to ToArray; property Count: Integer read mapped.Count; property Item[i: Integer]: T read mapped[i] write mapped[i]; default; end; {$ELSEIF COOPER} List<T> = public class mapped to java.util.ArrayList<T> public method &Add(Item: T); mapped to &add(Item); method AddRange(Items: List<T>); mapped to addAll(Items); method ToArray: array of T; mapped to toArray; property Count: Integer read mapped.size; property Item[i: Integer]: T read mapped[i] write mapped[i]; default; end; {$ELSEIF NOUGAT} List<T> = public class mapped to Foundation.NSMutableArray where T is class; public method &Add(Item: T); mapped to addObject(Item); method AddRange(Items: List<T>); mapped to addObjectsFromArray(Items); method ToArray: array of T; property Count: Integer read mapped.count; property Item[i: Integer]: T read mapped[i] write mapped[i]; default; end; {$ENDIF} implementation {$IF NOUGAT} method List<T>.ToArray: array of T; begin result := new T[mapped.count]; for i: Integer := 0 to mapped.count - 1 do result[i] := mapped.objectAtIndex(i); end; {$ENDIF} end.
program testsqrt02(output); procedure quadraticformula(a,b,c:real); {input: the coeffients for a parabola ax^2 + bx + c prints out the roots} var discriminant, axisofsymmetry:real; isimaginary:boolean; begin axisofsymmetry := (-1 * b) / (2 * a); discriminant := (b * b) - (4 * a * c); if discriminant < 0 then begin discriminant := -1 * discriminant; discriminant := sqrt(discriminant); writeln('root 1: x = ', axisofsymmetry, ' + ', discriminant / (2 * a), 'i'); writeln('root 2: x = ', axisofsymmetry, ' - ', discriminant / (2 * a), 'i') end else begin discriminant := sqrt(discriminant); writeln('root 1: x = ', axisofsymmetry + (discriminant / (2 * a))); writeln('root 2: x = ', axisofsymmetry - (discriminant / (2 * a))) end end; begin quadraticformula(9,3,-14); quadraticformula(2,37,-4); quadraticformula(3.9,-19.6,0.1); quadraticformula(1,1,1); end.
unit UProcesoAdministrador; interface uses Forms, SysUtils, Strutils, DBclient, Classes, DB, UDAOParametro, UModulo, UDMAplicacion; type TProcesoAdministrador = class private {METODOS PROPIOS} FDatosModulo : TClientDataSet; public {CONSTRUCTORES} constructor Create; destructor Destroy; {PROPIEDADES} property DatosModulo : TClientDataSet read FDatosModulo; Procedure VerificarVersion(p_NombModu: string;p_VersModu: string; P_VeriRuta: Boolean); function ObtenerDatosModulo(P_NombModu: string; P_NombOpci: string): TModulo; end; implementation function TProcesoAdministrador.ObtenerDatosModulo(P_NombModu: string; P_NombOpci: string): TModulo; var Codierro : Integer; DatoPara : TDAOParametro; NumePuer : string; PuerNume : Integer; begin DatoPara := TDAOParametro.create; FDatosModulo := DatoPara.BuscarInformacionModulo(P_NombModu); Result := TModulo.Create; with FDatosModulo do begin First; if not eof then begin with Result do begin NombreModulo := P_NombModu; Version := IfThen(Locate('PROPIEDAD','VERSION',[]), Fields[2].value, ''); IpFtpDescarga := IfThen(Locate('PROPIEDAD','FTPHOST',[]), Fields[2].value, ''); NumePuer := IfThen(Locate('PROPIEDAD','FTPPUERTO',[]), Fields[2].value,''); UsuarioFtpDescarga := IfThen(Locate('PROPIEDAD','FTPUSUARIO',[]), Fields[2].value,''); PasswordFtpDescarga := IfThen(Locate('PROPIEDAD','FTPPASSWORD',[]), Fields[2].value,''); RutaFtpDescarga := IfThen(Locate('PROPIEDAD','FTPRUTAAPLICACION',[]), Fields[2].value,''); RutaDestino := IfThen(Locate('PROPIEDAD','RUTADESTINO',[]), Fields[2].value,''); ArchivoEjecutable := IfThen(Locate('PROPIEDAD','ARCHIVOEJECUTABLE',[]), Fields[2].value,''); val(NumePuer, PuerNume, CodiErro); PuertoFtpDescarga:= PuerNume; if (Trim(Version) = '') or (Trim(IpFtpDescarga) = '') or (Trim(NumePuer) = '') or (Trim(UsuarioFtpDescarga) = '') or (Trim(PasswordFtpDescarga) = '') or (Trim(RutaFtpDescarga) = '') or (Trim(RutaDestino) = '') or (Trim(ArchivoEjecutable) = '') or (CodiErro <> 0) or (LowerCase(ExtractFileExt(ArchivoEjecutable)) <> '.exe') then raise Exception.Create('Imposible ejecutar la Opción [' + P_NombOpci + '].' + #13#10 + 'El Parámetro [' + P_NombModu + '] tiene información incorrecta.' ) else begin RutaFtpDescarga := ifThen(AnsiRightStr(RutaFtpDescarga,1) = '\', RutaFtpDescarga,RutaFtpDescarga + '\'); if MidStr(RutaDestino,2,1) = ':' then RutaDestino := ifThen(AnsiRightStr(RutaDestino,1) = '\', RutaDestino,RutaDestino + '\') else begin {SE LE DA UN TRATAMIENTO ESPACIAL AL MODULO DE CARPETA DIGITAL (DURENTE UN TIEMPO DE 1 MES) YA QE LA RUTA LOCAL DEL EJECUTABLE DE ESTE MÓDULO NO TIENE UNIDAD DE DISCO Y AHORA TODOS LA TIENEN} if P_NombModu = 'MODULOCARPETADIGITAL' then begin RutaDestino := ifThen(AnsiLeftStr(RutaDestino,1) = '\', RutaDestino, '\' + RutaDestino ); RutaDestino := ExtractFileDir(Application.ExeName) + RutaDestino; RutaDestino := ifThen(AnsiRightStr(RutaDestino,1) = '\', RutaDestino,RutaDestino + '\'); end else raise Exception.Create('Imposible ejecutar la Opción [' + P_NombOpci + '].' + #13#10 + '* Ruta de Instalación incorrecta. ' + 'No se especifica la Unidad de Disco.'); end; end; end; end else raise Exception.Create('Imposible ejecutar la Opción [' + P_NombOpci + '].' + #13#10 + 'No existe el Parámetro [' + P_NombModu + '].' ); end; end; Procedure TProcesoAdministrador.VerificarVersion(p_NombModu: string;p_VersModu: string; P_VeriRuta:Boolean); begin DMAplicacion.VerificarAplicacion(p_NombModu,p_VersModu, 'ADMINISTRADOR FABRICA UNIANDES',P_VeriRuta); end; {$REGION 'CONSTRUTOR AND DESTRUCTOR'} constructor TProcesoAdministrador.Create; begin FDatosModulo := TClientDataSet.Create(nil); end; destructor TProcesoAdministrador.Destroy; begin FDatosModulo.Free; end; {$ENDREGION} {$REGION 'GETTERS AND SETTERS'} {$ENDREGION} end.
Unit AfsVolumes; { Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } Interface Uses AdvObjects, AdvStringHashes, AdvStreams, AdvExceptions, AdvObjectLists, AdvIterators, AdvItems; Type TAfsMode = (amRead, amWrite, amCreate); TAfsShare = (asNone, asRead, asWrite); // Simple types TAfsHandle = NativeUInt; // Forward declarations TAfsVolume = Class; TAfsList = Class; TAfsEntity = Class; EAfs = Class(EAdvException); TAfsObject = Class(TAdvStringHashEntry) Protected Procedure RaiseError(Const sMethod, sException : String); Override; End; { TAfsObject } TAfsClass = Class Of TAfsObject; TAfsIterator = Class(TAdvIterator) Private FVolume : TAfsVolume; Procedure SetVolume(Const Value: TAfsVolume); Protected Procedure RaiseError(Const sMethod, sMessage : String); Override; Function GetCurrent : TAfsEntity; Virtual; Abstract; Public Constructor Create(oVolume : TAfsVolume); Overload; Virtual; Destructor Destroy; Override; Property Current : TAfsEntity Read GetCurrent; Property Volume : TAfsVolume Read FVolume Write SetVolume; End; { TAfsIterator } TAfsIteratorClass = Class Of TAfsIterator; TAfsVolume = Class(TAfsObject) Private FMode : TAfsMode; Protected Function GetAllocation : Cardinal; Virtual; Procedure SetAllocation(Value : Cardinal); Virtual; Public Function Link : TAfsVolume; Overload; Function Clone : TAfsVolume; Overload; Procedure Open; Overload; Virtual; Procedure Format; Overload; Virtual; Procedure Close; Overload; Virtual; Procedure Delete; Overload; Virtual; Function Exists : Boolean; Overload; Virtual; Abstract; Function Active : Boolean; Overload; Virtual; Abstract; Function Open(Const libName, sName : String; amMode : TAfsMode; asShare : TAfsShare) : TAfsHandle; Overload; Virtual; Abstract; Procedure Read(oHandle : TAfsHandle; Var Buffer; iCount : Cardinal); Virtual; Abstract; Procedure Write(oHandle : TAfsHandle; Const Buffer; iCount : Cardinal); Virtual; Abstract; Procedure Close(oHandle : TAfsHandle); Overload; Virtual; Abstract; Function GetSize(oHandle : TAfsHandle) : Int64; Virtual; Abstract; Function GetPosition(oHandle : TAfsHandle) : Int64; Virtual; Abstract; Procedure SetPosition(oHandle : TAfsHandle; Const iValue : Int64); Virtual; Abstract; Function Exists(Const sName : String) : Boolean; Overload; Virtual; Abstract; Procedure Rename(Const sSource, sDestination : String); Overload; Virtual; Abstract; Procedure Delete(Const sName : String); Overload; Virtual; Abstract; Function OpenIterator : TAfsIterator; Virtual; Abstract; Procedure CloseIterator(oIterator : TAfsIterator); Virtual; Abstract; Property Allocation : Cardinal Read GetAllocation Write SetAllocation; Property Mode : TAfsMode Read FMode Write FMode; End; { TAfsVolume } TAfsVolumeClass = Class Of TAfsVolume; TAfsStream = Class(TAdvAccessStream) Private FVolume : TAfsVolume; FHandle : TAfsHandle; Procedure SetVolume(Const Value: TAfsVolume); Protected Function GetPosition : Int64; Override; Procedure SetPosition(Const Value : Int64); Override; Function GetSize : Int64; Override; Procedure SetSize(Const Value : Int64); Override; Public Constructor Create(oVolume : TAfsVolume; oHandle : TAfsHandle); Overload; Destructor Destroy; Override; Procedure Read(Var Buffer; iCount : Cardinal); Override; Procedure Write(Const Buffer; iCount : Cardinal); Override; Function Readable : Int64; Override; Property Volume : TAfsVolume Read FVolume Write SetVolume; Property Handle : TAfsHandle Read FHandle Write FHandle; End; { TAfsStream } TAfsEntity = Class(TAfsObject) Private FVolume : TAfsVolume; FStream : TAfsStream; FMode : TAfsMode; FShare : TAfsShare; Procedure SetMode(Value : TAfsMode); Procedure SetShare(Value : TAfsShare); Procedure SetVolume(Const Value: TAfsVolume); Public Constructor Create; Overload; Override; Destructor Destroy; Override; Constructor Create(oVolume : TAfsVolume; Const sName : String = ''); Overload; Procedure Assign(oSource : TAdvObject); Override; Procedure Open; Overload; Virtual; Procedure Open(amMode : TAfsMode; asShare : TAfsShare = asRead); Overload; Procedure Open(Const sName : String; amMode : TAfsMode; asShare : TAfsShare = asRead); Overload; Procedure Close; Function Valid : Boolean; Overload; Virtual; Property Volume : TAfsVolume Read FVolume Write SetVolume; Property Stream : TAfsStream Read FStream; Property Mode : TAfsMode Read FMode Write SetMode; Property Share : TAfsShare Read FShare Write SetShare; End; { TAfsEntity } TAfsEntityClass = Class Of TAfsEntity; TAfsEntities = Class(TAdvStringHashTable) End; { TAfsEntities } TAfsContainer = Class(TAfsEntity) Private FItems : TAfsEntities; Protected Property Items : TAfsEntities Read FItems; Public Constructor Create; Override; Destructor Destroy; Override; End; { TAfsContainer } TAfsRoot = Class(TAfsContainer) Public Property Items; End; { TAfsRoot } TAfsFolder = Class(TAfsContainer) Public Property Items; End; { TAfsFolder } TAfsFile = Class(TAfsEntity) End; { TAfsFile } TAfsList = Class(TAdvObjectList) Private Function GetEntities(Index : Integer) : TAfsEntity; Procedure SetEntities(Index : Integer; Const Value : TAfsEntity); Protected Function CompareName(pA, pB : Pointer) : Integer; Overload; Virtual; Procedure DefaultCompare(Out aCompare : TAdvItemsCompare); Overload; Override; Function ItemClass : TAdvClass; Override; Public Property Entities[Index : Integer] : TAfsEntity Read GetEntities Write SetEntities; Default; End; { TAfsList } TAfsFiles = Class(TAfsList) Private Function GetFiles(Index : Integer) : TAfsFile; Procedure SetFiles(Index : Integer; Const Value : TAfsFile); Public Property Files[Index : Integer] : TAfsFile Read GetFiles Write SetFiles; Default; End; { TAfsFiles } Implementation Uses StringSupport, MathSupport; Procedure TAfsObject.RaiseError(Const sMethod, sException : String); Begin { Procedure TAfsObject.Error } RaiseError(EAfs, sMethod, sException); End; { Procedure TAfsObject.Error } Procedure TAfsIterator.RaiseError(Const sMethod, sMessage : String); Begin { Procedure TAfsIterator.Error } RaiseError(EAfs, sMethod, sMessage); End; { Procedure TAfsIterator.Error } Constructor TAfsIterator.Create(oVolume : TAfsVolume); Begin { Constructor TAfsIterator.Create } Create; FVolume := oVolume; End; { Constructor TAfsIterator.Create } Function TAfsVolume.GetAllocation : Cardinal; Begin { Function TAfsVolume.GetAllocation } Result := 0; End; { Function TAfsVolume.GetAllocation } Procedure TAfsVolume.SetAllocation(Value : Cardinal); Begin { Procedure TAfsVolume.SetAllocation } RaiseError('SetAllocation', 'Cannot set allocation unit size.'); End; { Procedure TAfsVolume.SetAllocation } Function TAfsVolume.Clone: TAfsVolume; Begin Result := TAfsVolume(Inherited Clone); End; Function TAfsVolume.Link: TAfsVolume; Begin Result := TAfsVolume(Inherited Link); End; Procedure TAfsVolume.Open; Begin { Procedure TAfsVolume.Open } End; { Procedure TAfsVolume.Open } Procedure TAfsVolume.Format; Begin { Procedure TAfsVolume.Format } End; { Procedure TAfsVolume.Format } Procedure TAfsVolume.Close; Begin { Procedure TAfsVolume.Close } End; { Procedure TAfsVolume.Close } Procedure TAfsVolume.Delete; Begin { Procedure TAfsVolume.Delete } End; { Procedure TAfsVolume.Delete } Function TAfsStream.GetPosition : Int64; Begin { Function TAfsStream.GetPosition } Result := FVolume.GetPosition(FHandle); End; { Function TAfsStream.GetPosition } Procedure TAfsStream.SetPosition(Const Value : Int64); Begin { Procedure TAfsStream.SetPosition } FVolume.SetPosition(FHandle, Value); End; { Procedure TAfsStream.SetPosition } Function TAfsStream.GetSize : Int64; Begin { Function TAfsStream.GetSize } Result := FVolume.GetSize(FHandle); End; { Function TAfsStream.GetSize } Procedure TAfsStream.SetSize(Const Value : Int64); Begin { Procedure TAfsStream.SetSize } RaiseError('SetSize', 'Not implemented'); // FVolume.SetSize(FHandle, Value); End; { Procedure TAfsStream.SetSize } Constructor TAfsStream.Create(oVolume : TAfsVolume; oHandle : TAfsHandle); Begin { Constructor TAfsStream.Create } Create; FVolume := oVolume; FHandle := oHandle; End; { Constructor TAfsStream.Create } Procedure TAfsStream.Read(Var Buffer; iCount : Cardinal); Begin { Procedure TAfsStream.Read } FVolume.Read(FHandle, Buffer, iCount); End; { Procedure TAfsStream.Read } Procedure TAfsStream.Write(Const Buffer; iCount : Cardinal); Begin { Procedure TAfsStream.Write } FVolume.Write(FHandle, Buffer, iCount); End; { Procedure TAfsStream.Write } Function TAfsStream.Readable : Int64; Begin { Function TAfsStream.Readable } Result := Size - Position; End; { Function TAfsStream.Readable } Procedure TAfsEntity.SetMode(Value : TAfsMode); Begin { Procedure TAfsEntity.SetMode } FMode := Value; End; { Procedure TAfsEntity.SetMode } Procedure TAfsEntity.SetShare(Value : TAfsShare); Begin { Procedure TAfsEntity.SetShare } FShare := Value; End; { Procedure TAfsEntity.SetShare } Constructor TAfsEntity.Create; Begin { Constructor TAfsEntity.Create } Inherited Create; FStream := TAfsStream.Create; FShare := asRead; End; { Constructor TAfsEntity.Create } Destructor TAfsEntity.Destroy; Begin { Destructor TAfsEntity.Destroy } FStream.Free; FVolume.Free; Inherited; End; { Destructor TAfsEntity.Destroy } Constructor TAfsEntity.Create(oVolume : TAfsVolume; Const sName : String); Begin { Constructor TAfsEntity.Create } Create; FVolume := oVolume; Name := sName; End; { Constructor TAfsEntity.Create } Procedure TAfsEntity.Assign(oSource : TAdvObject); Begin { Procedure TAfsEntity.Assign } Inherited; FVolume := TAfsEntity(oSource).Volume; FMode := TAfsEntity(oSource).Mode; FShare := TAfsEntity(oSource).Share; End; { Procedure TAfsEntity.Assign } Procedure TAfsEntity.Open; Begin { Procedure TAfsEntity.Open } If Not Assigned(FVolume) Then RaiseError('Open', 'AFS volume not assigned.') Else Begin { If } FStream.Volume := FVolume.Link; FStream.Handle := FVolume.Open('', Name, FMode, FShare); If FStream.Handle = 0 Then RaiseError('Open', StringFormat('Unable to open ''%s'' in volume ''%s''', [Name, FVolume.Name])); End { If } End; { Procedure TAfsEntity.Open } Procedure TAfsEntity.Open(amMode : TAfsMode; asShare : TAfsShare = asRead); Begin { Procedure TAfsEntity.Open } FMode := amMode; FShare := asShare; Open; End; { Procedure TAfsEntity.Open } Procedure TAfsEntity.Open(Const sName : String; amMode : TAfsMode; asShare : TAfsShare); Begin { Procedure TAfsEntity.Open } Name := sName; Open(amMode, asShare); End; { Procedure TAfsEntity.Open } Procedure TAfsEntity.Close; Begin { Procedure TAfsEntity.Close } If FStream.Handle <> 0 Then Begin { If } FVolume.Close(FStream.Handle); FStream.Handle := 0; FStream.Volume := Nil; End; { If } End; { Procedure TAfsEntity.Close } Function TAfsEntity.Valid : Boolean; Begin { Function TAfsEntity.Valid } Result := Assigned(FVolume) And Assigned(FStream); End; { Function TAfsEntity.Valid } Procedure TAfsEntity.SetVolume(Const Value: TAfsVolume); Begin { Procedure TAfsEntity.SetVolume } FVolume.Free; FVolume := Value; End; { Procedure TAfsEntity.SetVolume } Constructor TAfsContainer.Create; Begin { Constructor TAfsContainer.Create } Inherited Create; FItems := TAfsEntities.Create; FItems.Capacity := 37; // Arbitrary low prime End; { Constructor TAfsContainer.Create } Destructor TAfsContainer.Destroy; Begin { Destructor TAfsContainer.Destroy } FItems.Free; Inherited; End; { Destructor TAfsContainer.Destroy } Function TAfsList.GetEntities(Index : Integer) : TAfsEntity; Begin { Function TAfsList.GetEntities } Result := TAfsEntity(ItemByIndex[Index]); End; { Function TAfsList.GetEntities } Procedure TAfsList.SetEntities(Index : Integer; Const Value : TAfsEntity); Begin { Procedure TAfsList.SetEntities } ItemByIndex[Index] := Value; End; { Procedure TAfsList.SetEntities } Function TAfsList.CompareName(pA, pB : Pointer) : Integer; Begin { Function TAfsList.DefaultCompare } Result := IntegerCompare(Integer(TAfsEntity(pA).ClassType), Integer(TAfsEntity(pB).ClassType)); If Result = 0 Then Result := StringCompare(TAfsEntity(pA).Name, TAfsEntity(pB).Name); End; { Function TAfsList.DefaultCompare } Procedure TAfsList.DefaultCompare(Out aCompare: TAdvItemsCompare); Begin { Procedure TAfsList.DefaultCompare } aCompare := CompareName; End; { Procedure TAfsList.DefaultCompare } Function TAfsList.ItemClass : TAdvClass; Begin { Function TAfsList.ItemClass } Result := TAfsEntity; End; { Function TAfsList.ItemClass } Function TAfsFiles.GetFiles(Index : Integer) : TAfsFile; Begin { Function TAfsFiles.GetFiles } Result := TAfsFile(Entities[Index]); End; { Function TAfsFiles.GetFiles } Procedure TAfsFiles.SetFiles(Index : Integer; Const Value : TAfsFile); Begin { Procedure TAfsFiles.SetFiles } Entities[Index] := Value; End; { Procedure TAfsFiles.SetFiles } Destructor TAfsIterator.Destroy; Begin { Destructor TAfsIterator.Destroy } FVolume.Free; Inherited; End; { Destructor TAfsIterator.Destroy } Procedure TAfsIterator.SetVolume(Const Value: TAfsVolume); Begin { Procedure TAfsIterator.SetVolume } FVolume.Free; FVolume := Value; End; { Procedure TAfsIterator.SetVolume } Destructor TAfsStream.Destroy; Begin { Destructor TAfsStream.Destroy } FVolume.Free; Inherited; End; { Destructor TAfsStream.Destroy } Procedure TAfsStream.SetVolume(Const Value: TAfsVolume); Begin { Procedure TAfsStream.SetVolume } FVolume.Free; FVolume := Value; End; { Procedure TAfsStream.SetVolume } End. // AfsVolumes //
unit UnitModel; {$ifdef fpc} {$mode delphi} {$ifdef cpui386} {$define cpu386} {$endif} {$ifdef cpu386} {$asmmode intel} {$endif} {$ifdef cpuamd64} {$asmmode intel} {$endif} {$ifdef fpc_little_endian} {$define little_endian} {$else} {$ifdef fpc_big_endian} {$define big_endian} {$endif} {$endif} {$ifdef fpc_has_internal_sar} {$define HasSAR} {$endif} {-$pic off} {$define CAN_INLINE} {$ifdef FPC_HAS_TYPE_EXTENDED} {$define HAS_TYPE_EXTENDED} {$else} {$undef HAS_TYPE_EXTENDED} {$endif} {$ifdef FPC_HAS_TYPE_DOUBLE} {$define HAS_TYPE_DOUBLE} {$else} {$undef HAS_TYPE_DOUBLE} {$endif} {$ifdef FPC_HAS_TYPE_SINGLE} {$define HAS_TYPE_SINGLE} {$else} {$undef HAS_TYPE_SINGLE} {$endif} {$else} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$realcompatibility off} {$localsymbols on} {$define little_endian} {$ifndef cpu64} {$define cpu32} {$endif} {$define delphi} {$undef HasSAR} {$define UseDIV} {$define HAS_TYPE_EXTENDED} {$define HAS_TYPE_DOUBLE} {$define HAS_TYPE_SINGLE} {$endif} {$ifdef cpu386} {$define cpux86} {$endif} {$ifdef cpuamd64} {$define cpux86} {$endif} {$ifdef win32} {$define windows} {$endif} {$ifdef win64} {$define windows} {$endif} {$ifdef wince} {$define windows} {$endif} {$ifdef windows} {$define win} {$endif} {$ifdef sdl20} {$define sdl} {$endif} {$rangechecks off} {$extendedsyntax on} {$writeableconst on} {$hints off} {$booleval off} {$typedaddress off} {$stackframes off} {$varstringchecks on} {$typeinfo on} {$overflowchecks off} {$longstrings on} {$openstrings on} {$ifndef HAS_TYPE_DOUBLE} {$error No double floating point precision} {$endif} {$ifdef fpc} {$define CAN_INLINE} {$else} {$undef CAN_INLINE} {$ifdef ver180} {$define CAN_INLINE} {$else} {$ifdef conditionalexpressions} {$if compilerversion>=18} {$define CAN_INLINE} {$ifend} {$endif} {$endif} {$endif} interface uses SysUtils, Classes, Math, Vulkan, Kraft, PasVulkan.Framework, PasVulkan.Streams; const VULKAN_MODEL_VERTEX_BUFFER_BIND_ID=0; type PVulkanModelVector2=^TVulkanModelVector2; TVulkanModelVector2=packed record case TVkInt32 of 0:( x,y:TVkFloat; ); 1:( u,v:TVkFloat; ); 2:( r,g:TVkFloat; ); end; PVulkanModelVector3=^TVulkanModelVector3; TVulkanModelVector3=packed record case TVkInt32 of 0:( x,y,z:TVkFloat; ); 1:( u,v,w:TVkFloat; ); 2:( r,g,b:TVkFloat; ); end; PVulkanModelVector4=^TVulkanModelVector4; TVulkanModelVector4=packed record case TVkInt32 of 0:( x,y,z,w:TVkFloat; ); 1:( u,v,w_,q:TVkFloat; ); 2:( r,g,b,a:TVkFloat; ); end; PVulkanModelQuaternion=^TVulkanModelQuaternion; TVulkanModelQuaternion=packed record x,y,z,w:TVkFloat; end; PVulkanModelQTangent=^TVulkanModelQTangent; TVulkanModelQTangent=packed record x,y,z,w:TVkInt16; end; PVulkanModelMatrix3x3=^TVulkanModelMatrix3x3; TVulkanModelMatrix3x3=packed record case TVkInt32 of 0:( RawComponents:array[0..2,0..2] of TVkFloat; ); 1:( Vectors:array[0..2] of TVulkanModelVector3; ); 2:( Tangent:TVulkanModelVector3; Bitangent:TVulkanModelVector3; Normal:TVulkanModelVector3; ); end; PVulkanModelVertex=^TVulkanModelVertex; TVulkanModelVertex=packed record Position:TVulkanModelVector3; QTangent:TVulkanModelQTangent; TexCoord:TVulkanModelVector2; Material:TVkInt32; { // In future maybe also: BlendIndices:array[0..7] of TVkUInt16; BlendWeight:array[0..7] of TVkUInt16; } end; TVulkanModelVertices=array of TVulkanModelVertex; PVulkanModelIndex=^TVulkanModelIndex; TVulkanModelIndex=TVkUInt32; TVulkanModelIndices=array of TVulkanModelIndex; PVulkanModelMaterial=^TVulkanModelMaterial; TVulkanModelMaterial=record Name:ansistring; Texture:ansistring; Ambient:TVulkanModelVector3; Diffuse:TVulkanModelVector3; Emission:TVulkanModelVector3; Specular:TVulkanModelVector3; Shininess:TVkFloat; end; TVulkanModelMaterials=array of TVulkanModelMaterial; PVulkanModelPart=^TVulkanModelPart; TVulkanModelPart=record Material:TVkInt32; StartIndex:TVkInt32; CountIndices:TVkInt32; end; TVulkanModelParts=array of TVulkanModelPart; PVulkanModelSphere=^TVulkanModelSphere; TVulkanModelSphere=record Center:TVulkanModelVector3; Radius:TVkFloat; end; PVulkanModelAABB=^TVulkanModelAABB; TVulkanModelAABB=record Min:TVulkanModelVector3; Max:TVulkanModelVector3; end; PVulkanModelObject=^TVulkanModelObject; TVulkanModelObject=record Name:ansistring; Sphere:TVulkanModelSphere; AABB:TVulkanModelAABB; end; TVulkanModelObjects=array of TVulkanModelObject; EModelLoad=class(Exception); TVulkanModelBuffers=array of TpvVulkanBuffer; PVulkanModelBufferSize=^TVulkanModelBufferSize; TVulkanModelBufferSize=TVkUInt32; TVulkanModelBufferSizes=array of TVulkanModelBufferSize; TVulkanModel=class private fVulkanDevice:TpvVulkanDevice; fUploaded:boolean; fSphere:TVulkanModelSphere; fAABB:TVulkanModelAABB; fMaterials:TVulkanModelMaterials; fCountMaterials:TVkInt32; fVertices:TVulkanModelVertices; fCountVertices:TVkInt32; fIndices:TVulkanModelIndices; fCountIndices:TVkInt32; fParts:TVulkanModelParts; fCountParts:TVkInt32; fObjects:TVulkanModelObjects; fCountObjects:TVkInt32; fKraftMesh:TKraftMesh; fKraftConvexHull:TKraftConvexHull; fVertexBuffers:TVulkanModelBuffers; fIndexBuffers:TVulkanModelBuffers; fBufferSizes:TVulkanModelBufferSizes; fCountBuffers:TVkInt32; public constructor Create(const aVulkanDevice:TpvVulkanDevice); reintroduce; destructor Destroy; override; procedure Clear; procedure MakeCube(const aSizeX,aSizeY,aSizeZ:TVkFloat); procedure LoadFromStream(const aStream:TStream;const aDoFree:boolean=false); procedure Upload(const aQueue:TpvVulkanQueue; const aCommandBuffer:TpvVulkanCommandBuffer; const aFence:TpvVulkanFence); procedure Unload; procedure Draw(const aCommandBuffer:TpvVulkanCommandBuffer;const aInstanceCount:TVkUInt32=1;const aFirstInstance:TVkUInt32=0); property Uploaded:boolean read fUploaded; property Sphere:TVulkanModelSphere read fSphere; property AABB:TVulkanModelAABB read fAABB; property Materials:TVulkanModelMaterials read fMaterials; property CountMaterials:TVkInt32 read fCountMaterials; property Vertices:TVulkanModelVertices read fVertices; property CountVertices:TVkInt32 read fCountVertices; property Indices:TVulkanModelIndices read fIndices; property CountIndices:TVkInt32 read fCountIndices; property Parts:TVulkanModelParts read fParts; property CountParts:TVkInt32 read fCountParts; property Objects:TVulkanModelObjects read fObjects; property CountObjects:TVkInt32 read fCountObjects; property KraftMesh:TKraftMesh read fKraftMesh write fKraftMesh; property KraftConvexHull:TKraftConvexHull read fKraftConvexHull write fKraftConvexHull; end; implementation uses UnitChunkStream; function VulkanModelVector3Length(const v:TVulkanModelVector3):TVkFloat; {$ifdef CAN_INLINE}inline;{$endif} begin result:=sqr(v.x)+sqr(v.y)+sqr(v.z); if result>0.0 then begin result:=sqrt(result); end else begin result:=0.0; end; end; function VulkanModelVector3Normalize(const v:TVulkanModelVector3):TVulkanModelVector3; {$ifdef CAN_INLINE}inline;{$endif} var f:TVkFloat; begin f:=sqr(v.x)+sqr(v.y)+sqr(v.z); if f>0.0 then begin f:=sqrt(f); result.x:=v.x/f; result.y:=v.y/f; result.z:=v.z/f; end else begin result.x:=0.0; result.y:=0.0; result.z:=0.0; end; end; function VulkanModelVector3Cross(const v0,v1:TVulkanModelVector3):TVulkanModelVector3; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=(v0.y*v1.z)-(v0.z*v1.y); result.y:=(v0.z*v1.x)-(v0.x*v1.z); result.z:=(v0.x*v1.y)-(v0.y*v1.x); end; function VulkanModelVector3Add(const v0,v1:TVulkanModelVector3):TVulkanModelVector3; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=v0.x+v1.x; result.y:=v0.y+v1.y; result.z:=v0.z+v1.z; end; function VulkanModelVector3Sub(const v0,v1:TVulkanModelVector3):TVulkanModelVector3; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=v0.x-v1.x; result.y:=v0.y-v1.y; result.z:=v0.z-v1.z; end; function VulkanModelVector3Dot(const v0,v1:TVulkanModelVector3):TVkFloat; {$ifdef CAN_INLINE}inline;{$endif} begin result:=(v0.x*v1.x)+(v0.y*v1.y)+(v0.z*v1.z); end; function VulkanModelVector3ScalarMul(const v:TVulkanModelVector3;const f:TVkFloat):TVulkanModelVector3; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=v.x*f; result.y:=v.y*f; result.z:=v.z*f; end; procedure VulkanModelRobustOrthoNormalize(var Tangent,Bitangent,Normal:TVulkanModelVector3;const Tolerance:TVkFloat=1e-3); var Bisector,Axis:TVulkanModelVector3; begin begin if VulkanModelVector3Length(Normal)<Tolerance then begin // Degenerate case, compute new normal Normal:=VulkanModelVector3Cross(Tangent,Bitangent); if VulkanModelVector3Length(Normal)<Tolerance then begin Tangent.x:=1.0; Tangent.y:=0.0; Tangent.z:=0.0; Bitangent.x:=0.0; Bitangent.y:=1.0; Bitangent.z:=0.0; Normal.x:=0.0; Normal.y:=0.0; Normal.z:=1.0; exit; end; end; Normal:=VulkanModelVector3Normalize(Normal); end; begin // Project tangent and bitangent onto the normal orthogonal plane Tangent:=VulkanModelVector3Sub(Tangent,VulkanModelVector3ScalarMul(Normal,VulkanModelVector3Dot(Tangent,Normal))); Bitangent:=VulkanModelVector3Sub(Bitangent,VulkanModelVector3ScalarMul(Normal,VulkanModelVector3Dot(Bitangent,Normal))); end; begin // Check for several degenerate cases if VulkanModelVector3Length(Tangent)<Tolerance then begin if VulkanModelVector3Length(Bitangent)<Tolerance then begin Tangent:=VulkanModelVector3Normalize(Normal); if (Tangent.x<=Tangent.y) and (Tangent.x<=Tangent.z) then begin Tangent.x:=1.0; Tangent.y:=0.0; Tangent.z:=0.0; end else if (Tangent.y<=Tangent.x) and (Tangent.y<=Tangent.z) then begin Tangent.x:=0.0; Tangent.y:=1.0; Tangent.z:=0.0; end else begin Tangent.x:=0.0; Tangent.y:=0.0; Tangent.z:=1.0; end; Tangent:=VulkanModelVector3Sub(Tangent,VulkanModelVector3ScalarMul(Normal,VulkanModelVector3Dot(Tangent,Normal))); Bitangent:=VulkanModelVector3Normalize(VulkanModelVector3Cross(Normal,Tangent)); end else begin Tangent:=VulkanModelVector3Normalize(VulkanModelVector3Cross(Bitangent,Normal)); end; end else begin Tangent:=VulkanModelVector3Normalize(Tangent); if VulkanModelVector3Length(Bitangent)<Tolerance then begin Bitangent:=VulkanModelVector3Normalize(VulkanModelVector3Cross(Normal,Tangent)); end else begin Bitangent:=VulkanModelVector3Normalize(Bitangent); Bisector:=VulkanModelVector3Add(Tangent,Bitangent); if VulkanModelVector3Length(Bisector)<Tolerance then begin Bisector:=Tangent; end else begin Bisector:=VulkanModelVector3Normalize(Bisector); end; Axis:=VulkanModelVector3Normalize(VulkanModelVector3Cross(Bisector,Normal)); if VulkanModelVector3Dot(Axis,Tangent)>0.0 then begin Tangent:=VulkanModelVector3Normalize(VulkanModelVector3Add(Bisector,Axis)); Bitangent:=VulkanModelVector3Normalize(VulkanModelVector3Sub(Bisector,Axis)); end else begin Tangent:=VulkanModelVector3Normalize(VulkanModelVector3Sub(Bisector,Axis)); Bitangent:=VulkanModelVector3Normalize(VulkanModelVector3Add(Bisector,Axis)); end; end; end; end; Bitangent:=VulkanModelVector3Normalize(VulkanModelVector3Cross(Normal,Tangent)); Tangent:=VulkanModelVector3Normalize(VulkanModelVector3Cross(Bitangent,Normal)); Normal:=VulkanModelVector3Normalize(VulkanModelVector3Cross(Tangent,Bitangent)); end; function VulkanModelMatrix3x3ToQTangent(aMatrix:TVulkanModelMatrix3x3):TVulkanModelQuaternion; const Threshold=1.0/32767.0; var Scale,t,s,Renormalization:TVkFloat; begin VulkanModelRobustOrthoNormalize(aMatrix.Tangent, aMatrix.Bitangent, aMatrix.Normal); if ((((((aMatrix.RawComponents[0,0]*aMatrix.RawComponents[1,1]*aMatrix.RawComponents[2,2])+ (aMatrix.RawComponents[0,1]*aMatrix.RawComponents[1,2]*aMatrix.RawComponents[2,0]) )+ (aMatrix.RawComponents[0,2]*aMatrix.RawComponents[1,0]*aMatrix.RawComponents[2,1]) )- (aMatrix.RawComponents[0,2]*aMatrix.RawComponents[1,1]*aMatrix.RawComponents[2,0]) )- (aMatrix.RawComponents[0,1]*aMatrix.RawComponents[1,0]*aMatrix.RawComponents[2,2]) )- (aMatrix.RawComponents[0,0]*aMatrix.RawComponents[1,2]*aMatrix.RawComponents[2,1]) )<0.0 then begin // Reflection matrix, so flip y axis in case the tangent frame encodes a reflection Scale:=-1.0; aMatrix.RawComponents[2,0]:=-aMatrix.RawComponents[2,0]; aMatrix.RawComponents[2,1]:=-aMatrix.RawComponents[2,1]; aMatrix.RawComponents[2,2]:=-aMatrix.RawComponents[2,2]; end else begin // Rotation matrix, so nothing is doing to do Scale:=1.0; end; begin // Convert to quaternion t:=aMatrix.RawComponents[0,0]+(aMatrix.RawComponents[1,1]+aMatrix.RawComponents[2,2]); if t>2.9999999 then begin result.x:=0.0; result.y:=0.0; result.z:=0.0; result.w:=1.0; end else if t>0.0000001 then begin s:=sqrt(1.0+t)*2.0; result.x:=(aMatrix.RawComponents[1,2]-aMatrix.RawComponents[2,1])/s; result.y:=(aMatrix.RawComponents[2,0]-aMatrix.RawComponents[0,2])/s; result.z:=(aMatrix.RawComponents[0,1]-aMatrix.RawComponents[1,0])/s; result.w:=s*0.25; end else if (aMatrix.RawComponents[0,0]>aMatrix.RawComponents[1,1]) and (aMatrix.RawComponents[0,0]>aMatrix.RawComponents[2,2]) then begin s:=sqrt(1.0+(aMatrix.RawComponents[0,0]-(aMatrix.RawComponents[1,1]+aMatrix.RawComponents[2,2])))*2.0; result.x:=s*0.25; result.y:=(aMatrix.RawComponents[1,0]+aMatrix.RawComponents[0,1])/s; result.z:=(aMatrix.RawComponents[2,0]+aMatrix.RawComponents[0,2])/s; result.w:=(aMatrix.RawComponents[1,2]-aMatrix.RawComponents[2,1])/s; end else if aMatrix.RawComponents[1,1]>aMatrix.RawComponents[2,2] then begin s:=sqrt(1.0+(aMatrix.RawComponents[1,1]-(aMatrix.RawComponents[0,0]+aMatrix.RawComponents[2,2])))*2.0; result.x:=(aMatrix.RawComponents[1,0]+aMatrix.RawComponents[0,1])/s; result.y:=s*0.25; result.z:=(aMatrix.RawComponents[2,1]+aMatrix.RawComponents[1,2])/s; result.w:=(aMatrix.RawComponents[2,0]-aMatrix.RawComponents[0,2])/s; end else begin s:=sqrt(1.0+(aMatrix.RawComponents[2,2]-(aMatrix.RawComponents[0,0]+aMatrix.RawComponents[1,1])))*2.0; result.x:=(aMatrix.RawComponents[2,0]+aMatrix.RawComponents[0,2])/s; result.y:=(aMatrix.RawComponents[2,1]+aMatrix.RawComponents[1,2])/s; result.z:=s*0.25; result.w:=(aMatrix.RawComponents[0,1]-aMatrix.RawComponents[1,0])/s; end; s:=sqr(result.x)+sqr(result.y)+sqr(result.z)+sqr(result.w); if s>0.0 then begin s:=sqrt(s); result.x:=result.x/s; result.y:=result.y/s; result.z:=result.z/s; result.w:=result.w/s; end else begin result.x:=0.0; result.y:=0.0; result.z:=0.0; result.w:=1.0; end; end; begin // Make sure, that we don't end up with 0 as w component if abs(result.w)<=Threshold then begin Renormalization:=sqrt(1.0-sqr(Threshold)); result.x:=result.x*Renormalization; result.y:=result.y*Renormalization; result.z:=result.z*Renormalization; if result.w>0.0 then begin result.w:=Threshold; end else begin result.w:=-Threshold; end; end; end; if ((Scale<0.0) and (result.w>=0.0)) or ((Scale>=0.0) and (result.w<0.0)) then begin // Encode reflection into quaternion's w element by making sign of w negative, // if y axis needs to be flipped, otherwise it stays positive result.x:=-result.x; result.y:=-result.y; result.z:=-result.z; result.w:=-result.w; end; end; function VulkanModelMatrix3x3FromQTangent(pQTangent:TVulkanModelQuaternion):TVulkanModelMatrix3x3; var f,qx2,qy2,qz2,qxqx2,qxqy2,qxqz2,qxqw2,qyqy2,qyqz2,qyqw2,qzqz2,qzqw2:TVkFloat; begin f:=sqr(pQTangent.x)+sqr(pQTangent.y)+sqr(pQTangent.z)+sqr(pQTangent.w); if f>0.0 then begin f:=sqrt(f); pQTangent.x:=pQTangent.x/f; pQTangent.y:=pQTangent.y/f; pQTangent.z:=pQTangent.z/f; pQTangent.w:=pQTangent.w/f; end else begin pQTangent.x:=0.0; pQTangent.y:=0.0; pQTangent.z:=0.0; pQTangent.w:=1.0; end; qx2:=pQTangent.x+pQTangent.x; qy2:=pQTangent.y+pQTangent.y; qz2:=pQTangent.z+pQTangent.z; qxqx2:=pQTangent.x*qx2; qxqy2:=pQTangent.x*qy2; qxqz2:=pQTangent.x*qz2; qxqw2:=pQTangent.w*qx2; qyqy2:=pQTangent.y*qy2; qyqz2:=pQTangent.y*qz2; qyqw2:=pQTangent.w*qy2; qzqz2:=pQTangent.z*qz2; qzqw2:=pQTangent.w*qz2; result.RawComponents[0,0]:=1.0-(qyqy2+qzqz2); result.RawComponents[0,1]:=qxqy2+qzqw2; result.RawComponents[0,2]:=qxqz2-qyqw2; result.RawComponents[1,0]:=qxqy2-qzqw2; result.RawComponents[1,1]:=1.0-(qxqx2+qzqz2); result.RawComponents[1,2]:=qyqz2+qxqw2; result.RawComponents[2,0]:=(result.RawComponents[0,1]*result.RawComponents[1,2])-(result.RawComponents[0,2]*result.RawComponents[1,1]); result.RawComponents[2,1]:=(result.RawComponents[0,2]*result.RawComponents[1,0])-(result.RawComponents[0,0]*result.RawComponents[1,2]); result.RawComponents[2,2]:=(result.RawComponents[0,0]*result.RawComponents[1,1])-(result.RawComponents[0,1]*result.RawComponents[1,0]); {result.RawComponents[2,0]:=qxqz2+qyqw2; result.RawComponents[2,1]:=qyqz2-qxqw2; result.RawComponents[2,2]:=1.0-(qxqx2+qyqy2);} if pQTangent.w<0.0 then begin result.RawComponents[2,0]:=-result.RawComponents[2,0]; result.RawComponents[2,1]:=-result.RawComponents[2,1]; result.RawComponents[2,2]:=-result.RawComponents[2,2]; end; end; constructor TVulkanModel.Create(const aVulkanDevice:TpvVulkanDevice); begin inherited Create; fVulkanDevice:=aVulkanDevice; fUploaded:=false; fKraftMesh:=nil; fKraftConvexHull:=nil; fVertexBuffers:=nil; fIndexBuffers:=nil; fBufferSizes:=nil; fCountBuffers:=0; Clear; end; destructor TVulkanModel.Destroy; begin Unload; Clear; inherited Destroy; end; procedure TVulkanModel.Clear; begin fMaterials:=nil; fCountMaterials:=0; fVertices:=nil; fCountVertices:=0; fIndices:=nil; fCountIndices:=0; fParts:=nil; fCountParts:=0; fObjects:=nil; fCountObjects:=0; end; procedure TVulkanModel.MakeCube(const aSizeX,aSizeY,aSizeZ:TVkFloat); type PCubeVertex=^TCubeVertex; TCubeVertex=record Position:TVulkanModelVector3; Tangent:TVulkanModelVector3; Bitangent:TVulkanModelVector3; Normal:TVulkanModelVector3; TexCoord:TVulkanModelVector2; end; const CubeVertices:array[0..23] of TCubeVertex= (// Left (Position:(x:-1;y:-1;z:-1;);Tangent:(x:0;y:0;z:1;);Bitangent:(x:0;y:1;z:0;);Normal:(x:-1;y:0;z:0;);TexCoord:(u:0;v:0)), (Position:(x:-1;y: 1;z:-1;);Tangent:(x:0;y:0;z:1;);Bitangent:(x:0;y:1;z:0;);Normal:(x:-1;y:0;z:0;);TexCoord:(u:0;v:1)), (Position:(x:-1;y: 1;z: 1;);Tangent:(x:0;y:0;z:1;);Bitangent:(x:0;y:1;z:0;);Normal:(x:-1;y:0;z:0;);TexCoord:(u:1;v:1)), (Position:(x:-1;y:-1;z: 1;);Tangent:(x:0;y:0;z:1;);Bitangent:(x:0;y:1;z:0;);Normal:(x:-1;y:0;z:0;);TexCoord:(u:1;v:0)), // Right (Position:(x: 1;y:-1;z: 1;);Tangent:(x:0;y:0;z:-1;);Bitangent:(x:0;y:1;z:0;);Normal:(x:1;y:0;z:0;);TexCoord:(u:0;v:0)), (Position:(x: 1;y: 1;z: 1;);Tangent:(x:0;y:0;z:-1;);Bitangent:(x:0;y:1;z:0;);Normal:(x:1;y:0;z:0;);TexCoord:(u:0;v:1)), (Position:(x: 1;y: 1;z:-1;);Tangent:(x:0;y:0;z:-1;);Bitangent:(x:0;y:1;z:0;);Normal:(x:1;y:0;z:0;);TexCoord:(u:1;v:1)), (Position:(x: 1;y:-1;z:-1;);Tangent:(x:0;y:0;z:-1;);Bitangent:(x:0;y:1;z:0;);Normal:(x:1;y:0;z:0;);TexCoord:(u:1;v:0)), // Bottom (Position:(x:-1;y:-1;z:-1;);Tangent:(x:1;y:0;z:0;);Bitangent:(x:0;y:0;z:1;);Normal:(x:0;y:-1;z:0;);TexCoord:(u:0;v:0)), (Position:(x:-1;y:-1;z: 1;);Tangent:(x:1;y:0;z:0;);Bitangent:(x:0;y:0;z:1;);Normal:(x:0;y:-1;z:0;);TexCoord:(u:0;v:1)), (Position:(x: 1;y:-1;z: 1;);Tangent:(x:1;y:0;z:0;);Bitangent:(x:0;y:0;z:1;);Normal:(x:0;y:-1;z:0;);TexCoord:(u:1;v:1)), (Position:(x: 1;y:-1;z:-1;);Tangent:(x:1;y:0;z:0;);Bitangent:(x:0;y:0;z:1;);Normal:(x:0;y:-1;z:0;);TexCoord:(u:1;v:0)), // Top (Position:(x:-1;y: 1;z:-1;);Tangent:(x:1;y:0;z:0;);Bitangent:(x:0;y:0;z:-1;);Normal:(x:0;y:1;z:0;);TexCoord:(u:0;v:0)), (Position:(x: 1;y: 1;z:-1;);Tangent:(x:1;y:0;z:0;);Bitangent:(x:0;y:0;z:-1;);Normal:(x:0;y:1;z:0;);TexCoord:(u:0;v:1)), (Position:(x: 1;y: 1;z: 1;);Tangent:(x:1;y:0;z:0;);Bitangent:(x:0;y:0;z:-1;);Normal:(x:0;y:1;z:0;);TexCoord:(u:1;v:1)), (Position:(x:-1;y: 1;z: 1;);Tangent:(x:1;y:0;z:0;);Bitangent:(x:0;y:0;z:-1;);Normal:(x:0;y:1;z:0;);TexCoord:(u:1;v:0)), // Back (Position:(x: 1;y:-1;z:-1;);Tangent:(x:-1;y:0;z:0;);Bitangent:(x:0;y:1;z:0;);Normal:(x:0;y:0;z:-1;);TexCoord:(u:0;v:0)), (Position:(x: 1;y: 1;z:-1;);Tangent:(x:-1;y:0;z:0;);Bitangent:(x:0;y:1;z:0;);Normal:(x:0;y:0;z:-1;);TexCoord:(u:0;v:1)), (Position:(x:-1;y: 1;z:-1;);Tangent:(x:-1;y:0;z:0;);Bitangent:(x:0;y:1;z:0;);Normal:(x:0;y:0;z:-1;);TexCoord:(u:1;v:1)), (Position:(x:-1;y:-1;z:-1;);Tangent:(x:-1;y:0;z:0;);Bitangent:(x:0;y:1;z:0;);Normal:(x:0;y:0;z:-1;);TexCoord:(u:1;v:0)), // Front (Position:(x:-1;y:-1;z:1;);Tangent:(x:1;y:0;z:0;);Bitangent:(x:0;y:1;z:0;);Normal:(x:0;y:0;z:1;);TexCoord:(u:0;v:0)), (Position:(x:-1;y: 1;z:1;);Tangent:(x:1;y:0;z:0;);Bitangent:(x:0;y:1;z:0;);Normal:(x:0;y:0;z:1;);TexCoord:(u:0;v:1)), (Position:(x: 1;y: 1;z:1;);Tangent:(x:1;y:0;z:0;);Bitangent:(x:0;y:1;z:0;);Normal:(x:0;y:0;z:1;);TexCoord:(u:1;v:1)), (Position:(x: 1;y:-1;z:1;);Tangent:(x:1;y:0;z:0;);Bitangent:(x:0;y:1;z:0;);Normal:(x:0;y:0;z:1;);TexCoord:(u:1;v:0)) ); CubeIndices:array[0..35] of TVkInt32= ( 0, 1, 2, 0, 2, 3, // Right 4, 5, 6, 4, 6, 7, // Bottom 8, 9, 10, 8, 10, 11, // Top 12, 13, 14, 12, 14, 15, // Back 16, 17, 18, 16, 18, 19, // Front 20, 21, 22, 20, 22, 23); var Index:TVkInt32; Material:PVulkanModelMaterial; ModelVertex:PVulkanModelVertex; CubeVertex:PCubeVertex; m:TVulkanModelMatrix3x3; q:TVulkanModelQuaternion; Part:PVulkanModelPart; AObject:PVulkanModelObject; begin fCountMaterials:=1; fCountVertices:=length(CubeVertices); fCountIndices:=length(CubeIndices); fCountParts:=1; fCountObjects:=1; SetLength(fMaterials,fCountMaterials); SetLength(fVertices,fCountVertices); SetLength(fIndices,fCountIndices); SetLength(fParts,fCountParts); SetLength(fObjects,fCountObjects); Material:=@fMaterials[0]; Material^.Name:='cube'; Material^.Texture:='cube'; Material^.Ambient.r:=0.1; Material^.Ambient.g:=0.1; Material^.Ambient.b:=0.1; Material^.Diffuse.r:=0.8; Material^.Diffuse.g:=0.8; Material^.Diffuse.b:=0.8; Material^.Emission.r:=0.0; Material^.Emission.g:=0.0; Material^.Emission.b:=0.0; Material^.Specular.r:=0.1; Material^.Specular.g:=0.1; Material^.Specular.b:=0.1; Material^.Shininess:=1.0; for Index:=0 to fCountVertices-1 do begin ModelVertex:=@fVertices[Index]; CubeVertex:=@CubeVertices[Index]; ModelVertex^.Position.x:=CubeVertex^.Position.x*aSizeX*0.5; ModelVertex^.Position.y:=CubeVertex^.Position.y*aSizeY*0.5; ModelVertex^.Position.z:=CubeVertex^.Position.z*aSizeZ*0.5; m.Tangent:=CubeVertex^.Tangent; m.Bitangent:=CubeVertex^.Bitangent; m.Normal:=CubeVertex^.Normal; q:=VulkanModelMatrix3x3ToQTangent(m); ModelVertex^.QTangent.x:=Min(Max(round(Min(Max(q.x,-1.0),1.0)*32767),-32767),32767); ModelVertex^.QTangent.y:=Min(Max(round(Min(Max(q.y,-1.0),1.0)*32767),-32767),32767); ModelVertex^.QTangent.z:=Min(Max(round(Min(Max(q.z,-1.0),1.0)*32767),-32767),32767); ModelVertex^.QTangent.w:=Min(Max(round(Min(Max(q.w,-1.0),1.0)*32767),-32767),32767); ModelVertex^.TexCoord:=CubeVertex^.TexCoord; ModelVertex^.Material:=0; end; for Index:=0 to fCountIndices-1 do begin fIndices[Index]:=CubeIndices[Index]; end; Part:=@fParts[0]; Part^.Material:=0; Part^.StartIndex:=0; Part^.CountIndices:=fCountIndices; AObject:=@fObjects[0]; AObject^.Name:='cube'; AObject^.AABB.Min.x:=-(aSizeX*0.5); AObject^.AABB.Min.y:=-(aSizeY*0.5); AObject^.AABB.Min.z:=-(aSizeZ*0.5); AObject^.AABB.Max.x:=aSizeX*0.5; AObject^.AABB.Max.y:=aSizeY*0.5; AObject^.AABB.Max.z:=aSizeZ*0.5; AObject^.Sphere.Center:=VulkanModelVector3ScalarMul(VulkanModelVector3Sub(AObject^.AABB.Max,AObject^.AABB.Min),0.5); AObject^.Sphere.Radius:=VulkanModelVector3Length(VulkanModelVector3Sub(AObject^.AABB.Max,AObject^.AABB.Min))/sqrt(3.0); end; procedure TVulkanModel.LoadFromStream(const aStream:TStream;const aDoFree:boolean=false); const ModelSignature:TChunkSignature=('m','d','l',#0); ModelVersion:TVkUInt32=0; var Signature:TChunkSignature; Version:TVkUInt32; ChunkOffset,CountChunks:TVkInt32; Chunks:TChunks; function GetChunkStream(const ChunkSignature:TChunkSignature;const WithMemoryCopy:boolean=true):TChunkStream; var Index:TVkInt32; Chunk:PChunk; begin result:=nil; for Index:=0 to CountChunks-1 do begin Chunk:=@Chunks[Index]; if Chunk^.Signature=ChunkSignature then begin result:=TChunkStream.Create(aStream,Chunk^.Offset,Chunk^.Size,WithMemoryCopy); exit; end; end; end; procedure ReadBOVO; const ChunkSignature:TChunkSignature=('B','O','V','O'); var ChunkStream:TChunkStream; begin ChunkStream:=GetChunkStream(ChunkSignature,false); try if assigned(ChunkStream) and (ChunkStream.Size<>0) then begin fSphere.Center.x:=ChunkStream.ReadFloat; fSphere.Center.y:=ChunkStream.ReadFloat; fSphere.Center.z:=ChunkStream.ReadFloat; fSphere.Radius:=ChunkStream.ReadFloat; fAABB.Min.x:=ChunkStream.ReadFloat; fAABB.Min.y:=ChunkStream.ReadFloat; fAABB.Min.z:=ChunkStream.ReadFloat; fAABB.Max.x:=ChunkStream.ReadFloat; fAABB.Max.y:=ChunkStream.ReadFloat; fAABB.Max.z:=ChunkStream.ReadFloat; end else begin raise EModelLoad.Create('Missing "'+String(ChunkSignature[0]+ChunkSignature[1]+ChunkSignature[2]+ChunkSignature[3])+'" chunk'); end; finally ChunkStream.Free; end; end; procedure ReadMATE; const ChunkSignature:TChunkSignature=('M','A','T','E'); var ChunkStream:TChunkStream; Index:TVkInt32; Material:PVulkanModelMaterial; begin ChunkStream:=GetChunkStream(ChunkSignature,true); try if assigned(ChunkStream) and (ChunkStream.Size<>0) then begin fCountMaterials:=ChunkStream.ReadInt32; SetLength(fMaterials,fCountMaterials); for Index:=0 to fCountMaterials-1 do begin Material:=@fMaterials[Index]; Material^.Name:=ChunkStream.ReadString; Material^.Texture:=ChunkStream.ReadString; Material^.Ambient.r:=ChunkStream.ReadFloat; Material^.Ambient.g:=ChunkStream.ReadFloat; Material^.Ambient.b:=ChunkStream.ReadFloat; Material^.Diffuse.r:=ChunkStream.ReadFloat; Material^.Diffuse.g:=ChunkStream.ReadFloat; Material^.Diffuse.b:=ChunkStream.ReadFloat; Material^.Emission.r:=ChunkStream.ReadFloat; Material^.Emission.g:=ChunkStream.ReadFloat; Material^.Emission.b:=ChunkStream.ReadFloat; Material^.Specular.r:=ChunkStream.ReadFloat; Material^.Specular.g:=ChunkStream.ReadFloat; Material^.Specular.b:=ChunkStream.ReadFloat; Material^.Shininess:=ChunkStream.ReadFloat; end; end else begin raise EModelLoad.Create('Missing "'+String(ChunkSignature[0]+ChunkSignature[1]+ChunkSignature[2]+ChunkSignature[3])+'" chunk'); end; finally ChunkStream.Free; end; end; procedure ReadVBOS; const ChunkSignature:TChunkSignature=('V','B','O','S'); var ChunkStream:TChunkStream; VertexIndex:TVkInt32; q:TVulkanModelQuaternion; m:TVulkanModelMatrix3x3; begin ChunkStream:=GetChunkStream(ChunkSignature,true); try if assigned(ChunkStream) and (ChunkStream.Size<>0) then begin fCountVertices:=ChunkStream.ReadInt32; SetLength(fVertices,fCountVertices); if fCountVertices>0 then begin ChunkStream.ReadWithCheck(fVertices[0],fCountVertices*SizeOf(TVulkanModelVertex)); if assigned(fKraftMesh) then begin for VertexIndex:=0 to fCountVertices-1 do begin fKraftMesh.AddVertex(Kraft.Vector3(fVertices[VertexIndex].Position.x,fVertices[VertexIndex].Position.y,fVertices[VertexIndex].Position.z)); q.x:=Vertices[VertexIndex].QTangent.x/32767.0; q.y:=Vertices[VertexIndex].QTangent.y/32767.0; q.z:=Vertices[VertexIndex].QTangent.z/32767.0; q.w:=Vertices[VertexIndex].QTangent.w/32767.0; m:=VulkanModelMatrix3x3FromQTangent(q); fKraftMesh.AddNormal(Kraft.Vector3(m.Normal.x,m.Normal.y,m.Normal.z)); end; end; end; end else begin raise EModelLoad.Create('Missing "'+String(ChunkSignature[0]+ChunkSignature[1]+ChunkSignature[2]+ChunkSignature[3])+'" chunk'); end; finally ChunkStream.Free; end; end; procedure ReadIBOS; const ChunkSignature:TChunkSignature=('I','B','O','S'); var ChunkStream:TChunkStream; Index:TVkInt32; begin ChunkStream:=GetChunkStream(ChunkSignature,true); try if assigned(ChunkStream) and (ChunkStream.Size<>0) then begin fCountIndices:=ChunkStream.ReadInt32; SetLength(fIndices,fCountIndices); if fCountIndices>0 then begin ChunkStream.ReadWithCheck(fIndices[0],fCountIndices*SizeOf(TVulkanModelIndex)); if assigned(fKraftMesh) then begin Index:=0; while (Index+2)<fCountIndices-1 do begin fKraftMesh.AddTriangle(fIndices[Index],fIndices[Index+1],fIndices[Index+2], fIndices[Index],fIndices[Index+1],fIndices[Index+2]); inc(Index,3); end; fKraftMesh.Finish; end; end; end else begin raise EModelLoad.Create('Missing "'+String(ChunkSignature[0]+ChunkSignature[1]+ChunkSignature[2]+ChunkSignature[3])+'" chunk'); end; finally ChunkStream.Free; end; end; procedure ReadPART; const ChunkSignature:TChunkSignature=('P','A','R','T'); var ChunkStream:TChunkStream; Index:TVkInt32; Part:PVulkanModelPart; begin ChunkStream:=GetChunkStream(ChunkSignature,true); try if assigned(ChunkStream) and (ChunkStream.Size<>0) then begin fCountParts:=ChunkStream.ReadInt32; SetLength(fParts,fCountParts); for Index:=0 to fCountParts-1 do begin Part:=@fParts[Index]; Part^.Material:=ChunkStream.ReadInt32; Part^.StartIndex:=ChunkStream.ReadInt32; Part^.CountIndices:=ChunkStream.ReadInt32; end; end else begin raise EModelLoad.Create('Missing "'+String(ChunkSignature[0]+ChunkSignature[1]+ChunkSignature[2]+ChunkSignature[3])+'" chunk'); end; finally ChunkStream.Free; end; end; procedure ReadOBJS; const ChunkSignature:TChunkSignature=('O','B','J','S'); var ChunkStream:TChunkStream; ObjectIndex:TVkInt32; AObject:PVulkanModelObject; begin ChunkStream:=GetChunkStream(ChunkSignature,true); try if assigned(ChunkStream) and (ChunkStream.Size<>0) then begin fCountObjects:=ChunkStream.ReadInt32; SetLength(fObjects,fCountObjects); for ObjectIndex:=0 to fCountObjects-1 do begin AObject:=@fObjects[ObjectIndex]; AObject^.Name:=ChunkStream.ReadString; AObject^.Sphere.Center.x:=ChunkStream.ReadFloat; AObject^.Sphere.Center.y:=ChunkStream.ReadFloat; AObject^.Sphere.Center.z:=ChunkStream.ReadFloat; AObject^.Sphere.Radius:=ChunkStream.ReadFloat; AObject^.AABB.Min.x:=ChunkStream.ReadFloat; AObject^.AABB.Min.y:=ChunkStream.ReadFloat; AObject^.AABB.Min.z:=ChunkStream.ReadFloat; AObject^.AABB.Max.x:=ChunkStream.ReadFloat; AObject^.AABB.Max.y:=ChunkStream.ReadFloat; AObject^.AABB.Max.z:=ChunkStream.ReadFloat; end; end else begin raise EModelLoad.Create('Missing "'+String(ChunkSignature[0]+ChunkSignature[1]+ChunkSignature[2]+ChunkSignature[3])+'" chunk'); end; finally ChunkStream.Free; end; end; procedure ReadCOHU; const ChunkSignature:TChunkSignature=('C','O','H','U'); var ChunkStream:TChunkStream; begin ChunkStream:=GetChunkStream(ChunkSignature,true); try if assigned(ChunkStream) and (ChunkStream.Size<>0) then begin if assigned(fKraftConvexHull) then begin fKraftConvexHull.LoadFromStream(ChunkStream); end; end else begin raise EModelLoad.Create('Missing "'+String(ChunkSignature[0]+ChunkSignature[1]+ChunkSignature[2]+ChunkSignature[3])+'" chunk'); end; finally ChunkStream.Free; end; end; begin if assigned(aStream) then begin try Chunks:=nil; try begin if aStream.Seek(0,soBeginning)<>0 then begin raise EModelLoad.Create('Stream seek error'); end; end; begin if aStream.Read(Signature,SizeOf(TChunkSignature))<>SizeOf(TChunkSignature) then begin raise EModelLoad.Create('Stream read error'); end; if Signature<>ModelSignature then begin raise EModelLoad.Create('Invalid model file signature'); end; end; begin if aStream.Read(Version,SizeOf(TVkUInt32))<>SizeOf(TVkUInt32) then begin raise EModelLoad.Create('Stream read error'); end; if Version<>ModelVersion then begin raise EModelLoad.Create('Invalid model file version'); end; end; begin if aStream.Read(CountChunks,SizeOf(TVkInt32))<>SizeOf(TVkInt32) then begin raise EModelLoad.Create('Stream read error'); end; if aStream.Read(ChunkOffset,SizeOf(TVkInt32))<>SizeOf(TVkInt32) then begin raise EModelLoad.Create('Stream read error'); end; if aStream.Seek(ChunkOffset,soBeginning)<>ChunkOffset then begin raise EModelLoad.Create('Stream seek error'); end; if CountChunks=0 then begin raise EModelLoad.Create('Model file without chunks'); end; SetLength(Chunks,CountChunks); if aStream.Read(Chunks[0],CountChunks*SizeOf(TChunk))<>(CountChunks*SizeOf(TChunk)) then begin raise EModelLoad.Create('Stream read error'); end; end; begin ReadBOVO; ReadMATE; ReadVBOS; ReadIBOS; ReadPART; ReadOBJS; ReadCOHU; end; finally SetLength(Chunks,0); end; finally if aDoFree then begin aStream.Free; end; end; end; end; procedure TVulkanModel.Upload(const aQueue:TpvVulkanQueue; const aCommandBuffer:TpvVulkanCommandBuffer; const aFence:TpvVulkanFence); type TRemapIndices=array of TVkInt64; var BufferIndex,IndexIndex,CountTemporaryVertices:TVkInt32; MaxIndexedIndex:TVkUInt32; MaxCount,CurrentIndex,RemainingCount,ToDoCount,VertexIndex:TVkInt64; TemporaryVertices:TVulkanModelVertices; TemporaryIndices:TVulkanModelIndices; TemporaryRemapIndices:TRemapIndices; begin if not fUploaded then begin if fVulkanDevice.PhysicalDevice.Features.fullDrawIndexUint32<>0 then begin MaxIndexedIndex:=high(TVkUInt32)-1; end else begin MaxIndexedIndex:=fVulkanDevice.PhysicalDevice.Properties.limits.maxDrawIndexedIndexValue; end; // Make sure that MaxCount is divisible by three (one triangle = three vertices) MaxCount:=Max(0,(MaxIndexedIndex+1)-((MaxIndexedIndex+1) mod 3)); if fCountIndices=0 then begin fCountBuffers:=0; end else if fCountIndices<=MaxCount then begin // Good, the whole model fits into TVkFloat vertex and index buffers fCountBuffers:=1; SetLength(fVertexBuffers,fCountBuffers); SetLength(fIndexBuffers,fCountBuffers); SetLength(fBufferSizes,fCountBuffers); fBufferSizes[0]:=fCountIndices; fVertexBuffers[0]:=TpvVulkanBuffer.Create(fVulkanDevice, fCountVertices*SizeOf(TVulkanModelVertex), TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_VERTEX_BUFFER_BIT), TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE), [], TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) ); fVertexBuffers[0].UploadData(aQueue, aCommandBuffer, aFence, fVertices[0], 0, fCountVertices*SizeOf(TVulkanModelVertex), TpvVulkanBufferUseTemporaryStagingBufferMode.Yes); fIndexBuffers[0]:=TpvVulkanBuffer.Create(fVulkanDevice, fCountIndices*SizeOf(TVulkanModelIndex), TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_INDEX_BUFFER_BIT), TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE), [], TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) ); fIndexBuffers[0].UploadData(aQueue, aCommandBuffer, aFence, fIndices[0], 0, fCountIndices*SizeOf(TVulkanModelIndex), TpvVulkanBufferUseTemporaryStagingBufferMode.Yes); end else begin // In this case, we do to need split the model into multipe vertex and index buffers // Avoid signed 2^31 overflow issues if MaxCount>=High(TVkInt32) then begin MaxCount:=(High(TVkInt32)-1)-((High(TVkInt32)-1) mod 3); end; TemporaryVertices:=nil; TemporaryIndices:=nil; TemporaryRemapIndices:=nil; try SetLength(TemporaryRemapIndices,fCountIndices); fCountBuffers:=(fCountIndices+(MaxCount-1)) div MaxCount; SetLength(fVertexBuffers,fCountBuffers); SetLength(fIndexBuffers,fCountBuffers); SetLength(fBufferSizes,fCountBuffers); BufferIndex:=0; CurrentIndex:=0; RemainingCount:=fCountIndices; while (BufferIndex<fCountBuffers) and (RemainingCount>0) do begin if RemainingCount>MaxCount then begin ToDoCount:=MaxCount; end else begin ToDoCount:=RemainingCount; end; fBufferSizes[BufferIndex]:=ToDoCount; FillChar(TemporaryRemapIndices,length(TemporaryRemapIndices)*SizeOf(TVkInt64),#$ff); if length(TemporaryIndices)<ToDoCount then begin SetLength(TemporaryIndices,ToDoCount*2); end; CountTemporaryVertices:=0; for IndexIndex:=0 to ToDoCount-1 do begin VertexIndex:=TemporaryRemapIndices[fIndices[CurrentIndex+IndexIndex]]; if VertexIndex<0 then begin VertexIndex:=CountTemporaryVertices; inc(CountTemporaryVertices); TemporaryRemapIndices[fIndices[CurrentIndex+IndexIndex]]:=VertexIndex; if length(TemporaryVertices)<CountTemporaryVertices then begin SetLength(TemporaryVertices,CountTemporaryVertices*2); end; TemporaryVertices[VertexIndex]:=fVertices[fIndices[CurrentIndex+IndexIndex]]; end; TemporaryIndices[IndexIndex]:=VertexIndex; end; fVertexBuffers[BufferIndex]:=TpvVulkanBuffer.Create(fVulkanDevice, CountTemporaryVertices*SizeOf(TVulkanModelVertex), TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_VERTEX_BUFFER_BIT), TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE), [], TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) ); fVertexBuffers[BufferIndex].UploadData(aQueue, aCommandBuffer, aFence, TemporaryVertices[0], 0, CountTemporaryVertices*SizeOf(TVulkanModelVertex), TpvVulkanBufferUseTemporaryStagingBufferMode.Yes); fIndexBuffers[BufferIndex]:=TpvVulkanBuffer.Create(fVulkanDevice, fBufferSizes[BufferIndex]*SizeOf(TVulkanModelIndex), TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_INDEX_BUFFER_BIT), TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE), [], TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) ); fIndexBuffers[BufferIndex].UploadData(aQueue, aCommandBuffer, aFence, TemporaryIndices[0], 0, fBufferSizes[BufferIndex]*SizeOf(TVulkanModelIndex), TpvVulkanBufferUseTemporaryStagingBufferMode.Yes); inc(CurrentIndex,ToDoCount); dec(RemainingCount,ToDoCount); inc(BufferIndex); end; fCountBuffers:=BufferIndex; SetLength(fVertexBuffers,fCountBuffers); SetLength(fIndexBuffers,fCountBuffers); SetLength(fBufferSizes,fCountBuffers); finally TemporaryVertices:=nil; TemporaryIndices:=nil; TemporaryRemapIndices:=nil; end; end; fUploaded:=true; end; end; procedure TVulkanModel.Unload; var Index:TVkInt32; begin if fUploaded then begin fUploaded:=false; for Index:=0 to fCountBuffers-1 do begin FreeAndNil(fVertexBuffers[Index]); FreeAndNil(fIndexBuffers[Index]); end; fVertexBuffers:=nil; fIndexBuffers:=nil; fBufferSizes:=nil; fCountBuffers:=0; end; end; procedure TVulkanModel.Draw(const aCommandBuffer:TpvVulkanCommandBuffer;const aInstanceCount:TVkUInt32=1;const aFirstInstance:TVkUInt32=0); const Offsets:array[0..0] of TVkDeviceSize=(0); var Index:TVkInt32; begin for Index:=0 to fCountBuffers-1 do begin aCommandBuffer.CmdBindVertexBuffers(VULKAN_MODEL_VERTEX_BUFFER_BIND_ID,1,@fVertexBuffers[Index].Handle,@Offsets); aCommandBuffer.CmdBindIndexBuffer(fIndexBuffers[Index].Handle,0,VK_INDEX_TYPE_UINT32); aCommandBuffer.CmdDrawIndexed(fBufferSizes[Index],aInstanceCount,0,0,aFirstInstance); end; end; end.
unit ZPL2Parser; interface uses Windows, SysUtils, Classes, ZPL2, ZPL2Barcodes, ZPL2Label; type TZPL2Parser = class strict private FZPL2Label: TZPL2Label; procedure ParseACommand(const A_Command: string; ZPL2TextField: TZPL2TextField); procedure ParseBarcode128(const BC_Command, BY_Command, FO_Command, FD_Command: string); procedure ParseBarcode39(const B3_Command, BY_Command, FO_Command, FD_Command: string); procedure ParseB3Command(const B3_Command: string; ZPL2BarcodeCode39: TZPL2BarcodeCode39); procedure ParseBCCommand(const BC_Command: string; ZPL2BarcodeCode128: TZPL2BarcodeCode128); procedure ParseBQCommand(const BQ_Command: string; ZPL2BarcodeQR: TZPL2BarcodeQR); procedure ParseBXCommand(const BX_Command: string; ZPL2BarcodeDatamatrix: TZPL2BarcodeDatamatrix); procedure ParseBYCommand(const BY_Command: string; ZPL2Barcode1D: TZPL2Barcode1D); procedure ParseCFCommand(const CF_Command: string); /// <summary> /// Parses the command for the international font settings. /// </summary> procedure ParseCICommand(const CI_Command: string); procedure ParseComment(const FX_Command: string); procedure ParseDatamatrix(const BX_Command, FO_Command, FD_Command: string); procedure ParseFDCommand(const FD_Command: string; ZPL2TextLabelItem: TZPL2TextLabelItem; FH: boolean = false; FH_Inidicator: char = #0); procedure ParseFOCommand(const FO_Command: string; ZPL2LabelItem: TZPL2LabelItem); procedure ParseFXCommand(const FX_Command: string; ZPL2CommentField: TZPL2CommentField); procedure ParseGBCommand(const GB_Command: string; ZPL2GraphicBox: TZPL2GraphicBox); procedure ParseGCCommand(const GC_Command: string; ZPL2GraphicCircle: TZPL2GraphicCircle); procedure ParseGDCommand(const GD_Command: string; ZPL2GraphicDiagonalLine: TZPL2GraphicDiagonalLine); procedure ParseGECommand(const GE_Command: string; ZPL2GraphicEllipse: TZPL2GraphicEllipse); procedure ParseGFCommand(GF_Command: string; ZPL2GraphicField: TZPL2GraphicField); procedure ParseGraphicBox(const GB_Command, FO_Command: string); procedure ParseGraphicCircle(const GC_Command, FO_Command: string); procedure ParseGraphicDiagonalLine(const GD_Command, FO_Command: string); procedure ParseGraphicEllipse(const GE_Command, FO_Command: string); procedure ParseGraphicField(const GF_Command, FO_Command: string); /// <summary> /// Parses the command for the label home settings. /// </summary> procedure ParseLHCommand(const LH_Command: string); /// <summary> /// Parses the command for the media darkness setting. /// </summary> procedure ParseMDCommand(const MD_Command: string); /// <summary> /// Parses the command for the print quantity settings. /// </summary> procedure ParsePQCommand(const PQ_Command: string); /// <summary> /// Parses the command for the print rate settings. /// </summary> procedure ParsePRCommand(const PR_Command: string); /// <summary> /// Parses the command for the print width setting. /// </summary> procedure ParsePWCommand(const PW_Command: string); procedure ParseQRCode(const BQ_Command, FO_Command, FD_Command: string); procedure ParseRotation(const Rotation: char; ZPL2RotationLabelItem: TZPL2RotationLabelItem); procedure ParseTextField(const A_Command, FO_Command, FD_Command: string; const FH: boolean = false; const FH_Inidicator: char = #0); public /// <summary> /// Parses the given data of the label to the item list and settings and checks for errors (throws exceptions!). /// </summary> procedure Parse(const LabelData: string; ZPL2Label: TZPL2Label); end; implementation uses {$if CompilerVersion >= 22.0} System.UITypes, System.RegularExpressions, System.RegularExpressionsCore; {$else} PerlRegEx; {$ifend} {$region 'Unit Methods'} /// <summary> /// Wrapper for Windows API OemToChar. /// </summary> procedure AsciiToAnsi(var s: string); var buff: string; begin if s <> '' then begin SetLength(buff, length(s) + 1); {$IFDEF UNICODE} if OemToCharW(PAnsiChar(AnsiString(s)), PWideChar(buff)) then {$ELSE} if OemToCharA(PChar(s), PChar(buff)) then {$ENDIF} s := Trim(string(buff)); end; end; {$endregion} {$region 'TZPL2Parser' } procedure TZPL2Parser.Parse(const LabelData: string; ZPL2Label: TZPL2Label); const REGEX_LABEL_PARSING = '(\^|~)[a-zA-Z][0-9a-zA-Z@][\S *(\r\n)]*(?=(\r\n)*\^|~|$)'; INVALID_DATA = 'Invalid label data.'; var A, Barcode, BY, FO: string; FH: boolean; FH_Indicator: Char; sMatchedText: string; begin A := ''; BY := 'BY2'; FO := ''; FH_Indicator := #0; FH := false; if not Assigned(ZPL2Label) or (Trim(LabelData) = '') then exit; FZPL2Label := ZPL2Label; FZPL2Label.Init; with TPerlRegEx.Create do begin try Options := Options + [preUnGreedy]; RegEx := REGEX_LABEL_PARSING; Subject := UTF8String(LabelData); if Match then begin sMatchedText := string(MatchedText); if Trim(sMatchedText) <> ZPL2_XA then begin raise EParserError.Create(INVALID_DATA + ' First command must be ''' + ZPL2_XA + '''!' + sLineBreak + 'Found: ''' + sMatchedText + ''''); end; while MatchAgain do begin sMatchedText := string(MatchedText); {$REGION 'ZPL2_A (Scaleable/Bitmapped font)'} if Pos(ZPL2_A, sMatchedText) = 1 then begin A := sMatchedText; continue; end; {$ENDREGION} {$REGION 'ZPL2_B3 (Barcode Code 39)'} if Pos(ZPL2_B3, sMatchedText) = 1 then begin Barcode := sMatchedText; while MatchAgain do begin sMatchedText := string(MatchedText); if (Pos(ZPL2_FH, sMatchedText) = 1) or (Pos(ZPL2_FD, sMatchedText) = 1) then begin if (Pos(ZPL2_FH, sMatchedText) = 1) then begin FH := true; continue; end; if (Pos(ZPL2_FD, sMatchedText) = 1) then begin ParseBarcode39(Barcode, BY, FO, sMatchedText); FO := ''; FH := false; end else raise EParserError.Create(INVALID_DATA + ' No ' + ZPL2_FD + ' command found after the ' + ZPL2_B3 + ' command ' + Barcode); end else raise EParserError.Create(INVALID_DATA + ' No (valid) command found after the ' + ZPL2_B3 + ' command ' + Barcode); break; end; continue; end; {$ENDREGION} {$REGION 'ZPL2_BC (Barcode Code 128)'} if Pos(ZPL2_BC, sMatchedText) = 1 then begin Barcode := sMatchedText; while MatchAgain do begin sMatchedText := string(MatchedText); if (Pos(ZPL2_FH, sMatchedText) = 1) or (Pos(ZPL2_FD, sMatchedText) = 1) then begin if (Pos(ZPL2_FH, sMatchedText) = 1) then begin FH := true; continue; end; if (Pos(ZPL2_FD, sMatchedText) = 1) then begin // delete Subset B start character sMatchedText := StringReplace(sMatchedText, '>:', '', [rfReplaceAll]); ParseBarcode128(Barcode, BY, FO, sMatchedText); FO := ''; FH := false; end else raise EParserError.Create(INVALID_DATA + ' No ' + ZPL2_FD + ' command found after the ' + ZPL2_BC + ' command ' + Barcode); end else raise EParserError.Create(INVALID_DATA + ' No (valid) command found after the ' + ZPL2_BC + ' command ' + Barcode); break; end; continue; end; {$ENDREGION} {$REGION 'ZPL2_BQ (QR Code)'} if Pos(ZPL2_BQ, sMatchedText) = 1 then begin Barcode := sMatchedText; while MatchAgain do begin sMatchedText := string(MatchedText); if (Pos(ZPL2_FH, sMatchedText) = 1) or (Pos(ZPL2_FD, sMatchedText) = 1) then begin if (Pos(ZPL2_FH, sMatchedText) = 1) then begin FH := true; continue; end; if (Pos(ZPL2_FD, sMatchedText) = 1) then begin ParseQRCode(Barcode, FO, sMatchedText); FO := ''; FH := false; end else raise EParserError.Create(INVALID_DATA + ' No ' + ZPL2_FD + ' command found after the ' + ZPL2_BQ + ' command ' + Barcode); end else raise EParserError.Create(INVALID_DATA + ' No (valid) command found after the ' + ZPL2_BQ + ' command ' + Barcode); break; end; continue; end; {$ENDREGION} {$REGION 'ZPL2_BX (Datamatrix Code)'} if Pos(ZPL2_BX, sMatchedText) = 1 then begin Barcode := sMatchedText; while MatchAgain do begin sMatchedText := string(MatchedText); if (Pos(ZPL2_FH, sMatchedText) = 1) or (Pos(ZPL2_FD, sMatchedText) = 1) then begin if (Pos(ZPL2_FH, sMatchedText) = 1) then begin FH := true; continue; end; if (Pos(ZPL2_FD, sMatchedText) = 1) then begin ParseDatamatrix(Barcode, FO, sMatchedText); FO := ''; FH := false; end else raise EParserError.Create(INVALID_DATA + ' No ' + ZPL2_FD + ' command found after the ' + ZPL2_BX + ' command ' + Barcode); end else raise EParserError.Create(INVALID_DATA + ' No (valid) command found after the ' + ZPL2_BX + ' command ' + Barcode); break; end; continue; end; {$ENDREGION} {$REGION 'ZPL2_BY (Barcode Field Default)'} if Pos(ZPL2_BY, sMatchedText) = 1 then begin BY := sMatchedText; continue; end; {$ENDREGION} {$REGION 'ZPL2_CF (Change International font)'} if Pos(ZPL2_CF, sMatchedText) = 1 then begin ParseCFCommand(sMatchedText); continue; end; {$ENDREGION} {$REGION 'ZPL2_CI (Change International font)'} if Pos(ZPL2_CI, sMatchedText) = 1 then begin ParseCICommand(sMatchedText); continue; end; {$ENDREGION} {$REGION 'ZPL2_FO (Field Orientation)'} if Pos(ZPL2_FO, sMatchedText) = 1 then begin FO := sMatchedText; continue; end; {$ENDREGION} {$REGION 'ZPL2_FD (Field Data)'} if (Pos(ZPL2_FD, sMatchedText) = 1) then //and (A <> '') then begin ParseTextField(A, FO, sMatchedText, FH, FH_Indicator); A := ''; FO := ''; FH := false; FH_Indicator := #0; continue; end; {$ENDREGION} {$REGION 'ZPL2_FH (Field Hexadezimal indicator)'} if Pos(ZPL2_FH, sMatchedText) = 1 then begin FH := true; if Length(MatchedText) > 3 then FH_Indicator := Char(MatchedText[4]); continue; end; {$ENDREGION} {$REGION 'ZPL2_FX (Comment)'} if Pos(ZPL2_FX, sMatchedText) = 1 then begin ParseComment(sMatchedText); continue; end; {$ENDREGION} {$REGION 'ZPL2_GB (Graphic Box)'} if Pos(ZPL2_GB, sMatchedText) = 1 then begin ParseGraphicBox(sMatchedText, FO); FO := ''; continue; end; {$ENDREGION} {$REGION 'ZPL2_GC (Graphic Circle)'} if Pos(ZPL2_GC, sMatchedText) = 1 then begin ParseGraphicCircle(sMatchedText, FO); FO := ''; continue; end; {$ENDREGION} {$REGION 'ZPL2_GD (Graphic Diagonal line)'} if Pos(ZPL2_GD, sMatchedText) = 1 then begin ParseGraphicDiagonalLine(sMatchedText, FO); FO := ''; continue; end; {$ENDREGION} {$REGION 'ZPL2_GE (Graphic Ellipse)'} if Pos(ZPL2_GE, sMatchedText) = 1 then begin ParseGraphicEllipse(sMatchedText, FO); FO := ''; continue; end; {$ENDREGION} {$REGION 'ZPL2_GF (Graphic Field)'} if Pos(ZPL2_GF, sMatchedText) = 1 then begin ParseGraphicField(sMatchedText, FO); FO := ''; continue; end; {$ENDREGION} {$REGION 'ZPL2_LH (Label Home)'} if Pos(ZPL2_LH, sMatchedText) = 1 then begin ParseLHCommand(sMatchedText); continue; end; {$ENDREGION} {$REGION 'ZPL2_LR (Label Reverse print)'} if Pos(ZPL2_LR, sMatchedText) = 1 then begin if Length(sMatchedText) > 3 then begin case MatchedText[4] of 'Y': FZPL2Label.LabelReversePrint := true; 'N': FZPL2Label.LabelReversePrint := false; else raise EParserError.Create('Invalid label reverse print data (value): ' + MatchedText[4]); end; end else raise EParserError.Create('Invalid label reverse print data: ' + sMatchedText); continue; end; {$ENDREGION} {$REGION 'ZPL2_MC (Map Clear)'} if Pos(ZPL2_MC, sMatchedText) = 1 then begin if Length(MatchedText) > 3 then begin case MatchedText[4] of 'Y': FZPL2Label.MapClear := true; 'N': FZPL2Label.MapClear := false; else raise EParserError.Create('Invalid map clear data (value): ' + MatchedText[4]); end; end else raise EParserError.Create('Invalid map clear data: ' + sMatchedText); continue; end; {$ENDREGION} {$REGION 'ZPL2_MD (Media Darkness)'} if Pos(ZPL2_MD, sMatchedText) = 1 then begin ParseMDCommand(sMatchedText); continue; end; {$ENDREGION} {$REGION 'ZPL2_MM (Print Mode)'} if Pos(ZPL2_MM, sMatchedText) = 1 then begin if Length(sMatchedText) > 3 then begin case MatchedText[4] of 'T': FZPL2Label.PrintMode := pmTearOff; 'P': FZPL2Label.PrintMode := pmPeelOff; 'R': FZPL2Label.PrintMode := pmRewind; 'A': FZPL2Label.PrintMode := pmApplicator; 'C': FZPL2Label.PrintMode := pmCutter; else raise EParserError.Create('Invalid print mode data (value): ' + MatchedText[4]); end; end else raise EParserError.Create('Invalid print mode data: ' + sMatchedText); continue; end; {$ENDREGION} {$REGION 'ZPL2_MN (Media Tracking)'} if Pos(ZPL2_MN, sMatchedText) = 1 then begin if Length(sMatchedText) > 3 then begin case MatchedText[4] of 'N': FZPL2Label.MediaTracking := mnContinuous; 'Y', 'W': FZPL2Label.MediaTracking := mnNonContinuousWeb; 'M': FZPL2Label.MediaTracking := mnNonContinuousMark; else raise EParserError.Create('Invalid media tracking data (value): ' + MatchedText[4]); end; end else raise EParserError.Create('Invalid media tracking data: ' + sMatchedText); continue; end; {$ENDREGION} {$REGION 'ZPL2_MT (Media Type)'} if Pos(ZPL2_MT, sMatchedText) = 1 then begin if Length(sMatchedText) > 3 then begin case MatchedText[4] of 'T': FZPL2Label.MediaType := mtThermalTransferMedia; 'D': FZPL2Label.MediaType := mtDirectThermalMedia; else raise EParserError.Create('Invalid media type data (value): ' + MatchedText[4]); end; end else raise EParserError.Create('Invalid media type data: ' + sMatchedText); continue; end; {$ENDREGION} {$REGION 'ZPL2_PO (Print Orientation)'} if Pos(ZPL2_PO, sMatchedText) = 1 then begin if Length(sMatchedText) > 3 then begin case MatchedText[4] of 'I': FZPL2Label.PrintUpsideDown := true; 'N': FZPL2Label.PrintUpsideDown := false; else raise EParserError.Create('Invalid print orientation data (value): ' + MatchedText[4]); end; end else raise EParserError.Create('Invalid print orientation data: ' + sMatchedText); continue; end; {$ENDREGION} {$REGION 'ZPL2_PQ (Print Quantity)'} if Pos(ZPL2_PQ, sMatchedText) = 1 then begin ParsePQCommand(sMatchedText); continue; end; {$ENDREGION} {$REGION 'ZPL2_PR (Print Rate)'} if Pos(ZPL2_PR, sMatchedText) = 1 then begin ParsePRCommand(sMatchedText); continue; end; {$ENDREGION} {$REGION 'ZPL2_PW (Print Width)'} if Pos(ZPL2_PW, sMatchedText) = 1 then begin ParsePWCommand(sMatchedText); continue; end; {$ENDREGION} if Pos(ZPL2_XA, sMatchedText) = 1 then continue; {$REGION 'ZPL2_XB (Suppress Backfeed)'} if Pos(ZPL2_XB, sMatchedText) = 1 then begin FZPL2Label.SuppressBackfeed := true; continue; end; {$ENDREGION} if Pos(ZPL2_XZ, sMatchedText) = 1 then continue; end; end else raise EParserError.Create('Invalid ZPL2 file'); finally Free; end; end; end; procedure TZPL2Parser.ParseACommand(const A_Command: string; ZPL2TextField: TZPL2TextField); const INVALID_DATA = 'Invalid font data'; begin with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_A + '[A-Z0-9][NRIB],\d{1,5},\d{1,5}'; Subject := UTF8String(A_Command); if Match then begin try ZPL2TextField.Font := TZPL2Font(Ord(MatchedText[3])); except raise EParserError.Create(INVALID_DATA + ' (font character): ' + MatchedText[3]); end; ParseRotation(Char(MatchedText[4]), ZPL2TextField); RegEx := '\b\d{1,5}\b'; Subject := UTF8String(A_Command); if Match then begin try ZPL2TextField.Height := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (font height value): ' + string(MatchedText)); end; if MatchAgain then begin try ZPL2TextField.Width := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (font width value): ' + string(MatchedText)); end; end; end else raise EParserError.Create(INVALID_DATA + ' (font width and/or height value): ' + A_Command); end else raise EParserError.Create(INVALID_DATA + ': ' + A_Command); finally Free; end; end; end; procedure TZPL2Parser.ParseB3Command(const B3_Command: string; ZPL2BarcodeCode39: TZPL2BarcodeCode39); const INVALID_DATA = 'Invalid Code39 data'; begin with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_B3 + '[NRIB],[YN],\d{1,5},[YN],[YN]'; Subject := UTF8String(B3_Command); if Match then begin ParseRotation(Char(MatchedText[4]), ZPL2BarcodeCode39); RegEx := '\b\w+\b'; Subject := UTF8String(Copy(B3_Command, 6, Length(B3_Command) - 5)); if Match then begin try case MatchedText[1] of 'Y': ZPL2BarcodeCode39.Mod43CheckDigit := true; else ZPL2BarcodeCode39.Mod43CheckDigit := false; end; except raise EParserError.Create(INVALID_DATA + ' ( Mod 43 check digit value): ' + string(MatchedText)); end; if MatchAgain then begin try ZPL2BarcodeCode39.Height := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (barcode height value): ' + string(MatchedText)); end; end; if MatchAgain then begin try case MatchedText[1] of 'Y': ZPL2BarcodeCode39.PrintInterpretationLine := true; else ZPL2BarcodeCode39.PrintInterpretationLine := false; end; except raise EParserError.Create(INVALID_DATA + ' (print interpretation line value): ' + string(MatchedText)); end; end; if MatchAgain then begin try case MatchedText[1] of 'Y': ZPL2BarcodeCode39.PrintInterpretationLineAboveCode := true; else ZPL2BarcodeCode39.PrintInterpretationLineAboveCode := false; end; except raise EParserError.Create(INVALID_DATA + ' (print interpretation line above code value): ' + string(MatchedText)); end; end; end; end else raise EParserError.Create(INVALID_DATA + ': ' + B3_Command); finally Free; end; end; end; procedure TZPL2Parser.ParseBarcode128(const BC_Command, BY_Command, FO_Command, FD_Command: string); var ZPL2BarcodeCode128: TZPL2BarcodeCode128; begin ZPL2BarcodeCode128 := TZPL2BarcodeCode128.Create(nil); try ParseFOCommand(FO_Command, ZPL2BarcodeCode128); ParseBYCommand(BY_Command, ZPL2BarcodeCode128); ParseBCCommand(BC_Command, ZPL2BarcodeCode128); ParseFDCommand(FD_Command, ZPL2BarcodeCode128); FZPL2Label.Items.Add(ZPL2BarcodeCode128); except ZPL2BarcodeCode128.Free; raise; end; end; procedure TZPL2Parser.ParseBarcode39(const B3_Command, BY_Command, FO_Command, FD_Command: string); var ZPL2BarcodeCode39: TZPL2BarcodeCode39; begin ZPL2BarcodeCode39 := TZPL2BarcodeCode39.Create(nil); try ParseFOCommand(FO_Command, ZPL2BarcodeCode39); ParseBYCommand(BY_Command, ZPL2BarcodeCode39); ParseB3Command(B3_Command, ZPL2BarcodeCode39); ParseFDCommand(FD_Command, ZPL2BarcodeCode39); FZPL2Label.Items.Add(ZPL2BarcodeCode39); except ZPL2BarcodeCode39.Free; raise; end; end; procedure TZPL2Parser.ParseBCCommand(const BC_Command: string; ZPL2BarcodeCode128: TZPL2BarcodeCode128); const INVALID_DATA = 'Invalid Code128 data'; var PerlRegEx: TPerlRegEx; begin PerlRegEx := TPerlRegEx.Create; try PerlRegEx.RegEx := '\' + ZPL2_BC + '[NRIB],(\d{1,5})?,([YN])?,([YN])?(,([YN])?(,([NUAD])?)?)?'; PerlRegEx.Subject := UTF8String(BC_Command); if PerlRegEx.Match then begin ParseRotation(Char(PerlRegEx.MatchedText[4]), ZPL2BarcodeCode128); PerlRegEx.RegEx := '\b\w+\b'; PerlRegEx.Subject := UTF8String(Copy(BC_Command, Length(ZPL2_BC) + 3, Length(BC_Command) - Length(ZPL2_BC) - 1)); if PerlRegEx.Match then begin if PerlRegEx.MatchedText <> '' then begin try ZPL2BarcodeCode128.Height := StrToInt(string(PerlRegEx.MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (barcode height value): ' + string(PerlRegEx.MatchedText)); end; end; if PerlRegEx.MatchAgain then begin if PerlRegEx.MatchedText <> '' then begin try case PerlRegEx.MatchedText[1] of 'Y': ZPL2BarcodeCode128.PrintInterpretationLine := true; else ZPL2BarcodeCode128.PrintInterpretationLine := false; end; except raise EParserError.Create(INVALID_DATA + ' (print interpretation line value): ' + string(PerlRegEx.MatchedText)); end; end else ZPL2BarcodeCode128.PrintInterpretationLine := true; end; if PerlRegEx.MatchAgain then begin if PerlRegEx.MatchedText <> '' then begin try case PerlRegEx.MatchedText[1] of 'Y': ZPL2BarcodeCode128.PrintInterpretationLineAboveCode := true; else ZPL2BarcodeCode128.PrintInterpretationLineAboveCode := false; end; except raise EParserError.Create(INVALID_DATA + ' (print interpretation line above code value): ' + string(PerlRegEx.MatchedText)); end; end else ZPL2BarcodeCode128.PrintInterpretationLineAboveCode := false; end; end; end else raise EParserError.Create(INVALID_DATA + ': ' + BC_Command); finally PerlRegEx.Free; end; end; procedure TZPL2Parser.ParseBQCommand(const BQ_Command: string; ZPL2BarcodeQR: TZPL2BarcodeQR); const INVALID_DATA = 'Invalid QR code data'; begin with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_BQ + '[N],(1|2),(\d|10)'; Subject := UTF8String(BQ_Command); if Match then begin ParseRotation('N', ZPL2BarcodeQR); RegEx := '\b\d{1,2}\b'; Subject := UTF8String(BQ_Command); if Match then begin // ignore QR model, use always model 2 if MatchAgain then begin try ZPL2BarcodeQR.MagnificationFactor := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (magnification factor value): ' + string(MatchedText)); end; end; end else raise EParserError.Create(INVALID_DATA + ' (model and/or magnification factor value): ' + BQ_Command); end else raise EParserError.Create(INVALID_DATA + ': ' + BQ_Command); finally Free; end; end; end; procedure TZPL2Parser.ParseBXCommand(const BX_Command: string; ZPL2BarcodeDatamatrix: TZPL2BarcodeDatamatrix); const INVALID_DATA = 'Invalid datamatrix data'; begin with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_BX + '[NRIB],\d{1,4},(5|8|10|14|20)?0,(\d{1,2})?,(\d{1,2})?,([1-6])?,([\S])?'; Subject := UTF8String(BX_Command); if Match then begin ParseRotation(Char(MatchedText[4]), ZPL2BarcodeDatamatrix); RegEx := '\b\d{1,5}\b'; Subject := UTF8String(BX_Command); if Match then begin try ZPL2BarcodeDatamatrix.Modulsize := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (modul size value): ' + string(MatchedText)); end; if MatchAgain then begin try case StrToInt(string(MatchedText)) of 0: ZPL2BarcodeDatamatrix.QualityLevel := ql_0; 50: ZPL2BarcodeDatamatrix.QualityLevel := ql_50; 80: ZPL2BarcodeDatamatrix.QualityLevel := ql_80; 100: ZPL2BarcodeDatamatrix.QualityLevel := ql_100; 140: ZPL2BarcodeDatamatrix.QualityLevel := ql_140; 200: ZPL2BarcodeDatamatrix.QualityLevel := ql_200; end; except raise EParserError.Create(INVALID_DATA + ' (quality level value): ' + string(MatchedText)); end; end; end else raise EParserError.Create(INVALID_DATA + ' (modul size and/or quality level value): ' + BX_Command); end else raise EParserError.Create(INVALID_DATA + ': ' + BX_Command); finally Free; end; end; end; procedure TZPL2Parser.ParseBYCommand(const BY_Command: string; ZPL2Barcode1D: TZPL2Barcode1D); const INVALID_DATA = 'Invalid Barcode data'; begin with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_BY + '(\d|10)(,[23]\.\d)?'; Subject := UTF8String(BY_Command); if Match then begin RegEx := '\b\w+\b'; Subject := UTF8String(Copy(BY_Command, 4, Length(BY_Command) - 4)); if Match then begin try ZPL2Barcode1D.Linewidth := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (' + ZPL2_BY + ' command): ' + BY_Command); end; end; if MatchAgain then begin // wide bar to narrow bar width ratio is not used end; if MatchAgain then begin try ZPL2Barcode1D.Height := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (' + ZPL2_BY + ' command): ' + BY_Command); end; end; end; finally Free; end; end; end; procedure TZPL2Parser.ParseCFCommand(const CF_Command: string); const INVALID_DATA = 'Invalid change default font data'; var // s: string; h, w: string; ZPL2CFItem: TZPL2CFItem; begin h := ''; w := ''; ZPL2CFItem := TZPL2CFItem.Create(nil); try with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_CF + '[A-Z0-9](,(\d{1,5})?)?(,\d{1,5})?'; Subject := UTF8String(CF_Command); if Match then begin //s := string(MatchedText); RegEx := '\b\w*\b'; Subject := UTF8String(Copy(CF_Command, Length(ZPL2_CF) + 1, Length(CF_Command) - Length(ZPL2_CF))); if Match then begin if Length(MatchedText) = 1 then ZPL2CFItem.Font := TZPL2Font(Ord(MatchedText[1])) else raise EParserError.Create(INVALID_DATA + ' (font value must contain 1 character): ' + MatchedText); end else raise EParserError.Create(INVALID_DATA + ' (value): ' + CF_Command); if MatchAgain then h := MatchedText; if MatchAgain then w := MatchedText; if (h = '') and (w = '') then exit; if h = '' then begin ZPL2CFItem.Height_Empty := true; h := w; end; if w = '' then begin ZPL2CFItem.Width_Empty := true; w := h; end; try ZPL2CFItem.Height := StrToIntDef(h, FZPL2Label.CF.Height); ZPL2CFItem.Width:= StrToIntDef(w, FZPL2Label.CF.Width); except raise EParserError.Create(INVALID_DATA + '(width and/or height out of allowed range): ' + CF_Command); end; FZPL2Label.Items.Add(ZPL2CFItem); end else raise EParserError.Create(INVALID_DATA + ': ' + CF_Command); finally Free; end; end; except ZPL2CFItem.Free; raise; end; end; procedure TZPL2Parser.ParseCICommand(const CI_Command: string); const INVALID_DATA = 'Invalid change international font data'; var s: string; begin with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_CI + '([12])?\d((,\d{1,3},\d{1,3}){1,256})?'; Subject := UTF8String(CI_Command); if Match then begin s := string(MatchedText); Delete(s, 1, 3); Delete(s, Pos(',', s), Length(s) - Pos(',', s) + 1); try FZPL2Label.InternationalFont := TZPL2InternationalFont(StrToInt(s)); except raise EParserError.Create(INVALID_DATA + ' (value): ' + s); end; end else raise EParserError.Create(INVALID_DATA + ': ' + CI_Command); finally Free; end; end; end; procedure TZPL2Parser.ParseComment(const FX_Command: string); var ZPL2CommentField: TZPL2CommentField; begin ZPL2CommentField := TZPL2CommentField.Create(nil); try ParseFXCommand(FX_Command, ZPL2CommentField); FZPL2Label.Items.Add(ZPL2CommentField); except ZPL2CommentField.Free; raise; end; end; procedure TZPL2Parser.ParseDatamatrix(const BX_Command, FO_Command, FD_Command: string); var ZPL2BarcodeDatamatrix: TZPL2BarcodeDatamatrix; begin ZPL2BarcodeDatamatrix := TZPL2BarcodeDatamatrix.Create(nil); try ParseFOCommand(FO_Command, ZPL2BarcodeDatamatrix); ParseBXCommand(BX_Command, ZPL2BarcodeDatamatrix); ParseFDCommand(FD_Command, ZPL2BarcodeDatamatrix); FZPL2Label.Items.Add(ZPL2BarcodeDatamatrix); except ZPL2BarcodeDatamatrix.Free; raise; end; end; procedure TZPL2Parser.ParseFDCommand(const FD_Command: string; ZPL2TextLabelItem: TZPL2TextLabelItem; FH: boolean; FH_Inidicator: char); var s: string; begin with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_FD + '[\S *]{1,3072}'; Subject := UTF8String(FD_Command); if Match then begin // convert hex characters if FH then begin if FH_Inidicator = #0 then FH_Inidicator := '_'; RegEx := UTF8String(FH_Inidicator) + '[0-9A-Fa-f]{2}'; Subject := UTF8String(Copy(FD_Command, 4, Length(FD_Command) - 3)); if Match then begin s := string(AnsiChar(StrToInt('$' + Copy(string(MatchedText), 2, 2)))); AsciiToAnsi(s); Replacement := UTF8String(s); Replace; while MatchAgain do begin s := string(AnsiChar(StrToInt('$' + Copy(string(MatchedText), 2, 2)))); AsciiToAnsi(s); Replacement := UTF8String(s); Replace; end; end; ZPL2TextLabelItem.Text := string(Subject); end else ZPL2TextLabelItem.Text := Copy(FD_Command, 4, Length(FD_Command) - 3); end else raise EParserError.Create('Invalid field data: ' + FD_Command); finally Free; end; end; end; procedure TZPL2Parser.ParseFOCommand(const FO_Command: string; ZPL2LabelItem: TZPL2LabelItem); var s: UTF8String; begin with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_FO + '(\d{1,5})?,(\d{1,5})?'; Subject := UTF8String(FO_Command); if Match then begin s := MatchedText; RegEx := '\d{1,5}(?=,)'; Subject := s; if Match then begin try ZPL2LabelItem.X := StrToInt(string(MatchedText)); except raise EParserError.Create('Invalid field origin data (x coordinate value): ' + MatchedText); end; end else ZPL2LabelItem.X := 0; RegEx := '(?<=,)\d{1,5}'; if Match then begin try ZPL2LabelItem.Y := StrToInt(string(MatchedText)); except raise EParserError.Create('Invalid field origin data (y coordinate value): ' + MatchedText); end; end else ZPL2LabelItem.Y := 0; end else raise EParserError.Create('Invalid field origin data: ' + MatchedText); finally Free; end; end; end; procedure TZPL2Parser.ParseFXCommand(const FX_Command: string; ZPL2CommentField: TZPL2CommentField); begin with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_FX + '[\S *]+'; Subject := UTF8String(FX_Command); if Match then ZPL2CommentField.Text := Copy(FX_Command, 4, Length(FX_Command) - 3) else raise EParserError.Create('Invalid comment field data: ' + FX_Command); finally Free; end; end; end; procedure TZPL2Parser.ParseGBCommand(const GB_Command: string; ZPL2GraphicBox: TZPL2GraphicBox); const INVALID_DATA = 'Invalid graphic box data'; var s: UTF8String; begin with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_GB + '(\d{1,5})?(,(\d{1,5})?){2}([BW])?(,[0-8])?'; Subject := UTF8String(GB_Command); if Match then begin s := MatchedText; Delete(s, 1, 3); RegEx := '[^,]*'; Subject := s; if Match then begin if MatchedText <> '' then begin try if StrToInt(string(MatchedText)) > 0 then ZPL2GraphicBox.Width := StrToInt(string(MatchedText)) else ZPL2GraphicBox.Width := 1; except raise EParserError.Create(INVALID_DATA + ' (width value): ' + string(MatchedText)); end; end else ZPL2GraphicBox.Width := 1; if MatchAgain then begin if MatchedText <> '' then begin try if StrToInt(string(MatchedText)) > 0 then ZPL2GraphicBox.Height := StrToInt(string(MatchedText)) else ZPL2GraphicBox.Height := 1; except raise EParserError.Create(INVALID_DATA + ' (height value): ' + string(MatchedText)); end; end else ZPL2GraphicBox.Height := 1; end; if MatchAgain then begin if MatchedText <> '' then begin try if StrToInt(string(MatchedText)) > 0 then ZPL2GraphicBox.Border := StrToInt(string(MatchedText)) else ZPL2GraphicBox.Border := 1; except raise EParserError.Create(INVALID_DATA + ' (border thickness value): ' + string(MatchedText)); end; end else ZPL2GraphicBox.Border := 1; end; if MatchAgain then begin if MatchedText <> '' then begin try case MatchedText[1] of 'B': ZPL2GraphicBox.LineColor := lcBlack; 'W': ZPL2GraphicBox.LineColor := lcWhite; else ZPL2GraphicBox.LineColor := lcBlack; end; except raise EParserError.Create(INVALID_DATA + ' (line color value): ' + string(MatchedText)); end; end else ZPL2GraphicBox.LineColor := lcBlack; end; if MatchAgain then begin if MatchedText <> '' then begin try ZPL2GraphicBox.CornerRounding := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (corner roundness value): ' + string(MatchedText)); end; end else ZPL2GraphicBox.CornerRounding := 0; end; end; end else raise EParserError.Create(INVALID_DATA + ': ' + GB_Command); finally Free; end; end; end; procedure TZPL2Parser.ParseGCCommand(const GC_Command: string; ZPL2GraphicCircle: TZPL2GraphicCircle); const INVALID_DATA = 'Invalid graphic circle data'; var s: UTF8String; begin with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_GC + '(\d{1,4},){2}[BW]'; Subject := UTF8String(GC_Command); if Match then begin s := MatchedText; Delete(s, 1, 3); RegEx := '\b\w+\b'; Subject := s; if Match then begin try ZPL2GraphicCircle.Diameter := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (diameter value): ' + string(MatchedText)); end; if MatchAgain then begin try ZPL2GraphicCircle.Border := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (border thickness value): ' + string(MatchedText)); end; end; if MatchAgain then begin try case MatchedText[1] of 'B': ZPL2GraphicCircle.LineColor := lcBlack; 'W': ZPL2GraphicCircle.LineColor := lcWhite; else ZPL2GraphicCircle.LineColor := lcBlack; end; except raise EParserError.Create(INVALID_DATA + ' (line color value): ' + string(MatchedText)); end; end; end; end else raise EParserError.Create(INVALID_DATA + ': ' + GC_Command); finally Free; end; end; end; procedure TZPL2Parser.ParseGDCommand(const GD_Command: string; ZPL2GraphicDiagonalLine: TZPL2GraphicDiagonalLine); const INVALID_DATA = 'Invalid graphic diagonal line data'; var s: UTF8String; begin with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_GD + '(\d{1,4},){3}[BW],[LR/\\]'; Subject := UTF8String(GD_Command); if Match then begin s := MatchedText; Delete(s, 1, 3); RegEx := '\b\w+\b'; Subject := s; if Match then begin try ZPL2GraphicDiagonalLine.Width := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (width value): ' + string(MatchedText)); end; if MatchAgain then begin try ZPL2GraphicDiagonalLine.Height := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (height value): ' + string(MatchedText)); end; end; if MatchAgain then begin try ZPL2GraphicDiagonalLine.Border := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (border thickness value): ' + string(MatchedText)); end; end; if MatchAgain then begin try case MatchedText[1] of 'B': ZPL2GraphicDiagonalLine.LineColor := lcBlack; 'W': ZPL2GraphicDiagonalLine.LineColor := lcWhite; else ZPL2GraphicDiagonalLine.LineColor := lcBlack; end; except raise EParserError.Create(INVALID_DATA + ' (line color value): ' + string(MatchedText)); end; end; if MatchAgain then begin case MatchedText[1] of 'R', '/': ZPL2GraphicDiagonalLine.Orientation := loRightLeaning; 'L', '\': ZPL2GraphicDiagonalLine.Orientation := loLeftLeaning; else raise EParserError.Create(INVALID_DATA + ' (line orientation value): ' + string(MatchedText)); end; end; end; end else raise EParserError.Create(INVALID_DATA + ': ' + GD_Command); finally Free; end; end; end; procedure TZPL2Parser.ParseGECommand(const GE_Command: string; ZPL2GraphicEllipse: TZPL2GraphicEllipse); const INVALID_DATA = 'Invalid graphic ellipse data'; var s: UTF8String; begin with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_GE + '(\d{1,4},){3}[BW]'; Subject := UTF8String(GE_Command); if Match then begin s := MatchedText; Delete(s, 1, 3); RegEx := '\b\w+\b'; Subject := s; if Match then begin try ZPL2GraphicEllipse.Width := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (width value): ' + string(MatchedText)); end; if MatchAgain then begin try ZPL2GraphicEllipse.Height := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (height value): ' + string(MatchedText)); end; end; if MatchAgain then begin try ZPL2GraphicEllipse.Border := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (border thickness value): ' + string(MatchedText)); end; end; if MatchAgain then begin try case MatchedText[1] of 'B': ZPL2GraphicEllipse.LineColor := lcBlack; 'W': ZPL2GraphicEllipse.LineColor := lcWhite; else ZPL2GraphicEllipse.LineColor := lcBlack; end; except raise EParserError.Create(INVALID_DATA + ' (line color value): ' + string(MatchedText)); end; end; end; end else raise EParserError.Create(INVALID_DATA + ': ' + GE_Command); finally Free; end; end; end; procedure TZPL2Parser.ParseGFCommand(GF_Command: string; ZPL2GraphicField: TZPL2GraphicField); const INVALID_DATA = 'Invalid graphic field data'; var i, j: integer; Bytes, BytesPerRow, Max_Len: word; s: UTF8String; s1, Data: string; Rows: TStrings; begin Bytes := 0; BytesPerRow := 0; with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_GF + 'A,(\d{1,5},){3}'; Subject := UTF8String(GF_Command); if Match then begin s := MatchedText; RegEx := '\d{1,5}'; Subject := s; if Match then begin // The first match can be ignored, it is identical to the second one if MatchAgain then begin try Bytes := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (byte count value):' + string(MatchedText)); end; end; if MatchAgain then begin try BytesPerRow := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (bytes per row value): ' + string(MatchedText)); end; end; end; RegEx := '\' + ZPL2_GF + 'A,(\d{1,5},){3}'; Subject := UTF8String(GF_Command); // Delete first row if Match then begin Replace; GF_Command := Trim(string(Subject)); end; end else raise EParserError.Create(INVALID_DATA + ': ' + GF_Command); finally Free; end; end; Max_Len := BytesPerRow * 2; // Delete all line breaks to get a continuous string Data := StringReplace(GF_Command, sLineBreak, '', [rfReplaceAll]); Data := Trim(StringReplace(Data, ',', sLineBreak, [rfReplaceAll])); i := 0; Rows := TStringList.Create; try Rows.Text := Data; while i < Rows.Count do begin j := 1; s1 := Rows[i]; // if the row contains more data than specified, move the excess to new rows if Length(s1) > Max_Len then begin Rows[i] := Copy(s1, 1, Max_Len); Delete(s1, 1, Max_Len); while Length(s1) > Max_Len do begin Rows.Insert(i + j, Copy(s1, 1, Max_Len)); Delete(s1, 1, Max_Len); Inc(j); end; Rows.Insert(i + j, s1); Inc(j); end; Inc(i, j); end; Data := Rows.Text; if Bytes <> Rows.Count * BytesPerRow then Bytes := Rows.Count * BytesPerRow; ZPL2GraphicField.SetGraphic(Bytes, BytesPerRow, Data); finally Rows.Free; end; end; procedure TZPL2Parser.ParseGraphicBox(const GB_Command, FO_Command: string); var ZPL2GraphicBox: TZPL2GraphicBox; begin ZPL2GraphicBox := TZPL2GraphicBox.Create(nil); try ParseFOCommand(FO_Command, ZPL2GraphicBox); ParseGBCommand(GB_Command, ZPL2GraphicBox); FZPL2Label.Items.Add(ZPL2GraphicBox); if FZPL2Label.LabelReversePrint and (FZPL2Label.Items.Count = 1) then FZPL2Label.LabelHeight := TZPL2GraphicBox(FZPL2Label.Items[0]).Height; except ZPL2GraphicBox.Free; raise; end; end; procedure TZPL2Parser.ParseGraphicCircle(const GC_Command, FO_Command: string); var ZPL2GraphicCircle: TZPL2GraphicCircle; begin ZPL2GraphicCircle := TZPL2GraphicCircle.Create(nil); try ParseFOCommand(FO_Command, ZPL2GraphicCircle); ParseGCCommand(GC_Command, ZPL2GraphicCircle); FZPL2Label.Items.Add(ZPL2GraphicCircle); except ZPL2GraphicCircle.Free; raise; end; end; procedure TZPL2Parser.ParseGraphicDiagonalLine(const GD_Command, FO_Command: string); var ZPL2GraphicDiagonalLine: TZPL2GraphicDiagonalLine; begin ZPL2GraphicDiagonalLine := TZPL2GraphicDiagonalLine.Create(nil); try ParseFOCommand(FO_Command, ZPL2GraphicDiagonalLine); ParseGDCommand(GD_Command, ZPL2GraphicDiagonalLine); FZPL2Label.Items.Add(ZPL2GraphicDiagonalLine); except ZPL2GraphicDiagonalLine.Free; raise; end; end; procedure TZPL2Parser.ParseGraphicEllipse(const GE_Command, FO_Command: string); var ZPL2GraphicEllipse: TZPL2GraphicEllipse; begin ZPL2GraphicEllipse := TZPL2GraphicEllipse.Create(nil); try ParseFOCommand(FO_Command, ZPL2GraphicEllipse); ParseGECommand(GE_Command, ZPL2GraphicEllipse); FZPL2Label.Items.Add(ZPL2GraphicEllipse); except ZPL2GraphicEllipse.Free; raise; end; end; procedure TZPL2Parser.ParseGraphicField(const GF_Command, FO_Command: string); var ZPL2GraphicField: TZPL2GraphicField; begin ZPL2GraphicField := TZPL2GraphicField.Create(nil); try ParseFOCommand(FO_Command, ZPL2GraphicField); ParseGFCommand(GF_Command, ZPL2GraphicField); FZPL2Label.Items.Add(ZPL2GraphicField); except ZPL2GraphicField.Free; raise; end; end; procedure TZPL2Parser.ParseLHCommand(const LH_Command: string); const INVALID_DATA = 'Invalid label home data'; var s: UTF8String; begin with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_LH + '\d{1,5},\d{1,5}'; Subject := UTF8String(LH_Command); if Match then begin s := MatchedText; Delete(s, 1, 3); RegEx := '\b\w+\b'; Subject := s; if Match then begin try FZPL2Label.LabelHome_X := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (x coordinate value): ' + string(MatchedText)); end; if MatchAgain then begin try FZPL2Label.LabelHome_Y := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (y coordinate value): ' + string(MatchedText)); end; end; end; end else raise EParserError.Create(INVALID_DATA + ': ' + LH_Command); finally Free; end; end; end; procedure TZPL2Parser.ParseMDCommand(const MD_Command: string); const INVALID_DATA = 'Invalid media darkness data'; var s: string; begin with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_MD + '(-)?(([0-2])?\d(\.\d)?|30(\.0)?)$'; Subject := UTF8String(MD_Command); if Match then begin s := string(MatchedText); Delete(s, 1, 3); try FZPL2Label.MediaDarkness := StrToFloat(s, GetLocaleFormatSettingsWithDotDecimalSeparator); except raise EParserError.Create(INVALID_DATA + ' (value): ' + s); end; end else raise EParserError.Create(INVALID_DATA + ': ' + MD_Command); finally Free; end; end; end; procedure TZPL2Parser.ParsePQCommand(const PQ_Command: string); const INVALID_DATA = 'Invalid print quantitiy data'; var s: UTF8String; begin with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_PQ + '(\d{1,8},){3}[YN]'; Subject := UTF8String(PQ_Command); if Match then begin s := MatchedText; Delete(s, 1, 3); RegEx := '\b\w+\b'; Subject := s; if Match then begin try FZPL2Label.PrintQuantity := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (quantitiy count value): ' + string(MatchedText)); end; if MatchAgain then begin try FZPL2Label.PrintQuantityTillPauseAndCut := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (print quantity till pause and cut value): ' + string(MatchedText)); end; end; if MatchAgain then begin try FZPL2Label.ReplicatesCount := StrToInt(string(MatchedText)); except raise EParserError.Create(INVALID_DATA + ' (replicates count value): ' + string(MatchedText)); end; end; if MatchAgain then begin try case MatchedText[1] of 'Y': FZPL2Label.OverridePauseCount := true; else FZPL2Label.OverridePauseCount := false; end; except raise EParserError.Create(INVALID_DATA + ' (override pause count value): ' + string(MatchedText)); end; end; end; end else raise EParserError.Create(INVALID_DATA + ': ' + PQ_Command); finally Free; end; end; end; procedure TZPL2Parser.ParsePRCommand(const PR_Command: string); const INVALID_DATA = 'Invalid print rate data'; var s: UTF8String; begin with TPerlRegEx.Create do begin try // The second and third parameter of the PR command are currently not used! // Add the comment part of the next line to the regular expression if you are going to use them aswell. RegEx := '\' + ZPL2_PR + '([2345689ABCDE]|10|11|12)'; // (,[2345689ABCDE]|10|11|12){0,2}' Subject := UTF8String(PR_Command); if Match then begin s := MatchedText; Delete(s, 1, 3); RegEx := '\b\w+\b'; Subject := s; if Match then begin try case MatchedText[1] of '2', 'A': FZPL2Label.PrintSpeed := sp50_8mm; '3', 'B': FZPL2Label.PrintSpeed := sp76_2mm; '4', 'C': FZPL2Label.PrintSpeed := sp101_6mm; '5': FZPL2Label.PrintSpeed := sp127mm; '6', 'D': FZPL2Label.PrintSpeed := sp152_4mm; '8', 'E': FZPL2Label.PrintSpeed := sp203_2mm; '9': FZPL2Label.PrintSpeed := sp220_5mm; '1': begin case MatchedText[2] of '0': FZPL2Label.PrintSpeed := sp245mm; '1': FZPL2Label.PrintSpeed := sp269_5mm; '2': FZPL2Label.PrintSpeed := sp304_8mm; else raise EParserError.Create(INVALID_DATA + ' (print speed value): ' + string(MatchedText)); end; end; else raise EParserError.Create(INVALID_DATA + ' (print speed value): ' + string(MatchedText)); end; except raise EParserError.Create(INVALID_DATA + ' (print speed value): ' + string(MatchedText)); end; end; end else raise EParserError.Create(INVALID_DATA + ': ' + PR_Command); finally Free; end; end; end; procedure TZPL2Parser.ParsePWCommand(const PW_Command: string); const INVALID_DATA = 'Invalid print width data'; var s: UTF8String; begin with TPerlRegEx.Create do begin try RegEx := '\' + ZPL2_PW + '([2-9]$|[1-9][\d]{1,5}$)'; Subject := UTF8String(PW_Command); if Match then begin s := MatchedText; Delete(s, 1, 3); try FZPL2Label.PrintWidth := StrToInt(string(s)); except raise EParserError.Create(INVALID_DATA + ' (width value): ' + string(s)); end; end else raise EParserError.Create(INVALID_DATA + ': ' + PW_Command); finally Free; end; end; end; procedure TZPL2Parser.ParseQRCode(const BQ_Command, FO_Command, FD_Command: string); procedure ParseFDCommand(const FD_Command: string; ZPL2BarcodeQR: TZPL2BarcodeQR); const INVALID_DATA = 'Invalid QR code data'; var s: string; posComma, posFD: integer; begin posComma := Pos(',', FD_Command); if posComma > 0 then begin if (posComma > 1) and (Uppercase(FD_Command[posComma - 1]) = 'M') then Inc(posComma); // to fetch the character after the comma posFD := Pos(ZPL2_FD, FD_Command); if posFD > 0 then begin Inc(posFD, Length(ZPL2_FD)); Dec(posComma, Length(ZPL2_FD)); s := Copy(FD_Command, posFD, posComma); Self.ParseFDCommand(ZPL2_FD + Copy(FD_Command, posComma + Length(ZPL2_FD) + 1, Length(FD_Command) - posComma - Length(ZPL2_FD)), ZPL2BarcodeQR); end; end else begin s := ''; ZPL2BarcodeQR.ErrorCorrectionLevel := eclHighReliabilityLevel; // default, if not specified end; with TPerlRegEx.Create do begin try if s <> '' then begin RegEx := '[\S](A,|M,[N|A|B|K])'; Subject := UTF8String(s); if Match then begin try case MatchedText[1] of 'H': ZPL2BarcodeQR.ErrorCorrectionLevel := eclUltraHighReliabilityLevel; 'Q': ZPL2BarcodeQR.ErrorCorrectionLevel := eclHighReliabilityLevel; 'M': ZPL2BarcodeQR.ErrorCorrectionLevel := eclStandardLevel; 'L': ZPL2BarcodeQR.ErrorCorrectionLevel := eclHighDensityLevel; else ZPL2BarcodeQR.ErrorCorrectionLevel := eclStandardLevel; end; except raise EParserError.Create(INVALID_DATA + ' (error correction level value): ' + string(MatchedText)); end; end else raise EParserError.Create(INVALID_DATA + ' (QR switches in FD command): ' + s); end; finally Free; end; end; end; var ZPL2BarcodeQR: TZPL2BarcodeQR; begin ZPL2BarcodeQR := TZPL2BarcodeQR.Create(nil); try ParseFOCommand(FO_Command, ZPL2BarcodeQR); ParseBQCommand(BQ_Command, ZPL2BarcodeQR); ParseFDCommand(FD_Command, ZPL2BarcodeQR); FZPL2Label.Items.Add(ZPL2BarcodeQR); except ZPL2BarcodeQR.Free; raise; end; end; procedure TZPL2Parser.ParseRotation(const Rotation: char; ZPL2RotationLabelItem: TZPL2RotationLabelItem); begin case Rotation of 'N': ZPL2RotationLabelItem.Rotation := zrNO_ROTATION; 'B': ZPL2RotationLabelItem.Rotation := zrROTATE_90_DEGREES; 'I': ZPL2RotationLabelItem.Rotation := zrROTATE_180_DEGREES; 'R': ZPL2RotationLabelItem.Rotation := zrROTATE_270_DEGREES; else raise EParserError.Create('Invalid rotation char: ' + Rotation); end; end; procedure TZPL2Parser.ParseTextField(const A_Command, FO_Command, FD_Command: string; const FH: boolean = false; const FH_Inidicator: char = #0); var ZPL2TextField: TZPL2TextField; begin ZPL2TextField := TZPL2TextField.Create(nil); try ParseFOCommand(FO_Command, ZPL2TextField); if A_Command <> '' then ParseACommand(A_Command, ZPL2TextField) else begin ZPL2TextField.Font := FZPL2Label.CF.Font; ZPL2TextField.Height := FZPL2Label.CF.Height; ZPL2TextField.Width := FZPL2Label.CF.Width; ZPL2TextField.Rotation := zrNO_ROTATION; end; ParseFDCommand(FD_Command, ZPL2TextField, FH, FH_Inidicator); FZPL2Label.Items.Add(ZPL2TextField); except ZPL2TextField.Free; raise; end; end; {$endregion} end.
unit JPL.Files; { Jacek Pazera http://www.pazera-software.com } {$IFDEF FPC} {$mode objfpc}{$H+} {$WARN 5057 off : Local variable "$1" does not seem to be initialized} {$ENDIF} interface uses SysUtils, Classes, {$IFDEF MSWINDOWS}Windows,{$ENDIF} {$IFDEF LINUX}BaseUnix,{$ENDIF} //MFPC.Classes.Streams, {%H-}JPL.Strings; type TFileInfoRec = record FullFileName: string; Directory: string; // directory + path delimiter Path: string; ShortFileName: string; BaseFileName: string; Extension: string; StatOK: Boolean; DeviceNo: UInt64; // QWord; InodeNo: Cardinal; FileMode: Cardinal; HardLinks: UInt64; // QWord; OwnerUserID: Cardinal; OwnerGroupID: Cardinal; Size: Int64; BlockSize: Int64; Blocks: Int64; CreationTime: TDateTime; LastWriteTime: TDateTime; LastAccessTime: TDateTime; ReadOnly: Boolean; end; procedure ClearFileInfoRec(var fir: TFileInfoRec); function GetFileInfoRec(const FileName: string; out fir: TFileInfoRec; bOnlyNames: Boolean = False): Boolean; function FileSizeInt(const FileName: string): int64; {$IFDEF MSWINDOWS} function FileGetCreationTime(const FileName: string): TDateTime; function FileGetTimes(const FileName: string; out CreationTime, LastAccessTime, LastWriteTime: TDateTime): Boolean; {$ENDIF} function DelFile(const FileName: string): Boolean; function GetIncFileName(const fName: string; NumPrefix: string = '_'; xpad: integer = 3): string; function GetUniqueFileName(Prefix: string = ''; Len: BYTE = 10; Ext: string = ''): string; implementation function GetIncFileName(const fName: string; NumPrefix: string = '_'; xpad: integer = 3): string; var i: integer; ShortName, Ext, fOut: string; begin Result := ''; if not FileExists(fName) then begin Result := fName; Exit; end; Ext := ExtractFileExt(fName); ShortName := ChangeFileExt(fName, ''); for i := 1 to 100000 do begin fOut := ShortName + NumPrefix + Pad(IntToStr(i), xpad, '0') + Ext; if not FileExists(fOut) then begin Result := fOut; Break; end; end; end; function GetUniqueFileName(Prefix: string = ''; Len: BYTE = 10; Ext: string = ''): string; var x: integer; bt: BYTE; s: string; begin x := 0; s := ''; Randomize; while x < Len do begin bt := Random(254) + 1; if not ( (bt in [48..57]) or (x in [65..90]) or (x in [97..122]) ) then Continue; Inc(x); s := s + Char(bt); end; s := Prefix + s; if (Ext <> '') and (Ext[1] <> '.') then Ext := '.' + Ext; Result := ChangeFileExt(s, Ext); end; {$HINTS OFF} function DelFile(const FileName: string): Boolean; var w: WORD; begin Result := True; try {$IFDEF MSWINDOWS} if not SysUtils.DeleteFile(FileName) then try {$WARNINGS OFF} w := 0 and not faReadOnly and not faSysFile and not faHidden; FileSetAttr(FileName, w); {$WARNINGS ON} SysUtils.DeleteFile(FileName); except Result := not FileExists(FileName); end; {$ELSE} SysUtils.DeleteFile(FileName); {$ENDIF} Result := not FileExists(FileName); except Result := not FileExists(FileName); end; end; {$HINTS ON} {$IFDEF MSWINDOWS} // From DSiWin32.pas by Primož Gabrijelčič: https://github.com/gabr42/OmniThreadLibrary/tree/master/src function DSiFileSize(const fileName: string): int64; var fHandle: THandle; begin fHandle := CreateFile( PChar(fileName), 0, FILE_SHARE_READ OR FILE_SHARE_WRITE OR FILE_SHARE_DELETE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 ); if fHandle = INVALID_HANDLE_VALUE then Result := -1 else try Int64Rec(Result).Lo := GetFileSize(fHandle, @Int64Rec(Result).Hi); finally CloseHandle(fHandle); end; end; {$ENDIF} function _FileSizeInt(const FileName: string): int64; var fs: TFileStream; begin Result := 0; if not FileExists(FileName) then Exit; fs := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone); try Result := fs.Size; finally fs.Free; end; end; function FileSizeInt(const FileName: string): int64; {$IFNDEF MSWINDOWS} var fir: TFileInfoRec; {$ENDIF} begin //Result := 0; try Result := _FileSizeInt(FileName); except on E: Exception do try {$IFDEF MSWINDOWS} Result := DSiFileSize(FileName); {$ELSE} if not GetFileInfoRec(FileName, fir, False) then Exit(-1); Result := fir.Size; {$ENDIF} except Result := -1; end; end; end; {$IFDEF MSWINDOWS} {$WARN SYMBOL_PLATFORM OFF} // http://forum.lazarus.freepascal.org/index.php/topic,6705.0.html function FileGetCreationTime(const FileName: string): TDateTime; var SearchRec: TSearchRec; SysTime: SYSTEMTIME; FileTime: TFILETIME; begin if FindFirst(FileName, faAnyFile, SearchRec) = 0 then begin FileTimeToLocalFileTime(SearchRec.FindData.ftCreationTime, FileTime); FileTimeToSystemTime(FileTime, SysTime); Result := SystemTimeToDateTime(SysTime); end else Result := 0; end; function FileGetTimes(const FileName: string; out CreationTime, LastAccessTime, LastWriteTime: TDateTime): Boolean; var SearchRec: TSearchRec; SysTime: SYSTEMTIME; FileTime: TFILETIME; begin if FindFirst(FileName, faAnyFile, SearchRec) = 0 then begin FileTimeToLocalFileTime(SearchRec.FindData.ftCreationTime, FileTime); FileTimeToSystemTime(FileTime, SysTime); CreationTime := SystemTimeToDateTime(SysTime); //TODO: bad dates FileTimeToLocalFileTime(SearchRec.FindData.ftLastAccessTime, FileTime); FileTimeToSystemTime(FileTime, SysTime); LastAccessTime := SystemTimeToDateTime(SysTime); FileTimeToLocalFileTime(SearchRec.FindData.ftLastWriteTime, FileTime); FileTimeToSystemTime(FileTime, SysTime); LastWriteTime := SystemTimeToDateTime(SysTime); Result := True; end else Result := False; end; {$WARN SYMBOL_PLATFORM ON} {$ENDIF} procedure ClearFileInfoRec(var fir: TFileInfoRec); begin fir.FullFileName := ''; fir.Directory := ''; fir.Path := ''; fir.ShortFileName := ''; fir.BaseFileName := ''; fir.Extension := ''; fir.StatOK := False; fir.DeviceNo := 0; fir.InodeNo := 0; fir.FileMode := 0; fir.HardLinks := 0; fir.OwnerUserID := 0; fir.OwnerGroupID := 0; fir.Size := 0; fir.BlockSize := 0; fir.Blocks := 0; fir.CreationTime := 0; fir.LastWriteTime := 0; fir.LastAccessTime := 0; fir.ReadOnly := True; end; function GetFileInfoRec(const FileName: string; out fir: TFileInfoRec; bOnlyNames: Boolean = False): Boolean; var {$IFDEF LINUX} st: BaseUnix.stat; {$ENDIF} {$IFDEF MSWINDOWS} tc, ta, tw: TDateTime; {$ENDIF} begin Result := False; if not FileExists(FileName) then Exit; ClearFileInfoRec(fir{%H-}); fir.FullFileName := ExpandFileName(FileName); fir.Directory := ExtractFileDir(fir.FullFileName); fir.Path := ExtractFilePath(fir.FullFileName); fir.ShortFileName := ExtractFileName(FileName); fir.BaseFileName := ChangeFileExt(fir.ShortFileName, ''); fir.Extension := GetFileExt(FileName, True); if bOnlyNames then Exit(True); fir.ReadOnly := FileIsReadOnly(fir.FullFileName); {$IFDEF MSWINDOWS} fir.Size := FileSizeInt(FileName); if FileGetTimes(FileName, tc, ta, tw) then begin fir.CreationTime := tc; fir.LastAccessTime := ta; fir.LastWriteTime := tw; end; {$ENDIF} {$IFDEF LINUX} if FpStat(FileName, st{%H-}) = 0 then begin fir.StatOK := True; fir.DeviceNo := st.st_dev; fir.InodeNo := st.st_ino; fir.FileMode := st.st_mode; fir.HardLinks := st.st_nlink; fir.OwnerUserID := st.st_uid; fir.OwnerGroupID := st.st_gid; fir.Size := st.st_size; fir.BlockSize := st.st_blksize; fir.Blocks := st.st_blocks; fir.CreationTime := FileDateToDateTime(st.st_ctime); fir.LastAccessTime := FileDateToDateTime(st.st_atime); fir.LastWriteTime := FileDateToDateTime(st.st_mtime); end else fir.StatOK := False; {$ENDIF} Result := True; end; end.
unit uProjectsFrame; 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.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.Controls.Presentation, FMX.ListView, FMX.Objects, FMX.Layouts, FMX.Effects, FMX.Filter.Effects, FMX.Platform, System.Threading, System.ImageList, FMX.ImgList; type TProjectsFrame = class(TFrame) listViewProjects: TListView; ToolBar1: TToolBar; ToolBarBackgroundRect: TRectangle; Label1: TLabel; AddButton: TSpeedButton; btnSignOut: TButton; Layout1: TLayout; AddProjectCircleBTN: TCircle; Layout3: TLayout; procedure listViewProjectsItemClick(const Sender: TObject; const AItem: TListViewItem); procedure btnSignOutClick(Sender: TObject); procedure listViewProjectsDeletingItem(Sender: TObject; AIndex: Integer; var ACanDelete: Boolean); procedure AddProjectCircleBTNClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure LoadProjects; end; implementation {$R *.fmx} uses formMain, uDataModule, fieldlogger.data; procedure TProjectsFrame.AddProjectCircleBTNClick(Sender: TObject); begin frmMain.SetNewProjectScreen; end; procedure TProjectsFrame.btnSignOutClick(Sender: TObject); begin frmMain.SignOut; end; procedure TProjectsFrame.listViewProjectsDeletingItem(Sender: TObject; AIndex: Integer; var ACanDelete: Boolean); begin ACanDelete := mainDM.DeleteProject(listViewProjects.Items[AIndex].Tag); end; procedure TProjectsFrame.listViewProjectsItemClick(const Sender: TObject; const AItem: TListViewItem); begin frmMain.LoadProjectDetail(AItem.Tag); end; procedure TProjectsFrame.LoadProjects; begin frmMain.ShowActivity; TTask.Run(procedure begin try mainDM.LoadProjects(listViewProjects, frmMain.GetCurrentStyleId); finally TThread.Synchronize(nil, procedure begin frmMain.HideActivity; end); end; end); end; end.
unit uRabbitMQ; interface {$REGION 'Conditional-directive'} {$IF CompilerVersion<16} {$DEFINE CPU32BITS} {$ELSE} {$IF CompilerVersion<22} {$IF defined(CPU386) or defined(CPUX86)} {$DEFINE CPU32BITS} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDREGION} const LIBFILE = 'rabbitmq.dll'; // const // POOL_TABLE_SIZE = 16; // const // HEADER_SIZE = 7; // FOOTER_SIZE = 1; // (* 7 bytes up front, then payload, then 1 byte footer *) // // AMQP_PSEUDOFRAME_PROTOCOL_HEADER = 'A'; type Int8=SmallInt; UInt8=Byte; Int16=ShortInt; UInt16=Word; Int32=Integer; UInt32=Cardinal; PUInt64=^UInt64; {$IFDEF CPU32BITS} ssize_t = Int32; size_t = Int32; {$ELSE} ssize_t = Int64; size_t = Int64; {$ENDIF} {$REGION 'amqp_time.h'} const AMQP_MS_PER_S = 1000; AMQP_US_PER_MS = 1000; AMQP_NS_PER_S = 1000000000; AMQP_NS_PER_MS = 1000000; AMQP_NS_PER_US = 1000; (* This represents a point in time in reference to a monotonic clock. * * The internal representation is ns, relative to the monotonic clock. * * There are two 'special' values: * - 0: means 'this instant', its meant for polls with a 0-timeout, or * non-blocking option * - UINT64_MAX: means 'at infinity', its mean for polls with an infinite * timeout *) type (* * Structure used in select() call, taken from the BSD file sys/time.h. *) timeval = record tv_sec: UInt32; (* seconds *) tv_usec: UInt32; (* and microseconds *) end; ptimeval = ^timeval; amqp_time_t_ = record time_point_ns: UInt64; end; amqp_time_t = amqp_time_t_; pamqp_time_t = ^amqp_time_t; {$ENDREGION} {$REGION 'amqp_socket.h'} (* * * An abstract socket interface. *) amqp_socket_flag_enum = (AMQP_SF_NONE = 0, AMQP_SF_MORE = 1, AMQP_SF_POLLIN = 2, AMQP_SF_POLLOUT = 4, AMQP_SF_POLLERR = 8); amqp_socket_close_enum = (AMQP_SC_NONE = 0, AMQP_SC_FORCE = 1); // function amqp_os_socket_error: integer; cdecl; // // function amqp_os_socket_close(sockfd: integer): integer; cdecl; (* Socket callbacks. *) amqp_socket_send_fn = function(a: Pointer; const b: Pointer; c: size_t; d: integer): ssize_t; amqp_socket_recv_fn = function(a: Pointer; b: Pointer; c: size_t; d: integer): ssize_t; amqp_socket_open_fn = function(a: Pointer; const b: PAnsiChar; c: integer; d: ptimeval): integer; amqp_socket_close_fn = function(a: Pointer; b: amqp_socket_close_enum): integer; amqp_socket_get_sockfd_fn = function: integer; amqp_socket_delete_fn = procedure(a: Pointer); (* * V-table for amqp_socket_t *) amqp_socket_class_t = record send: amqp_socket_send_fn; recv: amqp_socket_recv_fn; open: amqp_socket_open_fn; close: amqp_socket_close_fn; get_sockfd: amqp_socket_get_sockfd_fn; delete: amqp_socket_delete_fn; end; pamqp_socket_class_t = ^amqp_socket_class_t; (* * Abstract base class for amqp_socket_t *) pamqp_socket_t = ^amqp_socket_t_; amqp_socket_t_ = record klass: pamqp_socket_class_t; end; amqp_socket_t = amqp_socket_t_; {$ENDREGION} {$REGION 'unsort'} amqp_boolean_t = integer; (* * * Bitmask for flags * * \since v0.1 *) amqp_flags_t = UInt32; (* * * Channel type * * \since v0.1 *) amqp_channel_t = UInt16; (* * * Buffer descriptor * * \since v0.1 *) pamqp_bytes_t = ^amqp_bytes_t_; amqp_bytes_t_ = record len: size_t; (* *< length of the buffer in bytes *) bytes: Pointer; (* *< pointer to the beginning of the buffer *) end; amqp_bytes_t = amqp_bytes_t_; (* * * Method number * * \since v0.1 *) pamqp_method_number_t = ^amqp_method_number_t; amqp_method_number_t = UInt32; (* * * A list of allocation blocks * * \since v0.1 *) amqp_pool_blocklist_t_ = record num_blocks: integer; (* *< Number of blocks in the block list *) blocklist: PPointer; end; amqp_pool_blocklist_t = amqp_pool_blocklist_t_; (* * * A memory pool * * \since v0.1 *) pamqp_pool_t = ^amqp_pool_t_; amqp_pool_t_ = record pagesize: size_t; (* *< the size of the page in bytes. * allocations less than or equal to this size are * allocated in the pages block list * allocations greater than this are allocated in their * own block in the large_blocks block list *) pages: amqp_pool_blocklist_t; (* *< blocks that are the size of pagesize *) large_blocks: amqp_pool_blocklist_t; (* *< allocations larger than the pagesize *) next_page: integer; (* *< an index to the next unused page block *) alloc_block: PAnsiChar; (* *< pointer to the current allocation block *) alloc_used: size_t; (* *< number of bytes in the current allocation block that has been used *) end; amqp_pool_t = amqp_pool_t_; (* * * Decimal data type * * \since v0.1 *) amqp_decimal_t_ = record decimals: UInt8; (* *< the location of the decimal point *) value: UInt32; (* *< the value before the decimal point is applied *) end; amqp_decimal_t = amqp_decimal_t_; (* * * An AMQP Field Array * * A repeated set of field values, all must be of the same type * * \since v0.1 *) pamqp_field_value_t_ = ^amqp_field_value_t_; amqp_array_t_ = record num_entries: integer; (* *< Number of entries in the table *) entries: pamqp_field_value_t_; (* *< linked list of field values *) end; amqp_array_t = amqp_array_t_; (* * * AMQP field table * * An AMQP field table is a set of key-value pairs. * A key is a UTF-8 encoded string up to 128 bytes long, and are not null * terminated. * A value can be one of several different datatypes. \sa amqp_field_value_kind_t * * \sa amqp_table_entry_t * * \since v0.1 *) pamqp_table_t = ^amqp_table_t_; pamqp_table_entry_t_ = ^amqp_table_entry_t_; amqp_table_t_ = record num_entries: integer; (* *< length of entries array *) entries: pamqp_table_entry_t_; (* *< an array of table entries *) end; amqp_table_t = amqp_table_t_; (* * * A field table value * * \since v0.1 *) amqp_field_value_t_ = record kind: UInt8; value: record case integer of 0: (&boolean: amqp_boolean_t); 1: (i8: Int8); 2: (u8: UInt8); 3: (i16: Int16); 4: (u16: UInt16); 5: (i32: Int32); 6: (u32: UInt32); 7: (i64: Int64); 8: (u64: UInt64); 9: (f32: Single); 10: (f64: Double); 11: (decimal: amqp_decimal_t); 12: (bytes: amqp_bytes_t); 13: (table: amqp_table_t); 14: (&array: amqp_array_t); end; end; amqp_field_value_t = amqp_field_value_t_; (* * * An entry in a field-table * * \sa amqp_table_encode(), amqp_table_decode(), amqp_table_clone() * * \since v0.1 *) amqp_table_entry_t_ = record key: amqp_bytes_t; (* *< the table entry key. Its a null-terminated UTF-8 string, * with a maximum size of 128 bytes *) value: amqp_field_value_t; (* *< the table entry values *) end; amqp_table_entry_t = amqp_table_entry_t_; pamqp_pool_table_entry_t = ^amqp_pool_table_entry_t_; pamqp_pool_table_entry_t_ = pamqp_pool_table_entry_t; amqp_pool_table_entry_t_ = record next: pamqp_pool_table_entry_t_; pool: amqp_pool_t; channel: amqp_channel_t; end; amqp_pool_table_entry_t = amqp_pool_table_entry_t_; pamqp_link_t_ = ^amqp_link_t_; pamqp_link_t = pamqp_link_t_; amqp_link_t_ = record next: pamqp_link_t_; data: Pointer; end; amqp_link_t = amqp_link_t_; (* * * An amqp method * * \since v0.1 *) pamqp_method_t = ^amqp_method_t_; amqp_method_t_ = record id: amqp_method_number_t; (* *< the method id number *) decoded: Pointer; (* *< pointer to the decoded method, * cast to the appropriate type to use *) end; amqp_method_t = amqp_method_t_; (* * * Response type * * \since v0.1 *) amqp_response_type_enum_ = (AMQP_RESPONSE_NONE = 0, (* the library got an EOF from the socket *) AMQP_RESPONSE_NORMAL, (* response normal, the RPC completed successfully *) AMQP_RESPONSE_LIBRARY_EXCEPTION, (* library error, an error occurred in the library , examine the library_error *) AMQP_RESPONSE_SERVER_EXCEPTION (* server exception, the broker returned an error, check replay *) ); amqp_response_type_enum = amqp_response_type_enum_; (* * * Reply from a RPC method on the broker * * \since v0.1 *) amqp_rpc_reply_t_ = record reply_type: amqp_response_type_enum; (* the reply type: * - AMQP_RESPONSE_NORMAL - the RPC completed successfully * - AMQP_RESPONSE_SERVER_EXCEPTION - the broker returned * an exception, check the reply field * - AMQP_RESPONSE_LIBRARY_EXCEPTION - the library * encountered an error, check the library_error field *) reply: amqp_method_t; (* *< in case of AMQP_RESPONSE_SERVER_EXCEPTION this * field will be set to the method returned from the broker *) library_error: integer; (* *< in case of AMQP_RESPONSE_LIBRARY_EXCEPTION this * field will be set to an error code. An error * string can be retrieved using amqp_error_string *) end; amqp_rpc_reply_t = amqp_rpc_reply_t_; amqp_connection_state_enum_ = (CONNECTION_STATE_IDLE = 0, CONNECTION_STATE_INITIAL, CONNECTION_STATE_HEADER, CONNECTION_STATE_BODY); amqp_connection_state_enum = amqp_connection_state_enum_; amqp_connection_state_t = Pointer; // amqp_connection_state_t = ^amqp_connection_state_t_; // // amqp_connection_state_t_ = record // pool_table: array [0 .. Pred(POOL_TABLE_SIZE)] of pamqp_pool_table_entry_t; // state: amqp_connection_state_enum; // channel_max: integer; // frame_max: integer; // (* Heartbeat interval in seconds. If this is <= 0, then heartbeats are not // * enabled, and next_recv_heartbeat and next_send_heartbeat are set to // * infinite *) // heartbeat: integer; // next_recv_heartbeat: amqp_time_t; // next_send_heartbeat: amqp_time_t; // (* buffer for holding frame headers. Allows us to delay allocating // * the raw frame buffer until the type, channel, and size are all known // *) // header_buffer: array [0 .. Pred(HEADER_SIZE + 1)] of char; // inbound_buffer: amqp_bytes_t; // inbound_offset: size_t; // target_size: size_t; // outbound_buffer: amqp_bytes_t; // socket: pamqp_socket_t; // sock_inbound_buffer: amqp_bytes_t; // sock_inbound_offset: size_t; // sock_inbound_limit: size_t; // first_queued_frame: pamqp_link_t; // last_queued_frame: pamqp_link_t; // most_recent_api_result: amqp_rpc_reply_t; // server_properties: amqp_table_t; // client_properties: amqp_table_t; // properties_pool: amqp_pool_t; // end; {$ENDREGION} {$REGION 'amqp_framing.h'} const AMQP_PROTOCOL_VERSION_MAJOR = 0; (* *< AMQP protocol version major *) AMQP_PROTOCOL_VERSION_MINOR = 9; (* *< AMQP protocol version minor *) AMQP_PROTOCOL_VERSION_REVISION = 1; (* *< AMQP protocol version revision *) AMQP_PROTOCOL_PORT = 5672; (* *< Default AMQP Port *) AMQP_FRAME_METHOD = 1; (* *< Constant: FRAME-METHOD *) AMQP_FRAME_HEADER = 2; (* *< Constant: FRAME-HEADER *) AMQP_FRAME_BODY = 3; (* *< Constant: FRAME-BODY *) AMQP_FRAME_HEARTBEAT = 8; (* *< Constant: FRAME-HEARTBEAT *) AMQP_FRAME_MIN_SIZE = 4096; (* *< Constant: FRAME-MIN-SIZE *) AMQP_FRAME_END = 206; (* *< Constant: FRAME-END *) AMQP_REPLY_SUCCESS = 200; (* *< Constant: REPLY-SUCCESS *) AMQP_CONTENT_TOO_LARGE = 311; (* *< Constant: CONTENT-TOO-LARGE *) AMQP_NO_ROUTE = 312; (* *< Constant: NO-ROUTE *) AMQP_NO_CONSUMERS = 313; (* *< Constant: NO-CONSUMERS *) AMQP_ACCESS_REFUSED = 403; (* *< Constant: ACCESS-REFUSED *) AMQP_NOT_FOUND = 404; (* *< Constant: NOT-FOUND *) AMQP_RESOURCE_LOCKED = 405; (* *< Constant: RESOURCE-LOCKED *) AMQP_PRECONDITION_FAILED = 406; (* *< Constant: PRECONDITION-FAILED *) AMQP_CONNECTION_FORCED = 320; (* *< Constant: CONNECTION-FORCED *) AMQP_INVALID_PATH = 402; (* *< Constant: INVALID-PATH *) AMQP_FRAME_ERROR = 501; (* *< Constant: FRAME-ERROR *) AMQP_SYNTAX_ERROR = 502; (* *< Constant: SYNTAX-ERROR *) AMQP_COMMAND_INVALID = 503; (* *< Constant: COMMAND-INVALID *) AMQP_CHANNEL_ERROR = 504; (* *< Constant: CHANNEL-ERROR *) AMQP_UNEXPECTED_FRAME = 505; (* *< Constant: UNEXPECTED-FRAME *) AMQP_RESOURCE_ERROR = 506; (* *< Constant: RESOURCE-ERROR *) AMQP_NOT_ALLOWED = 530; (* *< Constant: NOT-ALLOWED *) AMQP_NOT_IMPLEMENTED = 540; (* *< Constant: NOT-IMPLEMENTED *) AMQP_INTERNAL_ERROR = 541; (* *< Constant: INTERNAL-ERROR *) (* Function prototypes. *) (* * * Get constant name string from constant * * @param [in] constantNumber constant to get the name of * @returns string describing the constant. String is managed by * the library and should not be free()'d by the program *) function amqp_constant_name(constantNumber: integer): PAnsiChar; cdecl; (* * * Checks to see if a constant is a hard error * * A hard error occurs when something severe enough * happens that the connection must be closed. * * @param [in] constantNumber the error constant * @returns true if its a hard error, false otherwise *) function amqp_constant_is_hard_error(constantNumber: integer): amqp_boolean_t; cdecl; (* * * Get method name string from method number * * @param [in] methodNumber the method number * @returns method name string. String is managed by the library * and should not be freed()'d by the program *) function amqp_method_name(methodNumber: amqp_method_number_t): PAnsiChar; cdecl; (* * * Check whether a method has content * * A method that has content will receive the method frame * a properties frame, then 1 to N body frames * * @param [in] methodNumber the method number * @returns true if method has content, false otherwise *) function amqp_method_has_content(methodNumber: amqp_method_number_t): amqp_boolean_t; cdecl; (* * * Decodes a method from AMQP wireformat * * @param [in] methodNumber the method number for the decoded parameter * @param [in] pool the memory pool to allocate the decoded method from * @param [in] encoded the encoded byte string buffer * @param [out] decoded pointer to the decoded method struct * @returns 0 on success, an error code otherwise *) function amqp_decode_method(methodNumber: amqp_method_number_t; pool: pamqp_pool_t; encoded: amqp_bytes_t; var decoded: Pointer): integer; cdecl; (* * * Decodes a header frame properties structure from AMQP wireformat * * @param [in] class_id the class id for the decoded parameter * @param [in] pool the memory pool to allocate the decoded properties from * @param [in] encoded the encoded byte string buffer * @param [out] decoded pointer to the decoded properties struct * @returns 0 on success, an error code otherwise *) function amqp_decode_properties(class_id: UInt16; pool: pamqp_pool_t; encoded: amqp_bytes_t; var decoded: Pointer): integer; cdecl; (* * * Encodes a method structure in AMQP wireformat * * @param [in] methodNumber the method number for the decoded parameter * @param [in] decoded the method structure (e.g., amqp_connection_start_t) * @param [in] encoded an allocated byte buffer for the encoded method * structure to be written to. If the buffer isn't large enough * to hold the encoded method, an error code will be returned. * @returns 0 on success, an error code otherwise. *) function amqp_encode_method(methodNumber: amqp_method_number_t; decoded: pinteger; encoded: amqp_bytes_t): integer; cdecl; (* * * Encodes a properties structure in AMQP wireformat * * @param [in] class_id the class id for the decoded parameter * @param [in] decoded the properties structure (e.g., amqp_basic_properties_t) * @param [in] encoded an allocated byte buffer for the encoded properties to written to. * If the buffer isn't large enough to hold the encoded method, an * an error code will be returned * @returns 0 on success, an error code otherwise. *) function amqp_encode_properties(class_id: UInt16; decoded: Pointer; encoded: amqp_bytes_t): integer; cdecl; (* Method field records. *) const AMQP_CONNECTION_START_METHOD = $000A000A; (* *< connection.start method id @internal 10, 10; 655370 *) (* * connection.start method fields *) type amqp_connection_start_t_ = record version_major: UInt8; (* *< version-major *) version_minor: UInt8; (* *< version-minor *) server_properties: amqp_table_t; (* *< server-properties *) mechanisms: amqp_bytes_t; (* *< mechanisms *) locales: amqp_bytes_t; (* *< locales *) end; amqp_connection_start_t = amqp_connection_start_t_; pamqp_connection_start_t = ^amqp_connection_start_t; const AMQP_CONNECTION_START_OK_METHOD = $000A000B; (* *< connection.start-ok method id @internal 10, 11; 655371 *) (* * connection.start-ok method fields *) type amqp_connection_start_ok_t_ = record client_properties: amqp_table_t; (* *< client-properties *) mechanism: amqp_bytes_t; (* *< mechanism *) response: amqp_bytes_t; (* *< response *) locale: amqp_bytes_t; (* *< locale *) end; amqp_connection_start_ok_t = amqp_connection_start_ok_t_; pamqp_connection_start_ok_t = ^amqp_connection_start_ok_t; const AMQP_CONNECTION_SECURE_METHOD = $000A0014; (* *< connection.secure method id @internal 10, 20; 655380 *) (* * connection.secure method fields *) type amqp_connection_secure_t_ = record challenge: amqp_bytes_t; (* *< challenge *) end; amqp_connection_secure_t = amqp_connection_secure_t_; pamqp_connection_secure_t = ^amqp_connection_secure_t; const AMQP_CONNECTION_SECURE_OK_METHOD = $000A0015; (* *< connection.secure-ok method id @internal 10, 21; 655381 *) (* * connection.secure-ok method fields *) type amqp_connection_secure_ok_t_ = record response: amqp_bytes_t; (* *< response *) end; amqp_connection_secure_ok_t = amqp_connection_secure_ok_t_; pamqp_connection_secure_ok_t = ^amqp_connection_secure_ok_t; const AMQP_CONNECTION_TUNE_METHOD = $000A001E; (* *< connection.tune method id @internal 10, 30; 655390 *) (* * connection.tune method fields *) type amqp_connection_tune_t_ = record channel_max: UInt16; (* *< channel-max *) frame_max: UInt32; (* *< frame-max *) heartbeat: UInt16; (* *< heartbeat *) end; amqp_connection_tune_t = amqp_connection_tune_t_; pamqp_connection_tune_t = ^amqp_connection_tune_t; const AMQP_CONNECTION_TUNE_OK_METHOD = $000A001F; (* *< connection.tune-ok method id @internal 10, 31; 655391 *) (* * connection.tune-ok method fields *) type amqp_connection_tune_ok_t_ = record channel_max: UInt16; (* *< channel-max *) frame_max: UInt32; (* *< frame-max *) heartbeat: UInt16; (* *< heartbeat *) end; amqp_connection_tune_ok_t = amqp_connection_tune_ok_t_; pamqp_connection_tune_ok_t = ^amqp_connection_tune_ok_t; const AMQP_CONNECTION_OPEN_METHOD = $000A0028; (* *< connection.open method id @internal 10, 40; 655400 *) (* * connection.open method fields *) type amqp_connection_open_t_ = record virtual_host: amqp_bytes_t; (* *< virtual-host *) capabilities: amqp_bytes_t; (* *< capabilities *) insist: amqp_boolean_t; (* *< insist *) end; amqp_connection_open_t = amqp_connection_open_t_; pamqp_connection_open_t = ^amqp_connection_open_t; const AMQP_CONNECTION_OPEN_OK_METHOD = $000A0029; (* *< connection.open-ok method id @internal 10, 41; 655401 *) (* * connection.open-ok method fields *) type amqp_connection_open_ok_t_ = record known_hosts: amqp_bytes_t; (* *< known-hosts *) end; amqp_connection_open_ok_t = amqp_connection_open_ok_t_; pamqp_connection_open_ok_t = ^amqp_connection_open_ok_t; const AMQP_CONNECTION_CLOSE_METHOD = $000A0032; (* *< connection.close method id @internal 10, 50; 655410 *) (* * connection.close method fields *) type amqp_connection_close_t_ = record reply_code: UInt16; (* *< reply-code *) reply_text: amqp_bytes_t; (* *< reply-text *) class_id: UInt16; (* *< class-id *) method_id: UInt16; (* *< method-id *) end; amqp_connection_close_t = amqp_connection_close_t_; pamqp_connection_close_t = ^amqp_connection_close_t; const AMQP_CONNECTION_CLOSE_OK_METHOD = $000A0033; (* *< connection.close-ok method id @internal 10, 51; 655411 *) (* * connection.close-ok method fields *) type amqp_connection_close_ok_t_ = record dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_connection_close_ok_t = amqp_connection_close_ok_t_; pamqp_connection_close_ok_t = ^amqp_connection_close_ok_t; const AMQP_CONNECTION_BLOCKED_METHOD = $000A003C; (* *< connection.blocked method id @internal 10, 60; 655420 *) (* * connection.blocked method fields *) type amqp_connection_blocked_t_ = record reason: amqp_bytes_t; (* *< reason *) end; amqp_connection_blocked_t = amqp_connection_blocked_t_; pamqp_connection_blocked_t = ^amqp_connection_blocked_t; const AMQP_CONNECTION_UNBLOCKED_METHOD = $000A003D; (* *< connection.unblocked method id @internal 10, 61; 655421 *) (* * connection.unblocked method fields *) type amqp_connection_unblocked_t_ = record dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_connection_unblocked_t = amqp_connection_unblocked_t_; pamqp_connection_unblocked_t = ^amqp_connection_unblocked_t; const AMQP_CHANNEL_OPEN_METHOD = $0014000A; (* *< channel.open method id @internal 20, 10; 1310730 *) (* * channel.open method fields *) type amqp_channel_open_t_ = record out_of_band: amqp_bytes_t; (* *< out-of-band *) end; amqp_channel_open_t = amqp_channel_open_t_; pamqp_channel_open_t = ^amqp_channel_open_t; const AMQP_CHANNEL_OPEN_OK_METHOD = $0014000B; (* *< channel.open-ok method id @internal 20, 11; 1310731 *) (* * channel.open-ok method fields *) type amqp_channel_open_ok_t_ = record channel_id: amqp_bytes_t; (* *< channel-id *) end; amqp_channel_open_ok_t = amqp_channel_open_ok_t_; pamqp_channel_open_ok_t = ^amqp_channel_open_ok_t_; const AMQP_CHANNEL_FLOW_METHOD = $00140014; (* *< channel.flow method id @internal 20, 20; 1310740 *) (* * channel.flow method fields *) type amqp_channel_flow_t_ = record active: amqp_boolean_t; (* *< active *) end; amqp_channel_flow_t = amqp_channel_flow_t_; pamqp_channel_flow_t = ^amqp_channel_flow_t; const AMQP_CHANNEL_FLOW_OK_METHOD = $00140015; (* *< channel.flow-ok method id @internal 20, 21; 1310741 *) (* * channel.flow-ok method fields *) type amqp_channel_flow_ok_t_ = record active: amqp_boolean_t; (* *< active *) end; amqp_channel_flow_ok_t = amqp_channel_flow_ok_t_; pamqp_channel_flow_ok_t = ^amqp_channel_flow_ok_t; const AMQP_CHANNEL_CLOSE_METHOD = $00140028; (* *< channel.close method id @internal 20, 40; 1310760 *) (* * channel.close method fields *) type amqp_channel_close_t_ = record reply_code: UInt16; (* *< reply-code *) reply_text: amqp_bytes_t; (* *< reply-text *) class_id: UInt16; (* *< class-id *) method_id: UInt16; (* *< method-id *) end; amqp_channel_close_t = amqp_channel_close_t_; pamqp_channel_close_t = ^amqp_channel_close_t; const AMQP_CHANNEL_CLOSE_OK_METHOD = $00140029; (* *< channel.close-ok method id @internal 20, 41; 1310761 *) (* * channel.close-ok method fields *) type amqp_channel_close_ok_t_ = record dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_channel_close_ok_t = amqp_channel_close_ok_t_; pamqp_channel_close_ok_t = ^amqp_channel_close_ok_t; const AMQP_ACCESS_REQUEST_METHOD = $001E000A; (* *< access.request method id @internal 30, 10; 1966090 *) (* * access.request method fields *) type amqp_access_request_t_ = record realm: amqp_bytes_t; (* *< realm *) exclusive: amqp_boolean_t; (* *< exclusive *) passive: amqp_boolean_t; (* *< passive *) active: amqp_boolean_t; (* *< active *) write: amqp_boolean_t; (* *< write *) read: amqp_boolean_t; (* *< read *) end; amqp_access_request_t = amqp_access_request_t_; pamqp_access_request_t = ^amqp_access_request_t; const AMQP_ACCESS_REQUEST_OK_METHOD = $001E000B; (* *< access.request-ok method id @internal 30, 11; 1966091 *) (* * access.request-ok method fields *) type amqp_access_request_ok_t_ = record ticket: UInt16; (* *< ticket *) end; amqp_access_request_ok_t = amqp_access_request_ok_t_; pamqp_access_request_ok_t = ^amqp_access_request_ok_t; const AMQP_EXCHANGE_DECLARE_METHOD = $0028000A; (* *< exchange.declare method id @internal 40, 10; 2621450 *) (* * exchange.declare method fields *) type amqp_exchange_declare_t_ = record ticket: UInt16; (* *< ticket *) exchange: amqp_bytes_t; (* *< exchange *) &type: amqp_bytes_t; (* *< type *) passive: amqp_boolean_t; (* *< passive *) durable: amqp_boolean_t; (* *< durable *) auto_delete: amqp_boolean_t; (* *< auto-delete *) internal: amqp_boolean_t; (* *< internal *) nowait: amqp_boolean_t; (* *< nowait *) arguments: amqp_table_t; (* *< arguments *) end; amqp_exchange_declare_t = amqp_exchange_declare_t_; pamqp_exchange_declare_t = ^amqp_exchange_declare_t; const AMQP_EXCHANGE_DECLARE_OK_METHOD = $0028000B; (* *< exchange.declare-ok method id @internal 40, 11; 2621451 *) (* * exchange.declare-ok method fields *) type amqp_exchange_declare_ok_t_ = record dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_exchange_declare_ok_t = amqp_exchange_declare_ok_t_; pamqp_exchange_declare_ok_t = ^amqp_exchange_declare_ok_t; const AMQP_EXCHANGE_DELETE_METHOD = $00280014; (* *< exchange.delete method id @internal 40, 20; 2621460 *) (* * exchange.delete method fields *) type amqp_exchange_delete_t_ = record ticket: UInt16; (* *< ticket *) exchange: amqp_bytes_t; (* *< exchange *) if_unused: amqp_boolean_t; (* *< if-unused *) nowait: amqp_boolean_t; (* *< nowait *) end; amqp_exchange_delete_t = amqp_exchange_delete_t_; pamqp_exchange_delete_t = ^amqp_exchange_delete_t; const AMQP_EXCHANGE_DELETE_OK_METHOD = $00280015; (* *< exchange.delete-ok method id @internal 40, 21; 2621461 *) (* * exchange.delete-ok method fields *) type amqp_exchange_delete_ok_t_ = record dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_exchange_delete_ok_t = amqp_exchange_delete_ok_t_; pamqp_exchange_delete_ok_t = ^amqp_exchange_delete_ok_t; const AMQP_EXCHANGE_BIND_METHOD = $0028001E; (* *< exchange.bind method id @internal 40, 30; 2621470 *) (* * exchange.bind method fields *) type amqp_exchange_bind_t_ = record ticket: UInt16; (* *< ticket *) destination: amqp_bytes_t; (* *< destination *) source: amqp_bytes_t; (* *< source *) routing_key: amqp_bytes_t; (* *< routing-key *) nowait: amqp_boolean_t; (* *< nowait *) arguments: amqp_table_t; (* *< arguments *) end; amqp_exchange_bind_t = amqp_exchange_bind_t_; pamqp_exchange_bind_t = ^amqp_exchange_bind_t; const AMQP_EXCHANGE_BIND_OK_METHOD = $0028001F; (* *< exchange.bind-ok method id @internal 40, 31; 2621471 *) (* * exchange.bind-ok method fields *) type amqp_exchange_bind_ok_t_ = record dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_exchange_bind_ok_t = amqp_exchange_bind_ok_t_; pamqp_exchange_bind_ok_t = ^amqp_exchange_bind_ok_t; const AMQP_EXCHANGE_UNBIND_METHOD = $00280028; (* *< exchange.unbind method id @internal 40, 40; 2621480 *) (* * exchange.unbind method fields *) type amqp_exchange_unbind_t_ = record ticket: UInt16; (* *< ticket *) destination: amqp_bytes_t; (* *< destination *) source: amqp_bytes_t; (* *< source *) routing_key: amqp_bytes_t; (* *< routing-key *) nowait: amqp_boolean_t; (* *< nowait *) arguments: amqp_table_t; (* *< arguments *) end; amqp_exchange_unbind_t = amqp_exchange_unbind_t_; pamqp_exchange_unbind_t = ^amqp_exchange_unbind_t; const AMQP_EXCHANGE_UNBIND_OK_METHOD = $00280033; (* *< exchange.unbind-ok method id @internal 40, 51; 2621491 *) (* * exchange.unbind-ok method fields *) type amqp_exchange_unbind_ok_t_ = record dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_exchange_unbind_ok_t = amqp_exchange_unbind_ok_t_; pamqp_exchange_unbind_ok_t = ^amqp_exchange_unbind_ok_t; const AMQP_QUEUE_DECLARE_METHOD = $0032000A; (* *< queue.declare method id @internal 50, 10; 3276810 *) (* * queue.declare method fields *) type amqp_queue_declare_t_ = record ticket: UInt16; (* *< ticket *) queue: amqp_bytes_t; (* *< queue *) passive: amqp_boolean_t; (* *< passive *) durable: amqp_boolean_t; (* *< durable *) exclusive: amqp_boolean_t; (* *< exclusive *) auto_delete: amqp_boolean_t; (* *< auto-delete *) nowait: amqp_boolean_t; (* *< nowait *) arguments: amqp_table_t; (* *< arguments *) end; amqp_queue_declare_t = amqp_queue_declare_t_; pamqp_queue_declare_t = ^amqp_queue_declare_t; const AMQP_QUEUE_DECLARE_OK_METHOD = $0032000B; (* *< queue.declare-ok method id @internal 50, 11; 3276811 *) (* * queue.declare-ok method fields *) type amqp_queue_declare_ok_t_ = record queue: amqp_bytes_t; (* *< queue *) message_count: UInt32; (* *< message-count *) consumer_count: UInt32; (* *< consumer-count *) end; amqp_queue_declare_ok_t = amqp_queue_declare_ok_t_; pamqp_queue_declare_ok_t = ^amqp_queue_declare_ok_t; const AMQP_QUEUE_BIND_METHOD = $00320014; (* *< queue.bind method id @internal 50, 20; 3276820 *) (* * queue.bind method fields *) type amqp_queue_bind_t_ = record ticket: UInt16; (* *< ticket *) queue: amqp_bytes_t; (* *< queue *) exchange: amqp_bytes_t; (* *< exchange *) routing_key: amqp_bytes_t; (* *< routing-key *) nowait: amqp_boolean_t; (* *< nowait *) arguments: amqp_table_t; (* *< arguments *) end; amqp_queue_bind_t = amqp_queue_bind_t_; pamqp_queue_bind_t = ^amqp_queue_bind_t; const AMQP_QUEUE_BIND_OK_METHOD = $00320015; (* *< queue.bind-ok method id @internal 50, 21; 3276821 *) (* * queue.bind-ok method fields *) type amqp_queue_bind_ok_t_ = record dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_queue_bind_ok_t = amqp_queue_bind_ok_t_; pamqp_queue_bind_ok_t = ^amqp_queue_bind_ok_t; const AMQP_QUEUE_PURGE_METHOD = $0032001E; (* *< queue.purge method id @internal 50, 30; 3276830 *) (* * queue.purge method fields *) type amqp_queue_purge_t_ = record ticket: UInt16; (* *< ticket *) queue: amqp_bytes_t; (* *< queue *) nowait: amqp_boolean_t; (* *< nowait *) end; amqp_queue_purge_t = amqp_queue_purge_t_; pamqp_queue_purge_t = ^amqp_queue_purge_t; const AMQP_QUEUE_PURGE_OK_METHOD = $0032001F; (* *< queue.purge-ok method id @internal 50, 31; 3276831 *) (* * queue.purge-ok method fields *) type amqp_queue_purge_ok_t_ = record message_count: UInt32; (* *< message-count *) end; amqp_queue_purge_ok_t = amqp_queue_purge_ok_t_; pamqp_queue_purge_ok_t = ^amqp_queue_purge_ok_t; const AMQP_QUEUE_DELETE_METHOD = $00320028; (* *< queue.delete method id @internal 50, 40; 3276840 *) (* * queue.delete method fields *) type amqp_queue_delete_t_ = record ticket: UInt16; (* *< ticket *) queue: amqp_bytes_t; (* *< queue *) if_unused: amqp_boolean_t; (* *< if-unused *) if_empty: amqp_boolean_t; (* *< if-empty *) nowait: amqp_boolean_t; (* *< nowait *) end; amqp_queue_delete_t = amqp_queue_delete_t_; pamqp_queue_delete_t = ^amqp_queue_delete_t; const AMQP_QUEUE_DELETE_OK_METHOD = $00320029; (* *< queue.delete-ok method id @internal 50, 41; 3276841 *) (* * queue.delete-ok method fields *) type amqp_queue_delete_ok_t_ = record message_count: UInt32; (* *< message-count *) end; amqp_queue_delete_ok_t = amqp_queue_delete_ok_t_; pamqp_queue_delete_ok_t = ^amqp_queue_delete_ok_t; const AMQP_QUEUE_UNBIND_METHOD = $00320032; (* *< queue.unbind method id @internal 50, 50; 3276850 *) (* * queue.unbind method fields *) type amqp_queue_unbind_t_ = record ticket: UInt16; (* *< ticket *) queue: amqp_bytes_t; (* *< queue *) exchange: amqp_bytes_t; (* *< exchange *) routing_key: amqp_bytes_t; (* *< routing-key *) arguments: amqp_table_t; (* *< arguments *) end; amqp_queue_unbind_t = amqp_queue_unbind_t_; pamqp_queue_unbind_t = ^amqp_queue_unbind_t; const AMQP_QUEUE_UNBIND_OK_METHOD = $00320033; (* *< queue.unbind-ok method id @internal 50, 51; 3276851 *) (* * queue.unbind-ok method fields *) type amqp_queue_unbind_ok_t_ = record dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_queue_unbind_ok_t = amqp_queue_unbind_ok_t_; pamqp_queue_unbind_ok_t = ^amqp_queue_unbind_ok_t; const AMQP_BASIC_QOS_METHOD = $003C000A; (* *< basic.qos method id @internal 60, 10; 3932170 *) (* * basic.qos method fields *) type amqp_basic_qos_t_ = record prefetch_size: UInt32; (* *< prefetch-size *) prefetch_count: UInt16; (* *< prefetch-count *) global: amqp_boolean_t; (* *< global *) end; amqp_basic_qos_t = amqp_basic_qos_t_; pamqp_basic_qos_t = ^amqp_basic_qos_t; const AMQP_BASIC_QOS_OK_METHOD = $003C000B; (* *< basic.qos-ok method id @internal 60, 11; 3932171 *) (* * basic.qos-ok method fields *) type amqp_basic_qos_ok_t_ = record dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_basic_qos_ok_t = amqp_basic_qos_ok_t_; pamqp_basic_qos_ok_t = ^amqp_basic_qos_ok_t; const AMQP_BASIC_CONSUME_METHOD = $003C0014; (* *< basic.consume method id @internal 60, 20; 3932180 *) (* * basic.consume method fields *) type amqp_basic_consume_t_ = record ticket: UInt16; (* *< ticket *) queue: amqp_bytes_t; (* *< queue *) consumer_tag: amqp_bytes_t; (* *< consumer-tag *) no_local: amqp_boolean_t; (* *< no-local *) no_ack: amqp_boolean_t; (* *< no-ack *) exclusive: amqp_boolean_t; (* *< exclusive *) nowait: amqp_boolean_t; (* *< nowait *) arguments: amqp_table_t; (* *< arguments *) end; amqp_basic_consume_t = amqp_basic_consume_t_; pamqp_basic_consume_t = ^amqp_basic_consume_t; const AMQP_BASIC_CONSUME_OK_METHOD = $003C0015; (* *< basic.consume-ok method id @internal 60, 21; 3932181 *) (* * basic.consume-ok method fields *) type amqp_basic_consume_ok_t_ = record consumer_tag: amqp_bytes_t; (* *< consumer-tag *) end; amqp_basic_consume_ok_t = amqp_basic_consume_ok_t_; pamqp_basic_consume_ok_t = ^amqp_basic_consume_ok_t; const AMQP_BASIC_CANCEL_METHOD = $003C001E; (* *< basic.cancel method id @internal 60, 30; 3932190 *) (* * basic.cancel method fields *) type amqp_basic_cancel_t_ = record consumer_tag: amqp_bytes_t; (* *< consumer-tag *) nowait: amqp_boolean_t; (* *< nowait *) end; amqp_basic_cancel_t = amqp_basic_cancel_t_; pamqp_basic_cancel_t = ^amqp_basic_cancel_t; const AMQP_BASIC_CANCEL_OK_METHOD = $003C001F; (* *< basic.cancel-ok method id @internal 60, 31; 3932191 *) (* * basic.cancel-ok method fields *) type amqp_basic_cancel_ok_t_ = record consumer_tag: amqp_bytes_t; (* *< consumer-tag *) end; amqp_basic_cancel_ok_t = amqp_basic_cancel_ok_t_; pamqp_basic_cancel_ok_t = ^amqp_basic_cancel_ok_t; const AMQP_BASIC_PUBLISH_METHOD = $003C0028; (* *< basic.publish method id @internal 60, 40; 3932200 *) (* * basic.publish method fields *) type amqp_basic_publish_t_ = record ticket: UInt16; (* *< ticket *) exchange: amqp_bytes_t; (* *< exchange *) routing_key: amqp_bytes_t; (* *< routing-key *) mandatory: amqp_boolean_t; (* *< mandatory *) immediate: amqp_boolean_t; (* *< immediate *) end; amqp_basic_publish_t = amqp_basic_publish_t_; pamqp_basic_publish_t = ^amqp_basic_publish_t; const AMQP_BASIC_RETURN_METHOD = $003C0032; (* *< basic.return method id @internal 60, 50; 3932210 *) (* * basic.return method fields *) type amqp_basic_return_t_ = record reply_code: UInt16; (* *< reply-code *) reply_text: amqp_bytes_t; (* *< reply-text *) exchange: amqp_bytes_t; (* *< exchange *) routing_key: amqp_bytes_t; (* *< routing-key *) end; amqp_basic_return_t = amqp_basic_return_t_; pamqp_basic_return_t = ^amqp_basic_return_t; const AMQP_BASIC_DELIVER_METHOD = $003C003C; (* *< basic.deliver method id @internal 60, 60; 3932220 *) (* * basic.deliver method fields *) type amqp_basic_deliver_t_ = record consumer_tag: amqp_bytes_t; (* *< consumer-tag *) delivery_tag: UInt64; (* *< delivery-tag *) redelivered: amqp_boolean_t; (* *< redelivered *) exchange: amqp_bytes_t; (* *< exchange *) routing_key: amqp_bytes_t; (* *< routing-key *) end; amqp_basic_deliver_t = amqp_basic_deliver_t_; pamqp_basic_deliver_t = ^amqp_basic_deliver_t; const AMQP_BASIC_GET_METHOD = $003C0046; (* *< basic.get method id @internal 60, 70; 3932230 *) (* * basic.get method fields *) type amqp_basic_get_t_ = record ticket: UInt16; (* *< ticket *) queue: amqp_bytes_t; (* *< queue *) no_ack: amqp_boolean_t; (* *< no-ack *) end; amqp_basic_get_t = amqp_basic_get_t_; pamqp_basic_get_t = ^amqp_basic_get_t; const AMQP_BASIC_GET_OK_METHOD = $003C0047; (* *< basic.get-ok method id @internal 60, 71; 3932231 *) (* * basic.get-ok method fields *) type amqp_basic_get_ok_t_ = record delivery_tag: UInt64; (* *< delivery-tag *) redelivered: amqp_boolean_t; (* *< redelivered *) exchange: amqp_bytes_t; (* *< exchange *) routing_key: amqp_bytes_t; (* *< routing-key *) message_count: UInt32; (* *< message-count *) end; amqp_basic_get_ok_t = amqp_basic_get_ok_t_; pamqp_basic_get_ok_t = ^amqp_basic_get_ok_t; const AMQP_BASIC_GET_EMPTY_METHOD = $003C0048; (* *< basic.get-empty method id @internal 60, 72; 3932232 *) (* * basic.get-empty method fields *) type amqp_basic_get_empty_t_ = record cluster_id: amqp_bytes_t; (* *< cluster-id *) end; amqp_basic_get_empty_t = amqp_basic_get_empty_t_; pamqp_basic_get_empty_t = ^amqp_basic_get_empty_t; const AMQP_BASIC_ACK_METHOD = $003C0050; (* *< basic.ack method id @internal 60, 80; 3932240 *) (* * basic.ack method fields *) type amqp_basic_ack_t_ = record delivery_tag: UInt64; (* *< delivery-tag *) multiple: amqp_boolean_t; (* *< multiple *) end; amqp_basic_ack_t = amqp_basic_ack_t_; pamqp_basic_ack_t = ^amqp_basic_ack_t; const AMQP_BASIC_REJECT_METHOD = $003C005A; (* *< basic.reject method id @internal 60, 90; 3932250 *) (* * basic.reject method fields *) type amqp_basic_reject_t_ = record delivery_tag: UInt64; (* *< delivery-tag *) requeue: amqp_boolean_t; (* *< requeue *) end; amqp_basic_reject_t = amqp_basic_reject_t_; pamqp_basic_reject_t = ^amqp_basic_reject_t; const AMQP_BASIC_RECOVER_ASYNC_METHOD = $003C0064; (* *< basic.recover-async method id @internal 60, 100; 3932260 *) (* * basic.recover-async method fields *) type amqp_basic_recover_async_t_ = record requeue: amqp_boolean_t; (* *< requeue *) end; amqp_basic_recover_async_t = amqp_basic_recover_async_t_; pamqp_basic_recover_async_t = ^amqp_basic_recover_async_t; const AMQP_BASIC_RECOVER_METHOD = $003C006E; (* *< basic.recover method id @internal 60, 110; 3932270 *) (* * basic.recover method fields *) type amqp_basic_recover_t_ = record requeue: amqp_boolean_t; (* *< requeue *) end; amqp_basic_recover_t = amqp_basic_recover_t_; pamqp_basic_recover_t = ^amqp_basic_recover_t; const AMQP_BASIC_RECOVER_OK_METHOD = $003C006F; (* *< basic.recover-ok method id @internal 60, 111; 3932271 *) (* * basic.recover-ok method fields *) type amqp_basic_recover_ok_t_ = record dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_basic_recover_ok_t = amqp_basic_recover_ok_t_; pamqp_basic_recover_ok_t = ^amqp_basic_recover_ok_t; const AMQP_BASIC_NACK_METHOD = $003C0078; (* *< basic.nack method id @internal 60, 120; 3932280 *) (* * basic.nack method fields *) type amqp_basic_nack_t_ = record delivery_tag: UInt64; (* *< delivery-tag *) multiple: amqp_boolean_t; (* *< multiple *) requeue: amqp_boolean_t; (* *< requeue *) end; amqp_basic_nack_t = amqp_basic_nack_t_; pamqp_basic_nack_t = ^amqp_basic_nack_t; const AMQP_TX_SELECT_METHOD = $005A000A; (* *< tx.select method id @internal 90, 10; 5898250 *) (* * tx.select method fields *) type amqp_tx_select_t_ = record dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_tx_select_t = amqp_tx_select_t_; pamqp_tx_select_t = ^amqp_tx_select_t; const AMQP_TX_SELECT_OK_METHOD = $005A000B; (* *< tx.select-ok method id @internal 90, 11; 5898251 *) (* * tx.select-ok method fields *) type amqp_tx_select_ok_t_ = record dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_tx_select_ok_t = amqp_tx_select_ok_t_; pamqp_tx_select_ok_t = ^amqp_tx_select_ok_t; const AMQP_TX_COMMIT_METHOD = $005A0014; (* *< tx.commit method id @internal 90, 20; 5898260 *) (* * tx.commit method fields *) type amqp_tx_commit_t_ = record dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_tx_commit_t = amqp_tx_commit_t_; pamqp_tx_commit_t = ^amqp_tx_commit_t; const AMQP_TX_COMMIT_OK_METHOD = $005A0015; (* *< tx.commit-ok method id @internal 90, 21; 5898261 *) (* * tx.commit-ok method fields *) type amqp_tx_commit_ok_t_ = record dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_tx_commit_ok_t = amqp_tx_commit_ok_t_; pamqp_tx_commit_ok_t = ^amqp_tx_commit_ok_t; const AMQP_TX_ROLLBACK_METHOD = $005A001E; (* *< tx.rollback method id @internal 90, 30; 5898270 *) (* * tx.rollback method fields *) type amqp_tx_rollback_t_ = record dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_tx_rollback_t = amqp_tx_rollback_t_; pamqp_tx_rollback_t = ^amqp_tx_rollback_t; const AMQP_TX_ROLLBACK_OK_METHOD = $005A001F; (* *< tx.rollback-ok method id @internal 90, 31; 5898271 *) (* * tx.rollback-ok method fields *) type amqp_tx_rollback_ok_t_ = record dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_tx_rollback_ok_t = amqp_tx_rollback_ok_t_; pamqp_tx_rollback_ok_t = ^amqp_tx_rollback_ok_t; const AMQP_CONFIRM_SELECT_METHOD = $0055000A; (* *< confirm.select method id @internal 85, 10; 5570570 *) (* * confirm.select method fields *) type amqp_confirm_select_t_ = record nowait: amqp_boolean_t; (* *< nowait *) end; amqp_confirm_select_t = amqp_confirm_select_t_; pamqp_confirm_select_t = ^amqp_confirm_select_t; const AMQP_CONFIRM_SELECT_OK_METHOD = $0055000B; (* *< confirm.select-ok method id @internal 85, 11; 5570571 *) (* * confirm.select-ok method fields *) type amqp_confirm_select_ok_t_ = record dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_confirm_select_ok_t = amqp_confirm_select_ok_t_; pamqp_confirm_select_ok_t = ^amqp_confirm_select_ok_t; (* Class property records. *) const AMQP_CONNECTION_CLASS = ($000A); (* *< connection class id @internal 10 *) (* * connection class properties *) type amqp_connection_properties_t_ = record _flags: amqp_flags_t; (* *< bit-mask of set fields *) dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_connection_properties_t = amqp_connection_properties_t_; pamqp_connection_properties_t = ^amqp_connection_properties_t; const AMQP_CHANNEL_CLASS = ($0014); (* *< channel class id @internal 20 *) (* * channel class properties *) type amqp_channel_properties_t_ = record _flags: amqp_flags_t; (* *< bit-mask of set fields *) dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_channel_properties_t = amqp_channel_properties_t_; pamqp_channel_properties_t = ^amqp_channel_properties_t; const AMQP_ACCESS_CLASS = ($001E); (* *< access class id @internal 30 *) (* * access class properties *) type amqp_access_properties_t_ = record _flags: amqp_flags_t; (* *< bit-mask of set fields *) dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_access_properties_t = amqp_access_properties_t_; pamqp_access_properties_t = ^amqp_access_properties_t; const AMQP_EXCHANGE_CLASS = ($0028); (* *< exchange class id @internal 40 *) (* * exchange class properties *) type amqp_exchange_properties_t_ = record _flags: amqp_flags_t; (* *< bit-mask of set fields *) dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_exchange_properties_t = amqp_exchange_properties_t_; pamqp_exchange_properties_t = ^amqp_exchange_properties_t; const AMQP_QUEUE_CLASS = ($0032); (* *< queue class id @internal 50 *) (* * queue class properties *) type amqp_queue_properties_t_ = record _flags: amqp_flags_t; (* *< bit-mask of set fields *) dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_queue_properties_t = amqp_queue_properties_t_; pamqp_queue_properties_t = ^amqp_queue_properties_t; const AMQP_BASIC_CLASS = ($003C); (* *< basic class id @internal 60 *) AMQP_BASIC_CONTENT_TYPE_FLAG = (1 shl 15); (* *< basic.content-type property flag *) AMQP_BASIC_CONTENT_ENCODING_FLAG = (1 shl 14); (* *< basic.content-encoding property flag *) AMQP_BASIC_HEADERS_FLAG = (1 shl 13); (* *< basic.headers property flag *) AMQP_BASIC_DELIVERY_MODE_FLAG = (1 shl 12); (* *< basic.delivery-mode property flag *) AMQP_BASIC_PRIORITY_FLAG = (1 shl 11); (* *< basic.priority property flag *) AMQP_BASIC_CORRELATION_ID_FLAG = (1 shl 10); (* *< basic.correlation-id property flag *) AMQP_BASIC_REPLY_TO_FLAG = (1 shl 9); (* *< basic.reply-to property flag *) AMQP_BASIC_EXPIRATION_FLAG = (1 shl 8); (* *< basic.expiration property flag *) AMQP_BASIC_MESSAGE_ID_FLAG = (1 shl 7); (* *< basic.message-id property flag *) AMQP_BASIC_TIMESTAMP_FLAG = (1 shl 6); (* *< basic.timestamp property flag *) AMQP_BASIC_TYPE_FLAG = (1 shl 5); (* *< basic.type property flag *) AMQP_BASIC_USER_ID_FLAG = (1 shl 4); (* *< basic.user-id property flag *) AMQP_BASIC_APP_ID_FLAG = (1 shl 3); (* *< basic.app-id property flag *) AMQP_BASIC_CLUSTER_ID_FLAG = (1 shl 2); (* *< basic.cluster-id property flag *) (* * basic class properties *) type amqp_basic_properties_t_ = record _flags: amqp_flags_t; (* *< bit-mask of set fields *) content_type: amqp_bytes_t; (* *< content-type *) content_encoding: amqp_bytes_t; (* *< content-encoding *) headers: amqp_table_t; (* *< headers *) delivery_mode: UInt8; (* *< delivery-mode *) priority: UInt8; (* *< priority *) correlation_id: amqp_bytes_t; (* *< correlation-id *) reply_to: amqp_bytes_t; (* *< reply-to *) expiration: amqp_bytes_t; (* *< expiration *) message_id: amqp_bytes_t; (* *< message-id *) timestamp: UInt64; (* *< timestamp *) &type: amqp_bytes_t; (* *< type *) user_id: amqp_bytes_t; (* *< user-id *) app_id: amqp_bytes_t; (* *< app-id *) cluster_id: amqp_bytes_t; (* *< cluster-id *) end; amqp_basic_properties_t = amqp_basic_properties_t_; pamqp_basic_properties_t = ^amqp_basic_properties_t; pamqp_basic_properties_t_ = ^amqp_basic_properties_t_; const AMQP_TX_CLASS = ($005A); (* *< tx class id @internal 90 *) (* * tx class properties *) type amqp_tx_properties_t_ = record _flags: amqp_flags_t; (* *< bit-mask of set fields *) dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_tx_properties_t = amqp_tx_properties_t_; const AMQP_CONFIRM_CLASS = ($0055); (* *< confirm class id @internal 85 *) (* * confirm class properties *) type pamqp_confirm_properties_t_ = ^amqp_confirm_properties_t_; pamqp_confirm_properties_t = pamqp_confirm_properties_t_; amqp_confirm_properties_t_ = record _flags: amqp_flags_t; (* *< bit-mask of set fields *) dummy: char; (* *< Dummy field to avoid empty struct *) end; amqp_confirm_properties_t = amqp_confirm_properties_t_; (* API functions for methods *) (* * * amqp_channel_open * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @returns amqp_channel_open_ok_t *) function amqp_channel_open(state: amqp_connection_state_t; channel: amqp_channel_t): pamqp_channel_open_ok_t; cdecl; (* * * amqp_channel_flow * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @param [in] active active * @returns amqp_channel_flow_ok_t *) function amqp_channel_flow(state: amqp_connection_state_t; channel: amqp_channel_t; active: amqp_boolean_t): pamqp_channel_flow_ok_t; cdecl; (* * * amqp_exchange_declare * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @param [in] exchange exchange * @param [in] type type * @param [in] passive passive * @param [in] durable durable * @param [in] auto_delete auto_delete * @param [in] internal internal * @param [in] arguments arguments * @returns amqp_exchange_declare_ok_t *) function amqp_exchange_declare(state: amqp_connection_state_t; channel: amqp_channel_t; exchange: amqp_bytes_t; &type: amqp_bytes_t; passive: amqp_boolean_t; durable: amqp_boolean_t; auto_delete: amqp_boolean_t; internal: amqp_boolean_t; arguments: amqp_table_t): pamqp_exchange_declare_ok_t; cdecl; (* * * amqp_exchange_delete * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @param [in] exchange exchange * @param [in] if_unused if_unused * @returns amqp_exchange_delete_ok_t *) function amqp_exchange_delete(state: amqp_connection_state_t; channel: amqp_channel_t; exchange: amqp_bytes_t; if_unused: amqp_boolean_t): pamqp_exchange_delete_ok_t; cdecl; (* * * amqp_exchange_bind * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @param [in] destination destination * @param [in] source source * @param [in] routing_key routing_key * @param [in] arguments arguments * @returns amqp_exchange_bind_ok_t *) function amqp_exchange_bind(state: amqp_connection_state_t; channel: amqp_channel_t; destination: amqp_bytes_t; source: amqp_bytes_t; routing_key: amqp_bytes_t; arguments: amqp_table_t) : pamqp_exchange_bind_ok_t; cdecl; (* * * amqp_exchange_unbind * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @param [in] destination destination * @param [in] source source * @param [in] routing_key routing_key * @param [in] arguments arguments * @returns amqp_exchange_unbind_ok_t *) function amqp_exchange_unbind(state: amqp_connection_state_t; channel: amqp_channel_t; destination: amqp_bytes_t; source: amqp_bytes_t; routing_key: amqp_bytes_t; arguments: amqp_table_t) : pamqp_exchange_unbind_ok_t; cdecl; (* * * amqp_queue_declare * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @param [in] queue queue * @param [in] passive passive * @param [in] durable durable * @param [in] exclusive exclusive * @param [in] auto_delete auto_delete * @param [in] arguments arguments * @returns amqp_queue_declare_ok_t *) function amqp_queue_declare(state: amqp_connection_state_t; channel: amqp_channel_t; queue: amqp_bytes_t; passive: amqp_boolean_t; durable: amqp_boolean_t; exclusive: amqp_boolean_t; auto_delete: amqp_boolean_t; arguments: amqp_table_t): pamqp_queue_declare_ok_t; cdecl; (* * * amqp_queue_bind * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @param [in] queue queue * @param [in] exchange exchange * @param [in] routing_key routing_key * @param [in] arguments arguments * @returns amqp_queue_bind_ok_t *) function amqp_queue_bind(state: amqp_connection_state_t; channel: amqp_channel_t; queue: amqp_bytes_t; exchange: amqp_bytes_t; routing_key: amqp_bytes_t; arguments: amqp_table_t) : pamqp_queue_bind_ok_t; cdecl; (* * * amqp_queue_purge * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @param [in] queue queue * @returns amqp_queue_purge_ok_t *) function amqp_queue_purge(state: amqp_connection_state_t; channel: amqp_channel_t; queue: amqp_bytes_t): pamqp_queue_purge_ok_t; cdecl; (* * * amqp_queue_delete * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @param [in] queue queue * @param [in] if_unused if_unused * @param [in] if_empty if_empty * @returns amqp_queue_delete_ok_t *) function amqp_queue_delete(state: amqp_connection_state_t; channel: amqp_channel_t; queue: amqp_bytes_t; if_unused: amqp_boolean_t; if_empty: amqp_boolean_t): pamqp_queue_delete_ok_t; cdecl; (* * * amqp_queue_unbind * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @param [in] queue queue * @param [in] exchange exchange * @param [in] routing_key routing_key * @param [in] arguments arguments * @returns amqp_queue_unbind_ok_t *) function amqp_queue_unbind(state: amqp_connection_state_t; channel: amqp_channel_t; queue: amqp_bytes_t; exchange: amqp_bytes_t; routing_key: amqp_bytes_t; arguments: amqp_table_t) : pamqp_queue_unbind_ok_t; cdecl; (* * * amqp_basic_qos * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @param [in] prefetch_size prefetch_size * @param [in] prefetch_count prefetch_count * @param [in] global global * @returns amqp_basic_qos_ok_t *) function amqp_basic_qos(state: amqp_connection_state_t; channel: amqp_channel_t; prefetch_size: UInt32; prefetch_count: UInt16; global: amqp_boolean_t): pamqp_basic_qos_ok_t; cdecl; (* * * amqp_basic_consume * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @param [in] queue queue * @param [in] consumer_tag consumer_tag * @param [in] no_local no_local * @param [in] no_ack no_ack * @param [in] exclusive exclusive * @param [in] arguments arguments * @returns amqp_basic_consume_ok_t *) function amqp_basic_consume(state: amqp_connection_state_t; channel: amqp_channel_t; queue: amqp_bytes_t; consumer_tag: amqp_bytes_t; no_local: amqp_boolean_t; no_ack: amqp_boolean_t; exclusive: amqp_boolean_t; arguments: amqp_table_t): pamqp_basic_consume_ok_t; cdecl; (* * * amqp_basic_cancel * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @param [in] consumer_tag consumer_tag * @returns amqp_basic_cancel_ok_t *) function amqp_basic_cancel(state: amqp_connection_state_t; channel: amqp_channel_t; consumer_tag: amqp_bytes_t): pamqp_basic_cancel_ok_t; cdecl; (* * * amqp_basic_recover * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @param [in] requeue requeue * @returns amqp_basic_recover_ok_t *) function amqp_basic_recover(state: amqp_connection_state_t; channel: amqp_channel_t; requeue: amqp_boolean_t): pamqp_basic_recover_ok_t; cdecl; (* * * amqp_tx_select * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @returns amqp_tx_select_ok_t *) function amqp_tx_select(state: amqp_connection_state_t; channel: amqp_channel_t): pamqp_tx_select_ok_t; cdecl; (* * * amqp_tx_commit * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @returns amqp_tx_commit_ok_t *) function amqp_tx_commit(state: amqp_connection_state_t; channel: amqp_channel_t): pamqp_tx_commit_ok_t; cdecl; (* * * amqp_tx_rollback * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @returns amqp_tx_rollback_ok_t *) function amqp_tx_rollback(state: amqp_connection_state_t; channel: amqp_channel_t): pamqp_tx_rollback_ok_t; cdecl; (* * * amqp_confirm_select * * @param [in] state connection state * @param [in] channel the channel to do the RPC on * @returns amqp_confirm_select_ok_t *) function amqp_confirm_select(state: amqp_connection_state_t; channel: amqp_channel_t): pamqp_confirm_select_ok_t; cdecl; {$ENDREGION} {$REGION 'amqp.h'} const AMQP_VERSION_MAJOR = 0; AMQP_VERSION_MINOR = 8; AMQP_VERSION_PATCH = 1; AMQP_VERSION_IS_RELEASE = 0; (* * * Returns the rabbitmq-c version as a packed integer. * * See \ref AMQP_VERSION * * \return packed 32-bit integer representing version of library at runtime * * \sa AMQP_VERSION, amqp_version() * * \since v0.4.0 *) function amqp_version_number: UInt32; cdecl; (* * * Returns the rabbitmq-c version as a string. * * See \ref AMQP_VERSION_STRING * * \return a statically allocated string describing the version of rabbitmq-c. * * \sa amqp_version_number(), AMQP_VERSION_STRING, AMQP_VERSION * * \since v0.1 *) function amqp_version: PAnsiChar; cdecl; (* * * \def AMQP_DEFAULT_FRAME_SIZE * * Default frame size (128Kb) * * \sa amqp_login(), amqp_login_with_properties() * * \since v0.4.0 *) const AMQP_DEFAULT_FRAME_SIZE = 131072; (* * * \def AMQP_DEFAULT_MAX_CHANNELS * * Default maximum number of channels (0, no limit) * * \sa amqp_login(), amqp_login_with_properties() * * \since v0.4.0 *) AMQP_DEFAULT_MAX_CHANNELS = 0; (* * * \def AMQP_DEFAULT_HEARTBEAT * * Default heartbeat interval (0, heartbeat disabled) * * \sa amqp_login(), amqp_login_with_properties() * * \since v0.4.0 *) AMQP_DEFAULT_HEARTBEAT = 0; (* * * boolean type 0 = false, true otherwise * * \since v0.1 *) type (* 0-9 0-9-1 Qpid/Rabbit Type Remarks --------------------------------------------------------------------------- t t Boolean b b Signed 8-bit B Unsigned 8-bit U s Signed 16-bit (A1) u Unsigned 16-bit I I I Signed 32-bit i Unsigned 32-bit L l Signed 64-bit (B) l Unsigned 64-bit f f 32-bit float d d 64-bit float D D D Decimal s Short string (A2) S S S Long string A Nested Array T T T Timestamp (u64) F F F Nested Table V V V Void x Byte array Remarks: A1, A2: Notice how the types **CONFLICT** here. In Qpid and Rabbit, 's' means a signed 16-bit integer; in 0-9-1, it means a short string. B: Notice how the signednesses **CONFLICT** here. In Qpid and Rabbit, 'l' means a signed 64-bit integer; in 0-9-1, it means an unsigned 64-bit integer. I'm going with the Qpid/Rabbit types, where there's a conflict, and the 0-9-1 types otherwise. 0-8 is a subset of 0-9, which is a subset of the other two, so this will work for both 0-8 and 0-9-1 branches of the code. *) (* * * Field value types * * \since v0.1 *) amqp_field_value_kind_t = (AMQP_FIELD_KIND_BOOLEAN = Ord('t'), (* < boolean type. 0 = false, 1 = true @see amqp_boolean_t *) AMQP_FIELD_KIND_I8 = Ord('b'), (* < 8-bit signed integer, datatype: int8_t *) AMQP_FIELD_KIND_U8 = Ord('B'), (* < 8-bit unsigned integer, datatype: uint8_t *) AMQP_FIELD_KIND_I16 = Ord('s'), (* < 16-bit signed integer, datatype: int16_t *) AMQP_FIELD_KIND_U16 = Ord('u'), (* < 16-bit unsigned integer, datatype: uint16_t *) AMQP_FIELD_KIND_I32 = Ord('I'), (* < 32-bit signed integer, datatype: int32_t *) AMQP_FIELD_KIND_U32 = Ord('i'), (* < 32-bit unsigned integer, datatype: uint32_t *) AMQP_FIELD_KIND_I64 = Ord('l'), (* < 64-bit signed integer, datatype: int64_t *) AMQP_FIELD_KIND_U64 = Ord('L'), (* < 64-bit unsigned integer, datatype: UInt64 *) AMQP_FIELD_KIND_F32 = Ord('f'), (* < single-precision floating point value, datatype: float *) AMQP_FIELD_KIND_F64 = Ord('d'), (* < double-precision floating point value, datatype: double *) AMQP_FIELD_KIND_DECIMAL = Ord('D'), (* < amqp-decimal value, datatype: amqp_decimal_t *) AMQP_FIELD_KIND_UTF8 = Ord('S'), (* < UTF-8 null-terminated character string, datatype: amqp_bytes_t *) AMQP_FIELD_KIND_ARRAY = Ord('A'), (* < field array (repeated values of another datatype. datatype: amqp_array_t *) AMQP_FIELD_KIND_TIMESTAMP = Ord('T'), (* < 64-bit timestamp. datatype UInt64 *) AMQP_FIELD_KIND_TABLE = Ord('F'), (* < field table. encapsulates a table inside a table entry. datatype: amqp_table_t *) AMQP_FIELD_KIND_VOID = Ord('V'), (* < empty entry *) AMQP_FIELD_KIND_BYTES = Ord('x') (* < unformatted byte string, datatype: amqp_bytes_t *) ); (* * * An AMQP frame * * \since v0.1 *) pamqp_frame_t = ^amqp_frame_t_; amqp_frame_t_ = record frame_type: UInt8; (* *< frame type. The types: * - AMQP_FRAME_METHOD - use the method union member * - AMQP_FRAME_HEADER - use the properties union member * - AMQP_FRAME_BODY - use the body_fragment union member *) channel: amqp_channel_t; (* *< the channel the frame was received on *) payload: record case integer of 0: (method: amqp_method_t); (* a method, use if frame_type == AMQP_FRAME_METHOD *) 1: (properties: record class_id: UInt16; (* < the class for the properties *) body_size: UInt64; (* < size of the body in bytes *) decoded: Pointer; (* < the decoded properties *) raw: amqp_bytes_t; (* < amqp-encoded properties structure *) end); 2: (body_fragment: amqp_bytes_t); (* < a body fragment, use if frame_type == AMQP_FRAME_BODY *) 3: (protocol_header: record transport_high: UInt8; (* < @internal first byte of handshake *) transport_low: UInt8; (* < @internal second byte of handshake *) protocol_version_major: UInt8; (* < @internal third byte of handshake *) protocol_version_minor: UInt8; (* < @internal fourth byte of handshake *) end); (* < Used only when doing the initial handshake with the broker, don't use otherwise *) end; end; amqp_frame_t = amqp_frame_t_; (* * * SASL method type * * \since v0.1 *) amqp_sasl_method_enum_ = (AMQP_SASL_METHOD_UNDEFINED = -1, (* Invalid SASL method *) AMQP_SASL_METHOD_PLAIN = 0, (* the PLAIN SASL method for authentication to the broker *) AMQP_SASL_METHOD_EXTERNAL = 1 (* the EXTERNAL SASL method for authentication to the broker *) ); amqp_sasl_method_enum = amqp_sasl_method_enum_; (* * * connection state object * * \since v0.1 *) // amqp_connection_state_t = ^amqp_connection_state_t_; // (* * // * Socket object // * // * \since v0.4.0 // *) // amqp_socket_t = amqp_socket_t_; (* * * Status codes * * \since v0.4.0 *) (* NOTE: When updating this enum, update the strings in librabbitmq/amqp_api.c *) amqp_status_enum_ = (AMQP_STATUS_OK = $0, (* Operation successful *) AMQP_STATUS_NO_MEMORY = -$0001, (* Memory allocation failed *) AMQP_STATUS_BAD_AMQP_DATA = -$0002, (* Incorrect or corrupt data was received from the broker.This is a protocol error. *) AMQP_STATUS_UNKNOWN_CLASS = -$0003, (* an unknown AMQP class was received.This is a protocol error. *) AMQP_STATUS_UNKNOWN_METHOD = -$0004, (* an unknown AMQP method was received.This is a protocol error. *) AMQP_STATUS_HOSTNAME_RESOLUTION_FAILED = -$0005, (* Unable to resolve the * hostname *) AMQP_STATUS_INCOMPATIBLE_AMQP_VERSION = -$0006, (* the broker advertised an incompaible AMQP version *) AMQP_STATUS_CONNECTION_CLOSED = -$0007, (* the connection to the broker has been closed *) AMQP_STATUS_BAD_URL = -$0008, (* malformed AMQP URL *) AMQP_STATUS_SOCKET_ERROR = -$0009, (* a socket error occurred *) AMQP_STATUS_INVALID_PARAMETER = -$000A, (* an Invalid parameter was passed into the function *) AMQP_STATUS_TABLE_TOO_BIG = -$000B, (* the amqp_table_t object cannot be serialized because the output buffer is too small *) AMQP_STATUS_WRONG_METHOD = -$000C, (* the wrong method was received *) AMQP_STATUS_TIMEOUT = -$000D, (* Operation timed out *) AMQP_STATUS_TIMER_FAILURE = -$000E, (* the underlying system timer facility failed *) AMQP_STATUS_HEARTBEAT_TIMEOUT = -$000F, (* timed out waiting for heartbeat *) AMQP_STATUS_UNEXPECTED_STATE = -$0010, (* Unexpected protocol state *) AMQP_STATUS_SOCKET_CLOSED = -$0011, (* underlying socket is closed *) AMQP_STATUS_SOCKET_INUSE = -$0012, (* underlying socket is already open *) AMQP_STATUS_BROKER_UNSUPPORTED_SASL_METHOD = -$0013, (* broker does not support the requested SASL mechanism *) AMQP_STATUS_UNSUPPORTED = -$0014, (* parameter is unsupported in This version *) _AMQP_STATUS_NEXT_VALUE = -$0015, (* Internal value *) AMQP_STATUS_TCP_ERROR = -$0100, (* a generic TCP error occurred *) AMQP_STATUS_TCP_SOCKETLIB_INIT_ERROR = -$0101, (* an error occurred trying to initialize the socket library *) _AMQP_STATUS_TCP_NEXT_VALUE = -$0102, (* Internal value *) AMQP_STATUS_SSL_ERROR = -$0200, (* a generic SSL error occurred. *) AMQP_STATUS_SSL_HOSTNAME_VERIFY_FAILED = -$0201, (* SSL validation of hostname against peer certificate failed *) AMQP_STATUS_SSL_PEER_VERIFY_FAILED = -$0202, (* SSL validation of peer certificate failed. *) AMQP_STATUS_SSL_CONNECTION_FAILED = -$0203, (* SSL handshake failed. *) _AMQP_STATUS_SSL_NEXT_VALUE = -$0204 (* Internal value *) ); amqp_status_enum = amqp_status_enum_; (* * * AMQP delivery modes. * Use these values for the #amqp_basic_properties_t::delivery_mode field. * * \since v0.5 *) amqp_delivery_mode_enum = (AMQP_DELIVERY_NONPERSISTENT = 1, (* Non - persistent message *) AMQP_DELIVERY_PERSISTENT = 2 (* persistent message *) ); const amqp_empty_bytes: amqp_bytes_t = (len: 0; bytes: nil); const amqp_empty_table: amqp_table_t = (num_entries: 0; entries: nil); const amqp_empty_array: amqp_array_t = (num_entries: 0; entries: nil); // {$INCLUDE <amqp_framing.h>} // (* * // * Empty bytes structure // * // * \since v0.2 // *) // const // amqp_empty_bytes: // AMQP_BEGIN_DECLS { AMQP_PUBLIC_VARIABLE }{ <= !!!4 unknown type }{ amqp_bytes_t }{ <= !!!4 unknown type }{ AMQP_END_DECLS }{ <= !!!4 unknown type }; // (* * // * Empty table structure // * // * \since v0.2 // *) // amqp_empty_table: // amqp_table_t { AMQP_PUBLIC_VARIABLE }{ <= !!!4 unknown type }; // (* * // * Empty table array structure // * // * \since v0.2 // *) // amqp_empty_array: // amqp_array_t { AMQP_PUBLIC_VARIABLE }{ <= !!!4 unknown type }; // (* Compatibility macros for the above, to avoid the need to update // code written against earlier versions of librabbitmq. *) // // (* * // * \def AMQP_EMPTY_BYTES // * // * Deprecated, use \ref amqp_empty_bytes instead // * // * \deprecated use \ref amqp_empty_bytes instead // * // * \since v0.1 // *) // amqp_empty_bytes = amqp_empty_bytes; // // (* * // * \def AMQP_EMPTY_TABLE // * // * Deprecated, use \ref amqp_empty_table instead // * // * \deprecated use \ref amqp_empty_table instead // * // * \since v0.1 // *) // amqp_empty_table = amqp_empty_table; // // (* * // * \def AMQP_EMPTY_ARRAY // * // * Deprecated, use \ref amqp_empty_array instead // * // * \deprecated use \ref amqp_empty_array instead // * // * \since v0.1 // *) // amqp_empty_array = amqp_empty_array; (* * * Initializes an amqp_pool_t memory allocation pool for use * * Readies an allocation pool for use. An amqp_pool_t * must be initialized before use * * \param [in] pool the amqp_pool_t structure to initialize. * Calling this function on a pool a pool that has * already been initialized will result in undefined * behavior * \param [in] pagesize the unit size that the pool will allocate * memory chunks in. Anything allocated against the pool * with a requested size will be carved out of a block * this size. Allocations larger than this will be * allocated individually * * \sa recycle_amqp_pool(), empty_amqp_pool(), amqp_pool_alloc(), * amqp_pool_alloc_bytes(), amqp_pool_t * * \since v0.1 *) procedure init_amqp_pool(pool: pamqp_pool_t; pagesize: size_t); cdecl; (* * * Recycles an amqp_pool_t memory allocation pool * * Recycles the space allocate by the pool * * This invalidates all allocations made against the pool before this call is * made, any use of any allocations made before recycle_amqp_pool() is called * will result in undefined behavior. * * Note: this may or may not release memory, to force memory to be released * call empty_amqp_pool(). * * \param [in] pool the amqp_pool_t to recycle * * \sa recycle_amqp_pool(), empty_amqp_pool(), amqp_pool_alloc(), * amqp_pool_alloc_bytes() * * \since v0.1 * *) procedure recycle_amqp_pool(pool: pamqp_pool_t); cdecl; (* * * Empties an amqp memory pool * * Releases all memory associated with an allocation pool * * \param [in] pool the amqp_pool_t to empty * * \since v0.1 *) procedure empty_amqp_pool(pool: pamqp_pool_t); cdecl; (* * * Allocates a block of memory from an amqp_pool_t memory pool * * Memory will be aligned on a 8-byte boundary. If a 0-length allocation is * requested, a NULL pointer will be returned. * * \param [in] pool the allocation pool to allocate the memory from * \param [in] amount the size of the allocation in bytes. * \return a pointer to the memory block, or NULL if the allocation cannot * be satisfied. * * \sa init_amqp_pool(), recycle_amqp_pool(), empty_amqp_pool(), * amqp_pool_alloc_bytes() * * \since v0.1 *) function amqp_pool_alloc(pool: pamqp_pool_t; amount: size_t): Pointer; cdecl; (* * * Allocates a block of memory from an amqp_pool_t to an amqp_bytes_t * * Memory will be aligned on a 8-byte boundary. If a 0-length allocation is * requested, output.bytes = NULL. * * \param [in] pool the allocation pool to allocate the memory from * \param [in] amount the size of the allocation in bytes * \param [in] output the location to store the pointer. On success * output.bytes will be set to the beginning of the buffer * output.len will be set to amount * On error output.bytes will be set to NULL and output.len * set to 0 * * \sa init_amqp_pool(), recycle_amqp_pool(), empty_amqp_pool(), * amqp_pool_alloc() * * \since v0.1 *) procedure amqp_pool_alloc_bytes(pool: pamqp_pool_t; amount: size_t; output: pamqp_bytes_t); cdecl; (* * * Wraps a c string in an amqp_bytes_t * * Takes a string, calculates its length and creates an * amqp_bytes_t that points to it. The string is not duplicated. * * For a given input cstr, The amqp_bytes_t output.bytes is the * same as cstr, output.len is the length of the string not including * the \0 terminator * * This function uses strlen() internally so cstr must be properly * terminated * * \param [in] cstr the c string to wrap * \return an amqp_bytes_t that describes the string * * \since v0.1 *) function amqp_cstring_bytes(const cstr: PAnsiChar): amqp_bytes_t; {$IFNDEF CPU32BITS} cdecl; {$ENDIF} (* * * Duplicates an amqp_bytes_t buffer. * * The buffer is cloned and the contents copied. * * The memory associated with the output is allocated * with amqp_bytes_malloc() and should be freed with * amqp_bytes_free() * * \param [in] src * \return a clone of the src * * \sa amqp_bytes_free(), amqp_bytes_malloc() * * \since v0.1 *) function amqp_bytes_malloc_dup(src: amqp_bytes_t): amqp_bytes_t; {$IFNDEF CPU32BITS} cdecl; {$ENDIF} (* * * Allocates a amqp_bytes_t buffer * * Creates an amqp_bytes_t buffer of the specified amount, the buffer should be * freed using amqp_bytes_free() * * \param [in] amount the size of the buffer in bytes * \returns an amqp_bytes_t with amount bytes allocated. * output.bytes will be set to NULL on error * * \sa amqp_bytes_free(), amqp_bytes_malloc_dup() * * \since v0.1 *) function amqp_bytes_malloc(amount: size_t): amqp_bytes_t; {$IFNDEF CPU32BITS} cdecl; {$ENDIF} (* * * Frees an amqp_bytes_t buffer * * Frees a buffer allocated with amqp_bytes_malloc() or amqp_bytes_malloc_dup() * * Calling amqp_bytes_free on buffers not allocated with one * of those two functions will result in undefined behavior * * \param [in] bytes the buffer to free * * \sa amqp_bytes_malloc(), amqp_bytes_malloc_dup() * * \since v0.1 *) procedure amqp_bytes_free(bytes: amqp_bytes_t); cdecl; (* * * Allocate and initialize a new amqp_connection_state_t object * * amqp_connection_state_t objects created with this function * should be freed with amqp_destroy_connection() * * \returns an opaque pointer on success, NULL or 0 on failure. * * \sa amqp_destroy_connection() * * \since v0.1 *) function amqp_new_connection: amqp_connection_state_t; cdecl; (* * * Get the underlying socket descriptor for the connection * * \warning Use the socket returned from this function carefully, incorrect use * of the socket outside of the library will lead to undefined behavior. * Additionally rabbitmq-c may use the socket differently version-to-version, * what may work in one version, may break in the next version. Be sure to * throughly test any applications that use the socket returned by this * function especially when using a newer version of rabbitmq-c * * \param [in] state the connection object * \returns the socket descriptor if one has been set, -1 otherwise * * \sa amqp_tcp_socket_new(), amqp_ssl_socket_new(), amqp_socket_open() * * \since v0.1 *) function amqp_get_sockfd(state: amqp_connection_state_t): integer; cdecl; (* * * Deprecated, use amqp_tcp_socket_new() or amqp_ssl_socket_new() * * \deprecated Use amqp_tcp_socket_new() or amqp_ssl_socket_new() * * Sets the socket descriptor associated with the connection. The socket * should be connected to a broker, and should not be read to or written from * before calling this function. A socket descriptor can be created and opened * using amqp_open_socket() * * \param [in] state the connection object * \param [in] sockfd the socket * * \sa amqp_open_socket(), amqp_tcp_socket_new(), amqp_ssl_socket_new() * * \since v0.1 *) procedure amqp_set_sockfd(state: amqp_connection_state_t; sockfd: integer); cdecl; (* * * Tune client side parameters * * \warning This function may call abort() if the connection is in a certain * state. As such it should probably not be called code outside the library. * connection parameters should be specified when calling amqp_login() or * amqp_login_with_properties() * * This function changes channel_max, frame_max, and heartbeat parameters, on * the client side only. It does not try to renegotiate these parameters with * the broker. Using this function will lead to unexpected results. * * \param [in] state the connection object * \param [in] channel_max the maximum number of channels. * The largest this can be is 65535 * \param [in] frame_max the maximum size of an frame. * The smallest this can be is 4096 * The largest this can be is 2147483647 * Unless you know what you're doing the recommended * size is 131072 or 128KB * \param [in] heartbeat the number of seconds between heartbeats * * \return AMQP_STATUS_OK on success, an amqp_status_enum value otherwise. * Possible error codes include: * - AMQP_STATUS_NO_MEMORY memory allocation failed. * - AMQP_STATUS_TIMER_FAILURE the underlying system timer indicated it * failed. * * \sa amqp_login(), amqp_login_with_properties() * * \since v0.1 *) function amqp_tune_connection(state: amqp_connection_state_t; channel_max: integer; frame_max: integer; heartbeat: integer): integer; cdecl; (* * * Get the maximum number of channels the connection can handle * * The maximum number of channels is set when connection negotiation takes * place in amqp_login() or amqp_login_with_properties(). * * \param [in] state the connection object * \return the maximum number of channels. 0 if there is no limit * * \since v0.1 *) function amqp_get_channel_max(state: amqp_connection_state_t): integer; cdecl; (* * * Get the maximum size of an frame the connection can handle * * The maximum size of an frame is set when connection negotiation takes * place in amqp_login() or amqp_login_with_properties(). * * \param [in] state the connection object * \return the maximum size of an frame. * * \since v0.6 *) function amqp_get_frame_max(state: amqp_connection_state_t): integer; cdecl; (* * * Get the number of seconds between heartbeats of the connection * * The number of seconds between heartbeats is set when connection * negotiation takes place in amqp_login() or amqp_login_with_properties(). * * \param [in] state the connection object * \return the number of seconds between heartbeats. * * \since v0.6 *) function amqp_get_heartbeat(state: amqp_connection_state_t): integer; cdecl; (* * * Destroys an amqp_connection_state_t object * * Destroys a amqp_connection_state_t object that was created with * amqp_new_connection(). If the connection with the broker is open, it will be * implicitly closed with a reply code of 200 (success). Any memory that * would be freed with amqp_maybe_release_buffers() or * amqp_maybe_release_buffers_on_channel() will be freed, and use of that * memory will caused undefined behavior. * * \param [in] state the connection object * \return AMQP_STATUS_OK on success. amqp_status_enum value failure * * \sa amqp_new_connection() * * \since v0.1 *) function amqp_destroy_connection(state: amqp_connection_state_t): integer; cdecl; (* * * Process incoming data * * \warning This is a low-level function intended for those who want to * have greater control over input and output over the socket from the * broker. Correctly using this function requires in-depth knowledge of AMQP * and rabbitmq-c. * * For a given buffer of data received from the broker, decode the first * frame in the buffer. If more than one frame is contained in the input buffer * the return value will be less than the received_data size, the caller should * adjust received_data buffer descriptor to point to the beginning of the * buffer + the return value. * * \param [in] state the connection object * \param [in] received_data a buffer of data received from the broker. The * function will return the number of bytes of the buffer it used. The * function copies these bytes to an internal buffer: this part of the buffer * may be reused after this function successfully completes. * \param [in,out] decoded_frame caller should pass in a pointer to an * amqp_frame_t struct. If there is enough data in received_data for a * complete frame, decoded_frame->frame_type will be set to something OTHER * than 0. decoded_frame may contain members pointing to memory owned by * the state object. This memory can be recycled with amqp_maybe_release_buffers() * or amqp_maybe_release_buffers_on_channel() * \return number of bytes consumed from received_data or 0 if a 0-length * buffer was passed. A negative return value indicates failure. Possible errors: * - AMQP_STATUS_NO_MEMORY failure in allocating memory. The library is likely in * an indeterminate state making recovery unlikely. Client should note the error * and terminate the application * - AMQP_STATUS_BAD_AMQP_DATA bad AMQP data was received. The connection * should be shutdown immediately * - AMQP_STATUS_UNKNOWN_METHOD: an unknown method was received from the * broker. This is likely a protocol error and the connection should be * shutdown immediately * - AMQP_STATUS_UNKNOWN_CLASS: a properties frame with an unknown class * was received from the broker. This is likely a protocol error and the * connection should be shutdown immediately * * \since v0.1 *) function amqp_handle_input(state: amqp_connection_state_t; received_data: amqp_bytes_t; var decoded_frame: amqp_frame_t): integer; cdecl; (* * * Check to see if connection memory can be released * * \deprecated This function is deprecated in favor of * amqp_maybe_release_buffers() or amqp_maybe_release_buffers_on_channel() * * Checks the state of an amqp_connection_state_t object to see if * amqp_release_buffers() can be called successfully. * * \param [in] state the connection object * \returns TRUE if the buffers can be released FALSE otherwise * * \sa amqp_release_buffers() amqp_maybe_release_buffers() * amqp_maybe_release_buffers_on_channel() * * \since v0.1 *) function amqp_release_buffers_ok(state: amqp_connection_state_t): amqp_boolean_t; cdecl; (* * * Release amqp_connection_state_t owned memory * * \deprecated This function is deprecated in favor of * amqp_maybe_release_buffers() or amqp_maybe_release_buffers_on_channel() * * \warning caller should ensure amqp_release_buffers_ok() returns true before * calling this function. Failure to do so may result in abort() being called. * * Release memory owned by the amqp_connection_state_t for reuse by the * library. Use of any memory returned by the library before this function is * called will result in undefined behavior. * * \note internally rabbitmq-c tries to reuse memory when possible. As a result * its possible calling this function may not have a noticeable effect on * memory usage. * * \param [in] state the connection object * * \sa amqp_release_buffers_ok() amqp_maybe_release_buffers() * amqp_maybe_release_buffers_on_channel() * * \since v0.1 *) procedure amqp_release_buffers(state: amqp_connection_state_t); cdecl; (* * * Release amqp_connection_state_t owned memory * * Release memory owned by the amqp_connection_state_t object related to any * channel, allowing reuse by the library. Use of any memory returned by the * library before this function is called with result in undefined behavior. * * \note internally rabbitmq-c tries to reuse memory when possible. As a result * its possible calling this function may not have a noticeable effect on * memory usage. * * \param [in] state the connection object * * \sa amqp_maybe_release_buffers_on_channel() * * \since v0.1 *) procedure amqp_maybe_release_buffers(state: amqp_connection_state_t); cdecl; (* * * Release amqp_connection_state_t owned memory related to a channel * * Release memory owned by the amqp_connection_state_t object related to the * specified channel, allowing reuse by the library. Use of any memory returned * the library for a specific channel will result in undefined behavior. * * \note internally rabbitmq-c tries to reuse memory when possible. As a result * its possible calling this function may not have a noticeable effect on * memory usage. * * \param [in] state the connection object * \param [in] channel the channel specifier for which memory should be * released. Note that the library does not care about the state of the * channel when calling this function * * \sa amqp_maybe_release_buffers() * * \since v0.4.0 *) procedure amqp_maybe_release_buffers_on_channel(state: amqp_connection_state_t; channel: amqp_channel_t); cdecl; (* * * Send a frame to the broker * * \param [in] state the connection object * \param [in] frame the frame to send to the broker * \return AMQP_STATUS_OK on success, an amqp_status_enum value on error. * Possible error codes: * - AMQP_STATUS_BAD_AMQP_DATA the serialized form of the method or * properties was too large to fit in a single AMQP frame, or the * method contains an invalid value. The frame was not sent. * - AMQP_STATUS_TABLE_TOO_BIG the serialized form of an amqp_table_t is * too large to fit in a single AMQP frame. Frame was not sent. * - AMQP_STATUS_UNKNOWN_METHOD an invalid method type was passed in * - AMQP_STATUS_UNKNOWN_CLASS an invalid properties type was passed in * - AMQP_STATUS_TIMER_FAILURE system timer indicated failure. The frame * was sent * - AMQP_STATUS_SOCKET_ERROR * - AMQP_STATUS_SSL_ERROR * * \since v0.1 *) function amqp_send_frame(state: amqp_connection_state_t; frame: pamqp_frame_t): integer; cdecl; (* * * Compare two table entries * * Works just like strcmp(), comparing two the table keys, datatype, then values * * \param [in] entry1 the entry on the left * \param [in] entry2 the entry on the right * \return 0 if entries are equal, 0 < if left is greater, 0 > if right is greater * * \since v0.1 *) function amqp_table_entry_cmp(entry1: pinteger; entry2: pinteger): integer; cdecl; (* * * Open a socket to a remote host * * \deprecated This function is deprecated in favor of amqp_socket_open() * * Looks up the hostname, then attempts to open a socket to the host using * the specified portnumber. It also sets various options on the socket to * improve performance and correctness. * * \param [in] hostname this can be a hostname or IP address. * Both IPv4 and IPv6 are acceptable * \param [in] portnumber the port to connect on. RabbitMQ brokers * listen on port 5672, and 5671 for SSL * \return a positive value indicates success and is the sockfd. A negative * value (see amqp_status_enum)is returned on failure. Possible error codes: * - AMQP_STATUS_TCP_SOCKETLIB_INIT_ERROR Initialization of underlying socket * library failed. * - AMQP_STATUS_HOSTNAME_RESOLUTION_FAILED hostname lookup failed. * - AMQP_STATUS_SOCKET_ERROR a socket error occurred. errno or WSAGetLastError() * may return more useful information. * * \note IPv6 support was added in v0.3 * * \sa amqp_socket_open() amqp_set_sockfd() * * \since v0.1 *) function amqp_open_socket(hostname: PAnsiChar; portnumber: integer): integer; cdecl; (* * * Send initial AMQP header to the broker * * \warning this is a low level function intended for those who want to * interact with the broker at a very low level. Use of this function without * understanding what it does will result in AMQP protocol errors. * * This function sends the AMQP protocol header to the broker. * * \param [in] state the connection object * \return AMQP_STATUS_OK on success, a negative value on failure. Possible * error codes: * - AMQP_STATUS_CONNECTION_CLOSED the connection to the broker was closed. * - AMQP_STATUS_SOCKET_ERROR a socket error occurred. It is likely the * underlying socket has been closed. errno or WSAGetLastError() may provide * further information. * - AMQP_STATUS_SSL_ERROR a SSL error occurred. The connection to the broker * was closed. * * \since v0.1 *) function amqp_send_header(state: amqp_connection_state_t): integer; cdecl; (* * * Checks to see if there are any incoming frames ready to be read * * Checks to see if there are any amqp_frame_t objects buffered by the * amqp_connection_state_t object. Having one or more frames buffered means * that amqp_simple_wait_frame() or amqp_simple_wait_frame_noblock() will * return a frame without potentially blocking on a read() call. * * \param [in] state the connection object * \return TRUE if there are frames enqueued, FALSE otherwise * * \sa amqp_simple_wait_frame() amqp_simple_wait_frame_noblock() * amqp_data_in_buffer() * * \since v0.1 *) function amqp_frames_enqueued(state: amqp_connection_state_t): amqp_boolean_t; cdecl; (* * * Read a single amqp_frame_t * * Waits for the next amqp_frame_t frame to be read from the broker. * This function has the potential to block for a long time in the case of * waiting for a basic.deliver method frame from the broker. * * The library may buffer frames. When an amqp_connection_state_t object * has frames buffered calling amqp_simple_wait_frame() will return an * amqp_frame_t without entering a blocking read(). You can test to see if * an amqp_connection_state_t object has frames buffered by calling the * amqp_frames_enqueued() function. * * The library has a socket read buffer. When there is data in an * amqp_connection_state_t read buffer, amqp_simple_wait_frame() may return an * amqp_frame_t without entering a blocking read(). You can test to see if an * amqp_connection_state_t object has data in its read buffer by calling the * amqp_data_in_buffer() function. * * \param [in] state the connection object * \param [out] decoded_frame the frame * \return AMQP_STATUS_OK on success, an amqp_status_enum value * is returned otherwise. Possible errors include: * - AMQP_STATUS_NO_MEMORY failure in allocating memory. The library is likely in * an indeterminate state making recovery unlikely. Client should note the error * and terminate the application * - AMQP_STATUS_BAD_AMQP_DATA bad AMQP data was received. The connection * should be shutdown immediately * - AMQP_STATUS_UNKNOWN_METHOD: an unknown method was received from the * broker. This is likely a protocol error and the connection should be * shutdown immediately * - AMQP_STATUS_UNKNOWN_CLASS: a properties frame with an unknown class * was received from the broker. This is likely a protocol error and the * connection should be shutdown immediately * - AMQP_STATUS_HEARTBEAT_TIMEOUT timed out while waiting for heartbeat * from the broker. The connection has been closed. * - AMQP_STATUS_TIMER_FAILURE system timer indicated failure. * - AMQP_STATUS_SOCKET_ERROR a socket error occurred. The connection has * been closed * - AMQP_STATUS_SSL_ERROR a SSL socket error occurred. The connection has * been closed. * * \sa amqp_simple_wait_frame_noblock() amqp_frames_enqueued() * amqp_data_in_buffer() * * \note as of v0.4.0 this function will no longer return heartbeat frames * when enabled by specifying a non-zero heartbeat value in amqp_login(). * Heartbeating is handled internally by the library. * * \since v0.1 *) function amqp_simple_wait_frame(state: amqp_connection_state_t; var decoded_frame: amqp_frame_t): integer; cdecl; (* * * Read a single amqp_frame_t with a timeout. * * Waits for the next amqp_frame_t frame to be read from the broker, up to * a timespan specified by tv. The function will return AMQP_STATUS_TIMEOUT * if the timeout is reached. The tv value is not modified by the function. * * If a 0 timeval is specified, the function behaves as if its non-blocking: it * will test to see if a frame can be read from the broker, and return immediately. * * If NULL is passed in for tv, the function will behave like * amqp_simple_wait_frame() and block until a frame is received from the broker * * The library may buffer frames. When an amqp_connection_state_t object * has frames buffered calling amqp_simple_wait_frame_noblock() will return an * amqp_frame_t without entering a blocking read(). You can test to see if an * amqp_connection_state_t object has frames buffered by calling the * amqp_frames_enqueued() function. * * The library has a socket read buffer. When there is data in an * amqp_connection_state_t read buffer, amqp_simple_wait_frame_noblock() may return * an amqp_frame_t without entering a blocking read(). You can test to see if an * amqp_connection_state_t object has data in its read buffer by calling the * amqp_data_in_buffer() function. * * \note This function does not return heartbeat frames. When enabled, heartbeating * is handed internally internally by the library * * \param [in,out] state the connection object * \param [out] decoded_frame the frame * \param [in] tv the maximum time to wait for a frame to be read. Setting * tv->tv_sec = 0 and tv->tv_usec = 0 will do a non-blocking read. Specifying * NULL for tv will make the function block until a frame is read. * \return AMQP_STATUS_OK on success. An amqp_status_enum value is returned * otherwise. Possible errors include: * - AMQP_STATUS_TIMEOUT the timeout was reached while waiting for a frame * from the broker. * - AMQP_STATUS_INVALID_PARAMETER the tv parameter contains an invalid value. * - AMQP_STATUS_NO_MEMORY failure in allocating memory. The library is likely in * an indeterminate state making recovery unlikely. Client should note the error * and terminate the application * - AMQP_STATUS_BAD_AMQP_DATA bad AMQP data was received. The connection * should be shutdown immediately * - AMQP_STATUS_UNKNOWN_METHOD: an unknown method was received from the * broker. This is likely a protocol error and the connection should be * shutdown immediately * - AMQP_STATUS_UNKNOWN_CLASS: a properties frame with an unknown class * was received from the broker. This is likely a protocol error and the * connection should be shutdown immediately * - AMQP_STATUS_HEARTBEAT_TIMEOUT timed out while waiting for heartbeat * from the broker. The connection has been closed. * - AMQP_STATUS_TIMER_FAILURE system timer indicated failure. * - AMQP_STATUS_SOCKET_ERROR a socket error occurred. The connection has * been closed * - AMQP_STATUS_SSL_ERROR a SSL socket error occurred. The connection has * been closed. * * \sa amqp_simple_wait_frame() amqp_frames_enqueued() amqp_data_in_buffer() * * \since v0.4.0 *) function amqp_simple_wait_frame_noblock(state: amqp_connection_state_t; var decoded_frame: amqp_frame_t; tv: ptimeval): integer; cdecl; (* * * Waits for a specific method from the broker * * \warning You probably don't want to use this function. If this function * doesn't receive exactly the frame requested it closes the whole connection. * * Waits for a single method on a channel from the broker. * If a frame is received that does not match expected_channel * or expected_method the program will abort * * \param [in] state the connection object * \param [in] expected_channel the channel that the method should be delivered on * \param [in] expected_method the method to wait for * \param [out] output the method * \returns AMQP_STATUS_OK on success. An amqp_status_enum value is returned * otherwise. Possible errors include: * - AMQP_STATUS_WRONG_METHOD a frame containing the wrong method, wrong frame * type or wrong channel was received. The connection is closed. * - AMQP_STATUS_NO_MEMORY failure in allocating memory. The library is likely in * an indeterminate state making recovery unlikely. Client should note the error * and terminate the application * - AMQP_STATUS_BAD_AMQP_DATA bad AMQP data was received. The connection * should be shutdown immediately * - AMQP_STATUS_UNKNOWN_METHOD: an unknown method was received from the * broker. This is likely a protocol error and the connection should be * shutdown immediately * - AMQP_STATUS_UNKNOWN_CLASS: a properties frame with an unknown class * was received from the broker. This is likely a protocol error and the * connection should be shutdown immediately * - AMQP_STATUS_HEARTBEAT_TIMEOUT timed out while waiting for heartbeat * from the broker. The connection has been closed. * - AMQP_STATUS_TIMER_FAILURE system timer indicated failure. * - AMQP_STATUS_SOCKET_ERROR a socket error occurred. The connection has * been closed * - AMQP_STATUS_SSL_ERROR a SSL socket error occurred. The connection has * been closed. * * \since v0.1 *) function amqp_simple_wait_method(state: amqp_connection_state_t; expected_channel: amqp_channel_t; expected_method: amqp_method_number_t; var output: amqp_method_t): integer; cdecl; (* * * Sends a method to the broker * * This is a thin wrapper around amqp_send_frame(), providing a way to send * a method to the broker on a specified channel. * * \param [in] state the connection object * \param [in] channel the channel object * \param [in] id the method number * \param [in] decoded the method object * \returns AMQP_STATUS_OK on success, an amqp_status_enum value otherwise. * Possible errors include: * - AMQP_STATUS_BAD_AMQP_DATA the serialized form of the method or * properties was too large to fit in a single AMQP frame, or the * method contains an invalid value. The frame was not sent. * - AMQP_STATUS_TABLE_TOO_BIG the serialized form of an amqp_table_t is * too large to fit in a single AMQP frame. Frame was not sent. * - AMQP_STATUS_UNKNOWN_METHOD an invalid method type was passed in * - AMQP_STATUS_UNKNOWN_CLASS an invalid properties type was passed in * - AMQP_STATUS_TIMER_FAILURE system timer indicated failure. The frame * was sent * - AMQP_STATUS_SOCKET_ERROR * - AMQP_STATUS_SSL_ERROR * * \since v0.1 *) function amqp_send_method(state: amqp_connection_state_t; channel: amqp_channel_t; id: amqp_method_number_t; decoded: Pointer): integer; cdecl; (* * * Sends a method to the broker and waits for a method response * * \param [in] state the connection object * \param [in] channel the channel object * \param [in] request_id the method number of the request * \param [in] expected_reply_ids a 0 terminated array of expected response * method numbers * \param [in] decoded_request_method the method to be sent to the broker * \return a amqp_rpc_reply_t: * - r.reply_type == AMQP_RESPONSE_NORMAL. RPC completed successfully * - r.reply_type == AMQP_RESPONSE_SERVER_EXCEPTION. The broker returned an * exception: * - If r.reply.id == AMQP_CHANNEL_CLOSE_METHOD a channel exception * occurred, cast r.reply.decoded to amqp_channel_close_t* to see details * of the exception. The client should amqp_send_method() a * amqp_channel_close_ok_t. The channel must be re-opened before it * can be used again. Any resources associated with the channel * (auto-delete exchanges, auto-delete queues, consumers) are invalid * and must be recreated before attempting to use them again. * - If r.reply.id == AMQP_CONNECTION_CLOSE_METHOD a connection exception * occurred, cast r.reply.decoded to amqp_connection_close_t* to see * details of the exception. The client amqp_send_method() a * amqp_connection_close_ok_t and disconnect from the broker. * - r.reply_type == AMQP_RESPONSE_LIBRARY_EXCEPTION. An exception occurred * within the library. Examine r.library_error and compare it against * amqp_status_enum values to determine the error. * * \sa amqp_simple_rpc_decoded() * * \since v0.1 *) function amqp_simple_rpc(state: amqp_connection_state_t; channel: amqp_channel_t; request_id: amqp_method_number_t; expected_reply_ids: pamqp_method_number_t; decoded_request_method: Pointer) : amqp_rpc_reply_t; cdecl; (* * * Sends a method to the broker and waits for a method response * * \param [in] state the connection object * \param [in] channel the channel object * \param [in] request_id the method number of the request * \param [in] reply_id the method number expected in response * \param [in] decoded_request_method the request method * \return a pointer to the method returned from the broker, or NULL on error. * On error amqp_get_rpc_reply() will return an amqp_rpc_reply_t with * details on the error that occurred. * * \since v0.1 *) function amqp_simple_rpc_decoded(state: amqp_connection_state_t; channel: amqp_channel_t; request_id: amqp_method_number_t; reply_id: amqp_method_number_t; decoded_request_method: Pointer) : Pointer; cdecl; (* * * Get the last global amqp_rpc_reply * * The API methods corresponding to most synchronous AMQP methods * return a pointer to the decoded method result. Upon error, they * return NULL, and we need some way of discovering what, if anything, * went wrong. amqp_get_rpc_reply() returns the most recent * amqp_rpc_reply_t instance corresponding to such an API operation * for the given connection. * * Only use it for operations that do not themselves return * amqp_rpc_reply_t; operations that do return amqp_rpc_reply_t * generally do NOT update this per-connection-global amqp_rpc_reply_t * instance. * * \param [in] state the connection object * \return the most recent amqp_rpc_reply_t: * - r.reply_type == AMQP_RESPONSE_NORMAL. RPC completed successfully * - r.reply_type == AMQP_RESPONSE_SERVER_EXCEPTION. The broker returned an * exception: * - If r.reply.id == AMQP_CHANNEL_CLOSE_METHOD a channel exception * occurred, cast r.reply.decoded to amqp_channel_close_t* to see details * of the exception. The client should amqp_send_method() a * amqp_channel_close_ok_t. The channel must be re-opened before it * can be used again. Any resources associated with the channel * (auto-delete exchanges, auto-delete queues, consumers) are invalid * and must be recreated before attempting to use them again. * - If r.reply.id == AMQP_CONNECTION_CLOSE_METHOD a connection exception * occurred, cast r.reply.decoded to amqp_connection_close_t* to see * details of the exception. The client amqp_send_method() a * amqp_connection_close_ok_t and disconnect from the broker. * - r.reply_type == AMQP_RESPONSE_LIBRARY_EXCEPTION. An exception occurred * within the library. Examine r.library_error and compare it against * amqp_status_enum values to determine the error. * * \sa amqp_simple_rpc_decoded() * * \since v0.1 *) function amqp_get_rpc_reply(state: amqp_connection_state_t): amqp_rpc_reply_t; cdecl; (* * * Login to the broker * * After using amqp_open_socket and amqp_set_sockfd, call * amqp_login to complete connecting to the broker * * \param [in] state the connection object * \param [in] vhost the virtual host to connect to on the broker. The default * on most brokers is "/" * \param [in] channel_max the limit for number of channels for the connection. * 0 means no limit, and is a good default (AMQP_DEFAULT_MAX_CHANNELS) * Note that the maximum number of channels the protocol supports * is 65535 (2^16, with the 0-channel reserved). The server can * set a lower channel_max and then the client will use the lowest * of the two * \param [in] frame_max the maximum size of an AMQP frame on the wire to * request of the broker for this connection. 4096 is the minimum * size, 2^31-1 is the maximum, a good default is 131072 (128KB), or * AMQP_DEFAULT_FRAME_SIZE * \param [in] heartbeat the number of seconds between heartbeat frames to * request of the broker. A value of 0 disables heartbeats. * Note rabbitmq-c only has partial support for heartbeats, as of * v0.4.0 they are only serviced during amqp_basic_publish() and * amqp_simple_wait_frame()/amqp_simple_wait_frame_noblock() * \param [in] sasl_method the SASL method to authenticate with the broker. * followed by the authentication information. * For AMQP_SASL_METHOD_PLAIN, the AMQP_SASL_METHOD_PLAIN * should be followed by two arguments in this order: * const char* username, and const char* password. * \return amqp_rpc_reply_t indicating success or failure. * - r.reply_type == AMQP_RESPONSE_NORMAL. Login completed successfully * - r.reply_type == AMQP_RESPONSE_LIBRARY_EXCEPTION. In most cases errors * from the broker when logging in will be represented by the broker closing * the socket. In this case r.library_error will be set to * AMQP_STATUS_CONNECTION_CLOSED. This error can represent a number of * error conditions including: invalid vhost, authentication failure. * - r.reply_type == AMQP_RESPONSE_SERVER_EXCEPTION. The broker returned an * exception: * - If r.reply.id == AMQP_CHANNEL_CLOSE_METHOD a channel exception * occurred, cast r.reply.decoded to amqp_channel_close_t* to see details * of the exception. The client should amqp_send_method() a * amqp_channel_close_ok_t. The channel must be re-opened before it * can be used again. Any resources associated with the channel * (auto-delete exchanges, auto-delete queues, consumers) are invalid * and must be recreated before attempting to use them again. * - If r.reply.id == AMQP_CONNECTION_CLOSE_METHOD a connection exception * occurred, cast r.reply.decoded to amqp_connection_close_t* to see * details of the exception. The client amqp_send_method() a * amqp_connection_close_ok_t and disconnect from the broker. * * \since v0.1 *) function amqp_login(state: amqp_connection_state_t; const vhost: PAnsiChar; channel_max: integer; frame_max: integer; heartbeat: integer; sasl_method: amqp_sasl_method_enum): amqp_rpc_reply_t; varargs; cdecl; (* * * Login to the broker passing a properties table * * This function is similar to amqp_login() and differs in that it provides a * way to pass client properties to the broker. This is commonly used to * negotiate newer protocol features as they are supported by the broker. * * \param [in] state the connection object * \param [in] vhost the virtual host to connect to on the broker. The default * on most brokers is "/" * \param [in] channel_max the limit for the number of channels for the connection. * 0 means no limit, and is a good default (AMQP_DEFAULT_MAX_CHANNELS) * Note that the maximum number of channels the protocol supports * is 65535 (2^16, with the 0-channel reserved). The server can * set a lower channel_max and then the client will use the lowest * of the two * \param [in] frame_max the maximum size of an AMQP frame ont he wire to * request of the broker for this connection. 4096 is the minimum * size, 2^31-1 is the maximum, a good default is 131072 (128KB), or * AMQP_DEFAULT_FRAME_SIZE * \param [in] heartbeat the number of seconds between heartbeat frame to * request of the broker. A value of 0 disables heartbeats. * Note rabbitmq-c only has partial support for hearts, as of * v0.4.0 heartbeats are only serviced during amqp_basic_publish(), * and amqp_simple_wait_frame()/amqp_simple_wait_frame_noblock() * \param [in] properties a table of properties to send the broker. * \param [in] sasl_method the SASL method to authenticate with the broker * followed by the authentication information. * For AMQP_SASL_METHOD_PLAN, the AMQP_SASL_METHOD_PLAIN parameter * should be followed by two arguments in this order: * const char* username, and const char* password. * \return amqp_rpc_reply_t indicating success or failure. * - r.reply_type == AMQP_RESPONSE_NORMAL. Login completed successfully * - r.reply_type == AMQP_RESPONSE_LIBRARY_EXCEPTION. In most cases errors * from the broker when logging in will be represented by the broker closing * the socket. In this case r.library_error will be set to * AMQP_STATUS_CONNECTION_CLOSED. This error can represent a number of * error conditions including: invalid vhost, authentication failure. * - r.reply_type == AMQP_RESPONSE_SERVER_EXCEPTION. The broker returned an * exception: * - If r.reply.id == AMQP_CHANNEL_CLOSE_METHOD a channel exception * occurred, cast r.reply.decoded to amqp_channel_close_t* to see details * of the exception. The client should amqp_send_method() a * amqp_channel_close_ok_t. The channel must be re-opened before it * can be used again. Any resources associated with the channel * (auto-delete exchanges, auto-delete queues, consumers) are invalid * and must be recreated before attempting to use them again. * - If r.reply.id == AMQP_CONNECTION_CLOSE_METHOD a connection exception * occurred, cast r.reply.decoded to amqp_connection_close_t* to see * details of the exception. The client amqp_send_method() a * amqp_connection_close_ok_t and disconnect from the broker. * * \since v0.4.0 *) function amqp_login_with_properties(state: amqp_connection_state_t; const vhost: PAnsiChar; channel_max: integer; frame_max: integer; heartbeat: integer; const properties: pamqp_table_t; sasl_method: amqp_sasl_method_enum): amqp_rpc_reply_t; varargs; cdecl; // type // pamqp_basic_properties_t_ = ^amqp_basic_properties_t_; // // amqp_basic_properties_t_ ; // // amqp_basic_properties_t = amqp_basic_properties_t_; (* * * Publish a message to the broker * * Publish a message on an exchange with a routing key. * * Note that at the AMQ protocol level basic.publish is an async method: * this means error conditions that occur on the broker (such as publishing to * a non-existent exchange) will not be reflected in the return value of this * function. * * \param [in] state the connection object * \param [in] channel the channel identifier * \param [in] exchange the exchange on the broker to publish to * \param [in] routing_key the routing key to use when publishing the message * \param [in] mandatory indicate to the broker that the message MUST be routed * to a queue. If the broker cannot do this it should respond with * a basic.return method. * \param [in] immediate indicate to the broker that the message MUST be delivered * to a consumer immediately. If the broker cannot do this it should * response with a basic.return method. * \param [in] properties the properties associated with the message * \param [in] body the message body * \return AMQP_STATUS_OK on success, amqp_status_enum value on failure. Note * that basic.publish is an async method, the return value from this * function only indicates that the message data was successfully * transmitted to the broker. It does not indicate failures that occur * on the broker, such as publishing to a non-existent exchange. * Possible error values: * - AMQP_STATUS_TIMER_FAILURE: system timer facility returned an error * the message was not sent. * - AMQP_STATUS_HEARTBEAT_TIMEOUT: connection timed out waiting for a * heartbeat from the broker. The message was not sent. * - AMQP_STATUS_NO_MEMORY: memory allocation failed. The message was * not sent. * - AMQP_STATUS_TABLE_TOO_BIG: a table in the properties was too large * to fit in a single frame. Message was not sent. * - AMQP_STATUS_CONNECTION_CLOSED: the connection was closed. * - AMQP_STATUS_SSL_ERROR: a SSL error occurred. * - AMQP_STATUS_TCP_ERROR: a TCP error occurred. errno or * WSAGetLastError() may provide more information * * Note: this function does heartbeat processing as of v0.4.0 * * \since v0.1 *) function amqp_basic_publish(state: amqp_connection_state_t; channel: amqp_channel_t; exchange: amqp_bytes_t; routing_key: amqp_bytes_t; mandatory: amqp_boolean_t; immediate: amqp_boolean_t; const properties: pamqp_basic_properties_t_; body: amqp_bytes_t): integer; cdecl; (* * * Closes an channel * * \param [in] state the connection object * \param [in] channel the channel identifier * \param [in] code the reason for closing the channel, AMQP_REPLY_SUCCESS is a good default * \return amqp_rpc_reply_t indicating success or failure * * \since v0.1 *) function amqp_channel_close(state: amqp_connection_state_t; channel: amqp_channel_t; code: integer): amqp_rpc_reply_t; cdecl; (* * * Closes the entire connection * * Implicitly closes all channels and informs the broker the connection * is being closed, after receiving acknowldgement from the broker it closes * the socket. * * \param [in] state the connection object * \param [in] code the reason code for closing the connection. AMQP_REPLY_SUCCESS is a good default. * \return amqp_rpc_reply_t indicating the result * * \since v0.1 *) function amqp_connection_close(state: amqp_connection_state_t; code: integer): amqp_rpc_reply_t; cdecl; (* * * Acknowledges a message * * Does a basic.ack on a received message * * \param [in] state the connection object * \param [in] channel the channel identifier * \param [in] delivery_tag the delivery tag of the message to be ack'd * \param [in] multiple if true, ack all messages up to this delivery tag, if * false ack only this delivery tag * \return 0 on success, 0 > on failing to send the ack to the broker. * this will not indicate failure if something goes wrong on the broker * * \since v0.1 *) function amqp_basic_ack(state: amqp_connection_state_t; channel: amqp_channel_t; delivery_tag: UInt64; multiple: amqp_boolean_t): integer; cdecl; (* * * Do a basic.get * * Synchonously polls the broker for a message in a queue, and * retrieves the message if a message is in the queue. * * \param [in] state the connection object * \param [in] channel the channel identifier to use * \param [in] queue the queue name to retrieve from * \param [in] no_ack if true the message is automatically ack'ed * if false amqp_basic_ack should be called once the message * retrieved has been processed * \return amqp_rpc_reply indicating success or failure * * \since v0.1 *) function amqp_basic_get(state: amqp_connection_state_t; channel: amqp_channel_t; queue: amqp_bytes_t; no_ack: amqp_boolean_t): amqp_rpc_reply_t; cdecl; (* * * Do a basic.reject * * Actively reject a message that has been delivered * * \param [in] state the connection object * \param [in] channel the channel identifier * \param [in] delivery_tag the delivery tag of the message to reject * \param [in] requeue indicate to the broker whether it should requeue the * message or just discard it. * \return 0 on success, 0 > on failing to send the reject method to the broker. * This will not indicate failure if something goes wrong on the broker. * * \since v0.1 *) function amqp_basic_reject(state: amqp_connection_state_t; channel: amqp_channel_t; delivery_tag: UInt64; requeue: amqp_boolean_t): integer; cdecl; (* * * Do a basic.nack * * Actively reject a message, this has the same effect as amqp_basic_reject() * however, amqp_basic_nack() can negatively acknowledge multiple messages with * one call much like amqp_basic_ack() can acknowledge mutliple messages with * one call. * * \param [in] state the connection object * \param [in] channel the channel identifier * \param [in] delivery_tag the delivery tag of the message to reject * \param [in] multiple if set to 1 negatively acknowledge all unacknowledged * messages on this channel. * \param [in] requeue indicate to the broker whether it should requeue the * message or dead-letter it. * \return AMQP_STATUS_OK on success, an amqp_status_enum value otherwise. * * \since v0.5.0 *) function amqp_basic_nack(state: amqp_connection_state_t; channel: amqp_channel_t; delivery_tag: UInt64; multiple: amqp_boolean_t; requeue: amqp_boolean_t): integer; cdecl; (* * * Check to see if there is data left in the receive buffer * * Can be used to see if there is data still in the buffer, if so * calling amqp_simple_wait_frame will not immediately enter a * blocking read. * * \param [in] state the connection object * \return true if there is data in the recieve buffer, false otherwise * * \since v0.1 *) function amqp_data_in_buffer(state: amqp_connection_state_t): amqp_boolean_t; cdecl; (* * * Get the error string for the given error code. * * \deprecated This function has been deprecated in favor of * \ref amqp_error_string2() which returns statically allocated * string which do not need to be freed by the caller. * * The returned string resides on the heap; the caller is responsible * for freeing it. * * \param [in] err return error code * \return the error string * * \since v0.1 *) function amqp_error_string(err: integer): PAnsiChar; cdecl; (* * * Get the error string for the given error code. * * Get an error string associated with an error code. The string is statically * allocated and does not need to be freed * * \param [in] err the error code * \return the error string * * \since v0.4.0 *) function amqp_error_string2(err: integer): PAnsiChar; cdecl; (* * * Deserialize an amqp_table_t from AMQP wireformat * * This is an internal function and is not typically used by * client applications * * \param [in] encoded the buffer containing the serialized data * \param [in] pool memory pool used to allocate the table entries from * \param [in] output the amqp_table_t structure to fill in. Any existing * entries will be erased * \param [in,out] offset The offset into the encoded buffer to start * reading the serialized table. It will be updated * by this function to end of the table * \return AMQP_STATUS_OK on success, an amqp_status_enum value on failure * Possible error codes: * - AMQP_STATUS_NO_MEMORY out of memory * - AMQP_STATUS_BAD_AMQP_DATA invalid wireformat * * \since v0.1 *) function amqp_decode_table(encoded: amqp_bytes_t; pool: pamqp_pool_t; output: pamqp_table_t; var offset: size_t): integer; cdecl; (* * * Serializes an amqp_table_t to the AMQP wireformat * * This is an internal function and is not typically used by * client applications * * \param [in] encoded the buffer where to serialize the table to * \param [in] input the amqp_table_t to serialize * \param [in,out] offset The offset into the encoded buffer to start * writing the serialized table. It will be updated * by this function to where writing left off * \return AMQP_STATUS_OK on success, an amqp_status_enum value on failure * Possible error codes: * - AMQP_STATUS_TABLE_TOO_BIG the serialized form is too large for the * buffer * - AMQP_STATUS_BAD_AMQP_DATA invalid table * * \since v0.1 *) function amqp_encode_table(encoded: amqp_bytes_t; input: pamqp_table_t; var offset: size_t): integer; cdecl; (* * * Create a deep-copy of an amqp_table_t object * * Creates a deep-copy of an amqp_table_t object, using the provided pool * object to allocate the necessary memory. This memory can be freed later by * call recycle_amqp_pool(), or empty_amqp_pool() * * \param [in] original the table to copy * \param [in,out] clone the table to copy to * \param [in] pool the initialized memory pool to do allocations for the table * from * \return AMQP_STATUS_OK on success, amqp_status_enum value on failure. * Possible error values: * - AMQP_STATUS_NO_MEMORY - memory allocation failure. * - AMQP_STATUS_INVALID_PARAMETER - invalid table (e.g., no key name) * * \since v0.4.0 *) function amqp_table_clone(const original: pamqp_table_t; var clone: amqp_table_t; pool: pamqp_pool_t): integer; cdecl; (* * * A message object * * \since v0.4.0 *) type pamqp_message_t = ^amqp_message_t_; amqp_message_t_ = record properties: amqp_basic_properties_t; (* *< message properties *) body: amqp_bytes_t; (* *< message body *) pool: amqp_pool_t; (* *< pool used to allocate properties *) end; amqp_message_t = amqp_message_t_; (* * * Reads the next message on a channel * * Reads a complete message (header + body) on a specified channel. This * function is intended to be used with amqp_basic_get() or when an * AMQP_BASIC_DELIVERY_METHOD method is received. * * \param [in,out] state the connection object * \param [in] channel the channel on which to read the message from * \param [in,out] message a pointer to a amqp_message_t object. Caller should * call amqp_message_destroy() when it is done using the * fields in the message object. The caller is responsible for * allocating/destroying the amqp_message_t object itself. * \param [in] flags pass in 0. Currently unused. * \returns a amqp_rpc_reply_t object. ret.reply_type == AMQP_RESPONSE_NORMAL on success. * * \since v0.4.0 *) function amqp_read_message(state: amqp_connection_state_t; channel: amqp_channel_t; var &message: amqp_message_t; flags: integer): amqp_rpc_reply_t; cdecl; (* * * Frees memory associated with a amqp_message_t allocated in amqp_read_message * * \param [in] message * * \since v0.4.0 *) procedure amqp_destroy_message(&message: pamqp_message_t); (* * * Envelope object * * \since v0.4.0 *) type pamqp_envelope_t = ^amqp_envelope_t_; amqp_envelope_t_ = record channel: amqp_channel_t; (* *< channel message was delivered on *) consumer_tag: amqp_bytes_t; (* *< the consumer tag the message was delivered to *) delivery_tag: UInt64; (* *< the messages delivery tag *) redelivered: amqp_boolean_t; (* *< flag indicating whether this message is being redelivered *) exchange: amqp_bytes_t; (* *< exchange this message was published to *) routing_key: amqp_bytes_t; (* *< the routing key this message was published with *) &message: amqp_message_t; (* *< the message *) end; amqp_envelope_t = amqp_envelope_t_; (* * * Wait for and consume a message * * Waits for a basic.deliver method on any channel, upon receipt of * basic.deliver it reads that message, and returns. If any other method is * received before basic.deliver, this function will return an amqp_rpc_reply_t * with ret.reply_type == AMQP_RESPONSE_LIBRARY_EXCEPTION, and * ret.library_error == AMQP_STATUS_UNEXPECTED_FRAME. The caller should then * call amqp_simple_wait_frame() to read this frame and take appropriate action. * * This function should be used after starting a consumer with the * amqp_basic_consume() function * * \param [in,out] state the connection object * \param [in,out] envelope a pointer to a amqp_envelope_t object. Caller * should call #amqp_destroy_envelope() when it is done using * the fields in the envelope object. The caller is responsible * for allocating/destroying the amqp_envelope_t object itself. * \param [in] timeout a timeout to wait for a message delivery. Passing in * NULL will result in blocking behavior. * \param [in] flags pass in 0. Currently unused. * \returns a amqp_rpc_reply_t object. ret.reply_type == AMQP_RESPONSE_NORMAL * on success. If ret.reply_type == AMQP_RESPONSE_LIBRARY_EXCEPTION, and * ret.library_error == AMQP_STATUS_UNEXPECTED_FRAME, a frame other * than AMQP_BASIC_DELIVER_METHOD was received, the caller should call * amqp_simple_wait_frame() to read this frame and take appropriate * action. * * \since v0.4.0 *) function amqp_consume_message(state: amqp_connection_state_t; var envelope: amqp_envelope_t; timeout: ptimeval; flags: integer): amqp_rpc_reply_t; cdecl; (* * * Frees memory associated with a amqp_envelope_t allocated in amqp_consume_message() * * \param [in] envelope * * \since v0.4.0 *) procedure amqp_destroy_envelope(var envelope: amqp_envelope_t); cdecl; (* * * Parameters used to connect to the RabbitMQ broker * * \since v0.2 *) type pamqp_connection_info = ^amqp_connection_info; amqp_connection_info = record user: PAnsiChar; (* *< the username to authenticate with the broker, default on most broker is 'guest' *) password: PAnsiChar; (* *< the password to authenticate with the broker, default on most brokers is 'guest' *) host: PAnsiChar; (* *< the hostname of the broker *) vhost: PAnsiChar; (* *< the virtual host on the broker to connect to, a good default is "/" *) port: integer; (* *< the port that the broker is listening on, default on most brokers is 5672 *) SSL: amqp_boolean_t; end; (* * * Initialze an amqp_connection_info to default values * * The default values are: * - user: "guest" * - password: "guest" * - host: "localhost" * - vhost: "/" * - port: 5672 * * \param [out] parsed the connection info to set defaults on * * \since v0.2 *) procedure amqp_default_connection_info(var parsed: amqp_connection_info); cdecl; (* * * Parse a connection URL * * An amqp connection url takes the form: * * amqp://[$USERNAME[:$PASSWORD]\@]$HOST[:$PORT]/[$VHOST] * * Examples: * amqp://guest:guest\@localhost:5672// * amqp://guest:guest\@localhost/myvhost * * Any missing parts of the URL will be set to the defaults specified in * amqp_default_connection_info. For amqps: URLs the default port will be set * to 5671 instead of 5672 for non-SSL URLs. * * \note This function modifies url parameter. * * \param [in] url URI to parse, note that this parameter is modified by the * function. * \param [out] parsed the connection info gleaned from the URI. The char* * members will point to parts of the url input parameter. * Memory management will depend on how the url is allocated. * \returns AMQP_STATUS_OK on success, AMQP_STATUS_BAD_URL on failure * * \since v0.2 *) function amqp_parse_url(URL: PAnsiChar; var parsed: amqp_connection_info): integer; cdecl; (* socket API *) (* * * Open a socket connection. * * This function opens a socket connection returned from amqp_tcp_socket_new() * or amqp_ssl_socket_new(). This function should be called after setting * socket options and prior to assigning the socket to an AMQP connection with * amqp_set_socket(). * * \param [in,out] self A socket object. * \param [in] host Connect to this host. * \param [in] port Connect on this remote port. * * \return AMQP_STATUS_OK on success, an amqp_status_enum on failure * * \since v0.4.0 *) function amqp_socket_open(self: pamqp_socket_t; const host: PAnsiChar; port: integer): integer; cdecl; (* * * Open a socket connection. * * This function opens a socket connection returned from amqp_tcp_socket_new() * or amqp_ssl_socket_new(). This function should be called after setting * socket options and prior to assigning the socket to an AMQP connection with * amqp_set_socket(). * * \param [in,out] self A socket object. * \param [in] host Connect to this host. * \param [in] port Connect on this remote port. * \param [in] timeout Max allowed time to spent on opening. If NULL - run in blocking mode * * \return AMQP_STATUS_OK on success, an amqp_status_enum on failure. * * \since v0.4.0 *) function amqp_socket_open_noblock(self: pamqp_socket_t; const host: PAnsiChar; port: integer; timeout: ptimeval): integer; cdecl; (* * * Get the socket descriptor in use by a socket object. * * Retrieve the underlying socket descriptor. This function can be used to * perform low-level socket operations that aren't supported by the socket * interface. Use with caution! * * \param [in,out] self A socket object. * * \return The underlying socket descriptor, or -1 if there is no socket descriptor * associated with * with * * \since v0.4.0 *) function amqp_socket_get_sockfd(self: pamqp_socket_t): integer; cdecl; (* * * Get the socket object associated with a amqp_connection_state_t * * \param [in] state the connection object to get the socket from * \return a pointer to the socket object, or NULL if one has not been assigned * * \since v0.4.0 *) function amqp_get_socket(state: amqp_connection_state_t): pamqp_socket_t; cdecl; (* * * Get the broker properties table * * \param [in] state the connection object * \return a pointer to an amqp_table_t containing the properties advertised * by the broker on connection. The connection object owns the table, it * should not be modified. * * \since v0.5.0 *) function amqp_get_server_properties(state: amqp_connection_state_t): pamqp_table_t; cdecl; (* * * Get the client properties table * * Get the properties that were passed to the broker on connection. * * \param [in] state the connection object * \return a pointer to an amqp_table_t containing the properties advertised * by the client on connection. The connection object owns the table, it * should not be modified. * * \since v0.7.0 *) function amqp_get_client_properties(state: amqp_connection_state_t): pamqp_table_t; cdecl; {$ENDREGION} {$REGION 'ampq_private.h'} const AMQ_COPYRIGHT = 'Copyright (c) 2007-2014 VMWare Inc, Tony Garnock-Jones,'' and Alan Antonuk.'; (* * Connection states: XXX FIX THIS * * - CONNECTION_STATE_INITIAL: The initial state, when we cannot be * sure if the next thing we will get is the first AMQP frame, or a * protocol header from the server. * * - CONNECTION_STATE_IDLE: The normal state between * frames. Connections may only be reconfigured, and the * connection's pools recycled, when in this state. Whenever we're * in this state, the inbound_buffer's bytes pointer must be NULL; * any other state, and it must point to a block of memory allocated * from the frame_pool. * * - CONNECTION_STATE_HEADER: Some bytes of an incoming frame have * been seen, but not a complete frame header's worth. * * - CONNECTION_STATE_BODY: A complete frame header has been seen, but * the frame is not yet complete. When it is completed, it will be * returned, and the connection will return to IDLE state. * *) type amqp_status_private_enum_ = ( // 0x00xx -> AMQP_STATUS_ // 0x01xx -> AMQP_STATUS_TCP_* // 0x02xx -> AMQP_STATUS_SSL_* AMQP_PRIVATE_STATUS_SOCKET_NEEDREAD = -$1301, AMQP_PRIVATE_STATUS_SOCKET_NEEDWRITE = -$1302); amqp_status_private_enum = amqp_status_private_enum_; {$ENDREGION} {$REGION 'amqp_tcp_socket.h'} function amqp_tcp_socket_new(state: amqp_connection_state_t): pamqp_socket_t; cdecl; (* * * Create a new TCP socket. * * Call amqp_connection_close() to release socket resources. * * \return A new socket object or NULL if an error occurred. * * \since v0.4.0 *) (* * * Assign an open file descriptor to a socket object. * * This function must not be used in conjunction with amqp_socket_open(), i.e. * the socket connection should already be open(2) when this function is * called. * * \param [in,out] self A TCP socket object. * \param [in] sockfd An open socket descriptor. * * \since v0.4.0 *) procedure amqp_tcp_socket_set_sockfd(self: pamqp_socket_t; sockfd: integer); {$ENDREGION} implementation function amqp_constant_name; external LIBFILE; function amqp_constant_is_hard_error; external LIBFILE; function amqp_method_name; external LIBFILE; function amqp_method_has_content; external LIBFILE; function amqp_decode_method; external LIBFILE; function amqp_decode_properties; external LIBFILE; function amqp_encode_method; external LIBFILE; function amqp_encode_properties; external LIBFILE; function amqp_channel_open; external LIBFILE; function amqp_channel_flow; external LIBFILE; function amqp_exchange_declare; external LIBFILE; function amqp_exchange_delete; external LIBFILE; function amqp_exchange_bind; external LIBFILE; function amqp_exchange_unbind; external LIBFILE; function amqp_queue_declare; external LIBFILE; function amqp_queue_bind; external LIBFILE; function amqp_queue_purge; external LIBFILE; function amqp_queue_delete; external LIBFILE; function amqp_queue_unbind; external LIBFILE; function amqp_basic_qos; external LIBFILE; function amqp_basic_consume; external LIBFILE; function amqp_basic_cancel; external LIBFILE; function amqp_basic_recover; external LIBFILE; function amqp_tx_select; external LIBFILE; function amqp_tx_commit; external LIBFILE; function amqp_tx_rollback; external LIBFILE; function amqp_confirm_select; external LIBFILE; function amqp_version_number; external LIBFILE; function amqp_version; external LIBFILE; procedure init_amqp_pool; external LIBFILE; procedure recycle_amqp_pool; external LIBFILE; procedure empty_amqp_pool; external LIBFILE; function amqp_pool_alloc; external LIBFILE; procedure amqp_pool_alloc_bytes; external LIBFILE; {$IFDEF CPU32BITS} function amqp_cstring_bytes_c(const cstr: PAnsiChar): UInt64; cdecl; external LIBFILE name 'amqp_cstring_bytes'; function amqp_bytes_malloc_dup_c(src: amqp_bytes_t): UInt64; cdecl; external LIBFILE name 'amqp_bytes_malloc_dup'; function amqp_bytes_malloc_c(amount: size_t): UInt64; cdecl; external LIBFILE name 'amqp_bytes_malloc'; function amqp_cstring_bytes(const cstr: PAnsiChar): amqp_bytes_t; begin PUInt64(@Result)^:=amqp_cstring_bytes_c(cstr); end; function amqp_bytes_malloc_dup(src: amqp_bytes_t): amqp_bytes_t; begin PUInt64(@Result)^:=amqp_bytes_malloc_dup_c(src); end; function amqp_bytes_malloc(amount: size_t): amqp_bytes_t; begin PUInt64(@Result)^:=amqp_bytes_malloc_c(amount); end; {$ELSE} function amqp_cstring_bytes; external LIBFILE; function amqp_bytes_malloc_dup; external LIBFILE; function amqp_bytes_malloc; external LIBFILE; {$ENDIF} procedure amqp_bytes_free; external LIBFILE; function amqp_new_connection; external LIBFILE; function amqp_get_sockfd; external LIBFILE; procedure amqp_set_sockfd; external LIBFILE; function amqp_tune_connection; external LIBFILE; function amqp_get_channel_max; external LIBFILE; function amqp_get_frame_max; external LIBFILE; function amqp_get_heartbeat; external LIBFILE; function amqp_destroy_connection; external LIBFILE; function amqp_handle_input; external LIBFILE; function amqp_release_buffers_ok; external LIBFILE; procedure amqp_release_buffers; external LIBFILE; procedure amqp_maybe_release_buffers; external LIBFILE; procedure amqp_maybe_release_buffers_on_channel; external LIBFILE; function amqp_send_frame; external LIBFILE; function amqp_table_entry_cmp; external LIBFILE; function amqp_open_socket; external LIBFILE; function amqp_send_header; external LIBFILE; function amqp_frames_enqueued; external LIBFILE; function amqp_simple_wait_frame; external LIBFILE; function amqp_simple_wait_frame_noblock; external LIBFILE; function amqp_simple_wait_method; external LIBFILE; function amqp_send_method; external LIBFILE; function amqp_simple_rpc; external LIBFILE; function amqp_simple_rpc_decoded; external LIBFILE; function amqp_get_rpc_reply; external LIBFILE; function amqp_login; external LIBFILE; function amqp_login_with_properties; external LIBFILE; function amqp_basic_publish; external LIBFILE; function amqp_channel_close; external LIBFILE; function amqp_connection_close; external LIBFILE; function amqp_basic_ack; external LIBFILE; function amqp_basic_get; external LIBFILE; function amqp_basic_reject; external LIBFILE; function amqp_basic_nack; external LIBFILE; function amqp_data_in_buffer; external LIBFILE; function amqp_error_string; external LIBFILE; function amqp_error_string2; external LIBFILE; function amqp_decode_table; external LIBFILE; function amqp_encode_table; external LIBFILE; function amqp_table_clone; external LIBFILE; function amqp_read_message; external LIBFILE; procedure amqp_destroy_message; external LIBFILE; function amqp_consume_message; external LIBFILE; procedure amqp_destroy_envelope; external LIBFILE; procedure amqp_default_connection_info; external LIBFILE; function amqp_parse_url; external LIBFILE; function amqp_socket_open; external LIBFILE; function amqp_socket_open_noblock; external LIBFILE; function amqp_socket_get_sockfd; external LIBFILE; function amqp_get_socket; external LIBFILE; function amqp_get_server_properties; external LIBFILE; function amqp_get_client_properties; external LIBFILE; function amqp_tcp_socket_new; external LIBFILE; procedure amqp_tcp_socket_set_sockfd; external LIBFILE; end.
unit UPaintSpace; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls, FileUtil, Forms, Graphics, Dialogs, Menus, ExtCtrls, UDoublePoint, Math, UUtils; type TPaintSpace = class private FPaintBox: TPaintBox; FLocalSpace: TDoubleRect; FOriginalSize: TDoublePoint; FWorldSpace: TDoubleRect; FFiguresBounds: TDoubleRect; FScaleChangeEvent: TEventHandler; FPositionChangeEvent: TEventHandler; FWorldSpaceChangeEvent: TEventHandler; procedure SetScale(AValue: Double); function GetScale: Double; function GetPosition: TDoublePoint; function GetCanvas: TCanvas; function GetPaintBox: TPaintBox; public property Canvas: TCanvas read GetCanvas; property PaintBox: TPaintBox read GetPaintBox; procedure SetPosForced(AValue: TDoublePoint); procedure SetPosSafely(AValue: TDoublePoint); property Position: TDoublePoint read GetPosition write SetPosForced; property Scale: Double read GetScale write SetScale; property LocalSpace: TDoubleRect read FLocalSpace; property WorldSpace: TDoubleRect read FWorldSpace; property FiguresBounds: TDoubleRect read FFiguresBounds; property OriginalSize: TDoublePoint read FOriginalSize; property OnScaleChange: TEventHandler read FScaleChangeEvent write FScaleChangeEvent; property OnPositionChange: TEventHandler read FPositionChangeEvent write FPositionChangeEvent; property OnWorldSpaceChange: TEventHandler read FWorldSpaceChangeEvent write FWorldSpaceChangeEvent; constructor Create(APaintBox: TPaintBox; AOriginalSize: TDoublePoint); procedure SetFiguresBounds(AMin, AMax: TDoublePoint); procedure SetScaleCenter(AValue: Double); procedure SetScalePoint(AValue: Double; APoint: TDoublePoint); function ToWorld(APoint: TDoublePoint): TDoublePoint; function ToLocal(APoint: TDoublePoint): TPoint; function ToLocal(APointArray: TDoublePointArray): TPointArray; const MAX_SCALE: Integer = 15; end; function DoubleRect(AWidth, AHeight: Double): TDoubleRect; implementation constructor TPaintSpace.Create(APaintBox: TPaintBox; AOriginalSize: TDoublePoint); begin FPaintBox:= APaintBox; FOriginalSize:= AOriginalSize; FLocalSpace.Width:= FPaintBox.Width; FLocalSpace.Height:= FPaintBox.Height; FLocalSpace.TopLeft:= GetDoublePoint; FWorldSpace.Width:= FOriginalSize.X; FWorldSpace.Height:= FOriginalSize.Y; FWorldSpace.TopLeft:= GetDoublePoint; end; procedure TPaintSpace.SetFiguresBounds(AMin, AMax: TDoublePoint); begin FFiguresBounds.TopLeft:= AMin; FFiguresBounds.Width:= AMax.X - FFiguresBounds.TopLeft.X; FFiguresBounds.Height:= AMax.Y - FFiguresBounds.TopLeft.Y; SetPosForced(Position); end; function TPaintSpace.GetCanvas: TCanvas; begin Result:= FPaintBox.Canvas; end; procedure TPaintSpace.SetScaleCenter(AValue: Double); var TempPoint: TDoublePoint; begin if (AValue <= 0) or (AValue > MAX_SCALE) then exit; TempPoint:= GetDoublePoint(FPaintBox.Width, FPaintBox.Height)/2; Position:= Position+TempPoint/Scale; Scale:= AValue; Position:= Position-TempPoint/Scale; end; procedure TPaintSpace.SetScalePoint(AValue: Double; APoint: TDoublePoint); var TempPoint: TDoublePoint; begin if (AValue <= 0) or (AValue > MAX_SCALE) then Exit; TempPoint:= APoint-Position*Scale; Position:= Position+TempPoint/Scale; Scale:= AValue; Position:= Position-TempPoint/Scale; end; procedure TPaintSpace.SetPosForced(AValue: TDoublePoint); var MinBound, MaxBound: TDoublePoint; begin MinBound.X:= Min(FFiguresBounds.TopLeft.X, 0); MinBound.Y:= Min(FFiguresBounds.TopLeft.Y, 0); MaxBound.X:= Max(FFiguresBounds.TopLeft.X+FFiguresBounds.Width, FOriginalSize.X); MaxBound.Y:= Max(FFiguresBounds.TopLeft.Y+FFiguresBounds.Height, FOriginalSize.Y); FLocalSpace.TopLeft:= AValue; FWorldSpace.TopLeft.X:= Min(FLocalSpace.TopLeft.X, MinBound.X); FWorldSpace.TopLeft.Y:= Min(FLocalSpace.TopLeft.Y, MinBound.Y); FWorldSpace.Width:= Max(FLocalSpace.TopLeft.X+FLocalSpace.Width, MaxBound.X)-FWorldSpace.TopLeft.X; FWorldSpace.Height:= Max(FLocalSpace.TopLeft.Y+FLocalSpace.Height, MaxBound.Y)-FWorldSpace.TopLeft.Y; if Assigned(FPositionChangeEvent) then FPositionChangeEvent; end; procedure TPaintSpace.SetPosSafely(AValue: TDoublePoint); var MinBound, MaxBound: TDoublePoint; begin FWorldSpace.Height:= Max(FLocalSpace.TopLeft.Y+FLocalSpace.Height, MaxBound.Y)-FWorldSpace.TopLeft.Y; if (AValue.X < FWorldSpace.TopLeft.X) or (AValue.Y < FWorldSpace.TopLeft.Y) or (AValue.X+FLocalSpace.Width > FWorldSpace.Width) or (AValue.Y+FLocalSpace.Height > FWorldSpace.Height) then Exit; FLocalSpace.TopLeft:= AValue; if Assigned(FPositionChangeEvent) then FPositionChangeEvent; end; procedure TPaintSpace.SetScale(AValue: Double); begin if (AValue <= 0) or (AValue > MAX_SCALE) then Exit; FLocalSpace.Width:= FPaintBox.Width/AValue; FLocalSpace.Height:= FPaintBox.Height/AValue; if Assigned(FScaleChangeEvent) then FScaleChangeEvent; end; function TPaintSpace.GetScale: Double; begin Result:= FPaintBox.Width/FLocalSpace.Width; end; function TPaintSpace.GetPosition: TDoublePoint; begin Result:= GetDoublePoint(FLocalSpace.TopLeft.X, FLocalSpace.TopLeft.Y); end; function TPaintSpace.GetPaintBox: TPaintBox; begin Result:= FPaintBox; end; function TPaintSpace.ToWorld(APoint: TDoublePoint): TDoublePoint; begin Result:= APoint/Scale + Position; end; function TPaintSpace.ToLocal(APoint: TDoublePoint): TPoint; begin Result:= ((APoint - Position) * Scale).ToPoint; end; function TPaintSpace.ToLocal(APointArray: TDoublePointArray): TPointArray; var i: Integer; begin SetLength(Result, Length(APointArray)); for i:= 0 to High(APointArray) do Result[i]:= ToLocal(APointArray[i]); end; function DoubleRect(AWidth, AHeight: Double): TDoubleRect; begin Result.Width:= AWidth; Result.Height:= AHeight; end; end.
unit VirtualEditTree; interface uses SysUtils, Windows, Messages, Classes, Controls, ActiveX, VirtualTrees, VTEditors, StdCtrls, ComCtrls; type TVirtualEditableColumn = class; TCustomVirtualEditTree = class; TEditLinkName = type string; TComboDrawItemEvent = procedure(Sender: TCustomVirtualEditTree; Column: TVirtualEditableColumn; Control: TComboBox; Index: Integer; Rect: TRect; State: TOwnerDrawState) of object; TComboMeasureItemEvent = procedure (Sender: TCustomVirtualEditTree; Column: TVirtualEditableColumn; Control: TComboBox; Index: Integer; var Height: Integer) of object; TVirtualEditableColumn = class(TVirtualTreeColumn, IUnknown) protected {private} FEditable: Boolean; FLink: TCustomEditLink; function GetEditLinkName: TEditLinkName; procedure SetEditLinkName(const Value: TEditLinkName); procedure SetLink(const Value: TCustomEditLink); protected function CanEdit(Node: PVirtualNode): Boolean; virtual; function CreateEditor(Node: PVirtualNode): IVTEditLink; virtual; protected // IUnknown function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; // IComboCustomDraw procedure ComboDrawItem(Sender: TComboEditLink; Control: TComboBox; Index: Integer; Rect: TRect; State: TOwnerDrawState); virtual; procedure ComboMeasureItem(Sender: TComboEditLink; Control: TComboBox; Index: Integer; var Height: Integer); virtual; public constructor Create(ACollection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; published property Editable: Boolean read FEditable write FEditable default True; property EditLinkName: TEditLinkName read GetEditLinkName write SetEditLinkName; property EditLink: TCustomEditLink read FLink write SetLink; end; TVTEditHeader = class(TVTHeader) protected {private} FLink: TCustomEditLink; function GetEditLinkName: TEditLinkName; procedure SetEditLinkName(const Value: TEditLinkName); procedure SetLink(const Value: TCustomEditLink); protected function CreateEditor(Node: PVirtualNode): IVTEditLink; virtual; protected // IUnknown function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; public destructor Destroy; override; published property EditLinkName: TEditLinkName read GetEditLinkName write SetEditLinkName; property EditLink: TCustomEditLink read FLink write SetLink; end; TCustomVirtualEditTree = class(TCustomVirtualStringTree) protected {private} FOnComboDrawItem: TComboDrawItemEvent; FOnComboMeasureItem: TComboMeasureItemEvent; procedure WMChar(var Message: TWMChar); message WM_CHAR; protected function GetHeaderClass: TVTHeaderClass; override; function GetColumnClass: TVirtualTreeColumnClass; override; function DoCreateEditor(Node: PVirtualNode; Column: TColumnIndex): IVTEditLink; override; procedure DoComboDrawItem(Sender: TVirtualEditableColumn; Control: TComboBox; Index: Integer; Rect: TRect; State: TOwnerDrawState); virtual; procedure DoComboMeasureItem(Sender: TVirtualEditableColumn; Control: TComboBox; Index: Integer; var Height: Integer); virtual; property OnColumnComboDrawItem: TComboDrawItemEvent read FOnComboDrawItem write FOnComboDrawItem; property OnColumnComboMeasureItem: TComboMeasureItemEvent read FOnComboMeasureItem write FOnComboMeasureItem; public function CanEdit(Node: PVirtualNode; Column: TColumnIndex): Boolean; override; end; TVirtualEditTree = class(TCustomVirtualEditTree) protected {private} function GetHeader: TVTEditHeader; procedure SetHeader(Value: TVTEditHeader); function GetOptions: TStringTreeOptions; procedure SetOptions(const Value: TStringTreeOptions); protected function GetOptionsClass: TTreeOptionsClass; override; public property Canvas; property DragSelection; property DragColumn; published property AccessibleName; property Action; property Align; property Alignment; property Anchors; property AnimationDuration; property AutoExpandDelay; property AutoScrollDelay; property AutoScrollInterval; property Background; property BackgroundOffsetX; property BackgroundOffsetY; property BiDiMode; property BevelEdges; property BevelInner; property BevelOuter; property BevelKind; property BevelWidth; property BorderStyle; property BottomSpace; property ButtonFillMode; property ButtonStyle; property BorderWidth; property ChangeDelay; property CheckImageKind; property ClipboardFormats; property Color; property Colors; property Constraints; property Ctl3D; property CustomCheckImages; property DefaultNodeHeight; property DefaultPasteMode; property DefaultText; property DragCursor; property DragHeight; property DragKind; property DragImageKind; property DragMode; property DragOperations; property DragType; property DragWidth; property DrawSelectionMode; property EditDelay; property Enabled; property Font; property Header: TVTEditHeader read GetHeader write SetHeader; property HintAnimation; property HintMode; property HotCursor; property Images; property IncrementalSearch; property IncrementalSearchDirection; property IncrementalSearchStart; property IncrementalSearchTimeout; property Indent; property LineMode; property LineStyle; property Margin; property NodeAlignment; property NodeDataSize; property ParentBiDiMode; property ParentColor default False; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property RootNodeCount; property ScrollBarOptions; property SelectionBlendFactor; property SelectionCurveRadius; property ShowHint; property StateImages; property TabOrder; property TabStop default True; property TextMargin; property TreeOptions: TStringTreeOptions read GetOptions write SetOptions; property Visible; property WantTabs; property OnAdvancedHeaderDraw; property OnAfterCellPaint; property OnAfterItemErase; property OnAfterItemPaint; property OnAfterPaint; property OnBeforeCellPaint; property OnBeforeItemErase; property OnBeforeItemPaint; property OnBeforePaint; property OnChange; property OnChecked; property OnCheckHotTrack; property OnChecking; property OnClick; property OnCollapsed; property OnCollapsing; property OnColumnClick; property OnColumnDblClick; property OnColumnResize; property OnCompareNodes; {$ifdef COMPILER_5_UP} property OnContextPopup; {$endif COMPILER_5_UP} property OnCreateDataObject; property OnCreateDragManager; property OnCreateEditor; property OnDblClick; property OnDragAllowed; property OnDragOver; property OnDragDrop; property OnEditCancelled; property OnEdited; property OnEditing; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnExpanded; property OnExpanding; property OnFocusChanged; property OnFocusChanging; property OnFreeNode; property OnGetCellIsEmpty; property OnGetCursor; property OnGetHeaderCursor; property OnGetText; property OnGetEditText; property OnPaintText; property OnGetHelpContext; property OnGetImageIndex; property OnGetImageIndexEx; property OnGetHint; property OnGetLineStyle; property OnGetNodeDataSize; property OnGetPopupMenu; property OnGetUserClipboardFormats; property OnHeaderClick; property OnHeaderDblClick; property OnHeaderDragged; property OnHeaderDraggedOut; property OnHeaderDragging; property OnHeaderDraw; property OnHeaderDrawQueryElements; property OnHeaderMouseDown; property OnHeaderMouseMove; property OnHeaderMouseUp; property OnHotChange; property OnAdvHotChange; property OnIncrementalSearch; property OnInitChildren; property OnInitNode; property OnKeyAction; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnLoadNode; property OnMeasureItem; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnNewText; property OnNodeCopied; property OnNodeCopying; property OnNodeMoved; property OnNodeMoving; property OnPaintBackground; property OnRenderOLEData; property OnResetNode; property OnResize; property OnSaveNode; property OnScroll; property OnShortenString; property OnShowScrollbar; property OnStartDock; property OnStartDrag; property OnStateChange; property OnStructureChange; property OnUpdating; property OnColumnComboDrawItem; property OnColumnComboMeasureItem; end; implementation { TVirtualEditableColumn } constructor TVirtualEditableColumn.Create(ACollection: TCollection); begin inherited; FEditable := True; end; destructor TVirtualEditableColumn.Destroy; begin FreeAndNil(FLink); inherited; end; function TVirtualEditableColumn.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; function TVirtualEditableColumn._AddRef: Integer; begin Result := -1; end; function TVirtualEditableColumn._Release: Integer; begin Result := -1; end; procedure TVirtualEditableColumn.ComboDrawItem(Sender: TComboEditLink; Control: TComboBox; Index: Integer; Rect: TRect; State: TOwnerDrawState); begin TCustomVirtualEditTree(Owner.Header.Treeview).DoComboDrawItem(Self, Control, Index, Rect, State); end; procedure TVirtualEditableColumn.ComboMeasureItem(Sender: TComboEditLink; Control: TComboBox; Index: Integer; var Height: Integer); begin TCustomVirtualEditTree(Owner.Header.Treeview).DoComboMeasureItem(Self, Control, Index, Height); end; procedure TVirtualEditableColumn.Assign(Source: TPersistent); begin if Source is TVirtualEditableColumn then begin FEditable := TVirtualEditableColumn(Source).FEditable; EditLinkName := TVirtualEditableColumn(Source).EditLinkName; end else inherited; end; function TVirtualEditableColumn.GetEditLinkName: TEditLinkName; begin if Assigned(FLink) then Result := FLink.GetName else Result := ''; end; procedure TVirtualEditableColumn.SetEditLinkName(const Value: TEditLinkName); var EditLinkClass: TCustomEditLinkClass; begin FreeAndNil(FLink); EditLinkClass := GetEditLinkClass(Value); if Assigned(EditLinkClass) then FLink := EditLinkClass.Create(Self); end; function TVirtualEditableColumn.CanEdit(Node: PVirtualNode): Boolean; begin Result := FEditable; end; function TVirtualEditableColumn.CreateEditor(Node: PVirtualNode): IVTEditLink; begin if Assigned(FLink) then Result := FLink.Link else Result := TStringEditLink.Create; end; procedure TVirtualEditableColumn.SetLink(const Value: TCustomEditLink); begin FLink.Assign(Value); end; { TCustomVirtualEditTree } procedure TCustomVirtualEditTree.WMChar(var Message: TWMChar); begin with Message do if (CharCode in [Ord(^H), 32..255] - [VK_HOME, VK_END, VK_PRIOR, VK_NEXT, VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT, VK_BACK, VK_TAB, VK_ADD, VK_SUBTRACT, VK_MULTIPLY, VK_DIVIDE, VK_ESCAPE, VK_SPACE, Ord('+'), Ord('-'), Ord('*'), Ord('/')]) and not Assigned(EditLink) then if Assigned(FocusedNode) and EditNode(FocusedNode, FocusedColumn) and Assigned(EditLink) then begin EditLink.ProcessMessage(TMessage(Message)); Message.CharCode := 0; end; inherited; end; function TCustomVirtualEditTree.GetHeaderClass: TVTHeaderClass; begin Result := TVTEditHeader; end; function TCustomVirtualEditTree.GetColumnClass: TVirtualTreeColumnClass; begin Result := TVirtualEditableColumn; end; function TCustomVirtualEditTree.CanEdit(Node: PVirtualNode; Column: TColumnIndex): Boolean; begin Result := inherited CanEdit(Node, Column); if Result and (Column >= 0) then Result := TVirtualEditableColumn(Header.Columns[Column]).Editable; end; function TCustomVirtualEditTree.DoCreateEditor(Node: PVirtualNode; Column: TColumnIndex): IVTEditLink; begin Result := nil; if Assigned(OnCreateEditor) then OnCreateEditor(Self, Node, Column, Result); if (Result = nil) then if Column >= 0 then Result := TVirtualEditableColumn(Header.Columns[Column]).CreateEditor(Node) else Result := TVTEditHeader(Header).CreateEditor(Node) else Result := inherited DoCreateEditor(Node, Column); end; procedure TCustomVirtualEditTree.DoComboDrawItem(Sender: TVirtualEditableColumn; Control: TComboBox; Index: Integer; Rect: TRect; State: TOwnerDrawState); begin if Assigned(FOnComboDrawItem) then FOnComboDrawItem(Self, Sender, Control, Index, Rect, State); end; procedure TCustomVirtualEditTree.DoComboMeasureItem(Sender: TVirtualEditableColumn; Control: TComboBox; Index: Integer; var Height: Integer); begin if Assigned(FOnComboMeasureItem) then FOnComboMeasureItem(Self, Sender, Control, Index, Height); end; { TVirtualEditTree } function TVirtualEditTree.GetOptionsClass: TTreeOptionsClass; begin Result := TStringTreeOptions; end; function TVirtualEditTree.GetOptions: TStringTreeOptions; begin Result := TStringTreeOptions(inherited TreeOptions); end; procedure TVirtualEditTree.SetOptions(const Value: TStringTreeOptions); begin inherited TreeOptions := Value; end; function TVirtualEditTree.GetHeader: TVTEditHeader; begin Result := TVTEditHeader(inherited Header); end; procedure TVirtualEditTree.SetHeader(Value: TVTEditHeader); begin inherited Header := Value; end; { TVTEditHeader } destructor TVTEditHeader.Destroy; begin FreeAndNil(FLink); inherited; end; function TVTEditHeader.GetEditLinkName: TEditLinkName; begin if Assigned(FLink) then Result := FLink.GetName else Result := ''; end; procedure TVTEditHeader.SetEditLinkName(const Value: TEditLinkName); var EditLinkClass: TCustomEditLinkClass; begin FreeAndNil(FLink); EditLinkClass := GetEditLinkClass(Value); if Assigned(EditLinkClass) then FLink := EditLinkClass.Create(Self); end; procedure TVTEditHeader.SetLink(const Value: TCustomEditLink); begin FLink.Assign(Value); end; function TVTEditHeader.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; function TVTEditHeader._AddRef: Integer; begin Result := -1; end; function TVTEditHeader._Release: Integer; begin Result := -1; end; function TVTEditHeader.CreateEditor(Node: PVirtualNode): IVTEditLink; begin if Assigned(FLink) then Result := FLink.Link else Result := TStringEditLink.Create; end; end.
namespace Sugar.TestFramework; interface type IAsyncToken = public interface method Done; method Done(Ex: Exception); method Wait; end; {$IF COOPER} AsyncToken = assembly class (IAsyncToken) private fEvent: Object := new Object; readonly; fOpen: Boolean := false; fException: Exception := nil; public method Done; method Done(Ex: Exception); {$HIDE W8} method Wait; end; {$ELSEIF WINDOWS_PHONE} AsyncToken = assembly class (IAsyncToken) public method Done; empty; method Done(Ex: Exception); empty; method Wait; empty; end; {$ELSEIF ECHOES} AsyncToken = assembly class (IAsyncToken) private fEvent: System.Threading.AutoResetEvent := new System.Threading.AutoResetEvent(false); fException: Exception := nil; public method Done; method Done(Ex: Exception); method Wait; end; {$ELSEIF NOUGAT} AsyncToken = assembly class (IAsyncToken) private fEvent: Foundation.NSCondition := new Foundation.NSCondition; fOpen: Boolean := false; fException: Exception := nil; public method Done; method Done(Ex: Exception); method Wait; end; {$ENDIF} implementation {$IF COOPER} method AsyncToken.Done; begin locking fEvent do begin fOpen := true; fEvent.notify; end; end; method AsyncToken.Done(Ex: Exception); begin locking fEvent do begin fOpen := true; fException := Ex; fEvent.notify; end; end; method AsyncToken.Wait; begin locking fEvent do while not fOpen do fEvent.wait; if assigned(fException) then raise fException; end; {$ELSEIF WINDOWS_PHONE} {$ELSEIF ECHOES} method AsyncToken.Done; begin locking fEvent do fEvent.Set; end; method AsyncToken.Done(Ex: Exception); begin locking fEvent do begin fException := Ex; fEvent.Set; end; end; method AsyncToken.Wait; begin if fEvent.WaitOne then if assigned(fException) then raise fException; end; {$ELSEIF NOUGAT} method AsyncToken.Done; begin locking fEvent do begin fOpen := true; fEvent.broadcast; end; end; method AsyncToken.Done(Ex: Exception); begin locking fEvent do begin fOpen := true; fException := Ex; fEvent.broadcast; end; end; method AsyncToken.Wait; begin fEvent.lock; fOpen := false; while not fOpen do fEvent.wait; fEvent.unlock; if assigned(fException) then raise fException; end; {$ENDIF} end.
unit Form_ImportEMail; {$H+} {*************************************************************} {*} interface {*} {*************************************************************} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Tadjform, StdCtrls, Buttons, BMPBtn, Grids,ActiveX, LanImp,ExtCtrls,IniFiles,Sqlctrls,LblMemo, ComCtrls, Spin; function ImportEmail(var Params: TLanImportInfo): integer; function CommitImportEmail: boolean; function GetIEMMessageError:string; type TFormImportEMail = class(TAdjustForm) lblmemoMessage: TLabelMemo; GroupBox1: TGroupBox; checkImportNoteText: TCheckBox; comboFiles: TComboBox; lFiles: TLabel; SGMess: TStringGrid; btnImport: TBMPBtn; btnCancel: TBMPBtn; btnViewDocument: TBMPBtn; SGIDMsg: TStringGrid; procedure FormCreate(Sender: TObject); procedure btnImportClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormShow(Sender: TObject); procedure SGMessSelectCell(Sender: TObject; Col, Row: Integer; var CanSelect: Boolean); procedure SGMessDblClick(Sender: TObject); procedure btnViewDocumentClick(Sender: TObject); private procedure FillGridMessages; procedure ResizeCols; public end; {*************************************************************} {*} implementation {*} {*************************************************************} {$R *.DFM} Uses ComObj,Filefuns,ShellApi; const colCount = 4; colFilesCount = 0; colFrom = 1; colSubject = 2; colReceived = 3; colMessage = 4; colw = 10; colwFilesCount = colw*5; colwSubject = colw*15; colwReceived = colw*12; var ImportedMessageID: string; MO: variant; colwMessage: integer=colw*40; colwFrom: integer=colw*22; IEMErrorMsg: string; Error: boolean; FormImportEMail: TFormImportEMail; AttemptImport: integer; MsgCount: integer; FileDesc, FileName: string; TempPath: array [0..255] of char; ProName,Pass:string; function GetIEMMessageError:string; begin Result:=IEMErrorMsg; end; //------------------------------------------------------------ function CommitImportEmail: boolean; var Logon:boolean; begin if ImportedMessageID='' then begin Result:=False; exit; end; Logon:=False; Error:=False; try OleInitialize(nil); MO:=CreateOleObject('MAPI.Session'); MO.Logon(profileName:=ProName,profilePassword:=Pass); Logon:=True; MO.GetMessage(ImportedMessageID).Delete; DelFile(FileName); except on e:Exception do begin IEMErrorMsg:=e.Message; Result:=False; Error:=True; end; end; if not Error then Result:=True; if Logon then MO.Logoff; end; function ImportEmail(var Params:TLanImportInfo): integer; var IniFile:TIniFile; begin Error:=False; IEMErrorMsg:=''; IniFile:=TIniFile.Create(Params.IniFileName); ProName:=IniFile.ReadString(LanImpSect,LanImpName,''); Pass:=IniFile.ReadString(LanImpSect,LanImpPass,''); IniFile.Free; try OleInitialize(nil); MO:=CreateOleObject('MAPI.Session'); MO.Logon(profileName:=ProName,profilePassword:=Pass); except on e:Exception do begin IEMErrorMsg:=e.Message; Error:=True; end; end; if Error then begin Result:=2; exit; end; FormImportEMail:=TFormImportEMail.Create(nil); ImportedMessageID:=''; with FormImportEMail do begin ShowModal; if AttemptImport=0 then begin StrPCopy(Params.ResultFileName,FileName); StrPCopy(Params.ResultDescription,FileDesc); end; Result:=AttemptImport; end; MO.Logoff; FormImportEMail.Free; end; procedure TFormImportEMail.FormCreate(Sender: TObject); begin Section:='ImportEMail'; GetTempPath(200,@TempPath[0]); with SGMess do begin ColCount:=colCount; Cells[colFilesCount, 0]:='Файлов'; Cells[colFrom, 0] :='Отправитель'; Cells[colSubject, 0] :='Тема'; Cells[colReceived, 0] :='Получено'; ResizeCols; lblmemoMessage.Memo.ScrollBars:=ssboth; end; end; procedure TFormImportEMail.ResizeCols; begin with SGMess do begin colwFrom:=Width-(colwFilesCount+colwSubject+colwReceived); ColWidths[colFilesCount] :=colwFilesCount; ColWidths[colFrom] :=colwFrom; ColWidths[colSubject] :=colwSubject; ColWidths[colReceived] :=colwReceived; end; end; //------------------------------------------------------------ procedure TFormImportEMail.btnImportClick(Sender: TObject); var MapiMessage: variant; begin ImportedMessageID:=SGIDMsg.Cells[0,SGMess.Row]; FileName:=''; FileDesc:=''; try MapiMessage:=MO.GetMessage(ImportedMessageID); if comboFiles.Visible then begin FileName:=TempPath+ComboFiles.Text; MapiMessage.Attachments.Item[comboFiles.ItemIndex+1].WriteToFile(FileName); end; if (checkImportNoteText.Visible)and(checkImportNoteText.State=cbChecked) then FileDesc:=MapiMessage.Text; if (FileName<>'')or(FileDesc<>'') then begin AttemptImport:=0; Close; end; except on e:Exception do begin IEMErrorMsg:=e.Message; AttemptImport:=2; end; end; end; //------------------------------------------------------------ procedure TFormImportEMail.btnCancelClick(Sender: TObject); begin AttemptImport:=1; Close; end; //------------------------------------------------------------ procedure TFormImportEMail.FillGridMessages; var MapiMessages,MapiMessage:variant; begin SGMess.RowCount:=2; SGMess.FixedRows:=1; MsgCount:=0; MapiMessages:=MO.Inbox.Messages; MapiMessages.Sort[2]; MapiMessage:=MapiMessages.GetFirst; while TVarData(MapiMessage).VBoolean do with SGMess do begin MsgCount:=MsgCount+1; RowCount:=MsgCount+1; SGIDMsg.RowCount:=MsgCount+1; SGIDMsg.Cells[0,MsgCount]:=MapiMessage.ID; Cells[colFilesCount,MsgCount]:=IntTostr(MapiMessage.Attachments.Count); Cells[colFrom,MsgCount]:=MapiMessage.Sender.Name+' ['+MapiMessage.Sender.Address+']'; Cells[colSubject,MsgCount]:=MapiMessage.Subject; Cells[colReceived,MsgCount]:=DateToStr(MapiMessage.TimeReceived); MapiMessage:=MapiMessages.GetNext; end; btnImport.Enabled:=MsgCount<>0; end; procedure TFormImportEMail.FormResize(Sender: TObject); begin ResizeCols; end; //------------------------------------------------------------ procedure TFormImportEMail.FormShow(Sender: TObject); var tmp:boolean; begin FillGridMessages; if MsgCount>0 then SGMessSelectCell(Sender,0,1,tmp) else begin btnViewDocument.Enabled:=False; comboFiles.Visible:=False; lFiles.Visible:=False; checkImportNoteText.Visible:=False; end; AttemptImport:=1; end; procedure TFormImportEMail.SGMessSelectCell(Sender: TObject; Col, Row: Integer; var CanSelect: Boolean); var MapiMessage: variant; i: integer; begin if Row=0 then exit; MapiMessage:=MO.GetMessage(SGIDMsg.Cells[0,Row]); lblmemoMessage.Memo.Lines.Clear; lblmemoMessage.Memo.Lines.Add(MapiMessage.Text); lblmemoMessage.Memo.SelStart:=0; lblmemoMessage.Memo.SelLength:=0; checkImportNoteText.Visible:=MapiMessage.Text<>''; lFiles.Visible:=MapiMessage.Attachments.Count<>0; comboFiles.Visible:=lFiles.Visible; comboFiles.Clear; for i:=1 to MapiMessage.Attachments.Count do begin if MapiMessage.Attachments.Item[i].Name<>'' then comboFiles.Items.Add(MapiMessage.Attachments.Item[i].Name) else comboFiles.Items.Add(MapiMessage.Attachments.Item[i].Source) end; if comboFiles.Visible then begin comboFiles.ItemIndex:=0; comboFiles.Text:=comboFiles.Items[0]; end; btnViewDocument.Enabled:=comboFiles.Visible; end; procedure TFormImportEMail.SGMessDblClick(Sender: TObject); begin btnImportClick(Sender); end; procedure TFormImportEMail.btnViewDocumentClick(Sender: TObject); var MapiMessage:variant; begin MapiMessage:=MO.GetMessage(SGIDMsg.Cells[0,SGMess.Row]); FileName:=TempPath+ComboFiles.Text; MapiMessage.Attachments.Item[comboFiles.ItemIndex+1].WriteToFile(FileName); ShellExecute(0,'Open',PChar(ComboFiles.Text),'',TempPath,SW_SHOWNORMAL); end; end.
{ SELECT RDB$GET_CONTEXT('SYSTEM', 'ENGINE_VERSION') FROM RDB$DATABASE; } unit UObjetoFirebird; interface uses Windows, Classes, SysUtils, Registry, Tlhelp32, PsAPI; type TFileUtil = class(TObject) private public class function getPathProcesso(exeFileName: String): String; static; class function getVersaoExecutavelExterno(Executavel: String): Double; static; end; TFirebirdUtil = class(TObject) private public class function getVersaoFirebird(): Double; static; class function getPathFirebird(): String; static; class function isFirebird21(): Boolean; static; class function isFirebird25(): Boolean; static; class function isFirebird30(): Boolean; static; end; implementation { TFileUtil } class function TFileUtil.getPathProcesso(exeFileName: String): String; var ContinueLoop: BOOL; FSnapshotHandle: THandle; FProcessEntry32: TProcessEntry32w; function GetPathFromPID(const PID: cardinal): String; var hProcess: THandle; Path: array [0 .. MAX_PATH - 1] of char; begin hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, PID); if hProcess <> 0 Then try if GetModuleFileNameEx(hProcess, 0, Path, MAX_PATH) = 0 Then RaiseLastOSError; Result := Path; finally CloseHandle(hProcess) end else RaiseLastOSError; end; begin FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); FProcessEntry32.dwSize := SizeOf(FProcessEntry32); ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32); Result := ''; while Integer(ContinueLoop) <> 0 do begin if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) = UpperCase(exeFileName)) or (UpperCase(FProcessEntry32.szExeFile) = UpperCase(exeFileName))) Then begin Result := GetPathFromPID(FProcessEntry32.th32ProcessID); // Essa linha nao funciona end; ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32); end; CloseHandle(FSnapshotHandle); end; class function TFileUtil.getVersaoExecutavelExterno(Executavel: String): Double; var VerInfoSize: DWORD; VerInfo: Pointer; VerValueSize: DWORD; VerValue: PVSFixedFileInfo; Dummy: DWORD; VersaoStr: String; begin Result := 0; VersaoStr := ''; VerInfoSize := GetFileVersionInfoSize(PChar(Executavel), Dummy); if VerInfoSize = 0 Then Exit; GetMem(VerInfo, VerInfoSize); GetFileVersionInfo(PChar(Executavel), 0, VerInfoSize, VerInfo); VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize); with VerValue^ do begin VersaoStr := IntToStr(dwFileVersionMS shr 16); VersaoStr := VersaoStr + ',' + IntToStr(dwFileVersionMS and $FFFF); VersaoStr := VersaoStr + IntToStr(dwFileVersionLS shr 16); VersaoStr := VersaoStr + IntToStr(dwFileVersionLS and $FFFF); end; FreeMem(VerInfo, VerInfoSize); Result := StrToFloatDef(VersaoStr, 0); end; { TFirebirdUtil } class function TFirebirdUtil.getPathFirebird(): String; begin Result := TFileUtil.getPathProcesso('fbserver.exe'); if (Result = EmptyStr) Then Result := TFileUtil.getPathProcesso('fbguard.exe'); end; class function TFirebirdUtil.getVersaoFirebird(): Double; var PathExecutavelFB: String; begin Result := 0; PathExecutavelFB := TFirebirdUtil.getPathFirebird; if (PathExecutavelFB <> EmptyStr) Then Result := TFileUtil.getVersaoExecutavelExterno(PathExecutavelFB); end; class function TFirebirdUtil.isFirebird21(): Boolean; var Versao: Double; begin Versao := TFirebirdUtil.getVersaoFirebird; Result := (Versao >= 2.1) and (Versao < 2.2); end; class function TFirebirdUtil.isFirebird25(): Boolean; var Versao: Double; begin Versao := TFirebirdUtil.getVersaoFirebird; Result := (Versao >= 2.5) and (Versao < 2.6); end; class function TFirebirdUtil.isFirebird30(): Boolean; var Versao: Double; begin Versao := TFirebirdUtil.getVersaoFirebird; Result := (Versao >= 3.0) and (Versao < 3.1); end; end.
program HelloWorld; begin { сюда вкорячу { многострочный комментарий, который бы должен бы { закрываться первой закрывающей скобкой } writeln('Hello, World!') { оператор вывода строки } end.
unit xe_JON36; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, MSHTML, System.JSON, MSXML2_TLB, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore, dxSkinOffice2010Silver, dxSkinSharp, cxLabel, cxTextEdit, Vcl.Menus, Vcl.StdCtrls, cxButtons, Vcl.OleCtrls, SHDocVw, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, dxSkinMetropolisDark, dxSkinOffice2007Silver; type TFrm_JON36 = class(TForm) edtEmail: TcxTextEdit; cxLabel1: TcxLabel; btnSendMail: TcxButton; btnClose: TcxButton; WebBrowser1: TWebBrowser; procedure WebBrowser1DocumentComplete(ASender: TObject; const pDisp: IDispatch; const URL: OleVariant); procedure btnCloseClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnSendMailClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); private function IsValidEmail(const Value: string): boolean; function pGetEMail(sCuSeq: String): String; { Private declarations } public { Public declarations } FTid, FEmail, FTAmt, FCuSeq : String; end; var Frm_JON36: TFrm_JON36; implementation {$R *.dfm} uses xe_Func, xe_Msg, xe_xml, xe_Query, xe_GNL, xe_Dm; procedure TFrm_JON36.btnCloseClick(Sender: TObject); begin Close; end; procedure TFrm_JON36.btnSendMailClick(Sender: TObject); Var sUrl : String; begin if Not IsValidEmail(edtEmail.Text) then begin GMessagebox('이메일 형식을 확인하세요.', CDMSE); edtEmail.SetFocus; Exit; end; // FTid := 'CMNP00000m01162008311510490857'; sUrl := Format('https://npg.nicepay.co.kr/issue/IssueLoader.do?TID=%s&type=0', [FTid]); WebBrowser1.Silent; WebBrowser1.Navigate(sUrl); end; procedure TFrm_JON36.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFrm_JON36.FormCreate(Sender: TObject); var Save: LongInt; // 폼타이틀 제거용. begin try //==================================================== // 폼 타이틀 제거.. Save := GetWindowLong(Handle, GWL_STYLE); if (Save and ws_Caption) = ws_Caption then begin case BorderStyle of bsSingle, bsSizeable: SetWindowLong(Handle, GWL_STYLE, Save and (not (WS_CAPTION)) or WS_BORDER); end; Height := Height - getSystemMetrics(SM_CYCAPTION); Self.Refresh; end; except end; SetWindowPos(Self.handle, HWND_TOPMOST, Self.Left, Self.Top, Self.Width, Self.Height, 0); end; procedure TFrm_JON36.FormDestroy(Sender: TObject); begin Frm_JON36 := Nil; end; procedure TFrm_JON36.FormShow(Sender: TObject); begin fSetFont(Frm_JON36, GS_FONTNAME); fSetSkin(Frm_JON36); edtEmail.Text := pGetEMail(FCuSeq); end; procedure TFrm_JON36.WebBrowser1DocumentComplete(ASender: TObject; const pDisp: IDispatch; const URL: OleVariant); var el, el1, el2 : IHTMLElement; idHttp : TIdHTTP; LHandler: TIdSSLIOHandlerSocketOpenSSL; Param1, Param2, Param3, Param4, Param5, Param6, Param7, Param8, Param9, Param10, Param11, Param12, Param13, Param14, Param15, Param16, Param17, Param18, Param19, Param20, Param21 : String; Requesthash, RequestBody: TStream; sUrl, sSource, sResult, sHash : String; jObj : TJSONObject; begin if WebBrowser1.Application = pDisp then begin if Text <> 'Level2' then begin el := (WebBrowser1.Document as IHTMLDocument3).getElementById('ordNm'); if Assigned(el) then el.setAttribute('value', '대리운전', 0); el1 := (WebBrowser1.Document as IHTMLDocument3).getElementById('appAmt'); if Assigned(el1) then el1.setAttribute('value', FTAmt, 0); if (Assigned(el)) And (Assigned(el1)) then begin Text := 'Level2'; ExecuteJavaScript(WebBrowser1,'showCardIssue();') end; end else begin Text := 'Level3'; el2 := (WebBrowser1.Document as IHTMLDocument3).getElementById('email_addr'); if Assigned(el2) then begin Param1 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'TID'); Param2 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'ord_nm'); Param3 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'app_dt'); Param4 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'app_tm'); Param5 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'goods_nm'); Param6 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'goods_amt'); Param7 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'co_nm'); Param8 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'tel_no'); Param9 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'app_no'); Param10 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'instmnt_mon'); Param11 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'moid'); Param12 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'mailk'); Param13 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'bank_nm'); Param14 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'accnt_no'); Param15 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'vacct_no'); Param16 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'cp_no'); Param17 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'fn_nm'); Param18 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'cc_dt'); Param19 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'cc_tm'); Param20 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'mid_url'); Param21 := ExecuteJavaScriptGetNameValue(WebBrowser1, 'svc_nm'); idHttp := TIdHTTP.Create(Nil); LHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil); try idHttp.ConnectTimeout := 3 * 1000; idHttp.ReadTimeout := 3 * 1000; idHttp.HandleRedirects := True; idHttp.Request.Charset := 'utf-8'; idHttp.Request.ContentType := 'application/json'; idHttp.IOHandler := LHandler; // hash값 추가됨 2021.12.03 LYB sUrl := 'https://npg.nicepay.co.kr/issue/createHashVal.do'; sSource := 'currency_type=KRW&p_ord_val=&org_p_val=' + '&hashVal=' + '&email_addr=' + Trim(edtEmail.Text) + '&selState=0&TID='+ Param1 + '&ord_nm=' + UrlEncode(UTF8Encode(Param2)) + '&app_dt='+Param3+ '&app_tm='+Param4+ '&goods_nm='+ UrlEncode(UTF8Encode(Param5)) + '&goods_amt='+Param6+ '&co_nm=' + UrlEncode(UTF8Encode(Param7)) + '&tel_no='+Param8+ '&app_no='+Param9+ '&instmnt_mon='+Param10+ '&moid='+Param11+ '&mailk='+Param12+ '&bank_nm='+Param13+ '&accnt_no='+Param14+ '&vacct_no='+Param15+ '&cp_no='+Param16+ '&fn_nm='+Param17+ '&cc_dt='+Param18+ '&cc_tm='+Param19+ '&mid_url='+Param20+ '&svc_nm=' + UrlEncode(UTF8Encode(Param21)); Requesthash := TStringStream.Create(sSource, TEncoding.UTF8); sResult := idHttp.Post(sUrl, Requesthash); jObj := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(sResult), 0) as TJSONObject; sHash := jObj.Get('hashVal').JsonValue.Value; sUrl := 'https://npg.nicepay.co.kr/issue/sendMailIssue.do'; sSource := 'currency_type=KRW&p_ord_val=&org_p_val=' + '&hashVal=' + sHash + '&email_addr=' + Trim(edtEmail.Text) + '&selState=0&TID='+ Param1 + '&ord_nm=' + UrlEncode(UTF8Encode(Param2)) + '&app_dt='+Param3+ '&app_tm='+Param4+ '&goods_nm='+ UrlEncode(UTF8Encode(Param5)) + '&goods_amt='+Param6+ '&co_nm=' + UrlEncode(UTF8Encode(Param7)) + '&tel_no='+Param8+ '&app_no='+Param9+ '&instmnt_mon='+Param10+ '&moid='+Param11+ '&mailk='+Param12+ '&bank_nm='+Param13+ '&accnt_no='+Param14+ '&vacct_no='+Param15+ '&cp_no='+Param16+ '&fn_nm='+Param17+ '&cc_dt='+Param18+ '&cc_tm='+Param19+ '&mid_url='+Param20+ '&svc_nm=' + UrlEncode(UTF8Encode(Param21)); RequestBody := TStringStream.Create(sSource, TEncoding.UTF8); sResult := idHttp.Post(sUrl, RequestBody); jObj := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(sResult), 0) as TJSONObject; Param1 := jObj.Get('code').JsonValue.Value; Param2 := jObj.Get('msg').JsonValue.Value; if Param1 = '00' then begin ShowMessage('메일 전송 완료'); Close; end else begin ShowMessage('메일 전송 중 오류 발생.'); end; finally LHandler.Free; idHttp.Free; end; end; end; end; end; function TFrm_JON36.IsValidEmail(const Value: string): boolean; function CheckAllowed(const s: string): boolean; var i: integer; begin Result := false; for i := 1 to Length(s) do begin // illegal char in s -> no valid address if not (s[i] in ['a'..'z', 'A'..'Z', '0'..'9', '_', '-', '.']) then Exit; end; Result := true; end; var i: integer; namePart, serverPart: string; begin // of IsValidEmail Result := false; i := Pos('@', Value); if (i = 0) or (pos('..', Value) > 0) then Exit; namePart := Copy(Value, 1, i - 1); serverPart := Copy(Value, i + 1, Length(Value)); if (Length(namePart) = 0) // @ or name missing or ((Length(serverPart) < 4)) {// name or server missing or } then Exit; // too short i := Pos('.', serverPart); // must have dot and at least 3 places from end if (i < 2) or (i > (Length(serverPart) - 2)) then Exit; Result := CheckAllowed(namePart) and CheckAllowed(serverPart); end; function TFrm_JON36.pGetEMail( sCuSeq : String) : String; var ls_TxLoad, ls_TxQry, ls_Msg_Err, sQueryTemp, ls_rxxml, sAlert : string; slReceive: TStringList; ErrCode: integer; xdom: msDomDocument; lst_Result: IXMLDomNodeList; ls_Rcrd: TStringList; bCheck : Boolean; begin bCheck := False; ls_TxLoad := GTx_UnitXmlLoad('SEL01.XML'); fGet_BlowFish_Query(GSQ_CUSTOMER_EMAIL, sQueryTemp); ls_TxQry := Format(sQueryTemp, [sCuSeq]); ls_TxLoad := StringReplace(ls_TxLoad, 'UserIDString', GT_USERIF.ID, [rfReplaceAll]); ls_TxLoad := StringReplace(ls_TxLoad, 'ClientVerString', VERSIONINFO, [rfReplaceAll]); ls_TxLoad := StringReplace(ls_TxLoad, 'ClientKeyString', 'GETEMAIL', [rfReplaceAll]); ls_TxLoad := StringReplace(ls_TxLoad, 'QueryString', ls_TxQry, [rfReplaceAll]); slReceive := TStringList.Create; try if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False) then begin ls_rxxml := slReceive[0]; if ls_rxxml <> '' then begin xdom := ComsDomDocument.Create; try if not xdom.loadXML(ls_rxxml) then Exit; ls_MSG_Err := GetXmlErrorCode(ls_rxxml); if ('0000' = ls_MSG_Err) then begin lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result'); ls_Rcrd := TStringList.Create; try Result := Trim(lst_Result.item[0].attributes.getNamedItem('Value').Text) finally ls_Rcrd.Free; end; end; finally xdom := Nil; end; end; end; finally FreeAndNil(slReceive); end; end; end.
{******************************************************************************} { CnPack For Delphi/C++Builder } { 中国人自己的开放源码第三方开发包 } { (C)Copyright 2001-2006 CnPack 开发组 } { ------------------------------------ } { } { 本开发包是开源的自由软件,您可以遵照 CnPack 的发布协议来修 } { 改和重新发布这一程序。 } { } { 发布这一开发包的目的是希望它有用,但没有任何担保。甚至没有 } { 适合特定目的而隐含的担保。更详细的情况请参阅 CnPack 发布协议。 } { } { 您应该已经和开发包一起收到一份 CnPack 发布协议的副本。如果 } { 还没有,可访问我们的网站: } { } { 网站地址:http://www.cnpack.org } { 电子邮件:master@cnpack.org } { } {******************************************************************************} unit ZhCommon; {* |<PRE> ================================================================================ * 软件名称:开发包基础库 * 单元名称:公共运行基础库单元 * 单元作者:CnPack开发组 * 备 注:该单元定义了组件包的基础类库 * 开发平台:PWin98SE + Delphi 5.0 * 兼容测试:PWin9X/2000/XP + Delphi 5/6 * 本 地 化:该单元中的字符串均符合本地化处理方式 * 单元标识:$Id: CnCommon.pas,v 1.42 2006/09/27 23:05:45 passion Exp $ * 修改记录: * 2005.08.02 by shenloqi * 增加了SameCharCounts,CharCounts ,RelativePath函数,重写了 * GetRelativePath函数 * 2005.07.08 by shenloqi * 修改了GetRelativePath函数,修改了FileMatchesExts函数,增加了 * 一系列通配符支持的函数:FileNameMatch,MatchExt,MatchFileName, * FileExtsToStrings,FileMasksToStrings,FileMatchesMasks * 2005.05.03 by hubdog * 增加ExploreFile函数 * 2004.09.18 by Shenloqi * 为Delphi5增加了BoolToStr函数 * 2004.05.21 by Icebird * 修改了函数GetLine, IsInt, IsFloat, CnDateToStr, MyDateToStr * 2003.10.29 by Shenloqi * 新增四个函数CheckWinXP,DllGetVersion,GetSelText,UnQuotedStr * 2002.08.12 V1.1 * 新增一个函数 CheckAppRunning by 周劲羽 * 2002.04.09 V1.0 * 整理单元,重设版本号 * 2002.03.17 V0.02 * 新增部分函数,并部分修改 * 2002.01.30 V0.01 * 创建单元(整理而来) ================================================================================ |</PRE>} interface {$I CnPack.inc} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, Math, {$IFDEF COMPILER6_UP} StrUtils, Variants, Types, {$ENDIF} FileCtrl, ShellAPI, CommDlg, MMSystem, StdCtrls, TLHelp32, ActiveX, ShlObj, ZhConsts, ZhIni, ZhIniStrUtils, CheckLst, IniFiles, MultiMon, TypInfo; //------------------------------------------------------------------------------ // 公共类型定义 //------------------------------------------------------------------------------ type PRGBColor = ^TRGBColor; TRGBColor = packed record b, g, r: Byte; end; PRGBArray = ^TRGBArray; TRGBArray = array[0..65535] of TRGBColor; const {$IFNDEF COMPILER6_UP} sLineBreak = {$IFDEF LINUX} #10 {$ENDIF} {$IFDEF MSWINDOWS} #13#10 {$ENDIF}; {$ENDIF} Alpha = ['A'..'Z', 'a'..'z', '_']; AlphaNumeric = Alpha + ['0'..'9']; //------------------------------------------------------------------------------ // 扩展的文件目录操作函数 //------------------------------------------------------------------------------ procedure ExploreDir(APath: string); {* 在资源管理器中打开指定目录 } procedure ExploreFile(AFile: string); {* 在资源管理器中打开指定文件 } function ForceDirectories(Dir: string): Boolean; {* 递归创建多级子目录} function MoveFile(const sName, dName: string): Boolean; {* 移动文件、目录,参数为源、目标名} function DeleteToRecycleBin(const FileName: string): Boolean; {* 删除文件到回收站} procedure FileProperties(const FName: string); {* 打开文件属性窗口} function OpenDialog(var FileName: string; Title: string; Filter: string; Ext: string): Boolean; {* 打开文件框} function GetDirectory(const Caption: string; var Dir: string; ShowNewButton: Boolean = True): Boolean; {* 显示选择文件夹对话框,支持设置默认文件夹} function FormatPath(APath: string; Width: Integer): string; {* 缩短显示不下的长路径名} procedure DrawCompactPath(Hdc: HDC; Rect: TRect; Str: string); {* 通过 DrawText 来画缩略路径} function SameCharCounts(s1, s2: string): Integer; {* 两个字符串的前面的相同字符数} function CharCounts(Str: PChar; Chr: Char): Integer; {* 在字符串中某字符出现的次数} function GetRelativePath(ATo, AFrom: string; const PathStr: string = '\'; const ParentStr: string = '..'; const CurrentStr: string = '.'; const UseCurrentDir: Boolean = False): string; {* 取两个目录的相对路径} {$IFNDEF BCB} function PathRelativePathToA(pszPath: PAnsiChar; pszFrom: PAnsiChar; dwAttrFrom: DWORD; pszTo: PAnsiChar; dwAttrTo: DWORD): BOOL; stdcall; function PathRelativePathToW(pszPath: PWideChar; pszFrom: PWideChar; dwAttrFrom: DWORD; pszTo: PWideChar; dwAttrTo: DWORD): BOOL; stdcall; function PathRelativePathTo(pszPath: PChar; pszFrom: PChar; dwAttrFrom: DWORD; pszTo: PChar; dwAttrTo: DWORD): BOOL; stdcall; function RelativePath(const AFrom, ATo: string; FromIsDir, ToIsDir: Boolean): string; {* 使用Windows API取两个目录的相对路径} {$ENDIF} function LinkPath(const Head, Tail: string): string; {* 连接两个路径, Head - 首路径,可以是 C:\Test、\\Test\C\Abc、http://www.abc.com/dir/ 等格式 Tail - 尾路径,可以是 ..\Test、Abc\Temp、\Test、/web/lib 等格式或绝对地址格式 } procedure RunFile(const FName: string; Handle: THandle = 0; const Param: string = ''); {* 运行一个文件} procedure OpenUrl(const Url: string); {* 打开一个链接} procedure MailTo(const Addr: string; const Subject: string = ''); {* 发送邮件} function WinExecute(FileName: string; Visibility: Integer = SW_NORMAL): Boolean; {* 运行一个文件并立即返回 } function WinExecAndWait32(FileName: string; Visibility: Integer = SW_NORMAL; ProcessMsg: Boolean = False): Integer; {* 运行一个文件并等待其结束} function WinExecWithPipe(const CmdLine, Dir: string; slOutput: TStrings; var dwExitCode: Cardinal): Boolean; overload; function WinExecWithPipe(const CmdLine, Dir: string; var Output: string; var dwExitCode: Cardinal): Boolean; overload; {* 用管道方式在 Dir 目录执行 CmdLine,Output 返回输出信息, dwExitCode 返回退出码。如果成功返回 True } function AppPath: string; {* 应用程序路径} function ModulePath: string; {* 当前执行模块所在的路径 } function GetProgramFilesDir: string; {* 取Program Files目录} function GetWindowsDir: string; {* 取Windows目录} function GetWindowsTempPath: string; {* 取临时文件路径} function CnGetTempFileName(const Ext: string): string; {* 返回一个临时文件名 } function GetSystemDir: string; {* 取系统目录} function ShortNameToLongName(const FileName: string): string; {* 短文件名转长文件名} function LongNameToShortName(const FileName: string): string; {* 长文件名转短文件名} function GetTrueFileName(const FileName: string): string; {* 取得真实长文件名,包含大小写} function FindExecFile(const AName: string; var AFullName: string): Boolean; {* 查找可执行文件的完整路径 } function GetSpecialFolderLocation(const Folder: Integer): string; {* 取得系统特殊文件夹位置,Folder 使用在 ShlObj 中定义的标识,如 CSIDL_DESKTOP } function AddDirSuffix(const Dir: string): string; {* 目录尾加'\'修正} function MakePath(const Dir: string): string; {* 目录尾加'\'修正} function MakeDir(const Path: string): string; {* 路径尾去掉 '\'} function GetUnixPath(const Path: string): string; {* 路径中的 '\' 转成 '/'} function GetWinPath(const Path: string): string; {* 路径中的 '/' 转成 '\'} function FileNameMatch(Pattern, FileName: PChar): Integer; {* 文件名是否与通配符匹配,返回值为0表示匹配,其他为不匹配} function MatchExt(const S, Ext: string): Boolean; {* 文件名是否与扩展名通配符匹配} function MatchFileName(const S, FN: string): Boolean; {* 文件名是否与通配符匹配} procedure FileExtsToStrings(const FileExts: string; ExtList: TStrings; CaseSensitive: Boolean); {* 转换扩展名通配符字符串为通配符列表} function FileMatchesExts(const FileName, FileExts: string; CaseSensitive: Boolean): Boolean; overload; function FileMatchesExts(const FileName: string; ExtList: TStrings): Boolean; overload; {* 文件名是否匹配扩展名通配符} procedure FileMasksToStrings(const FileMasks: string; MaskList: TStrings; CaseSensitive: Boolean); {* 转换文件通配符字符串为通配符列表} function FileMatchesMasks(const FileName, FileMasks: string; CaseSensitive: Boolean): Boolean; overload; function FileMatchesMasks(const FileName: string; MaskList: TStrings): Boolean; overload; {* 文件名是否匹配通配符} function FileMatchesExts(const FileName, FileExts: string): Boolean; overload; {* 文件名与扩展名列表比较。FileExts是如'.pas;.dfm;.inc'这样的字符串} function IsFileInUse(const FName: string): Boolean; {* 判断文件是否正在使用} function IsAscii(FileName: string): Boolean; {* 判断文件是否为 Ascii 文件} function IsValidFileName(const Name: string): Boolean; {* 判断文件是否是有效的文件名} function GetValidFileName(const Name: string): string; {* 返回有效的文件名 } function SetFileDate(const FileName: string; CreationTime, LastWriteTime, LastAccessTime: TFileTime): Boolean; {* 设置文件时间} function GetFileDate(const FileName: string; var CreationTime, LastWriteTime, LastAccessTime: TFileTime): Boolean; {* 取文件时间} function FileTimeToDateTime(const FileTime: TFileTime): TDateTime; {* 文件时间转本地日期时间} function DateTimeToFileTime(const DateTime: TDateTime): TFileTime; {* 本地日期时间转文件时间} function GetFileIcon(const FileName: string; var Icon: TIcon): Boolean; {* 取得与文件相关的图标,成功则返回True} function CreateBakFile(const FileName, Ext: string): Boolean; {* 创建备份文件} function FileTimeToLocalSystemTime(FTime: TFileTime): TSystemTime; {* 文件时间转本地时间} function LocalSystemTimeToFileTime(STime: TSystemTime): TFileTime; {* 本地时间转文件时间} function DateTimeToLocalDateTime(DateTime: TDateTime): TDateTime; {* UTC 时间转本地时间} function LocalDateTimeToDateTime(DateTime: TDateTime): TDateTime; {* 本地时间转 UTC 时间} {$IFDEF COMPILER5} type TValueRelationship = -1..1; function CompareValue(const A, B: Int64): TValueRelationship; function AnsiStartsText(const ASubText, AText: string): Boolean; {* AText 是否以 ASubText 开头 } function AnsiReplaceText(const AText, AFromText, AToText: string): string; {$ENDIF} {$IFNDEF COMPILER7_UP} function AnsiContainsText(const AText, ASubText: string): Boolean; {* AText 是否包含 ASubText } {$ENDIF} function CompareTextPos(const ASubText, AText1, AText2: string): TValueRelationship; {* 比较 SubText 在两个字符串中出现的位置的大小,如果相等则比较字符串本身,忽略大小写 } function Deltree(Dir: string; DelRoot: Boolean = True; DelEmptyDirOnly: Boolean = False): Boolean; {* 删除整个目录, DelRoot 表示是否删除目录本身} procedure DelEmptyTree(Dir: string; DelRoot: Boolean = True); {* 删除整个目录中的空目录, DelRoot 表示是否删除目录本身} function GetDirFiles(Dir: string): Integer; {* 取文件夹文件数} type TFindCallBack = procedure(const FileName: string; const Info: TSearchRec; var Abort: Boolean) of object; {* 查找指定目录下文件的回调函数} TDirCallBack = procedure(const SubDir: string) of object; {* 查找指定目录时进入子目录回调函数} function FindFile(const Path: string; const FileName: string = '*.*'; Proc: TFindCallBack = nil; DirProc: TDirCallBack = nil; bSub: Boolean = True; bMsg: Boolean = True): Boolean; {* 查找指定目录下文件,返回是否被中断 } function OpenWith(const FileName: string): Integer; {* 显示文件打开方式对话框} function CheckAppRunning(const FileName: string; var Running: Boolean): Boolean; {* 检查指定的应用程序是否正在运行 |<PRE> const FileName: string - 应用程序文件名,不带路径,如果不带扩展名, 默认为".EXE",大小写无所谓。 如 Notepad.EXE var Running: Boolean - 返回该应用程序是否运行,运行为 True Result: Boolean - 如果查找成功返回为 True,否则为 False |</PRE>} type TVersionNumber = packed record {* 文件版本号} Minor: Word; Major: Word; Build: Word; Release: Word; end; function GetFileVersionNumber(const FileName: string): TVersionNumber; {* 取文件版本号} function GetFileVersionStr(const FileName: string): string; {* 取文件版本字符串} function GetFileInfo(const FileName: string; var FileSize: Int64; var FileTime: TDateTime): Boolean; {* 取文件信息} function GetFileSize(const FileName: string): Int64; {* 取文件长度} function GetFileDateTime(const FileName: string): TDateTime; {* 取文件Delphi格式日期时间} function LoadStringFromFile(const FileName: string): string; {* 将文件读为字符串} function SaveStringToFile(const S, FileName: string): Boolean; {* 保存字符串到为文件} //------------------------------------------------------------------------------ // 环境变量相关 //------------------------------------------------------------------------------ function DelEnvironmentVar(const Name: string): Boolean; {* 删除当前进程中的环境变量 } function ExpandEnvironmentVar(var Value: string): Boolean; {* 扩展当前进程中的环境变量 } function GetEnvironmentVar(const Name: string; var Value: string; Expand: Boolean): Boolean; {* 返回当前进程中的环境变量 } function GetEnvironmentVars(const Vars: TStrings; Expand: Boolean): Boolean; {* 返回当前进程中的环境变量列表 } function SetEnvironmentVar(const Name, Value: string): Boolean; {* 设置当前进程中的环境变量 } //------------------------------------------------------------------------------ // 扩展的字符串操作函数 //------------------------------------------------------------------------------ function InStr(const sShort: string; const sLong: string): Boolean; {* 判断s1是否包含在s2中} function IntToStrEx(Value: Integer; Len: Integer; FillChar: Char = '0'): string; {* 扩展整数转字符串函数} function IntToStrSp(Value: Integer; SpLen: Integer = 3; Sp: Char = ','): string; {* 带分隔符的整数-字符转换} function IsFloat(const s: String): Boolean; {* 判断字符串是否可转换成浮点型} function IsInt(const s: String): Boolean; {* 判断字符串是否可转换成整型} function IsDateTime(const s: string): Boolean; {* 判断字符串是否可转换成 DateTime } function IsValidEmail(const s: string): Boolean; {* 判断是否有效的邮件地址 } function StrSpToInt(Value: String; Sp: Char = ','): Int64; {* 去掉字符串中的分隔符-字符转换} function ByteToBin(Value: Byte): string; {* 字节转二进制串} function StrRight(Str: string; Len: Integer): string; {* 返回字符串右边的字符} function StrLeft(Str: string; Len: Integer): string; {* 返回字符串左边的字符} function GetLine(C: Char; Len: Integer): string; {* 返回字符串行} function GetTextFileLineCount(FileName: String): Integer; {* 返回文本文件的行数} function Spc(Len: Integer): string; {* 返回空格串} procedure SwapStr(var s1, s2: string); {* 交换字串} procedure SeparateStrAndNum(const AInStr: string; var AOutStr: string; var AOutNum: Integer); {* 分割"非数字+数字"格式的字符串中的非数字和数字} function UnQuotedStr(const str: string; const ch: Char; const sep: string = ''): string; {* 去除被引用的字符串的引用} function CharPosWithCounter(const Sub: Char; const AStr: String; Counter: Integer = 1): Integer; {* 查找字符串中出现的第 Counter 次的字符的位置 } function CountCharInStr(const Sub: Char; const AStr: string): Integer; {* 查找字符串中字符的出现次数} function IsValidIdentChar(C: Char; First: Boolean = False): Boolean; {* 判断字符是否有效标识符字符,First 表示是否为首字符} {$IFDEF COMPILER5} function BoolToStr(B: Boolean; UseBoolStrs: Boolean = False): string; {* Delphi5没有实现布尔型转换为字符串,类似于Delphi6,7的实现} {$ENDIF COMPILER5} function LinesToStr(const Lines: string): string; {* 多行文本转单行(换行符转'\n')} function StrToLines(const Str: string): string; {* 单行文本转多行('\n'转换行符)} function MyDateToStr(Date: TDate): string; {* 日期转字符串,使用 yyyy.mm.dd 格式} function RegReadStringDef(const RootKey: HKEY; const Key, Name, Def: string): string; {* 取注册表键值} procedure ReadStringsFromIni(Ini: TCustomIniFile; const Section: string; Strings: TStrings); {* 从 INI 中读取字符串列表} procedure WriteStringsToIni(Ini: TCustomIniFile; const Section: string; Strings: TStrings); {* 写字符串列表到 INI 文件中} function VersionToStr(Version: DWORD): string; {* 版本号转成字符串,如 $01020000 --> '1.2.0.0' } function StrToVersion(s: string): DWORD; {* 字符串转成版本号,如 '1.2.0.0' --> $01020000,如果格式不正确,返回 $01000000 } function CnDateToStr(Date: TDateTime): string; {* 转换日期为 yyyy.mm.dd 格式字符串 } function CnStrToDate(const S: string): TDateTime; {* 将 yyyy.mm.dd 格式字符串转换为日期 } function DateTimeToFlatStr(const DateTime: TDateTime): string; {* 日期时间转 '20030203132345' 式样的 14 位数字字符串} function FlatStrToDateTime(const Section: string; var DateTime: TDateTime): Boolean; {* '20030203132345' 式样的 14 位数字字符串转日期时间} function StrToRegRoot(const s: string): HKEY; {* 字符串转注册表根键,支持 'HKEY_CURRENT_USER' 'HKCR' 长短两种格式} function RegRootToStr(Key: HKEY; ShortFormat: Boolean = True): string; {* 注册表根键转字符串,可选 'HKEY_CURRENT_USER' 'HKCR' 长短两种格式} function ExtractSubstr(const S: string; var Pos: Integer; const Delims: TSysCharSet): string; {* 从字符串中根据指定的分隔符分离出子串 |<PRE> const S: string - 源字符串 var Pos: Integer - 输入查找的起始位置,输出查找完成的结束位置 const Delims: TSysCharSet - 分隔符集合 Result: string - 返回子串 |</PRE>} function WildcardCompare(const FileWildcard, FileName: string; const IgnoreCase: Boolean = True): Boolean; {* 文件名通配符比较} function ScanCodeToAscii(Code: Word): Char; {* 根据当前键盘布局将键盘扫描码转换成 ASCII 字符,可在 WM_KEYDOWN 等处使用 由于不调用 ToAscii,故可支持使用 Accent Character 的键盘布局 } function IsDeadKey(Key: Word): Boolean; {* 返回一个虚拟键是否 Dead key} function VirtualKeyToAscii(Key: Word): Char; {* 根据当前键盘状态将虚拟键转换成 ASCII 字符,可在 WM_KEYDOWN 等处使用 可能会导致 Accent Character 不正确} function VK_ScanCodeToAscii(VKey: Word; Code: Word): Char; {* 根据当前的键盘布局将虚拟键和扫描码转换成 ASCII 字符。通过虚拟键来处理小键盘, 扫描码处理大键盘,支持 Accent Character 的键盘布局 } function GetShiftState: TShiftState; {* 返回当前的按键状态,暂不支持 ssDouble 状态 } function IsShiftDown: Boolean; {* 判断当前 Shift 是否按下 } function IsAltDown: Boolean; {* 判断当前 Alt 是否按下 } function IsCtrlDown: Boolean; {* 判断当前 Ctrl 是否按下 } function IsInsertDown: Boolean; {* 判断当前 Insert 是否按下 } function IsCapsLockDown: Boolean; {* 判断当前 Caps Lock 是否按下 } function IsNumLockDown: Boolean; {* 判断当前 NumLock 是否按下 } function IsScrollLockDown: Boolean; {* 判断当前 Scroll Lock 是否按下 } function RemoveClassPrefix(const ClassName: string): string; {* 删除类名前缀 T} function CnAuthorEmailToStr(Author, Email: string): string; {* 用分号分隔的作者、邮箱字符串转换为输出格式,例如: |<PRE> Author = 'Tom;Jack;Bill' Email = 'tom@email.com;jack@email.com;Bill@email.net' Result = 'Tom(tom@email.com)' + #13#10 + 'Jack(jack@email.com)' + #13#10 + 'Bill(bill@email.net) |</PRE>} //------------------------------------------------------------------------------ // 扩展的对话框函数 //------------------------------------------------------------------------------ procedure InfoDlg(Mess: string; Caption: string = ''; Flags: Integer = MB_OK + MB_ICONINFORMATION); {* 显示提示窗口} function InfoOk(Mess: string; Caption: string = ''): Boolean; {* 显示提示确认窗口} procedure ErrorDlg(Mess: string; Caption: string = ''); {* 显示错误窗口} procedure WarningDlg(Mess: string; Caption: string = ''); {* 显示警告窗口} function QueryDlg(Mess: string; DefaultNo: Boolean = False; Caption: string = ''): Boolean; {* 显示查询是否窗口} const csDefComboBoxSection = 'History'; function CnInputQuery(const ACaption, APrompt: string; var Value: string; Ini: TCustomIniFile = nil; const Section: string = csDefComboBoxSection): Boolean; {* 输入对话框} function CnInputBox(const ACaption, APrompt, ADefault: string; Ini: TCustomIniFile = nil; const Section: string = csDefComboBoxSection): string; {* 输入对话框} //------------------------------------------------------------------------------ // 扩展日期时间操作函数 //------------------------------------------------------------------------------ function GetYear(Date: TDate): Integer; {* 取日期年份分量} function GetMonth(Date: TDate): Integer; {* 取日期月份分量} function GetDay(Date: TDate): Integer; {* 取日期天数分量} function GetHour(Time: TTime): Integer; {* 取时间小时分量} function GetMinute(Time: TTime): Integer; {* 取时间分钟分量} function GetSecond(Time: TTime): Integer; {* 取时间秒分量} function GetMSecond(Time: TTime): Integer; {* 取时间毫秒分量} //------------------------------------------------------------------------------ // 位操作函数 //------------------------------------------------------------------------------ type TByteBit = 0..7; {* Byte类型位数范围} TWordBit = 0..15; {* Word类型位数范围} TDWordBit = 0..31; {* DWord类型位数范围} procedure SetBit(var Value: Byte; Bit: TByteBit; IsSet: Boolean); overload; {* 设置二进制位} procedure SetBit(var Value: WORD; Bit: TWordBit; IsSet: Boolean); overload; {* 设置二进制位} procedure SetBit(var Value: DWORD; Bit: TDWordBit; IsSet: Boolean); overload; {* 设置二进制位} function GetBit(Value: Byte; Bit: TByteBit): Boolean; overload; {* 取二进制位} function GetBit(Value: WORD; Bit: TWordBit): Boolean; overload; {* 取二进制位} function GetBit(Value: DWORD; Bit: TDWordBit): Boolean; overload; {* 取二进制位} //------------------------------------------------------------------------------ // 系统功能函数 //------------------------------------------------------------------------------ type PDLLVERSIONINFO = ^TDLLVERSIONINFO; TDLLVERSIONINFO = packed record cbSize: DWORD; dwMajorVersion: DWORD; dwMinorVersion: DWORD; dwBuildNumber: DWORD; dwPlatformId: DWORD; end; PDLLVERSIONINFO2 = ^TDLLVERSIONINFO2; TDLLVERSIONINFO2 = packed record info1: TDLLVERSIONINFO; dwFlags: DWORD; ullVersion: ULARGE_INTEGER; end; procedure MoveMouseIntoControl(AWinControl: TControl); {* 移动鼠标到控件} procedure AddComboBoxTextToItems(ComboBox: TComboBox; MaxItemsCount: Integer = 10); {* 将 ComboBox 的文本内容增加到下拉列表中} function DynamicResolution(x, y: WORD): Boolean; {* 动态设置分辨率} procedure StayOnTop(Handle: HWND; OnTop: Boolean); {* 窗口最上方显示} procedure SetHidden(Hide: Boolean); {* 设置程序是否出现在任务栏} procedure SetTaskBarVisible(Visible: Boolean); {* 设置任务栏是否可见} procedure SetDesktopVisible(Visible: Boolean); {* 设置桌面是否可见} function ForceForegroundWindow(HWND: HWND): Boolean; {* 强制让一个窗口显示在前台} function GetWorkRect(const Form: TCustomForm = nil): TRect; {* 取桌面区域} procedure BeginWait; {* 显示等待光标} procedure EndWait; {* 结束等待光标} function CheckWindows9598: Boolean; {* 检测是否Win95/98平台} function CheckWinXP: Boolean; {* 检测是否WinXP以上平台} function DllGetVersion(const dllname: string; var DVI: TDLLVERSIONINFO2): Boolean; {* 获得Dll的版本信息} function GetOSString: string; {* 返回操作系统标识串} function GetComputeNameStr : string; {* 得到本机名} function GetLocalUserName: string; {* 得到本机用户名} function GetRegisteredCompany: string; {* 得到公司名} function GetRegisteredOwner: string; {* 得到注册用户名} //------------------------------------------------------------------------------ // 其它过程 //------------------------------------------------------------------------------ function GetControlScreenRect(AControl: TControl): TRect; {* 返回控件在屏幕上的坐标区域 } procedure SetControlScreenRect(AControl: TControl; ARect: TRect); {* 设置控件在屏幕上的坐标区域 } procedure ListboxHorizontalScrollbar(Listbox: TCustomListBox); {* 为 Listbox 增加水平滚动条} function TrimInt(Value, Min, Max: Integer): Integer; {* 输出限制在Min..Max之间} function CompareInt(V1, V2: Integer; Desc: Boolean = False): Integer; {* 比较两个整数,V1 > V2 返回 1,V1 < V2 返回 -1,V1 = V2 返回 0 如果 Desc 为 True,返回结果反向 } function IntToByte(Value: Integer): Byte; {* 输出限制在0..255之间} function InBound(Value: Integer; V1, V2: Integer): Boolean; {* 判断整数Value是否在V1和V2之间} function SameMethod(Method1, Method2: TMethod): Boolean; {* 比较两个方法地址是否相等} function HalfFind(List: TList; P: Pointer; SCompare: TListSortCompare): Integer; {* 二分法在排序列表中查找} type TFindRange = record tgFirst: Integer; tgLast: Integer; end; function HalfFindEx(List: TList; P: Pointer; SCompare: TListSortCompare): TFindRange; {* 二分法在排序列表中查找,支持重复记录,返回一个范围值} procedure CnSwap(var A, B: Byte); overload; {* 交换两个数} procedure CnSwap(var A, B: Integer); overload; {* 交换两个数} procedure CnSwap(var A, B: Single); overload; {* 交换两个数} procedure CnSwap(var A, B: Double); overload; {* 交换两个数} function RectEqu(Rect1, Rect2: TRect): Boolean; {* 比较两个Rect是否相等} procedure DeRect(Rect: TRect; var x, y, Width, Height: Integer); {* 分解一个TRect为左上角坐标x, y和宽度Width、高度Height} function EnSize(cx, cy: Integer): TSize; {* 返回一个TSize类型} function RectWidth(Rect: TRect): Integer; {* 计算TRect的宽度} function RectHeight(Rect: TRect): Integer; {* 计算TRect的高度} procedure Delay(const uDelay: DWORD); {* 延时} procedure BeepEx(const Freq: WORD = 1200; const Delay: WORD = 1); {* 在Win9X下让喇叭发声} function GetLastErrorMsg(IncludeErrorCode: Boolean = False): string; {* 取得最后一次错误信息} procedure ShowLastError; {* 显示Win32 Api运行结果信息} function GetHzPy(const AHzStr: string): string; {* 取汉字的拼音} function GetSelText(edt: TCustomEdit): string; {* 获得CustomEdit选中的字符串,可正确处理使用了XP样式的程序} function SoundCardExist: Boolean; {* 声卡是否存在} function FindFormByClass(AClass: TClass): TForm; {* 根据指定类名查找窗体} function InheritsFromClassName(ASrc: TClass; const AClass: string): Boolean; overload; {* 判断 ASrc 是否派生自类名为 AClass 的类 } function InheritsFromClassName(AObject: TObject; const AClass: string): Boolean; overload; {* 判断 AObject 是否派生自类名为 AClass 的类 } procedure KillProcessByFileName(const FileName: String); {* 根据文件名结束进程,不区分路径} function IndexStr(AText: string; AValues: array of string; IgCase: Boolean = True): Integer; {* 查找字符串在动态数组中的索引,用于string类型使用Case语句} function IndexInt(ANum: Integer; AValues: array of Integer): Integer; {* 查找整形变量在动态数组中的索引,用于变量使用Case语句} procedure TrimStrings(AList: TStrings); {* 删除空行和每一行的行首尾空格 } //============================================================================== // 级联属性操作相关函数 by Passion //============================================================================== function GetPropInfoIncludeSub(Instance: TObject; const PropName: string; AKinds: TTypeKinds = []): PPropInfo; {* 获得级联属性信息} function GetPropValueIncludeSub(Instance: TObject; PropName: string; PreferStrings: Boolean = True): Variant; {* 获得级联属性值} function SetPropValueIncludeSub(Instance: TObject; const PropName: string; const Value: Variant): Boolean; {* 设置级联属性值} procedure DoSetPropValueIncludeSub(Instance: TObject; const PropName: string; Value: Variant); {* 设置级联属性值,不处理异常} function StrToSetValue(const Value: string; PInfo: PTypeInfo): Integer; {* 字符串转集合值 } //============================================================================== // 其他杂项函数 by Passion //============================================================================== type TCnFontControl = class(TControl) public property ParentFont; property Font; end; function IsParentFont(AControl: TControl): Boolean; {* 判断某 Control 的 ParentFont 属性是否为 True,如无 Parent 则返回 False } function GetParentFont(AControl: TComponent): TFont; {* 取某 Control 的 Parent 的 Font 属性,如果没有返回 nil } const InvalidFileNameChar: set of Char = ['\', '/', ':', '*', '?', '"', '<', '>', '|']; implementation //------------------------------------------------------------------------------ // 扩展的文件目录操作函数 //------------------------------------------------------------------------------ // 在资源管理器中打开指定目录 procedure ExploreDir(APath: string); var strExecute: string; begin strExecute := Format('EXPLORER.EXE /e,%s', [APath]); WinExec(PChar(strExecute), SW_SHOWNORMAL); end; // 在资源管理器中打开指定文件 procedure ExploreFile(AFile: string); var strExecute: string; begin strExecute := Format('EXPLORER.EXE /e,/select,%s', [AFile]); WinExec(PChar(strExecute), SW_SHOWNORMAL); end; // 递归创建多级子目录 function ForceDirectories(Dir: string): Boolean; begin Result := True; if Length(Dir) = 0 then begin Result := False; Exit; end; Dir := ExcludeTrailingBackslash(Dir); if (Length(Dir) < 3) or DirectoryExists(Dir) or (ExtractFilePath(Dir) = Dir) then Exit; // avoid 'xyz:\' problem. Result := ForceDirectories(ExtractFilePath(Dir)) and CreateDir(Dir); end; // 移动文件、目录 function MoveFile(const sName, dName: string): Boolean; var s1, s2: AnsiString; lpFileOp: TSHFileOpStruct; begin s1 := PChar(sName) + #0#0; s2 := PChar(dName) + #0#0; with lpFileOp do begin Wnd := Application.Handle; wFunc := FO_MOVE; pFrom := PChar(s1); pTo := PChar(s2); fFlags := FOF_ALLOWUNDO; hNameMappings := nil; lpszProgressTitle := nil; fAnyOperationsAborted := True; end; try Result := SHFileOperation(lpFileOp) = 0; except Result := False; end; end; // 删除文件到回收站 function DeleteToRecycleBin(const FileName: string): Boolean; var s: AnsiString; lpFileOp: TSHFileOpStruct; begin s := PChar(FileName) + #0#0; with lpFileOp do begin Wnd := Application.Handle; wFunc := FO_DELETE; pFrom := PChar(s); pTo := nil; fFlags := FOF_ALLOWUNDO or FOF_SILENT or FOF_NOCONFIRMATION; hNameMappings := nil; lpszProgressTitle := nil; fAnyOperationsAborted := True; end; try Result := SHFileOperation(lpFileOp) = 0; except Result := False; end; end; // 打开文件属性窗口 procedure FileProperties(const FName: string); var SEI: SHELLEXECUTEINFO; begin with SEI do begin cbSize := SizeOf(SEI); fMask := SEE_MASK_NOCLOSEPROCESS or SEE_MASK_INVOKEIDLIST or SEE_MASK_FLAG_NO_UI; Wnd := Application.Handle; lpVerb := 'properties'; lpFile := PChar(FName); lpParameters := nil; lpDirectory := nil; nShow := 0; hInstApp := 0; lpIDList := nil; end; ShellExecuteEx(@SEI); end; // 缩短显示不下的长路径名 function FormatPath(APath: string; Width: Integer): string; var SLen: Integer; i, j: Integer; TString: string; begin SLen := Length(APath); if (SLen <= Width) or (Width <= 6) then begin Result := APath; Exit end else begin i := SLen; TString := APath; for j := 1 to 2 do begin while (TString[i] <> '\') and (SLen - i < Width - 8) do i := i - 1; i := i - 1; end; for j := SLen - i - 1 downto 0 do TString[Width - j] := TString[SLen - j]; for j := SLen - i to SLen - i + 2 do TString[Width - j] := '.'; Delete(TString, Width + 1, 255); Result := TString; end; end; // 通过 DrawText 来画缩略路径 procedure DrawCompactPath(Hdc: HDC; Rect: TRect; Str: string); begin DrawText(Hdc, PChar(Str), Length(Str), Rect, DT_PATH_ELLIPSIS); end; // 打开文件框 function OpenDialog(var FileName: string; Title: string; Filter: string; Ext: string): Boolean; var OpenName: TOPENFILENAME; TempFilename, ReturnFile: string; begin with OpenName do begin lStructSize := SizeOf(OpenName); hWndOwner := GetModuleHandle(''); Hinstance := SysInit.Hinstance; lpstrFilter := PChar(Filter + #0 + Ext + #0#0); lpstrCustomFilter := ''; nMaxCustFilter := 0; nFilterIndex := 1; nMaxFile := MAX_PATH; SetLength(TempFilename, nMaxFile + 2); lpstrFile := PChar(TempFilename); FillChar(lpstrFile^, MAX_PATH, 0); SetLength(TempFilename, nMaxFile + 2); nMaxFileTitle := MAX_PATH; SetLength(ReturnFile, MAX_PATH + 2); lpstrFileTitle := PChar(ReturnFile); FillChar(lpstrFile^, MAX_PATH, 0); lpstrInitialDir := '.'; lpstrTitle := PChar(Title); Flags := OFN_HIDEREADONLY + OFN_ENABLESIZING; nFileOffset := 0; nFileExtension := 0; lpstrDefExt := PChar(Ext); lCustData := 0; lpfnHook := nil; lpTemplateName := ''; end; Result := GetOpenFileName(OpenName); if Result then FileName := ReturnFile else FileName := ''; end; function SelectDirCB(Wnd: HWND; uMsg: UINT; lParam, lpData: LPARAM): Integer stdcall; begin if (uMsg = BFFM_INITIALIZED) and (lpData <> 0) then SendMessage(Wnd, BFFM_SETSELECTION, Integer(True), lpdata); Result := 0; end; function CnSelectDirectory(const Caption: string; const Root: WideString; var Directory: string; Owner: HWND; ShowNewButton: Boolean = True): Boolean; var BrowseInfo: TBrowseInfo; Buffer: PChar; RootItemIDList, ItemIDList: PItemIDList; ShellMalloc: IMalloc; IDesktopFolder: IShellFolder; Eaten, Flags: LongWord; begin Result := False; FillChar(BrowseInfo, SizeOf(BrowseInfo), 0); if (ShGetMalloc(ShellMalloc) = S_OK) and (ShellMalloc <> nil) then begin Buffer := ShellMalloc.Alloc(MAX_PATH); try SHGetDesktopFolder(IDesktopFolder); if Root = '' then RootItemIDList := nil else IDesktopFolder.ParseDisplayName(Application.Handle, nil, POleStr(Root), Eaten, RootItemIDList, Flags); with BrowseInfo do begin hwndOwner := Owner; pidlRoot := RootItemIDList; pszDisplayName := Buffer; lpszTitle := PChar(Caption); ulFlags := BIF_RETURNONLYFSDIRS; if ShowNewButton then ulFlags := ulFlags or $0040; lpfn := SelectDirCB; lparam := Integer(PChar(Directory)); end; ItemIDList := SHBrowseForFolder(BrowseInfo); Result := ItemIDList <> nil; if Result then begin ShGetPathFromIDList(ItemIDList, Buffer); ShellMalloc.Free(ItemIDList); Directory := Buffer; end; finally ShellMalloc.Free(Buffer); end; end; end; function GetDirectory(const Caption: string; var Dir: string; ShowNewButton: Boolean): Boolean; var OldErrorMode: UINT; BrowseRoot: WideString; OwnerHandle: HWND; begin OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS); try BrowseRoot := ''; if Screen.ActiveCustomForm <> nil then OwnerHandle := Screen.ActiveCustomForm.Handle else OwnerHandle := Application.Handle; Result := CnSelectDirectory(Caption, BrowseRoot, Dir, OwnerHandle, ShowNewButton); finally SetErrorMode(OldErrorMode); end; end; // 两个字符串的前面的相同字符数 function SameCharCounts(s1, s2: string): Integer; var Str1, Str2: PChar; begin Result := 1; s1 := s1 + #0; s2 := s2 + #0; Str1 := PChar(s1); Str2 := PChar(s2); while (s1[Result] = s2[Result]) and (s1[Result] <> #0) do begin Inc(Result); end; Dec(Result); {$IFDEF MSWINDOWS} if (StrByteType(Str1, Result - 1) = mbLeadByte) or (StrByteType(Str2, Result - 1) = mbLeadByte) then Dec(Result); {$ENDIF} {$IFDEF LINUX} if (StrByteType(Str1, Result - 1) <> mbSingleByte) or (StrByteType(Str2, Result - 1) <> mbSingleByte) then Dec(Result); {$ENDIF} end; // 在字符串中某字符出现的次数 function CharCounts(Str: PChar; Chr: Char): Integer; var p: PChar; begin Result := 0; p := StrScan(Str, Chr); while p <> nil do begin {$IFDEF MSWINDOWS} case StrByteType(Str, Integer(p - Str)) of mbSingleByte: begin Inc(Result); Inc(p); end; mbLeadByte: Inc(p); end; {$ENDIF} {$IFDEF LINUX} if StrByteType(Str, Integer(p - Str)) = mbSingleByte then begin Inc(Result); Inc(p); end; {$ENDIF} Inc(p); p := StrScan(p, Chr); end; end; // 取两个目录的相对路径 function GetRelativePath(ATo, AFrom: string; const PathStr: string = '\'; const ParentStr: string = '..'; const CurrentStr: string = '.'; const UseCurrentDir: Boolean = False): string; var i, HeadNum: Integer; begin ATo := StringReplace(ATo, '/', '\', [rfReplaceAll]); AFrom := StringReplace(AFrom, '/', '\', [rfReplaceAll]); while AnsiPos('\\', ATo) > 0 do ATo := StringReplace(ATo, '\\', '\', [rfReplaceAll]); while AnsiPos('\\', AFrom) > 0 do AFrom := StringReplace(AFrom, '\\', '\', [rfReplaceAll]); if StrRight(ATo, 1) = ':' then ATo := ATo + '\'; if StrRight(AFrom, 1) = ':' then AFrom := AFrom + '\'; HeadNum := SameCharCounts(AnsiUpperCase(ExtractFilePath(ATo)), AnsiUpperCase(ExtractFilePath(AFrom))); if HeadNum > 0 then begin ATo := StringReplace(Copy(ATo, HeadNum + 1, MaxInt), '\', PathStr, [rfReplaceAll]); AFrom := Copy(AFrom, HeadNum + 1, MaxInt); Result := ''; HeadNum := CharCounts(PChar(AFrom), '\'); for i := 1 to HeadNum do Result := Result + ParentStr + PathStr; if (Result = '') and UseCurrentDir then Result := CurrentStr + PathStr; Result := Result + ATo; end else Result := ATo; end; {$IFNDEF BCB} const shlwapi32 = 'shlwapi.dll'; function PathRelativePathToA; external shlwapi32 name 'PathRelativePathToA'; function PathRelativePathToW; external shlwapi32 name 'PathRelativePathToW'; function PathRelativePathTo; external shlwapi32 name 'PathRelativePathToA'; // 使用Windows API取两个目录的相对路径 function RelativePath(const AFrom, ATo: string; FromIsDir, ToIsDir: Boolean): string; function GetAttr(IsDir: Boolean): DWORD; begin if IsDir then Result := FILE_ATTRIBUTE_DIRECTORY else Result := FILE_ATTRIBUTE_NORMAL; end; var p: array[0..MAX_PATH] of Char; begin PathRelativePathTo(p, PChar(AFrom), GetAttr(FromIsDir), PChar(ATo), GetAttr(ToIsDir)); Result := StrPas(p); end; {$ENDIF} // 连接两个路径, // Head - 首路径,可以是 C:\Test、\\Test\C\Abc、http://www.abc.com/dir/ 等格式 // Tail - 尾路径,可以是 ..\Test、Abc\Temp、\Test、/web/lib 等格式或绝对地址格式 function LinkPath(const Head, Tail: string): string; var HeadIsUrl: Boolean; TailHasRoot: Boolean; TailIsRel: Boolean; AHead, ATail, S: string; UrlPos, i: Integer; begin if Head = '' then begin Result := Tail; Exit; end; if Tail = '' then begin Result := Head; Exit; end; TailHasRoot := (AnsiPos(':\', Tail) = 2) or // C:\Test (AnsiPos('\\', Tail) = 1) or // \\Name\C\Test (AnsiPos('://', Tail) > 0); // ftp://ftp.abc.com if TailHasRoot then begin Result := Tail; Exit; end; UrlPos := AnsiPos('://', Head); HeadIsUrl := UrlPos > 0; AHead := StringReplace(Head, '/', '\', [rfReplaceAll]); ATail := StringReplace(Tail, '/', '\', [rfReplaceAll]); TailIsRel := ATail[1] = '\'; // 尾路径是相对路径 if TailIsRel then begin if AnsiPos(':\', AHead) = 2 then Result := AHead[1] + ':' + ATail else if AnsiPos('\\', AHead) = 1 then begin S := Copy(AHead, 3, MaxInt); i := AnsiPos('\', S); if i > 0 then Result := Copy(AHead, 1, i + 1) + ATail else Result := AHead + ATail; end else if HeadIsUrl then begin S := Copy(AHead, UrlPos + 3, MaxInt); i := AnsiPos('\', S); if i > 0 then Result := Copy(AHead, 1, i + UrlPos + 1) + ATail else Result := AHead + ATail; end else begin Result := Tail; Exit; end; end else begin if Copy(ATail, 1, 2) = '.\' then Delete(ATail, 1, 2); AHead := MakeDir(AHead); i := Pos('..\', ATail); while i > 0 do begin AHead := ExtractFileDir(AHead); Delete(ATail, 1, 3); i := Pos('..\', ATail); end; Result := MakePath(AHead) + ATail; end; if HeadIsUrl then Result := StringReplace(Result, '\', '/', [rfReplaceAll]); end; // 运行一个文件 procedure RunFile(const FName: string; Handle: THandle; const Param: string); begin ShellExecute(Handle, nil, PChar(FName), PChar(Param), nil, SW_SHOWNORMAL); end; // 打开一个链接 procedure OpenUrl(const Url: string); const csPrefix = 'http://'; var AUrl: string; begin if Pos(csPrefix, Url) < 1 then AUrl := csPrefix + Url else AUrl := Url; RunFile(AUrl); end; // 发送邮件 procedure MailTo(const Addr: string; const Subject: string = ''); const csPrefix = 'mailto:'; csSubject = '?Subject='; var Url: string; begin if Pos(csPrefix, Addr) < 1 then Url := csPrefix + Addr else Url := Addr; if Subject <> '' then Url := Url + csSubject + Subject; RunFile(Url); end; // 运行一个文件并立即返回 function WinExecute(FileName: string; Visibility: Integer = SW_NORMAL): Boolean; var StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; begin FillChar(StartupInfo, SizeOf(StartupInfo), #0); StartupInfo.cb := SizeOf(StartupInfo); StartupInfo.dwFlags := STARTF_USESHOWWINDOW; StartupInfo.wShowWindow := Visibility; Result := CreateProcess(nil, PChar(FileName), nil, nil, False, CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInfo); end; // 运行一个文件并等待其结束 function WinExecAndWait32(FileName: string; Visibility: Integer; ProcessMsg: Boolean): Integer; var zAppName: array[0..512] of Char; zCurDir: array[0..255] of Char; WorkDir: string; StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; begin StrPCopy(zAppName, FileName); GetDir(0, WorkDir); StrPCopy(zCurDir, WorkDir); FillChar(StartupInfo, SizeOf(StartupInfo), #0); StartupInfo.cb := SizeOf(StartupInfo); StartupInfo.dwFlags := STARTF_USESHOWWINDOW; StartupInfo.wShowWindow := Visibility; if not CreateProcess(nil, zAppName, { pointer to command line string } nil, { pointer to process security attributes } nil, { pointer to thread security attributes } False, { handle inheritance flag } CREATE_NEW_CONSOLE or { creation flags } NORMAL_PRIORITY_CLASS, nil, { pointer to new environment block } nil, { pointer to current directory name } StartupInfo, { pointer to STARTUPINFO } ProcessInfo) then Result := -1 { pointer to PROCESS_INF } else begin if ProcessMsg then begin repeat Application.ProcessMessages; GetExitCodeProcess(ProcessInfo.hProcess, Cardinal(Result)); until (Result <> STILL_ACTIVE) or Application.Terminated; end else begin WaitforSingleObject(ProcessInfo.hProcess, INFINITE); GetExitCodeProcess(ProcessInfo.hProcess, Cardinal(Result)); end; end; end; // 用管道方式在 Dir 目录执行 CmdLine,Output 返回输出信息, // dwExitCode 返回退出码。如果成功返回 True function WinExecWithPipe(const CmdLine, Dir: string; slOutput: TStrings; var dwExitCode: Cardinal): Boolean; var HOutRead, HOutWrite: THandle; StartInfo: TStartupInfo; ProceInfo: TProcessInformation; sa: TSecurityAttributes; InStream: THandleStream; strTemp: string; PDir: PChar; procedure ReadLinesFromPipe(IsEnd: Boolean); var s: string; ls: TStringList; i: Integer; begin if InStream.Position < InStream.Size then begin SetLength(s, InStream.Size - InStream.Position); InStream.Read(PChar(s)^, InStream.Size - InStream.Position); strTemp := strTemp + s; ls := TStringList.Create; try ls.Text := strTemp; for i := 0 to ls.Count - 2 do slOutput.Add(ls[i]); strTemp := ls[ls.Count - 1]; finally ls.Free; end; end; if IsEnd and (strTemp <> '') then begin slOutput.Add(strTemp); strTemp := ''; end; end; begin dwExitCode := 0; Result := False; try FillChar(sa, sizeof(sa), 0); sa.nLength := sizeof(sa); sa.bInheritHandle := True; sa.lpSecurityDescriptor := nil; InStream := nil; strTemp := ''; HOutRead := INVALID_HANDLE_VALUE; HOutWrite := INVALID_HANDLE_VALUE; try Win32Check(CreatePipe(HOutRead, HOutWrite, @sa, 0)); FillChar(StartInfo, SizeOf(StartInfo), 0); StartInfo.cb := SizeOf(StartInfo); StartInfo.wShowWindow := SW_HIDE; StartInfo.dwFlags := STARTF_USESTDHANDLES + STARTF_USESHOWWINDOW; StartInfo.hStdError := HOutWrite; StartInfo.hStdInput := GetStdHandle(STD_INPUT_HANDLE); StartInfo.hStdOutput := HOutWrite; InStream := THandleStream.Create(HOutRead); if Dir <> '' then PDir := PChar(Dir) else PDir := nil; Win32Check(CreateProcess(nil, //lpApplicationName: PChar PChar(CmdLine), //lpCommandLine: PChar nil, //lpProcessAttributes: PSecurityAttributes nil, //lpThreadAttributes: PSecurityAttributes True, //bInheritHandles: BOOL NORMAL_PRIORITY_CLASS, //CREATE_NEW_CONSOLE, nil, PDir, StartInfo, ProceInfo)); while WaitForSingleObject(ProceInfo.hProcess, 100) = WAIT_TIMEOUT do begin ReadLinesFromPipe(False); Application.ProcessMessages; //if Application.Terminated then break; end; ReadLinesFromPipe(True); GetExitCodeProcess(ProceInfo.hProcess, dwExitCode); CloseHandle(ProceInfo.hProcess); CloseHandle(ProceInfo.hThread); Result := True; finally if InStream <> nil then InStream.Free; if HOutRead <> INVALID_HANDLE_VALUE then CloseHandle(HOutRead); if HOutWrite <> INVALID_HANDLE_VALUE then CloseHandle(HOutWrite); end; except ; end; end; function WinExecWithPipe(const CmdLine, Dir: string; var Output: string; var dwExitCode: Cardinal): Boolean; var slOutput: TStringList; begin slOutput := TStringList.Create; try Result := WinExecWithPipe(CmdLine, Dir, slOutput, dwExitCode); Output := slOutput.Text; finally slOutput.Free; end; end; // 应用程序路径 function AppPath: string; begin Result := ExtractFilePath(Application.ExeName); end; // 当前执行模块所在的路径 function ModulePath: string; var ModName: array[0..MAX_PATH] of Char; begin SetString(Result, ModName, GetModuleFileName(HInstance, ModName, SizeOf(ModName))); Result := ExtractFilePath(Result); end; const HKLM_CURRENT_VERSION_WINDOWS = 'Software\Microsoft\Windows\CurrentVersion'; HKLM_CURRENT_VERSION_NT = 'Software\Microsoft\Windows NT\CurrentVersion'; function RelativeKey(const Key: string): PChar; begin Result := PChar(Key); if (Key <> '') and (Key[1] = '\') then Inc(Result); end; function RegReadStringDef(const RootKey: HKEY; const Key, Name, Def: string): string; var RegKey: HKEY; Size: DWORD; StrVal: string; RegKind: DWORD; begin Result := Def; if RegOpenKeyEx(RootKey, RelativeKey(Key), 0, KEY_READ, RegKey) = ERROR_SUCCESS then begin RegKind := 0; Size := 0; if RegQueryValueEx(RegKey, PChar(Name), nil, @RegKind, nil, @Size) = ERROR_SUCCESS then if RegKind in [REG_SZ, REG_EXPAND_SZ] then begin SetLength(StrVal, Size); if RegQueryValueEx(RegKey, PChar(Name), nil, @RegKind, PByte(StrVal), @Size) = ERROR_SUCCESS then begin SetLength(StrVal, StrLen(PChar(StrVal))); Result := StrVal; end; end; RegCloseKey(RegKey); end; end; procedure StrResetLength(var S: AnsiString); begin SetLength(S, StrLen(PChar(S))); end; // 取Program Files目录 function GetProgramFilesDir: string; begin Result := RegReadStringDef(HKEY_LOCAL_MACHINE, HKLM_CURRENT_VERSION_WINDOWS, 'ProgramFilesDir', ''); end; // 取Windows目录 function GetWindowsDir: string; var Required: Cardinal; begin Result := ''; Required := GetWindowsDirectory(nil, 0); if Required <> 0 then begin SetLength(Result, Required); GetWindowsDirectory(PChar(Result), Required); StrResetLength(Result); end; end; // 取临时文件路径 function GetWindowsTempPath: string; var Required: Cardinal; begin Result := ''; Required := GetTempPath(0, nil); if Required <> 0 then begin SetLength(Result, Required); GetTempPath(Required, PChar(Result)); StrResetLength(Result); end; end; // 返回一个临时文件名 function CnGetTempFileName(const Ext: string): string; var Path: string; begin Path := MakePath(GetWindowsTempPath); repeat Result := Path + IntToStr(Random(MaxInt)) + Ext; until not FileExists(Result); end; // 取系统目录 function GetSystemDir: string; var Required: Cardinal; begin Result := ''; Required := GetSystemDirectory(nil, 0); if Required <> 0 then begin SetLength(Result, Required); GetSystemDirectory(PChar(Result), Required); StrResetLength(Result); end; end; function GetLongPathNameA(lpszShortPath: PAnsiChar; lpszLongPath: PAnsiChar; cchBuffer: DWORD): DWORD; stdcall; external 'kernel32.dll' name 'GetLongPathNameA'; // 短文件名转长文件名 function ShortNameToLongName(const FileName: string): string; var Buf: array[0..MAX_PATH] of Char; begin if GetLongPathNameA(PChar(FileName), @Buf, MAX_PATH) > 0 then Result := Buf else Result := FileName; end; // 长文件名转短文件名 function LongNameToShortName(const FileName: string): string; var Buf: PChar; BufSize: Integer; begin BufSize := GetShortPathName(PChar(FileName), nil, 0) + 1; GetMem(Buf, BufSize); try GetShortPathName(PChar(FileName), Buf, BufSize); Result := Buf; finally FreeMem(Buf); end; end; // 取得真实长文件名,包含大小写 function GetTrueFileName(const FileName: string): string; var AName: string; FindName: string; function DoFindFile(const FName: string): string; var F: TSearchRec; begin if SysUtils.FindFirst(FName, faAnyFile, F) = 0 then Result := F.Name else Result := ExtractFileName(FName); SysUtils.FindClose(F); end; begin AName := MakeDir(FileName); if (Length(AName) > 3) and (AName[2] = ':') then begin Result := ''; while Length(AName) > 3 do begin FindName := DoFindFile(AName); if FindName = '' then begin Result := AName; Exit; end; if Result = '' then Result := FindName else Result := FindName + '\' + Result; AName := ExtractFileDir(AName); end; Result := UpperCase(AName) + Result; end else Result := AName; end; // 查找可执行文件的完整路径 function FindExecFile(const AName: string; var AFullName: string): Boolean; var fn: array[0..MAX_PATH] of Char; pc: PChar; begin if (0 = SearchPath(nil, PChar(AName), '.exe', SizeOf(fn), fn, pc)) and (0 = SearchPath(nil, PChar(AName), '.com', SizeOf(fn), fn, pc)) and (0 = SearchPath(nil, PChar(AName), '.bat', SizeOf(fn), fn, pc)) then begin Result := False; end else begin Result := True; AFullName := fn; end; end; function PidlFree(var IdList: PItemIdList): Boolean; var Malloc: IMalloc; begin Result := False; if IdList = nil then Result := True else begin if Succeeded(SHGetMalloc(Malloc)) and (Malloc.DidAlloc(IdList) > 0) then begin Malloc.Free(IdList); IdList := nil; Result := True; end; end; end; function PidlToPath(IdList: PItemIdList): string; begin SetLength(Result, MAX_PATH); if SHGetPathFromIdList(IdList, PChar(Result)) then StrResetLength(Result) else Result := ''; end; // 取得系统特殊文件夹位置,Folder 使用在 ShlObj 中定义的标识,如 CSIDL_DESKTOP function GetSpecialFolderLocation(const Folder: Integer): string; var FolderPidl: PItemIdList; begin if Succeeded(SHGetSpecialFolderLocation(0, Folder, FolderPidl)) then begin Result := PidlToPath(FolderPidl); PidlFree(FolderPidl); end else Result := ''; end; // 目录尾加'\'修正 function AddDirSuffix(const Dir: string): string; begin Result := Trim(Dir); if Result = '' then Exit; if not IsPathDelimiter(Result, Length(Result)) then Result := Result + {$IFDEF MSWINDOWS} '\'; {$ELSE} '/'; {$ENDIF}; end; // 目录尾加'\'修正 function MakePath(const Dir: string): string; begin Result := AddDirSuffix(Dir); end; // 路径尾去掉 '\' function MakeDir(const Path: string): string; begin Result := Trim(Path); if Result = '' then Exit; if Result[Length(Result)] in ['/', '\'] then Delete(Result, Length(Result), 1); end; // 路径中的 '\' 转成 '/' function GetUnixPath(const Path: string): string; begin Result := StringReplace(Path, '\', '/', [rfReplaceAll]); end; // 路径中的 '/' 转成 '\' function GetWinPath(const Path: string): string; begin Result := StringReplace(Path, '/', '\', [rfReplaceAll]); end; function PointerXX(var X: PChar): PChar; {$IFDEF PUREPASCAL} begin Result := X; Inc(X); end; {$ELSE} asm { EAX = X } MOV EDX, [EAX] INC dword ptr [EAX] MOV EAX, EDX end; {$ENDIF} function Evaluate(var X: Char; const Value: Char): Char; {$IFDEF PUREPASCAL} begin X := Value; Result := X; end; {$ELSE} asm { EAX = X EDX = Value (DL) } MOV [EAX], DL MOV AL, [EAX] end; {$ENDIF} // 文件名是否与通配符匹配,返回值为0表示匹配 function FileNameMatch(Pattern, FileName: PChar): Integer; var p, n: PChar; c: Char; begin p := Pattern; n := FileName; while Evaluate(c, PointerXX(p)^) <> #0 do begin case c of '?': begin if n^ = '.' then begin while (p^ <> '.') and (p^ <> #0) do begin if (p^ <> '?') and (p^ <> '*') then begin Result := -1; Exit; end; Inc(p); end; end else begin if n^ <> #0 then Inc(n); end; end; '>': begin if n^ = '.' then begin if ((n + 1)^ = #0) and (FileNameMatch(p, n+1) = 0) then begin Result := 0; Exit; end; if FileNameMatch(p, n) = 0 then begin Result := 0; Exit; end; Result := -1; Exit; end; if n^ = #0 then begin Result := FileNameMatch(p, n); Exit; end; Inc(n); end; '*': begin while n^ <> #0 do begin if FileNameMatch(p, n) = 0 then begin Result := 0; Exit; end; Inc(n); end; end; '<': begin while n^ <> #0 do begin if FileNameMatch(p, n) = 0 then begin Result := 0; Exit; end; if (n^ = '.') and (StrScan(n + 1, '.') = nil) then begin Inc(n); Break; end; Inc(n); end; end; '"': begin if (n^ = #0) and (FileNameMatch(p, n) = 0) then begin Result := 0; Exit; end; if n^ <> '.' then begin Result := -1; Exit; end; Inc(n); end; else if (c = '.') and (n^ = #0) then begin while p^ <> #0 do begin if (p^ = '*') and ((p + 1)^ = #0) then begin Result := 0; Exit; end; if p^ <> '?' then begin Result := -1; Exit; end; Inc(p); end; Result := 0; Exit; end; if c <> n^ then begin Result := -1; Exit; end; Inc(n); end; end; if n^ = #0 then begin Result := 0; Exit; end; Result := -1; end; // 文件名是否与扩展名通配符匹配 function MatchExt(const S, Ext: string): Boolean; begin if S = '.*' then begin Result := True; Exit; end; Result := FileNameMatch(PChar(S), PChar(Ext)) = 0; end; // 文件名是否与通配符匹配 function MatchFileName(const S, FN: string): Boolean; begin if S = '*.*' then begin Result := True; Exit; end; Result := FileNameMatch(PChar(S), PChar(FN)) = 0; end; // 得到大小写是否敏感的字符串 function _CaseSensitive(const CaseSensitive: Boolean; const S: string): string; begin if CaseSensitive then Result := S else Result := AnsiUpperCase(S); end; // 转换扩展名通配符字符串为通配符列表 procedure FileExtsToStrings(const FileExts: string; ExtList: TStrings; CaseSensitive: Boolean); var Exts: string; i: Integer; begin Exts := StringReplace(FileExts, ';', ',', [rfReplaceAll]); ExtList.CommaText := Exts; for i := 0 to ExtList.Count - 1 do begin if StrScan(PChar(ExtList[i]), '.') <> nil then begin ExtList[i] := _CaseSensitive(CaseSensitive, ExtractFileExt(ExtList[i])); end else begin ExtList[i] := '.' + _CaseSensitive(CaseSensitive, ExtList[i]); end; if ExtList[i] = '.*' then begin if i > 0 then ExtList.Exchange(0, i); Exit; end; end; end; // 文件名是否匹配扩展名通配符 function FileMatchesExts(const FileName, FileExts: string; CaseSensitive: Boolean): Boolean; var ExtList: TStrings; FExt: string; i: Integer; begin ExtList := TStringList.Create; try FileExtsToStrings(FileExts, ExtList, CaseSensitive); FExt := _CaseSensitive(CaseSensitive, ExtractFileExt(FileName)); Result := False; for i := 0 to ExtList.Count - 1 do begin if MatchExt(ExtList[i], FExt) then begin Result := True; Exit; end; end; finally ExtList.Free; end; end; // 文件名是否匹配扩展名通配符 function FileMatchesExts(const FileName: string; ExtList: TStrings): Boolean; var FExt: string; i: Integer; begin FExt := _CaseSensitive(False, ExtractFileExt(FileName)); Result := False; for i := 0 to ExtList.Count - 1 do begin if MatchExt(ExtList[i], FExt) then begin Result := True; Exit; end; end; end; // 转换文件通配符字符串为通配符列表 procedure FileMasksToStrings(const FileMasks: string; MaskList: TStrings; CaseSensitive: Boolean); var Exts: string; i: Integer; begin Exts := StringReplace(FileMasks, ';', ',', [rfReplaceAll]); MaskList.CommaText := Exts; for i := 0 to MaskList.Count - 1 do begin if StrScan(PChar(MaskList[i]), '.') <> nil then begin if MaskList[i][1] = '.' then MaskList[i] := '*' + _CaseSensitive(CaseSensitive, MaskList[i]) else MaskList[i] := _CaseSensitive(CaseSensitive, MaskList[i]); end else begin MaskList[i] := '*.' + _CaseSensitive(CaseSensitive, MaskList[i]); end; if MaskList[i] = '*.*' then begin if i > 0 then MaskList.Exchange(0, i); Exit; end; end; end; // 文件名是否匹配通配符 function FileMatchesMasks(const FileName, FileMasks: string; CaseSensitive: Boolean): Boolean; var MaskList: TStrings; FFileName: string; i: Integer; begin MaskList := TStringList.Create; try FileMasksToStrings(FileMasks, MaskList, CaseSensitive); FFileName := _CaseSensitive(CaseSensitive, ExtractFileName(FileName)); Result := False; for i := 0 to MaskList.Count - 1 do begin if MatchFileName(MaskList[i], FFileName) then begin Result := True; Exit; end; end; finally MaskList.Free; end; end; // 文件名是否匹配通配符 function FileMatchesMasks(const FileName: string; MaskList: TStrings): Boolean; var FFileName: string; i: Integer; begin FFileName := _CaseSensitive(False, ExtractFileName(FileName)); Result := False; for i := 0 to MaskList.Count - 1 do begin if MatchFileName(MaskList[i], FFileName) then begin Result := True; Exit; end; end; end; // 文件名与扩展名列表比较 function FileMatchesExts(const FileName, FileExts: string): Boolean; begin Result := FileMatchesMasks(FileName, FileExts, False); end; // 判断文件是否正在使用 function IsFileInUse(const FName: string): Boolean; var HFileRes: HFILE; begin Result := False; if not FileExists(FName) then Exit; HFileRes := CreateFile(PChar(FName), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); Result := (HFileRes = INVALID_HANDLE_VALUE); if not Result then CloseHandle(HFileRes); end; // 判断文件是否为 Ascii 文件 function IsAscii(FileName: string): Boolean; const Sett=2048; var I: Integer; AFile: File; Bool: Boolean; TotSize, IncSize, ReadSize: Integer; C: array[0..Sett] of Byte; begin Result := False; if FileExists(FileName) then begin {$I-} AssignFile(AFile, FileName); Reset(AFile, 1); TotSize := FileSize(AFile); IncSize := 0; Bool := True; while (IncSize < TotSize) and (Bool = True) do begin ReadSize := Sett; if IncSize + ReadSize > TotSize then ReadSize := TotSize - IncSize; IncSize := IncSize + ReadSize; BlockRead(AFile, C, ReadSize); for I := 0 to ReadSize-1 do // Iterate if (C[I] < 32) and (not(C[I] in [9, 10, 13, 26])) then Bool := False; end; // while CloseFile(AFile); {$I+} if IOResult <> 0 then Result := False else Result := Bool; end; end; // 判断文件是否是有效的文件名 function IsValidFileName(const Name: string): Boolean; var i: Integer; begin Result := False; if (Name = '') or (Length(Name) > MAX_PATH) then Exit; for i := 1 to Length(Name) do begin if Name[i] in InvalidFileNameChar then Exit; end; Result := True; end; // 返回有效的文件名 function GetValidFileName(const Name: string): string; var i: Integer; begin Result := Name; for i := Length(Result) downto 1 do begin if Result[i] in InvalidFileNameChar then Delete(Result, i, 1); end; if Length(Result) > MAX_PATH - 1 then Result := Copy(Result, 1, MAX_PATH - 1); end; // 设置文件时间 function SetFileDate(const FileName: string; CreationTime, LastWriteTime, LastAccessTime: TFileTime): Boolean; var FileHandle: Integer; begin FileHandle := FileOpen(FileName, fmOpenWrite or fmShareDenyNone); if FileHandle > 0 then begin SetFileTime(FileHandle, @CreationTime, @LastAccessTime, @LastWriteTime); FileClose(FileHandle); Result := True; end else Result := False; end; // 取文件时间 function GetFileDate(const FileName: string; var CreationTime, LastWriteTime, LastAccessTime: TFileTime): Boolean; var FileHandle: Integer; begin FileHandle := FileOpen(FileName, fmOpenRead or fmShareDenyNone); if FileHandle > 0 then begin GetFileTime(FileHandle, @CreationTime, @LastAccessTime, @LastWriteTime); FileClose(FileHandle); Result := True; end else Result := False; end; // 取得与文件相关的图标 // FileName: e.g. "e:\hao\a.txt" // 成功则返回True function GetFileIcon(const FileName: string; var Icon: TIcon): Boolean; var SHFileInfo: TSHFileInfo; h: HWND; begin if not Assigned(Icon) then Icon := TIcon.Create; h := SHGetFileInfo(PChar(FileName), 0, SHFileInfo, SizeOf(SHFileInfo), SHGFI_ICON or SHGFI_SYSICONINDEX); Icon.Handle := SHFileInfo.hIcon; Result := (h <> 0); end; // 文件时间转本地日期时间 function FileTimeToDateTime(const FileTime: TFileTime): TDateTime; var SystemTime: TSystemTime; begin SystemTime := FileTimeToLocalSystemTime(FileTime); with SystemTime do Result := EncodeDate(wYear, wMonth, wDay) + EncodeTime(wHour, wMinute, wSecond, wMilliseconds); end; // 本地日期时间转文件时间 function DateTimeToFileTime(const DateTime: TDateTime): TFileTime; var SystemTime: TSystemTime; begin with SystemTime do begin DecodeDate(DateTime, wYear, wMonth, wDay); DecodeTime(DateTime, wHour, wMinute, wSecond, wMilliseconds); end; Result := LocalSystemTimeToFileTime(SystemTime); end; // 文件时间转本地时间 function FileTimeToLocalSystemTime(FTime: TFileTime): TSystemTime; var STime: TSystemTime; begin FileTimeToLocalFileTime(FTime, FTime); FileTimeToSystemTime(FTime, STime); Result := STime; end; // 本地时间转文件时间 function LocalSystemTimeToFileTime(STime: TSystemTime): TFileTime; var FTime: TFileTime; begin SystemTimeToFileTime(STime, FTime); LocalFileTimeToFileTime(FTime, FTime); Result := FTime; end; const MinutesPerDay = 60 * 24; SecondsPerDay = MinutesPerDay * 60; // UTC 时间转本地时间 function DateTimeToLocalDateTime(DateTime: TDateTime): TDateTime; var TimeZoneInfo: TTimeZoneInformation; begin FillChar(TimeZoneInfo, SizeOf(TimeZoneInfo), #0); if GetTimeZoneInformation(TimeZoneInfo) = TIME_ZONE_ID_DAYLIGHT then Result := DateTime - ((TimeZoneInfo.Bias + TimeZoneInfo.DaylightBias) / MinutesPerDay) else Result := DateTime - (TimeZoneInfo.Bias / MinutesPerDay); end; // 本地时间转 UTC 时间 function LocalDateTimeToDateTime(DateTime: TDateTime): TDateTime; var TimeZoneInfo: TTimeZoneInformation; begin FillChar(TimeZoneInfo, SizeOf(TimeZoneInfo), #0); if GetTimeZoneInformation(TimeZoneInfo) = TIME_ZONE_ID_DAYLIGHT then Result := DateTime + ((TimeZoneInfo.Bias + TimeZoneInfo.DaylightBias) / MinutesPerDay) else Result := DateTime + (TimeZoneInfo.Bias / MinutesPerDay); end; {$IFDEF COMPILER5} const LessThanValue = Low(TValueRelationship); EqualsValue = 0; GreaterThanValue = High(TValueRelationship); function CompareValue(const A, B: Int64): TValueRelationship; begin if A = B then Result := EqualsValue else if A < B then Result := LessThanValue else Result := GreaterThanValue; end; // AText 是否以 ASubText 开头 function AnsiStartsText(const ASubText, AText: string): Boolean; begin Result := AnsiPos(AnsiUpperCase(ASubText), AnsiUpperCase(AText)) = 1; end; function AnsiReplaceText(const AText, AFromText, AToText: string): string; begin Result := StringReplace(AText, AFromText, AToText, [rfReplaceAll, rfIgnoreCase]); end; {$ENDIF} {$IFNDEF COMPILER7_UP} // AText 是否包含 ASubText function AnsiContainsText(const AText, ASubText: string): Boolean; begin Result := AnsiPos(AnsiUpperCase(ASubText), AnsiUpperCase(AText)) > 0; end; {$ENDIF} // 比较 SubText 在两个字符串中出现的位置的大小,如果相等则比较字符串本身,忽略大小写 function CompareTextPos(const ASubText, AText1, AText2: string): TValueRelationship; begin Result := 0; if ASubText <> '' then Result := CompareValue(AnsiPos(AnsiUpperCase(ASubText), AnsiUpperCase(AText1)), AnsiPos(AnsiUpperCase(ASubText), AnsiUpperCase(AText2))); if Result = 0 then Result := CompareText(AText1, AText2); end; // 创建备份文件 function CreateBakFile(const FileName, Ext: string): Boolean; var BakFileName: string; AExt: string; begin if (Ext <> '') and (Ext[1] = '.') then AExt := Ext else AExt := '.' + Ext; BakFileName := FileName + AExt; Result := CopyFile(PChar(FileName), PChar(BakFileName), False); end; // 删除整个目录 function Deltree(Dir: string; DelRoot: Boolean; DelEmptyDirOnly: Boolean): Boolean; var sr: TSearchRec; fr: Integer; begin Result := True; if not DirectoryExists(Dir) then Exit; fr := FindFirst(AddDirSuffix(Dir) + '*.*', faAnyFile, sr); try while fr = 0 do begin if (sr.Name <> '.') and (sr.Name <> '..') then begin SetFileAttributes(PChar(AddDirSuffix(Dir) + sr.Name), FILE_ATTRIBUTE_NORMAL); if sr.Attr and faDirectory = faDirectory then Result := Deltree(AddDirSuffix(Dir) + sr.Name, True, DelEmptyDirOnly) else if not DelEmptyDirOnly then Result := DeleteFile(AddDirSuffix(Dir) + sr.Name); end; fr := FindNext(sr); end; finally FindClose(sr); end; if DelRoot then Result := RemoveDir(Dir); end; // 删除整个目录中的空目录, DelRoot 表示是否删除目录本身 procedure DelEmptyTree(Dir: string; DelRoot: Boolean = True); var sr: TSearchRec; fr: Integer; begin fr := FindFirst(AddDirSuffix(Dir) + '*.*', faDirectory, sr); try while fr = 0 do begin if (sr.Name <> '.') and (sr.Name <> '..') and (sr.Attr and faDirectory = faDirectory) then begin SetFileAttributes(PChar(AddDirSuffix(Dir) + sr.Name), FILE_ATTRIBUTE_NORMAL); DelEmptyTree(AddDirSuffix(Dir) + sr.Name, True); end; fr := FindNext(sr); end; finally FindClose(sr); end; if DelRoot then RemoveDir(Dir); end; // 取文件夹文件数 function GetDirFiles(Dir: string): Integer; var sr: TSearchRec; fr: Integer; begin Result := 0; fr := FindFirst(AddDirSuffix(Dir) + '*.*', faAnyFile, sr); while fr = 0 do begin if (sr.Name <> '.') and (sr.Name <> '..') then Inc(Result); fr := FindNext(sr); end; FindClose(sr); end; function FindFormByClass(AClass: TClass): TForm; var i: Integer; begin Result := nil; for i := 0 to Screen.FormCount - 1 do begin if Screen.Forms[i] is AClass then begin Result := Screen.Forms[i]; Exit; end; end; end; var FindAbort: Boolean; // 查找指定目录下文件 function FindFile(const Path: string; const FileName: string = '*.*'; Proc: TFindCallBack = nil; DirProc: TDirCallBack = nil; bSub: Boolean = True; bMsg: Boolean = True): Boolean; procedure DoFindFile(const Path, SubPath: string; const FileName: string; Proc: TFindCallBack; DirProc: TDirCallBack; bSub: Boolean; bMsg: Boolean); var APath: string; Info: TSearchRec; Succ: Integer; begin FindAbort := False; APath := MakePath(MakePath(Path) + SubPath); Succ := FindFirst(APath + FileName, faAnyFile - faVolumeID, Info); try while Succ = 0 do begin if (Info.Name <> '.') and (Info.Name <> '..') then begin if (Info.Attr and faDirectory) <> faDirectory then begin if Assigned(Proc) then Proc(APath + Info.FindData.cFileName, Info, FindAbort); end end; if bMsg then Application.ProcessMessages; if FindAbort then Exit; Succ := FindNext(Info); end; finally FindClose(Info); end; if bSub then begin Succ := FindFirst(APath + '*.*', faAnyFile - faVolumeID, Info); try while Succ = 0 do begin if (Info.Name <> '.') and (Info.Name <> '..') and (Info.Attr and faDirectory = faDirectory) then begin if Assigned(DirProc) then DirProc(MakePath(SubPath) + Info.Name); DoFindFile(Path, MakePath(SubPath) + Info.Name, FileName, Proc, DirProc, bSub, bMsg); if FindAbort then Exit; end; Succ := FindNext(Info); end; finally FindClose(Info); end; end; end; begin DoFindFile(Path, '', FileName, Proc, DirProc, bSub, bMsg); Result := not FindAbort; end; // 文件打开方式 function OpenWith(const FileName: string): Integer; begin Result := ShellExecute(Application.Handle, 'open', 'rundll32.exe', PChar('shell32.dll,OpenAs_RunDLL ' + FileName), '', SW_SHOW); end; // 检查指定的应用程序是否正在运行 // 作者:周劲羽 2002.08.12 function CheckAppRunning(const FileName: string; var Running: Boolean): Boolean; var hSnap: THandle; ppe: TProcessEntry32; AName: string; begin Result := False; AName := Trim(FileName); if AName = '' then Exit; // 如果为空直接退出 if ExtractFileExt(FileName) = '' then // 默认扩展名为 EXE AName := AName + '.EXE'; hSnap := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); // 创建当前进程快照 if hSnap <> INVALID_HANDLE_VALUE then try if Process32First(hSnap, ppe) then // 取第一个进程信息 repeat if AnsiCompareText(ExtractFileName(ppe.szExeFile), AName) = 0 then begin // 比较应用程序名 Running := True; Result := True; Exit; end; until not Process32Next(hSnap, ppe); // 取下一个进程信息 Result := GetLastError = ERROR_NO_MORE_FILES; // 判断查找是否正常结束 finally CloseHandle(hSnap); // 关闭句柄 end; end; // 取文件版本号 function GetFileVersionNumber(const FileName: string): TVersionNumber; var VersionInfoBufferSize: DWORD; dummyHandle: DWORD; VersionInfoBuffer: Pointer; FixedFileInfoPtr: PVSFixedFileInfo; VersionValueLength: UINT; begin FillChar(Result, SizeOf(Result), 0); if not FileExists(FileName) then Exit; VersionInfoBufferSize := GetFileVersionInfoSize(PChar(FileName), dummyHandle); if VersionInfoBufferSize = 0 then Exit; GetMem(VersionInfoBuffer, VersionInfoBufferSize); try try Win32Check(GetFileVersionInfo(PChar(FileName), dummyHandle, VersionInfoBufferSize, VersionInfoBuffer)); Win32Check(VerQueryValue(VersionInfoBuffer, '\', Pointer(FixedFileInfoPtr), VersionValueLength)); except Exit; end; Result.Major := FixedFileInfoPtr^.dwFileVersionMS shr 16; Result.Minor := FixedFileInfoPtr^.dwFileVersionMS; Result.Release := FixedFileInfoPtr^.dwFileVersionLS shr 16; Result.Build := FixedFileInfoPtr^.dwFileVersionLS; finally FreeMem(VersionInfoBuffer); end; end; // 取文件版本字符串 function GetFileVersionStr(const FileName: string): string; begin with GetFileVersionNumber(FileName) do Result := Format('%d.%d.%d.%d', [Major, Minor, Release, Build]); end; // 取文件信息 function GetFileInfo(const FileName: string; var FileSize: Int64; var FileTime: TDateTime): Boolean; var Handle: THandle; FindData: TWin32FindData; begin Result := False; Handle := FindFirstFile(PChar(FileName), FindData); if Handle <> INVALID_HANDLE_VALUE then begin Windows.FindClose(Handle); if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then begin Int64Rec(FileSize).Lo := FindData.nFileSizeLow; Int64Rec(FileSize).Hi := FindData.nFileSizeHigh; FileTime := FileTimeToDateTime(FindData.ftLastWriteTime); Result := True; end; end; end; // 取文件长度 function GetFileSize(const FileName: string): Int64; var FileTime: TDateTime; begin Result := -1; GetFileInfo(FileName, Result, FileTime); end; // 取文件Delphi格式日期时间 function GetFileDateTime(const FileName: string): TDateTime; var Size: Int64; begin Result := 0; GetFileInfo(FileName, Size, Result); end; // 将文件读为字符串 function LoadStringFromFile(const FileName: string): string; begin try with TStringList.Create do try LoadFromFile(FileName); Result := Text; finally Free; end; except Result := ''; end; end; // 保存字符串到为文件 function SaveStringToFile(const S, FileName: string): Boolean; begin try with TStringList.Create do try Text := S; SaveToFile(FileName); Result := True; finally Free; end; except Result := False; end; end; //------------------------------------------------------------------------------ // 环境变量相关 //------------------------------------------------------------------------------ procedure MultiSzToStrings(const Dest: TStrings; const Source: PChar); var P: PChar; begin Assert(Dest <> nil); Dest.Clear; if Source <> nil then begin P := Source; while P^ <> #0 do begin Dest.Add(P); P := StrEnd(P); Inc(P); end; end; end; function DelEnvironmentVar(const Name: string): Boolean; begin Result := SetEnvironmentVariable(PChar(Name), nil); end; function ExpandEnvironmentVar(var Value: string): Boolean; var R: Integer; Expanded: string; begin SetLength(Expanded, 1); R := ExpandEnvironmentStrings(PChar(Value), PChar(Expanded), 0); SetLength(Expanded, R); Result := ExpandEnvironmentStrings(PChar(Value), PChar(Expanded), R) <> 0; if Result then begin StrResetLength(Expanded); Value := Expanded; end; end; function GetEnvironmentVar(const Name: string; var Value: string; Expand: Boolean): Boolean; var R: DWORD; begin R := GetEnvironmentVariable(PChar(Name), nil, 0); SetLength(Value, R); R := GetEnvironmentVariable(PChar(Name), PChar(Value), R); Result := R <> 0; if not Result then Value := '' else begin SetLength(Value, R); if Expand then ExpandEnvironmentVar(Value); end; end; function GetEnvironmentVars(const Vars: TStrings; Expand: Boolean): Boolean; var Raw: PChar; Expanded: string; I: Integer; begin Vars.Clear; Raw := GetEnvironmentStrings; try MultiSzToStrings(Vars, Raw); Result := True; finally FreeEnvironmentStrings(Raw); end; if Expand then begin for I := 0 to Vars.Count - 1 do begin Expanded := Vars[I]; if ExpandEnvironmentVar(Expanded) then Vars[I] := Expanded; end; end; end; function SetEnvironmentVar(const Name, Value: string): Boolean; begin Result := SetEnvironmentVariable(PChar(Name), PChar(Value)); end; //------------------------------------------------------------------------------ // 扩展的字符串操作函数 //------------------------------------------------------------------------------ // 判断字符串是否可转换成浮点型 function IsFloat(const s: String): Boolean; var I: Real; E: Integer; begin Val(s, I, E); Result := E = 0; E := Trunc( I ); end; // 判断字符串是否可转换成整型 function IsInt(const s: String): Boolean; var I: Integer; E: Integer; begin Val(s, I, E); Result := E = 0; E := Trunc( I ); end; // 判断字符串是否可转换成 DateTime function IsDateTime(const s: string): Boolean; begin try StrToDateTime(s); Result := True; except Result := False; end; end; // 判断是否有效的邮件地址 function IsValidEmail(const s: string): Boolean; var i: Integer; AtCount: Integer; begin Result := False; if s = '' then Exit; AtCount := 0; for i := 1 to Length(s) do begin if s[i] = '@' then begin Inc(AtCount); if AtCount > 1 then Exit; end else if not (s[i] in ['0'..'9', 'a'..'z', 'A'..'Z', '_', '.', '-']) then Exit; end; Result := AtCount = 1; end; // 判断s1是否包含在s2中 function InStr(const sShort: string; const sLong: string): Boolean; var s1, s2: string; begin s1 := LowerCase(sShort); s2 := LowerCase(sLong); Result := Pos(s1, s2) > 0; end; // 扩展整数转字符串函数,参数分别为目标数、长度、填充字符(默认为0) function IntToStrEx(Value: Integer; Len: Integer; FillChar: Char = '0'): string; begin Result := IntToStr(Value); while Length(Result) < Len do Result := FillChar + Result; end; // 带分隔符的整数-字符转换 function IntToStrSp(Value: Integer; SpLen: Integer = 3; Sp: Char = ','): string; var s: string; i, j: Integer; begin s := IntToStr(Value); Result := ''; j := 0; for i := Length(s) downto 1 do begin Result := s[i] + Result; Inc(j); if ((j mod SpLen) = 0) and (i <> 1) then Result := Sp + Result; end; end; function StrSpToInt(Value: String; Sp: Char = ','): Int64; begin Result := StrToInt64(AnsiReplaceText(Value, Sp, '')); end; // 返回字符串右边的字符 function StrRight(Str: string; Len: Integer): string; begin if Len >= Length(Str) then Result := '' else Result := Copy(Str, Length(Str) - Len + 1, Len); end; // 返回字符串左边的字符 function StrLeft(Str: string; Len: Integer): string; begin if Len >= Length(Str) then Result := Str else Result := Copy(Str, 1, Len); end; // 字节转二进制串 function ByteToBin(Value: Byte): string; const V: Byte = 1; var i: Integer; begin for i := 7 downto 0 do if (V shl i) and Value <> 0 then Result := Result + '1' else Result := Result + '0'; end; // 返回字符串行 function GetLine(C: Char; Len: Integer): string; begin Result := StringOfChar(C, Len); end; // 返回文本文件的行数 function GetTextFileLineCount(FileName: String): Integer; var Lines: TStringList; begin Result := 0; Lines := TStringList.Create; try if FileExists(FileName) then begin Lines.LoadFromFile(FileName); Result := Result + Lines.Count; end; finally Lines.Free; end; end; // 返回空格串 function Spc(Len: Integer): string; begin Result := StringOfChar(' ', Len); end; // 交换字串 procedure SwapStr(var s1, s2: string); var tempstr: string; begin tempstr := s1; s1 := s2; s2 := tempstr; end; // 分割"非数字+数字"格式的字符串中的非数字和数字 procedure SeparateStrAndNum(const AInStr: string; var AOutStr: string; var AOutNum: Integer); var iLen: Integer; begin iLen := Length(AInStr); while (iLen > 0) and (AInStr[iLen] in ['0'..'9']) do Dec(iLen); AOutStr := Copy(AInStr, iLen + 1, MaxInt); if AOutStr = '' then AOutNum := -1 else AOutNum := StrToInt(AOutStr); AOutStr := Copy(AInStr, 1, iLen); end; // 去除被引用的字符串的引用 function UnQuotedStr(const str: string; const ch: Char; const sep: string = ''): string; var s: string; ps: PChar; begin Result := ''; s := str; ps := PChar(s); while ps <> nil do begin ps := AnsiStrScan(ps, ch); s := AnsiExtractQuotedStr(ps, ch); if (Result = '') or (s = '') then Result := Result + s else Result := Result + sep + s; end; end; // 查找字符串中出现的第 Counter 次的字符的位置 function CharPosWithCounter(const Sub: Char; const AStr: string; Counter: Integer = 1): Integer; var I, J: Integer; begin Result := 0; if Counter <= 0 then Exit; if AStr <> '' then begin J := 0; for I := 1 to Length(AStr) do begin if AStr[I] = Sub then Inc(J); if J = Counter then begin Result := I; Exit; end; end; end; end; function CountCharInStr(const Sub: Char; const AStr: string): Integer; var I: Integer; begin Result := 0; if AStr = '' then Exit; for I := 1 to Length(AStr) do if AStr[I] = Sub then Inc(Result); end; // 判断字符是否有效标识符字符,First 表示是否为首字符 function IsValidIdentChar(C: Char; First: Boolean): Boolean; begin if First then Result := C in Alpha else Result := C in AlphaNumeric; end; const csLinesCR = #13#10; csStrCR = '\n'; // 多行文本转单行(换行符转'\n') {$IFDEF COMPILER5} function BoolToStr(B: Boolean; UseBoolStrs: Boolean = False): string; const cSimpleBoolStrs: array [boolean] of String = ('0', '-1'); begin if UseBoolStrs then begin if B then Result := 'True' else Result := 'False'; end else Result := cSimpleBoolStrs[B]; end; {$ENDIF COMPILER5} function LinesToStr(const Lines: string): string; begin Result := StringReplace(Lines, csLinesCR, csStrCR, [rfReplaceAll]); end; // 单行文本转多行('\n'转换行符) function StrToLines(const Str: string): string; begin Result := StringReplace(Str, csStrCR, csLinesCR, [rfReplaceAll]); end; // 日期转字符串,使用 yyyy.mm.dd 格式 function MyDateToStr(Date: TDate): string; begin Result := CnDateToStr(Date); end; const csCount = 'Count'; csItem = 'Item'; procedure ReadStringsFromIni(Ini: TCustomIniFile; const Section: string; Strings: TStrings); var Count, i: Integer; begin Strings.Clear; Count := Ini.ReadInteger(Section, csCount, 0); for i := 0 to Count - 1 do if Ini.ValueExists(Section, csItem + IntToStr(i)) then Strings.Add(Ini.ReadString(Section, csItem + IntToStr(i), '')); end; procedure WriteStringsToIni(Ini: TCustomIniFile; const Section: string; Strings: TStrings); var i: Integer; begin Ini.WriteInteger(Section, csCount, Strings.Count); for i := 0 to Strings.Count - 1 do Ini.WriteString(Section, csItem + IntToStr(i), Strings[i]); end; // 版本号转成字符串,如 $01020000 --> '1.2.0.0' function VersionToStr(Version: DWORD): string; begin Result := Format('%d.%d.%d.%d', [Version div $1000000, version mod $1000000 div $10000, version mod $10000 div $100, version mod $100]); end; // 字符串转成版本号,如 '1.2.0.0' --> $01020000,如果格式不正确,返回 $01000000 function StrToVersion(s: string): DWORD; var Strs: TStrings; begin try Strs := TStringList.Create; try Strs.Text := StringReplace(s, '.', #13#10, [rfReplaceAll]); if Strs.Count = 4 then Result := StrToInt(Strs[0]) * $1000000 + StrToInt(Strs[1]) * $10000 + StrToInt(Strs[2]) * $100 + StrToInt(Strs[3]) else Result := $01000000; finally Strs.Free; end; except Result := $01000000; end; end; // 转换日期为 yyyy.mm.dd 格式字符串 function CnDateToStr(Date: TDateTime): string; begin Result := FormatDateTime('yyyy.mm.dd', Date); end; // 将 yyyy.mm.dd 格式字符串转换为日期 function CnStrToDate(const S: string): TDateTime; var i: Integer; Year, Month, Day: string; begin try i := 1; Year := ExtractSubstr(S, i, ['.', '/', '-']); Month := ExtractSubstr(S, i, ['.', '/', '-']); Day := ExtractSubstr(S, i, ['.', '/', '-']); Result := EncodeDate(StrToInt(Year), StrToInt(Month), StrToInt(Day)); except Result := 0; end; end; // 日期时间转 '20030203132345' 式样的 14 位数字字符串 function DateTimeToFlatStr(const DateTime: TDateTime): string; var Year, Month, Day, Hour, Min, Sec, MSec: Word; begin DecodeDate(DateTime, Year, Month, Day); DecodeTime(DateTime, Hour, Min, Sec, MSec); Result := IntToStrEx(Year, 4) + IntToStrEx(Month, 2) + IntToStrEx(Day, 2) + IntToStrEx(Hour, 2) + IntToStrEx(Min, 2) + IntToStrEx(Sec, 2); end; // '20030203132345' 式样的 14 位数字字符串转日期时间 function FlatStrToDateTime(const Section: string; var DateTime: TDateTime): Boolean; var Year, Month, Day, Hour, Min, Sec, MSec: Word; begin try Result := False; if Length(Section) <> 14 then Exit; Year := StrToInt(Copy(Section, 1, 4)); Month := StrToInt(Copy(Section, 5, 2)); Day := StrToInt(Copy(Section, 7, 2)); Hour := StrToInt(Copy(Section, 9, 2)); Min := StrToInt(Copy(Section, 11, 2)); Sec := StrToInt(Copy(Section, 13, 2)); MSec := 0; DateTime := EncodeDate(Year, Month, Day) + EncodeTime(Hour, Min, Sec, MSec); Result := True; except Result := False; end; end; // 字符串转注册表根键,支持 'HKEY_CURRENT_USER' 'HKCR' 长短两种格式 function StrToRegRoot(const s: string): HKEY; begin if SameText(s, 'HKEY_CLASSES_ROOT') or SameText(s, 'HKCR') then Result := HKEY_CLASSES_ROOT else if SameText(s, 'HKEY_CURRENT_USER') or SameText(s, 'HKCU') then Result := HKEY_CURRENT_USER else if SameText(s, 'HKEY_LOCAL_MACHINE') or SameText(s, 'HKLM') then Result := HKEY_LOCAL_MACHINE else if SameText(s, 'HKEY_USERS') or SameText(s, 'HKU') then Result := HKEY_USERS else if SameText(s, 'HKEY_PERFORMANCE_DATA') or SameText(s, 'HKPD') then Result := HKEY_PERFORMANCE_DATA else if SameText(s, 'HKEY_CURRENT_CONFIG') or SameText(s, 'HKCC') then Result := HKEY_CURRENT_CONFIG else if SameText(s, 'HKEY_DYN_DATA') or SameText(s, 'HKDD') then Result := HKEY_DYN_DATA else Result := HKEY_CURRENT_USER; end; // 注册表根键转字符串,可选 'HKEY_CURRENT_USER' 'HKCR' 长短两种格式 function RegRootToStr(Key: HKEY; ShortFormat: Boolean): string; begin if Key = HKEY_CLASSES_ROOT then if ShortFormat then Result := 'HKCR' else Result := 'HKEY_CLASSES_ROOT' else if Key = HKEY_CURRENT_USER then if ShortFormat then Result := 'HKCU' else Result := 'HKEY_CURRENT_USER' else if Key = HKEY_LOCAL_MACHINE then if ShortFormat then Result := 'HKLM' else Result := 'HKEY_LOCAL_MACHINE' else if Key = HKEY_USERS then if ShortFormat then Result := 'HKU' else Result := 'HKEY_USERS' else if Key = HKEY_PERFORMANCE_DATA then if ShortFormat then Result := 'HKPD' else Result := 'HKEY_PERFORMANCE_DATA' else if Key = HKEY_CURRENT_CONFIG then if ShortFormat then Result := 'HKCC' else Result := 'HKEY_CURRENT_CONFIG' else if Key = HKEY_DYN_DATA then if ShortFormat then Result := 'HKDD' else Result := 'HKEY_DYN_DATA' else Result := '' end; // 从字符串中分离出子串 function ExtractSubstr(const S: string; var Pos: Integer; const Delims: TSysCharSet): string; var i: Integer; begin i := Pos; while (i <= Length(S)) and not (S[i] in Delims) do Inc(i); Result := Copy(S, Pos, i - Pos); if (i <= Length(S)) and (S[i] in Delims) then Inc(i); Pos := i; end; // 文件名通配符比较 function WildcardCompare(const FileWildcard, FileName: string; const IgnoreCase: Boolean): Boolean; function WildCompare(var WildS, IstS: string): Boolean; var WildPos, FilePos, l, p: Integer; begin // Start at the first wildcard/filename character WildPos := 1; // Wildcard position. FilePos := 1; // FileName position. while (WildPos <= Length(WildS)) do begin // '*' matches any sequence of characters. if WildS[WildPos] = '*' then begin // We've reached the end of the wildcard string with a * and are done. if WildPos = Length(WildS) then begin Result := True; Exit; end else begin l := WildPos + 1; // Anything after a * in the wildcard must match literally. while (l < Length(WildS)) and (WildS[l + 1] <> '*') do Inc(l); // Check for the literal match immediately after the current position. p := Pos(Copy(WildS, WildPos + 1, l - WildPos), IstS); if p > 0 then FilePos := p - 1 else begin Result := False; Exit; end; end; end // '?' matches any character - other characters must literally match. else if (WildS[WildPos] <> '?') and ((Length(IstS) < WildPos) or (WildS[WildPos] <> IstS[FilePos])) then begin Result := False; Exit; end; // Match is OK so far - check the next character. Inc(WildPos); Inc(FilePos); end; Result := (FilePos > Length(IstS)); end; function LastCharPos(const S: string; C: Char): Integer; var i: Integer; begin i := Length(S); while (i > 0) and (S[i] <> C) do Dec(i); Result := i; end; var NameWild, NameFile, ExtWild, ExtFile: string; DotPos: Integer; begin // Parse to find the extension and name base of filename and wildcard. DotPos := LastCharPos(FileWildcard, '.'); if DotPos = 0 then begin // Assume .* if an extension is missing NameWild := FileWildcard; ExtWild := '*'; end else begin NameWild := Copy(FileWildcard, 1, DotPos - 1); ExtWild := Copy(FileWildcard, DotPos + 1, Length(FileWildcard)); end; // We could probably modify this to use ExtractFileExt, etc. DotPos := LastCharPos(FileName, '.'); if DotPos = 0 then DotPos := Length(FileName) + 1; NameFile := Copy(FileName, 1, DotPos - 1); ExtFile := Copy(FileName, DotPos + 1, Length(FileName)); // Case insensitive check if IgnoreCase then begin NameWild := AnsiUpperCase(NameWild); NameFile := AnsiUpperCase(NameFile); ExtWild := AnsiUpperCase(ExtWild); ExtFile := AnsiUpperCase(ExtFile); end; // Both the extension and the filename must match Result := WildCompare(NameWild, NameFile) and WildCompare(ExtWild, ExtFile); end; // 根据当前键盘布局将键盘扫描码转换成 ASCII 字符,可在 WM_KEYDOWN 等处使用 // 由于不调用 ToAscii,故可支持使用 Accent Character 的键盘布局 function ScanCodeToAscii(Code: Word): Char; var i: Byte; C: Cardinal; begin C := Code; if GetKeyState(VK_SHIFT) < 0 then C := C or $10000; if GetKeyState(VK_CONTROL) < 0 then C := C or $20000; if GetKeyState(VK_MENU) < 0 then C := C or $40000; for i := Low(Byte) to High(Byte) do if OemKeyScan(i) = C then begin Result := Char(i); Exit; end; Result := #0; end; // 返回一个虚拟键是否 Dead key function IsDeadKey(Key: Word): Boolean; begin Result := MapVirtualKey(Key, 2) and $80000000 <> 0; end; // 根据当前键盘状态将虚拟键转换成 ASCII 字符,可在 WM_KEYDOWN 等处使用 // 可能会导致 Accent Character 不正确 function VirtualKeyToAscii(Key: Word): Char; var KeyState: TKeyboardState; ScanCode: Word; Buff: array[0..1] of Char; begin Result := #0; if not IsDeadKey(Key) then begin case Key of VK_SHIFT, VK_CONTROL, VK_MENU: ; else begin ScanCode := MapVirtualKey(Key, 0); GetKeyboardState(KeyState); if ToAscii(Key, ScanCode, KeyState, @Buff, 0) = 1 then Result := Buff[0]; end; end; end; end; // 根据当前的键盘布局将虚拟键和扫描码转换成 ASCII 字符。通过虚拟键来处理小键盘, // 扫描码处理大键盘,支持 Accent Character 的键盘布局 function VK_ScanCodeToAscii(VKey: Word; Code: Word): Char; begin if (VKey >= VK_NUMPAD0) and (VKey <= VK_DIVIDE) then begin case VKey of VK_NUMPAD0..VK_NUMPAD9: if IsNumLockDown then Result := Char(Ord('0') + VKey - VK_NUMPAD0) else Result := #0; VK_MULTIPLY: Result := '*'; VK_ADD: Result := '+'; VK_SEPARATOR: Result := #13; VK_SUBTRACT: Result := '-'; VK_DECIMAL: Result := '.'; VK_DIVIDE: Result := '/'; else Result := #0; end; end else begin Result := ScanCodeToAscii(Code); end; end; // 返回当前的按键状态,暂不支持 ssDouble 状态 function GetShiftState: TShiftState; var KeyState: TKeyboardState; function IsDown(Key: Byte): Boolean; begin Result := (Key and $80) = $80; end; begin Result := []; GetKeyboardState(KeyState); if IsDown(KeyState[VK_LSHIFT]) or IsDown(KeyState[VK_RSHIFT]) then Include(Result, ssShift); if IsDown(KeyState[VK_LMENU]) or IsDown(KeyState[VK_RMENU]) then Include(Result, ssAlt); if IsDown(KeyState[VK_LCONTROL]) or IsDown(KeyState[VK_RCONTROL]) then Include(Result, ssCtrl); if IsDown(KeyState[VK_LBUTTON]) then Include(Result, ssLeft); if IsDown(KeyState[VK_RBUTTON]) then Include(Result, ssRight); if IsDown(KeyState[VK_MBUTTON]) then Include(Result, ssMiddle); end; // 判断当前 Shift 是否按下 function IsShiftDown: Boolean; begin Result := ssShift in GetShiftState; end; // 判断当前 Alt 是否按下 function IsAltDown: Boolean; begin Result := ssAlt in GetShiftState; end; // 判断当前 Ctrl 是否按下 function IsCtrlDown: Boolean; begin Result := ssCtrl in GetShiftState; end; // 判断当前 Insert 是否按下 function IsInsertDown: Boolean; var KeyState: TKeyboardState; begin GetKeyboardState(KeyState); Result := Odd(KeyState[VK_INSERT]); end; // 判断当前 Caps Lock 是否按下 function IsCapsLockDown: Boolean; var KeyState: TKeyboardState; begin GetKeyboardState(KeyState); Result := Odd(KeyState[VK_CAPITAL]); end; // 判断当前 NumLock 是否按下 function IsNumLockDown: Boolean; var KeyState: TKeyboardState; begin GetKeyboardState(KeyState); Result := Odd(KeyState[VK_NUMLOCK]); end; // 判断当前 Scroll Lock 是否按下 function IsScrollLockDown: Boolean; var KeyState: TKeyboardState; begin GetKeyboardState(KeyState); Result := Odd(KeyState[VK_SCROLL]); end; // 删除类名前缀 T function RemoveClassPrefix(const ClassName: string): string; begin Result := ClassName; if (Result <> '') and (UpperCase(Result[1]) = 'T') then Delete(Result, 1, 1); end; // 用分号分隔的作者、邮箱字符串转换为输出格式 function CnAuthorEmailToStr(Author, Email: string): string; var s1, s2: string; function GetLeftStr(var s: string; Sep: string): string; var i: Integer; begin Result := ''; i := AnsiPos(Sep, s); if i > 0 then begin Result := Trim(Copy(s, 1, i - 1)); Delete(s, 1, i); end else begin Result := s; s := ''; end; end; begin Result := ''; s1 := GetLeftStr(Author, ';'); s2 := GetLeftStr(Email, ';'); while s1 <> '' do begin if Result <> '' then Result := Result + #13#10; Result := Result + s1; if s2 <> '' then Result := Result + ' (' + s2 + ')'; s1 := GetLeftStr(Author, ';'); s2 := GetLeftStr(Email, ';'); end; end; //------------------------------------------------------------------------------ // 扩展的对话框函数 //------------------------------------------------------------------------------ // 显示提示窗口 procedure InfoDlg(Mess: string; Caption: string; Flags: Integer); begin if Caption = '' then Caption := SCnInformation; Application.MessageBox(PChar(Mess), PChar(Caption), Flags); end; // 显示提示确认窗口 function InfoOk(Mess: string; Caption: string): Boolean; begin if Caption = '' then Caption := SCnInformation; Result := Application.MessageBox(PChar(Mess), PChar(Caption), MB_OKCANCEL + MB_ICONINFORMATION) = IDOK; end; // 显示错误窗口 procedure ErrorDlg(Mess: string; Caption: string); begin if Caption = '' then Caption := SCnError; Application.MessageBox(PChar(Mess), PChar(Caption), MB_OK + MB_ICONSTOP); end; // 显示警告窗口 procedure WarningDlg(Mess: string; Caption: string); begin if Caption = '' then Caption := SCnWarning; Application.MessageBox(PChar(Mess), PChar(Caption), MB_OK + MB_ICONWARNING); end; // 显示查询是否窗口 function QueryDlg(Mess: string; DefaultNo: Boolean; Caption: string): Boolean; const Defaults: array[Boolean] of DWORD = (0, MB_DEFBUTTON2); begin if Caption = '' then Caption := SCnInformation; Result := Application.MessageBox(PChar(Mess), PChar(Caption), MB_YESNO + MB_ICONQUESTION + Defaults[DefaultNo]) = IDYES; end; function GetAveCharSize(Canvas: TCanvas): TPoint; var I: Integer; Buffer: array[0..51] of Char; begin for I := 0 to 25 do Buffer[I] := Chr(I + Ord('A')); for I := 0 to 25 do Buffer[I + 26] := Chr(I + Ord('a')); GetTextExtentPoint(Canvas.Handle, Buffer, 52, TSize(Result)); Result.X := Result.X div 52; end; // 输入对话框 function CnInputQuery(const ACaption, APrompt: string; var Value: string; Ini: TCustomIniFile; const Section: string): Boolean; var Form: TForm; Prompt: TLabel; Edit: TEdit; ComboBox: TComboBox; DialogUnits: TPoint; ButtonTop, ButtonWidth, ButtonHeight: Integer; begin Result := False; Edit := nil; ComboBox := nil; Form := TForm.Create(Application); with Form do try Scaled := False; Font.Handle := GetStockObject(DEFAULT_GUI_FONT); Canvas.Font := Font; DialogUnits := GetAveCharSize(Canvas); BorderStyle := bsDialog; Caption := ACaption; ClientWidth := MulDiv(180, DialogUnits.X, 4); ClientHeight := MulDiv(63, DialogUnits.Y, 8); Position := poScreenCenter; Prompt := TLabel.Create(Form); with Prompt do begin Parent := Form; AutoSize := True; Left := MulDiv(8, DialogUnits.X, 4); Top := MulDiv(8, DialogUnits.Y, 8); Caption := APrompt; end; if Assigned(Ini) then begin ComboBox := TComboBox.Create(Form); with ComboBox do begin Parent := Form; Left := Prompt.Left; Top := MulDiv(19, DialogUnits.Y, 8); Width := MulDiv(164, DialogUnits.X, 4); MaxLength := 255; ReadStringsFromIni(Ini, Section, ComboBox.Items); if (Value = '') and (ComboBox.Items.Count > 0) then Text := ComboBox.Items[0] else Text := Value; SelectAll; end; end else begin Edit := TEdit.Create(Form); with Edit do begin Parent := Form; Left := Prompt.Left; Top := MulDiv(19, DialogUnits.Y, 8); Width := MulDiv(164, DialogUnits.X, 4); MaxLength := 255; Text := Value; SelectAll; end; end; ButtonTop := MulDiv(41, DialogUnits.Y, 8); ButtonWidth := MulDiv(50, DialogUnits.X, 4); ButtonHeight := MulDiv(14, DialogUnits.Y, 8); with TButton.Create(Form) do begin Parent := Form; Caption := SCnMsgDlgOK; ModalResult := mrOk; Default := True; SetBounds(MulDiv(38, DialogUnits.X, 4), ButtonTop, ButtonWidth, ButtonHeight); end; with TButton.Create(Form) do begin Parent := Form; Caption := SCnMsgDlgCancel; ModalResult := mrCancel; Cancel := True; SetBounds(MulDiv(92, DialogUnits.X, 4), ButtonTop, ButtonWidth, ButtonHeight); end; if ShowModal = mrOk then begin if Assigned(ComboBox) then begin Value := ComboBox.Text; AddComboBoxTextToItems(ComboBox); WriteStringsToIni(Ini, Section, ComboBox.Items); end else Value := Edit.Text; Result := True; end; finally Form.Free; end; end; // 输入对话框 function CnInputBox(const ACaption, APrompt, ADefault: string; Ini: TCustomIniFile; const Section: string): string; begin Result := ADefault; CnInputQuery(ACaption, APrompt, Result, Ini, Section); end; //------------------------------------------------------------------------------ // 位扩展日期时间操作函数 //------------------------------------------------------------------------------ function GetYear(Date: TDate): Integer; var y, m, d: WORD; begin DecodeDate(Date, y, m, d); Result := y; end; function GetMonth(Date: TDate): Integer; var y, m, d: WORD; begin DecodeDate(Date, y, m, d); Result := m; end; function GetDay(Date: TDate): Integer; var y, m, d: WORD; begin DecodeDate(Date, y, m, d); Result := d; end; function GetHour(Time: TTime): Integer; var h, m, s, ms: WORD; begin DecodeTime(Time, h, m, s, ms); Result := h; end; function GetMinute(Time: TTime): Integer; var h, m, s, ms: WORD; begin DecodeTime(Time, h, m, s, ms); Result := m; end; function GetSecond(Time: TTime): Integer; var h, m, s, ms: WORD; begin DecodeTime(Time, h, m, s, ms); Result := s; end; function GetMSecond(Time: TTime): Integer; var h, m, s, ms: WORD; begin DecodeTime(Time, h, m, s, ms); Result := ms; end; //------------------------------------------------------------------------------ // 位操作函数 //------------------------------------------------------------------------------ // 设置位 procedure SetBit(var Value: Byte; Bit: TByteBit; IsSet: Boolean); begin if IsSet then Value := Value or (1 shl Bit) else Value := Value and not (1 shl Bit); end; procedure SetBit(var Value: WORD; Bit: TWordBit; IsSet: Boolean); begin if IsSet then Value := Value or (1 shl Bit) else Value := Value and not (1 shl Bit); end; procedure SetBit(var Value: DWORD; Bit: TDWordBit; IsSet: Boolean); begin if IsSet then Value := Value or (1 shl Bit) else Value := Value and not (1 shl Bit); end; // 取位 function GetBit(Value: Byte; Bit: TByteBit): Boolean; begin Result := Value and (1 shl Bit) <> 0; end; function GetBit(Value: WORD; Bit: TWordBit): Boolean; begin Result := Value and (1 shl Bit) <> 0; end; function GetBit(Value: DWORD; Bit: TDWordBit): Boolean; begin Result := Value and (1 shl Bit) <> 0; end; //------------------------------------------------------------------------------ // 系统功能函数 //------------------------------------------------------------------------------ // 移动鼠标到控件 procedure MoveMouseIntoControl(AWinControl: TControl); var rtControl: TRect; begin rtControl := AWinControl.BoundsRect; MapWindowPoints(AWinControl.Parent.Handle, 0, rtControl, 2); SetCursorPos(rtControl.Left + (rtControl.Right - rtControl.Left) div 2, rtControl.Top + (rtControl.Bottom - rtControl.Top) div 2); end; // 将 ComboBox 的文本内容增加到下拉列表中 procedure AddComboBoxTextToItems(ComboBox: TComboBox; MaxItemsCount: Integer = 10); var Text: string; begin if ComboBox.Text <> '' then begin Text := ComboBox.Text; if ComboBox.Items.IndexOf(ComboBox.Text) < 0 then ComboBox.Items.Insert(0, ComboBox.Text) else ComboBox.Items.Move(ComboBox.Items.IndexOf(ComboBox.Text), 0); while (MaxItemsCount > 1) and (ComboBox.Items.Count > MaxItemsCount) do ComboBox.Items.Delete(ComboBox.Items.Count - 1); ComboBox.Text := Text; end; end; // 动态设置分辨率 function DynamicResolution(x, y: WORD): Boolean; var lpDevMode: TDeviceMode; begin Result := EnumDisplaySettings(nil, 0, lpDevMode); if Result then begin lpDevMode.dmFields := DM_PELSWIDTH or DM_PELSHEIGHT; lpDevMode.dmPelsWidth := x; lpDevMode.dmPelsHeight := y; Result := ChangeDisplaySettings(lpDevMode, 0) = DISP_CHANGE_SUCCESSFUL; end; end; // 窗口最上方显示 procedure StayOnTop(Handle: HWND; OnTop: Boolean); const csOnTop: array[Boolean] of HWND = (HWND_NOTOPMOST, HWND_TOPMOST); begin SetWindowPos(Handle, csOnTop[OnTop], 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE); end; var WndLong: Integer; // 设置程序是否出现在任务栏 procedure SetHidden(Hide: Boolean); begin ShowWindow(Application.Handle, SW_HIDE); if Hide then SetWindowLong(Application.Handle, GWL_EXSTYLE, WndLong or WS_EX_TOOLWINDOW and not WS_EX_APPWINDOW or WS_EX_TOPMOST) else SetWindowLong(Application.Handle, GWL_EXSTYLE, WndLong); ShowWindow(Application.Handle, SW_SHOW); end; const csWndShowFlag: array[Boolean] of DWORD = (SW_HIDE, SW_RESTORE); // 设置任务栏是否可见 procedure SetTaskBarVisible(Visible: Boolean); var wndHandle: THandle; begin wndHandle := FindWindow('Shell_TrayWnd', nil); ShowWindow(wndHandle, csWndShowFlag[Visible]); end; // 设置桌面是否可见 procedure SetDesktopVisible(Visible: Boolean); var hDesktop: THandle; begin hDesktop := FindWindow('Progman', nil); ShowWindow(hDesktop, csWndShowFlag[Visible]); end; // 强制让一个窗口显示在前台 function ForceForegroundWindow(HWND: HWND): Boolean; var ThreadID1, ThreadID2: DWORD; begin if HWND = GetForegroundWindow then Result := True else begin ThreadID1 := GetWindowThreadProcessId(GetForegroundWindow, nil); ThreadID2 := GetWindowThreadProcessId(HWND, nil); if ThreadID1 <> ThreadID2 then begin AttachThreadInput(ThreadID1, ThreadID2, True); Result := SetForegroundWindow(HWND); AttachThreadInput(ThreadID1, ThreadID2, False); end else Result := SetForegroundWindow(HWND); if IsIconic(HWND) then ShowWindow(HWND, SW_RESTORE) else ShowWindow(HWND, SW_SHOW); end; end; // 取桌面区域 function GetWorkRect(const Form: TCustomForm = nil): TRect; var Monitor: TMonitor; MonInfo: TMonitorInfo; begin Result.Top := 0; Result.Left := 0; Result.Right := Screen.Width; Result.Bottom := Screen.Height; if Assigned(Form) then begin Monitor := Form.Monitor; if Assigned(Monitor) then begin MonInfo.cbSize := SizeOf(MonInfo); GetMonitorInfo(Monitor.Handle, @MonInfo); Result := MonInfo.rcWork; end; end else SystemParametersInfo(SPI_GETWORKAREA, 0, @Result, 0); end; // 显示等待光标 procedure BeginWait; begin Screen.Cursor := crHourGlass; end; // 结束等待光标 procedure EndWait; begin Screen.Cursor := crDefault; end; // 检测是否Win95/98平台 function CheckWindows9598: Boolean; var V: TOSVersionInfo; begin V.dwOSVersionInfoSize := SizeOf(V); Result := False; if not GetVersionEx(V) then Exit; if V.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS then Result := True; end; // 检测是否WinXP以上平台 function CheckWinXP: Boolean; begin Result := (Win32MajorVersion > 5) or ((Win32MajorVersion = 5) and (Win32MinorVersion >= 1)); end; // 获得Dll的版本信息 function DllGetVersion(const dllname: string; var DVI: TDLLVERSIONINFO2): Boolean; type _DllGetVersion = function (var DVI: TDLLVERSIONINFO2): DWORD; stdcall; var hMod:THandle; pfDllVersion: _DllGetVersion; begin Result := False; hMod := LoadLibrary(PChar(dllname)); if hMod <> 0 then try @pfDllVersion := GetProcAddress(hMod, 'DllGetVersion'); if @pfDllVersion = nil then Exit; FillChar(DVI, SizeOf(TDLLVERSIONINFO2), 0); DVI.info1.cbSize := SizeOf(TDLLVERSIONINFO2); Result := pfDllVersion(DVI) and $80000000 = 0; finally FreeLibrary(hMod); end; end; // 返回操作系统标识串 function GetOSString: string; var OSPlatform: string; BuildNumber: Integer; begin Result := 'Unknown Windows Version'; OSPlatform := 'Windows'; BuildNumber := 0; case Win32Platform of VER_PLATFORM_WIN32_WINDOWS: begin BuildNumber := Win32BuildNumber and $0000FFFF; case Win32MinorVersion of 0..9: begin if Trim(Win32CSDVersion) = 'B' then OSPlatform := 'Windows 95 OSR2' else OSPlatform := 'Windows 95'; end; 10..89: begin if Trim(Win32CSDVersion) = 'A' then OSPlatform := 'Windows 98' else OSPlatform := 'Windows 98 SE'; end; 90: OSPlatform := 'Windows Millennium'; end; end; VER_PLATFORM_WIN32_NT: begin if Win32MajorVersion in [3, 4] then OSPlatform := 'Windows NT' else if Win32MajorVersion = 5 then begin case Win32MinorVersion of 0: OSPlatform := 'Windows 2000'; 1: OSPlatform := 'Windows XP'; end; end; BuildNumber := Win32BuildNumber; end; VER_PLATFORM_WIN32s: begin OSPlatform := 'Win32s'; BuildNumber := Win32BuildNumber; end; end; if (Win32Platform = VER_PLATFORM_WIN32_WINDOWS) or (Win32Platform = VER_PLATFORM_WIN32_NT) then begin if Trim(Win32CSDVersion) = '' then Result := Format('%s %d.%d (Build %d)', [OSPlatform, Win32MajorVersion, Win32MinorVersion, BuildNumber]) else Result := Format('%s %d.%d (Build %d: %s)', [OSPlatform, Win32MajorVersion, Win32MinorVersion, BuildNumber, Win32CSDVersion]); end else Result := Format('%s %d.%d', [OSPlatform, Win32MajorVersion, Win32MinorVersion]) end; // 得到本机名 function GetComputeNameStr : string; var dwBuff : DWORD; aryCmpName : array [0..255] of Char; begin Result := ''; dwBuff := 256; FillChar(aryCmpName, SizeOf(aryCmpName), 0); if GetComputerName(aryCmpName, dwBuff) then Result := StrPas(aryCmpName); end; // 得到本机用户名 function GetLocalUserName: string; var Count: DWORD; begin Count := 256 + 1; // UNLEN + 1 // set buffer size to 256 + 2 characters SetLength(Result, Count); if GetUserName(PChar(Result), Count) then StrResetLength(Result) else Result := ''; end; function REG_CURRENT_VERSION: string; begin if CheckWindows9598 then Result := HKLM_CURRENT_VERSION_WINDOWS else Result := HKLM_CURRENT_VERSION_NT; end; function GetRegisteredCompany: string; begin Result := RegReadStringDef(HKEY_LOCAL_MACHINE, REG_CURRENT_VERSION, 'RegisteredOrganization', ''); end; function GetRegisteredOwner: string; begin Result := RegReadStringDef(HKEY_LOCAL_MACHINE, REG_CURRENT_VERSION, 'RegisteredOwner', ''); end; //------------------------------------------------------------------------------ // 其它过程 //------------------------------------------------------------------------------ // 返回控件在屏幕上的坐标区域 function GetControlScreenRect(AControl: TControl): TRect; var AParent: TWinControl; begin Assert(Assigned(AControl)); AParent := AControl.Parent; Assert(Assigned(AParent)); with AControl do begin Result.TopLeft := AParent.ClientToScreen(Point(Left, Top)); Result.BottomRight := AParent.ClientToScreen(Point(Left + Width, Top + Height)); end; end; // 设置控件在屏幕上的坐标区域 procedure SetControlScreenRect(AControl: TControl; ARect: TRect); var AParent: TWinControl; P1, P2: TPoint; begin Assert(Assigned(AControl)); AParent := AControl.Parent; Assert(Assigned(AParent)); P1 := AParent.ScreenToClient(ARect.TopLeft); P2 := AParent.ScreenToClient(ARect.BottomRight); AControl.SetBounds(P1.x, P1.y, P2.x - P1.x, P2.y - P1.y); end; // 为 Listbox 增加水平滚动条 procedure ListboxHorizontalScrollbar(Listbox: TCustomListBox); var i: Integer; Width, MaxWidth: Integer; begin Assert(Assigned(Listbox)); MaxWidth := 0; for i := 0 to Listbox.Items.Count - 1 do begin Width := Listbox.Canvas.TextWidth(Listbox.Items[i]) + 4; if Width > MaxWidth then MaxWidth := Width; end; if ListBox is TCheckListBox then Inc(MaxWidth, GetSystemMetrics(SM_CXMENUCHECK) + 2); SendMessage(Listbox.Handle, LB_SETHORIZONTALEXTENT, MaxWidth, 0); end; // 输出限制在Min..Max之间 function TrimInt(Value, Min, Max: Integer): Integer; overload; begin if Value > Max then Result := Max else if Value < Min then Result := Min else Result := Value; end; // 比较两个整数,V1 > V2 返回 1,V1 < V2 返回 -1,V1 = V2 返回 0 // 如果 Desc 为 True,返回结果反向 function CompareInt(V1, V2: Integer; Desc: Boolean = False): Integer; begin if V1 > V2 then Result := 1 else if V1 < V2 then Result := -1 else // V1 = V2 Result := 0; if Desc then Result := -Result; end; // 输出限制在0..255之间 function IntToByte(Value: Integer): Byte; overload; asm OR EAX, EAX JNS @@Positive XOR EAX, EAX RET @@Positive: CMP EAX, 255 JBE @@OK MOV EAX, 255 @@OK: end; // 由TRect分离出坐标、宽高 procedure DeRect(Rect: TRect; var x, y, Width, Height: Integer); begin x := Rect.Left; y := Rect.Top; Width := Rect.Right - Rect.Left; Height := Rect.Bottom - Rect.Top; end; // 比较两个Rect function RectEqu(Rect1, Rect2: TRect): Boolean; begin Result := (Rect1.Left = Rect2.Left) and (Rect1.Top = Rect2.Top) and (Rect1.Right = Rect2.Right) and (Rect1.Bottom = Rect2.Bottom); end; // 产生TSize类型 function EnSize(cx, cy: Integer): TSize; begin Result.cx := cx; Result.cy := cy; end; // 计算Rect的宽度 function RectWidth(Rect: TRect): Integer; begin Result := Rect.Right - Rect.Left; end; // 计算Rect的高度 function RectHeight(Rect: TRect): Integer; begin Result := Rect.Bottom - Rect.Top; end; // 判断范围 function InBound(Value: Integer; V1, V2: Integer): Boolean; begin Result := (Value >= Min(V1, V2)) and (Value <= Max(V1, V2)); end; // 比较两个方法地址是否相等 function SameMethod(Method1, Method2: TMethod): Boolean; begin Result := CompareMem(@Method1, @Method2, SizeOf(TMethod)); end; // 二分法在列表中查找 function HalfFind(List: TList; P: Pointer; SCompare: TListSortCompare): Integer; var L, R, M: Integer; Res: Integer; begin Result := -1; L := 0; R := List.Count - 1; if R < L then Exit; if SCompare(P, List[L]) < 0 then Exit; if SCompare(P, List[R]) > 0 then Exit; while True do begin M := (L + R) shr 1; Res := SCompare(P, List[M]); if Res > 0 then L := M else if Res < 0 then R := M else begin Result := M; Exit; end; if L = R then Exit else if R - L = 1 then begin if SCompare(P, List[L]) = 0 then Result := L else if SCompare(P, List[R]) = 0 then Result := R; Exit; end; end; end; // 二分法在排序列表中查找,支持重复记录,返回一个范围值 function HalfFindEx(List: TList; P: Pointer; SCompare: TListSortCompare): TFindRange; var i, Idx: Integer; begin Idx := HalfFind(List, P, SCompare); Result.tgFirst := Idx; for i := Idx - 1 downto 0 do if SCompare(P, List[i]) = 0 then Result.tgFirst := i else Break; Result.tgLast := Idx; for i := Idx + 1 to List.Count - 1 do if SCompare(P, List[i]) = 0 then Result.tgLast := i else Break; end; // 交换两个数 procedure CnSwap(var A, B: Byte); overload; var Tmp: Byte; begin Tmp := A; A := B; B := Tmp; end; procedure CnSwap(var A, B: Integer); overload; var Tmp: Integer; begin Tmp := A; A := B; B := Tmp; end; procedure CnSwap(var A, B: Single); overload; var Tmp: Single; begin Tmp := A; A := B; B := Tmp; end; procedure CnSwap(var A, B: Double); overload; var Tmp: Double; begin Tmp := A; A := B; B := Tmp; end; // 延时 procedure Delay(const uDelay: DWORD); var n: DWORD; begin n := GetTickCount; while GetTickCount - n <= uDelay do Application.ProcessMessages; end; // 在Win9X下让喇叭发声 procedure BeepEx(const Freq: WORD = 1200; const Delay: WORD = 1); const FREQ_SCALE = $1193180; var Temp: WORD; begin Temp := FREQ_SCALE div Freq; asm in al,61h; or al,3; out 61h,al; mov al,$b6; out 43h,al; mov ax,temp; out 42h,al; mov al,ah; out 42h,al; end; Sleep(Delay); asm in al,$61; and al,$fc; out $61,al; end; end; function GetLastErrorMsg(IncludeErrorCode: Boolean): string; var ErrNo: Integer; Buf: array[0..255] of Char; begin ErrNo := GetLastError; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nil, ErrNo, $400, Buf, 255, nil); if Buf = '' then StrCopy(@Buf, PChar(SUnknowError)); Result := Buf; if IncludeErrorCode then Result := Result + #10#13 + SErrorCode + IntToStr(ErrNo); end; // 显示Win32 Api运行结果信息 procedure ShowLastError; begin MessageBox(Application.Handle, PChar(GetLastErrorMsg), PChar(SCnInformation), MB_OK + MB_ICONINFORMATION); end; // 取汉字的拼音 function GetHzPy(const AHzStr: string): string; const ChinaCode: array[0..25, 0..1] of Integer = ((1601, 1636), (1637, 1832), (1833, 2077), (2078, 2273), (2274, 2301), (2302, 2432), (2433, 2593), (2594, 2786), (9999, 0000), (2787, 3105), (3106, 3211), (3212, 3471), (3472, 3634), (3635, 3722), (3723, 3729), (3730, 3857), (3858, 4026), (4027, 4085), (4086, 4389), (4390, 4557), (9999, 0000), (9999, 0000), (4558, 4683), (4684, 4924), (4925, 5248), (5249, 5589)); var i, j, HzOrd: Integer; begin Result := ''; i := 1; while i <= Length(AHzStr) do begin if (AHzStr[i] >= #160) and (AHzStr[i + 1] >= #160) then begin HzOrd := (Ord(AHzStr[i]) - 160) * 100 + Ord(AHzStr[i + 1]) - 160; for j := 0 to 25 do begin if (HzOrd >= ChinaCode[j][0]) and (HzOrd <= ChinaCode[j][1]) then begin Result := Result + Char(Byte('A') + j); Break; end; end; Inc(i); end else Result := Result + AHzStr[i]; Inc(i); end; end; // 获得CustomEdit选中的字符串,可以处理XP以上的系统 function GetSelText(edt: TCustomEdit): string; var Ver: TDLLVERSIONINFO2; iSelStart, Len: Integer; i, j, itemp: Integer; stext: string; begin Assert(Assigned(edt)); Result := edt.SelText; if not DllGetVersion('comctl32.dll', Ver) then Exit; if Ver.info1.dwMajorVersion <= 5 then Exit; with edt do begin Result := ''; if SelLength <= 0 then Exit; stext := edt.Text; iSelStart := 0; i := 0; j := 1; itemp := SelStart; while i < itemp do begin if ByteType(stext, j) <> mbLeadByte then Inc(i); Inc(iSelStart); Inc(j); end; Len := SelLength; i := 0; j := 1; while i < Len do begin Result := Result + stext[iSelStart + j]; if ByteType(stext, iSelStart + j) <> mbLeadByte then Inc(i); Inc(j); end; end; end; // 删除空行和每一行的行首尾空格 procedure TrimStrings(AList: TStrings); var i: Integer; begin for i := AList.Count - 1 downto 0 do begin AList[i] := Trim(AList[i]); if AList[i] = '' then AList.Delete(i); end; end; // 声卡是否存在 function SoundCardExist: Boolean; begin Result := WaveOutGetNumDevs > 0; end; // 判断 ASrc 是否派生自类名为 AClass 的类 function InheritsFromClassName(ASrc: TClass; const AClass: string): Boolean; begin Result := False; while ASrc <> nil do begin if ASrc.ClassNameIs(AClass) then begin Result := True; Exit; end; ASrc := ASrc.ClassParent; end; end; // 判断 AObject 是否派生自类名为 AClass 的类 function InheritsFromClassName(AObject: TObject; const AClass: string): Boolean; begin Result := InheritsFromClassName(AObject.ClassType, AClass); end; // 根据文件名结束进程,不区分路径 procedure KillProcessByFileName(const FileName: String); var ID:DWORD; S, Tmp: string; Ret: Boolean; SnapshotHandle: THandle; PE32: TProcessEntry32; hh: HWND; begin S := LowerCase(FileName); SnapshotHandle := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0); PE32.dwSize := SizeOf(PE32); Ret := Process32First(SnapshotHandle, PE32); while Integer(Ret) <> 0 do begin Tmp := LowerCase(PE32.szExeFile); if Pos(S, Tmp) > 0 then begin Id := PE32.th32ProcessID; hh := OpenProcess(PROCESS_ALL_ACCESS, True,Id); TerminateProcess(hh, 0); end; Ret := Process32Next(SnapshotHandle,PE32); end; end; // 获得级联属性信息 function GetPropInfoIncludeSub(Instance: TObject; const PropName: string; AKinds: TTypeKinds): PPropInfo; var AObject: TObject; Dot: Integer; RestProp: String; begin Dot := Pos('.', PropName); if Dot = 0 then begin Result := GetPropInfo(Instance, PropName, AKinds); end else begin if GetPropInfo(Instance, Copy(PropName, 1, Dot - 1)) <> nil then begin AObject := GetObjectProp(Instance, Copy(PropName, 1, Dot - 1)); if AObject = nil then Result := nil else begin RestProp := Copy(PropName, Dot + 1, Length(PropName) - Dot); Result := GetPropInfoIncludeSub(AObject, RestProp, AKinds); end; end else Result := nil; end; end; // 获得级联属性值 function GetPropValueIncludeSub(Instance: TObject; PropName: string; PreferStrings: Boolean = True): Variant; const SCnControlFont = '!Font'; var AObject: TObject; Dot: Integer; RestProp: String; IntToId: TIntToIdent; IdValue: String; PropInfo: PPropInfo; begin Result := Null; if Instance = nil then Exit; Dot := Pos('.', PropName); if Dot = 0 then begin if (Instance is TStrings) and (PropName = 'Text') then begin Result := (Instance as TStrings).Text; Exit; end else if (Instance is TListItem) and (PropName = 'Caption') then begin Result := (Instance as TListItem).Caption; Exit; end else if (Instance is TTreeNode) and (PropName = 'Text') then begin Result := (Instance as TTreeNode).Text; Exit; end else if PropName = SCnControlFont then // 在此内部处理 !Font 的情况 begin PropName := 'Font'; PropInfo := GetPropInfo(Instance, PropName); if PropInfo = nil then Exit; if PropInfo^.PropType^.Kind = tkClass then begin try Result := FontToString(TFont(GetObjectProp(Instance, PropName))); except ; end; Exit; end; end; PropInfo := GetPropInfo(Instance, PropName); if PropInfo = nil then Exit; if PropInfo^.PropType^.Kind = tkClass then begin Result := Integer(GetObjectProp(Instance, PropName)); Exit; end; Result := GetPropValue(Instance, PropName, PreferStrings); if (Result <> Null) and IsInt(Result) then // 如果返回整数,尝试将其转换成常量。 begin if PropInfo^.PropType^.Kind = tkInteger then begin IntToId := FindIntToIdent(PPropInfo(PropInfo)^.PropType^); if Assigned(IntToId) and IntToId(Result, IdValue) then Result := IdValue; end end end else begin // 递归寻找 AObject := nil; if GetPropInfo(Instance, Copy(PropName, 1, Dot - 1)) <> nil then AObject := GetObjectProp(Instance, Copy(PropName, 1, Dot - 1)); if AObject = nil then Result := Null else begin RestProp := Copy(PropName, Dot + 1, Length(PropName) - Dot); Result := GetPropValueIncludeSub(AObject, RestProp); end; end; end; // 设置级联属性值,不处理异常 procedure DoSetPropValueIncludeSub(Instance: TObject; const PropName: string; Value: Variant); var AObject: TObject; Dot, IntValue: Integer; RestProp: String; PropInfo: PPropInfo; IdToInt: TIdentToInt; begin Dot := Pos('.', PropName); if Dot = 0 then begin PropInfo := GetPropInfo(Instance, PropName); if PropInfo^.PropType^.Kind = tkInteger then begin IdToInt := FindIdentToInt(PPropInfo(PropInfo)^.PropType^); if Assigned(IdToInt) and IdToInt(Value, IntValue) then SetPropValue(Instance, PropName, IntValue) else SetPropValue(Instance, PropName, Value) end else begin if (PropInfo^.PropType^.Kind in [tkSet, tkEnumeration]) and (VarType(Value) <> varInteger) then Value := Trim(Value); SetPropValue(Instance, PropName, Value); end; end else begin // 递归设置 AObject := GetObjectProp(Instance, Copy(PropName, 1, Dot - 1)); RestProp := Copy(PropName, Dot + 1, Length(PropName) - Dot); DoSetPropValueIncludeSub(AObject, RestProp, Value); end; end; // 设置级联属性值 function SetPropValueIncludeSub(Instance: TObject; const PropName: string; const Value: Variant): Boolean; begin try DoSetPropValueIncludeSub(Instance, PropName, Value); Result := True; except Result := False; end; end; // 字符串转集合值 function StrToSetValue(const Value: string; PInfo: PTypeInfo): Integer; var EnumInfo: PTypeInfo; EnumValue: 0..SizeOf(Integer) * 8 - 1; S: string; Strings: TStrings; i: Integer; begin Result := 0; S := Trim(Value); if S = '' then Exit; if S[1] = '[' then Delete(S, 1, 1); if S = '' then Exit; if S[Length(S)] = ']' then Delete(S, Length(S), 1); EnumInfo := GetTypeData(PInfo).CompType^; Strings := TStringList.Create; try Strings.CommaText := S; for i := 0 to Strings.Count - 1 do begin EnumValue := GetEnumValue(EnumInfo, Trim(Strings[i])); if (EnumValue < GetTypeData(EnumInfo)^.MinValue) or (EnumValue > GetTypeData(EnumInfo)^.MaxValue) then Exit; // 不是有效的枚举值 Include(TIntegerSet(Result), EnumValue); end; finally Strings.Free; end; end; // 判断某 Control 的 ParentFont 属性是否为 True,如无 Parent 则返回 False function IsParentFont(AControl: TControl): Boolean; begin try Result := not (AControl.Parent = nil); if Result then Result := TCnFontControl(AControl).ParentFont; except Result := False; end; end; // 取某 Control 的 Parent 的 Font 属性,如果没有返回 nil function GetParentFont(AControl: TComponent): TFont; begin Result := nil; try if AControl <> nil then begin if AControl is TControl then begin if TControl(AControl).Parent <> nil then Result := TCnFontControl(TControl(AControl).Parent).Font; end else if AControl is TComponent then begin if (AControl.Owner <> nil) and (AControl.Owner is TControl) then Result := TCnFontControl(AControl.Owner).Font; end; end; except ; end; end; //查找字符串在动态数组中的索引,用于string类型使用Case语句 function IndexStr(AText: string; AValues: array of string; IgCase: Boolean = True): Integer; type TSameFunc = function(const S1, S2: string): Boolean; var Index: Integer; SameFunc: TSameFunc; begin Result := -1; if IgCase then SameFunc := AnsiSameText else SameFunc := AnsiSameStr; for Index := Low(AValues) to High(AValues) do if SameFunc(AValues[Index], AText) then begin Result := Index; Exit; end; end; // 查找整形变量在动态数组中的索引,用于变量使用Case语句 function IndexInt(ANum: Integer; AValues: array of Integer): Integer; var Index: Integer; begin Result := -1; for Index := Low(AValues) to High(AValues) do if ANum = AValues[Index] then begin Result := Index; Exit; end; end; initialization WndLong := GetWindowLong(Application.Handle, GWL_EXSTYLE); end.
unit uFrmDepartamentos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmDialogo, DBGridEhGrouping, ToolCtrlsEh, DBGridEhToolCtrls, DynVarsEh, Data.DB, IBCustomDataSet, IBTable, Vcl.ExtCtrls, Vcl.DBCtrls, JvDBControls, GridsEh, DBAxisGridsEh, DBGridEh, Vcl.ComCtrls, JvExComCtrls, JvComCtrls, FlatHeader, Vcl.Menus, System.Actions, Vcl.ActnList; type TfrmDepartamentos = class(TfrmDialogo) page1: TJvPageControl; tsCargos: TTabSheet; gridCargos: TDBGridEh; navCargos: TJvDBNavigator; TblDepartamentos: TIBTable; dsDepartamentos: TDataSource; TblDepartamentosID: TLargeintField; TblDepartamentosDEPARTAMENTO: TIBStringField; TblDepartamentosDESCRIPCION: TIBStringField; actnlst1: TActionList; actExportarCSV: TAction; pm1: TPopupMenu; mnuExportarCSV: TMenuItem; procedure TblDepartamentosAfterPost(DataSet: TDataSet); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure actExportarCSVExecute(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmDepartamentos: TfrmDepartamentos; implementation uses Datos, DanFW.InterbaseDBExpress, DanFW.Data.Export; {$R *.dfm} procedure TfrmDepartamentos.actExportarCSVExecute(Sender: TObject); begin inherited; ExportarCSV(dsDepartamentos.DataSet ); end; procedure TfrmDepartamentos.FormClose(Sender: TObject; var Action: TCloseAction); begin Cerrar(TblDepartamentos ); inherited; end; procedure TfrmDepartamentos.FormCreate(Sender: TObject); begin inherited; abrir(TblDepartamentos); end; procedure TfrmDepartamentos.TblDepartamentosAfterPost(DataSet: TDataSet); begin inherited; posting(TblDepartamentos); Actualizar(TblDepartamentos); end; end.
unit radios; interface const genrelist: array[0..7] of string = ( 'Eletronic', 'Downtempo', 'Rock/Metal', 'Ecletic', 'Hip-Hop', 'Old/Classical', 'Others', 'Brasileiras', ); const chn_eletronic: array[0..0] of string = ( 'Trance ( sense.fm )', 'Progressive ( sense.fm )', 'Psy ( schizoid )', 'Psy Prog ( schizoid )', 'Dubstep ( dubstep.fm )', 'House Funky ( kif )', 'Hardcore ( coretime )', 'Hardcore ( hardcoreradio )', 'Hardstyle ( hard.fm )', 'Hardstyle ( hardbase )', 'House Eletro ( housetime )', 'House SoulFull ( freshhouse )', 'House SoulFull ( deepinside )', 'Trance ( afterhours )', 'Dance ( vibefm )', 'Dance ( freshfm )', 'Dance ( sky )', 'Club ( DI )', 'Club ( c89.5 )', 'Club ( blitz )', 'Club ( playdio )', 'Club ( techno4ever )', 'Club ( pulsradio )', 'Club ( technobase )', 'Club ( frenchkiss )', 'Club ( radioseven )', 'Club ( rautemusik )', 'Club ( 1.fm )', 'Dance ( 1.fm )', 'Trance ( 1.fm )', 'House Funky ( rautemusik )', 'Progressive ( soma )', 'IDM ( soma )', 'Psy ( philosomatika )', 'Psy ( psyradio )', 'Psy Prog ( psyradio )', 'Trance ( neradio )', 'Hardstyle ( neradio )', 'Trance ( trancebase )', 'Drum''n''Bass ( dnbradio )', 'Drum''n''Bass ( bassdrive)', 'House Eletro ( DI )', 'House Tribal ( DI )', 'House Funky ( DI )', 'Hardstyle ( DI )', 'Trance ( DI )', 'Trance Vocal ( DI )', 'Eurodance ( DI )', 'Eurodance Classic ( DI )', 'House Latin ( DI )', 'House ( DI )', 'House Classic ( DI )', 'House Disco ( DI )', 'House SoulFull ( DI )', 'House Tech ( DI )', 'Harddance ( DI )', 'Techno ( DI )', 'Progressive ( DI )', 'Psy ( DI )', 'Hardcore ( DI )', 'DJ-Mixes ( DI )', 'DJ-Mixes ( DI )', 'Drum''n''Bass ( DI )', 'Drum''n''Bass Liquid ( DI )', 'Techno Classic ( DI )', 'Trance Classic ( DI )', 'Dubstep ( DI )', 'BreakBeat ( DI )', 'Futurepop ( DI )', 'Gabber ( DI )', 'Jumpstyle ( fear )', 'Hardstyle ( fear )', 'Hardcore ( fear )', 'Dance ( 181.fm )', 'Eurodance ( 181.fm )', 'Psy Mixes ( psychedelik )', 'Psy ( psychedelik )', 'Psy Prog ( psychedelik )', 'Psy Dark ( psychedelik )', 'Psy Dark ( triplag )', 'Psy Darkbient ( triplag )', 'Progressive ( frisky )', 'Alternative ( 1.fm )', 'Dance ( fg radio )', 'Dance ( ibizaglobal )', 'Dance ( fusionchicago )', 'Dance ( mixnation )', // industrial 'Post Industrial ( gothville )', 'Post Industrial ( gothradio )', 'Post Industrial ( darkness )', 'Post Industrial ( tormented )', 'Post Industrial ( digitalgunfire )', 'Post Industrial ( ultradark )', 'Post Industrial ( schwarze )', 'Post Industrial ( rantradio )', 'Post Industrial ( realindustrial )', ); const pls_eletronic: array[0..0] of string = ( 'http://www.sense.fm/192k-high.m3u', 'http://www.sense.fm/192k-prog.m3u', 'http://schizoid.in/schizoid-psy.pls', 'http://schizoid.in/schizoid-prog.pls', 'http://www.dubstep.fm/listen.pls', 'http://www.kifradio.com/www.kifradio.com.m3u', 'http://mp3.coretime.fm/listen.pls', 'http://www.hardcoreradio.nl/rhr.m3u', 'http://files.hard.fm/128.pls', 'http://mp3.hardbase.fm/listen.pls', 'http://high.housetime.fm/listen.pls', 'http://listen.freshhouse.fm/listen.pls', 'http://www.deepinside.co.uk/deepinside.m3u', 'http://stats.ah.fm/dynamicplaylist.m3u?quality=96', 'http://www.vibefm.ro/listen.pls', 'http://www.fresh.fm/media/audio/ListenHigh.pls', 'http://listen.sky.fm/public1/dancehits.pls', 'http://listen.di.fm/public3/club.pls', 'http://c895worldwide.com/web/streaming/c895sc128.pls', 'http://listen.blitz-radio.de/listen.pls', 'http://www.playdio.se/bredband.pls', 'http://listen.to.techno4ever.net/dsl/mp3', 'http://www.pulsradio.com/pls/puls-adsl.m3u', 'http://listen.technobase.fm/dsl.pls', 'http://stream.frenchkissfm.com/listen.pls', 'http://play.radioseven.se/128.pls', 'http://club-office.rautemusik.fm/listen.pls', 'http://www.1.fm/TuneIn/WM/energyclub128k/Listen.aspx', 'http://www.1.fm/TuneIn/WM/energydance128k/Listen.aspx', 'http://www.1.fm/trance.pls', 'http://funky-office.rautemusik.fm/listen.pls', 'http://somafm.com/tags.pls', 'http://somafm.com/cliqhop.pls', 'http://205.188.215.229:8012/listen.pls', 'http://streamer.psyradio.org:8030/listen.pls', 'http://streamer.psyradio.org:8010/listen.pls', 'http://listen.neradio.fm/listen.pls', 'http://www.neradio.se/listen.pls', 'http://mp3.trancebase.fm/listen.pls', 'http://www.dnbradio.com/hi.pls', 'http://www.bassdrive.com/v2/streams/BassDrive.pls', 'http://listen.di.fm/public3/electro.pls', 'http://listen.di.fm/public3/tribalhouse.pls', 'http://listen.di.fm/public3/funkyhouse.pls', 'http://listen.di.fm/public3/hardstyle.pls', 'http://listen.di.fm/public3/trance.pls', 'http://listen.di.fm/public3/vocaltrance.pls', 'http://listen.di.fm/public3/eurodance.pls', 'http://listen.di.fm/public3/classiceurodance.pls', 'http://listen.di.fm/public3/latinhouse.pls', 'http://listen.di.fm/public3/house.pls', 'http://listen.di.fm/public3/oldschoolhouse.pls', 'http://listen.di.fm/public3/discohouse.pls', 'http://listen.di.fm/public3/soulfulhouse.pls', 'http://listen.di.fm/public3/techhouse.pls', 'http://listen.di.fm/public3/harddance.pls', 'http://listen.di.fm/public3/techno.pls', 'http://listen.di.fm/public3/progressive.pls', 'http://listen.di.fm/public3/goapsy.pls', 'http://listen.di.fm/public3/hardcore.pls', 'http://listen.di.fm/public3/djmixes.pls', 'http://schizoid.in/schizoid-edm.pls', 'http://listen.di.fm/public3/drumandbass.pls', 'http://listen.di.fm/public3/liquiddnb.pls', 'http://listen.di.fm/public3/classictechno.pls', 'http://listen.di.fm/public3/classictrance.pls', 'http://listen.di.fm/public3/dubstep.pls', 'http://listen.di.fm/public3/breaks.pls', 'http://listen.di.fm/public3/futuresynthpop.pls', 'http://listen.di.fm/public3/gabber.pls', 'http://www.fear.fm/streamrelay/playlist/hard.pls', 'http://www.fear.fm/streamrelay/playlist/harder.pls', 'http://www.fear.fm/streamrelay/playlist/hardest.pls', 'http://www.181.fm/winamp.pls?station=181-energy98', 'http://www.181.fm/winamp.pls?station=181-energy93', 'http://www.psychedelik.com/tunein-lives_mixes.pls', 'http://www.psychedelik.com/tunein-psy.pls', 'http://www.psychedelik.com/tunein-prog.pls', 'http://www.psychedelik.com/tunein-dark.pls', 'http://www.triplag.com/webradio/darkpsy/triplag-darkpsy.php', 'http://www.triplag.com/webradio/chilltrip/triplag-chilltrip.php', 'http://friskyradio.com/frisky.m3u', 'http://www.1.fm/electronica.pls', 'http://fg.impek.tv/listen.pls', 'http://s6.viastreaming.net:7010/listen.pls', 'http://streams.fusionchicago.com/128.pls', 'http://www.mixnation.de/listen.pls', // industrial 'http://radio.gothville.com:8000/listen.pls', 'http://67.78.148.34:8002/listen.pls', 'http://radio.darkness.com/listen.pls', 'http://playlist.tormentedradio.com/radioG.pls', 'http://www.digitalgunfire.com/dg.pls', 'http://www.ultradarkradio.com/listen.pls', 'http://www.schwarze-welle.com/play.m3u', 'http://www.rantmedia.ca/industrial/rr-industrial128.pls', 'http://radio.realindustrialradio.com:8000/listen.pls', ); const chn_downtempo: array[0..0] of string = ( 'Chillout ( schizoid )', 'Dream Pop ( soma )', 'Post Rock ( soma )', 'Ambient ( bluemars )', 'Ambient Space ( bluemars )', 'Ambient Drone ( bluemars )', 'Minimal ( deepmix )', 'Chillout ( 1.fm )', 'Lounge ( rautemusik )', 'Lounge ( smoothlounge )', 'Lounge ( lounge-radio )', 'Chillout ( soma )', 'Ambient House ( soma )', 'Ambient Dark ( soma )', 'Ambient Space ( soma )', 'Ambient Drone ( soma )', 'Lounge Exotica ( soma )', 'Chillout ( psyradio )', 'Minimal ( psyradio )', 'New Age ( sky )', 'New Age Vocal ( sky )', 'Minimal ( DI )', 'Chillout ( DI )', 'Lounge ( DI )', 'Lounge Downtempo ( sky )', 'Ambient ( DI )', 'Ambient Drone ( DI )', 'Chillout ( bluefm )', 'Chillout ( 181.fm )', 'Chillout ( psychedelik )', 'Chillout ( buzzoutroom )', 'PsyChill ( DI )', 'Chillout Beats ( DI )', 'Ambient Space ( DI )', 'Chillout Beats ( entranced.fm )', 'Chillout Beats ( sky )', ); const pls_downtempo: array[0..0] of string = ( 'http://schizoid.in/schizoid-chill.pls', 'http://somafm.com/lush.pls', 'http://somafm.com/digitalis.pls', 'http://207.200.96.225:8024/listen.pls', 'http://207.200.96.225:8020/listen.pls', 'http://207.200.96.225:8022/listen.pls', 'http://deepmix.ru/deepmix128.pls', 'http://www.1.fm/tcl.pls', 'http://lounge-office.rautemusik.fm/listen.pls', 'http://www.smoothlounge.com/streams/smoothlounge_128.pls', 'http://www.lounge-radio.com/listen128.m3u', 'http://somafm.com/groovesalad.pls', 'http://somafm.com/beatblender.pls', 'http://somafm.com/doomed.pls', 'http://somafm.com/spacestation.pls', 'http://somafm.com/dronezone.pls', 'http://somafm.com/illstreet.pls', 'http://streamer.psyradio.org:8020/listen.pls', 'http://streamer.psyradio.org:8040/listen.pls', 'http://listen.sky.fm/public1/newage.pls', 'http://listen.sky.fm/public1/vocalnewage.pls', 'http://listen.di.fm/public3/minimal.pls', 'http://listen.di.fm/public3/chillout.pls', 'http://listen.di.fm/public3/lounge.pls', 'http://listen.sky.fm/public1/datempolounge.pls', 'http://listen.di.fm/public3/ambient.pls', 'http://listen.di.fm/public3/spacemusic.pls', 'http://bluefm.net/listen.pls', 'http://www.181.fm/winamp.pls?station=181-chilled', 'http://88.191.38.140:8002/listen.pls', 'http://www.buzzoutroom.com/listen.pls', 'http://listen.di.fm/public3/psychill.pls', 'http://listen.di.fm/public3/chilloutdreams.pls', 'http://listen.di.fm/public3/spacemusic.pls', 'http://loudcity.com/stations/entranced-fm/files/show/aacplus-hi.pls', 'http://listen.sky.fm/public1/dreamscapes.pls', ); const chn_rockmetal: array[0..0] of string = ( 'Classic Rock ( absolute )', 'Death Metal ( death.fm )', '80''s Rock ( 181.fm )', 'Indie Rock ( soma )', 'Punk Rock ( idobi )', 'Classic Rock ( 977music )', 'Alternative ( 977music )', 'Rock Metal ( 525 )', 'Rock Metal ( cxraggression )', 'Rock Metal ( cxrmetal )', 'Rock Metal ( cxrgrit )', 'Classic Rock ( sky )', 'Indie Rock ( sky )', 'Punk Rock ( sky )', 'Alternative ( sky )', 'Rock Metal ( therock.181.fm )', 'Rock Metal ( rock181.181.fm )', 'Alternative ( 181.fm )', 'Classic Rock ( 181. fm)', 'Rock Metal ( rautemusik )', 'Rock Metal ( x.1.fm )', 'Rock Metal ( hv.1.fm )', 'Rock Metal ( metalonly )', 'Rock Metal ( kinkfm )', 'Rock Metal ( rocky )', 'Classic Rock ( rock radio1 )', 'Classic Rock ( rock&rollfm )' ); const pls_rockmetal: array[0..0] of string = ( 'http://network.absoluteradio.co.uk/core/audio/mp3/live.pls?service=vcbb', 'http://loudcity.com/stations/death-fm/files/show/aacplus-hi.pls', 'http://www.181.fm/winamp.pls?station=181-hairband', 'http://somafm.com/indiepop.pls', 'http://idobi.com/services/iradio.pls', 'http://www.977music.com/itunes/classicrock.pls', 'http://www.977music.com/itunes/alternative.pls', 'http://fastcast4u.com:9256/listen.pls', 'http://www.chronixradio.com/stations/chronixaggression/listen/listen.pls', 'http://www.chronixradio.com/stations/cxrmetal/listen/listen.pls', 'http://www.chronixradio.com/stations/cxrgrit/listen/listen.pls', 'http://listen.sky.fm/public1/classicrock.pls', 'http://listen.sky.fm/public1/indierock.pls', 'http://listen.sky.fm/public1/poppunk.pls', 'http://listen.sky.fm/public1/altrock.pls', 'http://www.181.fm/winamp.pls?station=181-hardrock', 'http://www.181.fm/winamp.pls?station=181-rock', 'http://www.181.fm/winamp.pls?station=181-buzz', 'http://www.181.fm/winamp.pls?station=181-eagle', 'http://extreme-office.rautemusik.fm/listen.pls', 'http://www.1.fm/x.pls', 'http://www.1.fm/hv.pls', 'http://metal-only.de/listen.pls', 'http://www.kinkfm.com/streams/kink_aardschok.m3u', 'http://www.rockyfm.de/listen.pls', 'http://91.121.201.88:8000/listen.pls', 'http://tunein.swcast.net/launch.cgi/dade921/hi-band.pls' ); const chn_ecletic: array[0..0] of string = ( 'Ecletic ( wadio )', 'Ecletic ( iloveradio )', 'Ecletic ( maxxhits )', 'Ecletic ( eye97 )', 'Ecletic ( paradise )', 'Ecletic ( enjoystation )', 'Ecletic ( sky )', 'Ecletic ( 1.fm )', 'Ecletic ( hitz.977music )', 'Ecletic ( mix.977music )', 'Ecletic ( frequence3 )', 'Ecletic ( power.181.fm )', 'Ecletic ( mix.181.fm )', 'Ecletic ( point.181.fm )', 'Ecletic ( party.181.fm )', 'Ecletic ( office.181.fm )', 'Ecletic ( rautemusik )', 'Ecletic ( HitzRadio )', 'Ecletic ( absolute )' ); const pls_ecletic: array[0..0] of string = ( 'http://wad.io/listen/everywhere', 'http://www.iloveradio.de/listen.pls', 'http://www.maxxhits.eu/listen/listen-winamp.m3u', 'http://loudcity.com/stations/eye97/files/show/eye97.pls', 'http://www.radioparadise.com/musiclinks/rp_128-1.m3u', 'http://www.enjoystation.net/player/mp3.m3u', 'http://listen.sky.fm/public1/tophits.pls', 'http://www.1.fm/top40.pls', 'http://www.977music.com/977hitz.pls', 'http://www.977music.com/itunes/mix.pls', 'http://streams.frequence3.fr/mp3-192.m3u', 'http://www.181.fm/winamp.pls?station=181-power', 'http://www.181.fm/winamp.pls?station=181-themix', 'http://www.181.fm/winamp.pls?station=181-thepoint', 'http://www.181.fm/winamp.pls?station=181-party', 'http://www.181.fm/winamp.pls?station=181-office', 'http://main-office.rautemusik.fm/listen.pls', 'http://www.hitzradio.com/hitzradio.pls' 'http://network.absoluteradio.co.uk/core/audio/mp3/live.pls?service=vrbb', ); const chn_hiphop: array[0..0] of string = ( 'HipHop ( blackbeats )', 'HipHop ( powerhitz )', 'HipHop ( thugzone )', 'HipHop ( defjay )', 'HipHop ( rautemusik )', 'HipHop ( 1.fm )', 'HipHop ( hot108 )', 'HipHop ( beat.181.fm )', 'HipHop ( box.181.fm )', 'HipHop ( sky )', 'HipHop ( R&B.181.fm )', 'Classic Rap ( sky )', 'HipHop ( smoothbeats )', 'HipHop ( truehiphop )', ); const pls_hiphop: array[0..0] of string = ( 'http://www.blackbeats.fm/listen.m3u', 'http://www.powerhitz.com/ph.pls', 'http://www.thugzone.com/broadband-128.pls', 'http://www.defjay.com/listen.pls', 'http://jam-office.rautemusik.fm/listen.pls', 'http://www.1.fm/TuneIn/WM/energyjamz128k/Listen.aspx', 'http://www.hot108.com/hot108.pls', 'http://www.181.fm/winamp.pls?station=181-beat', 'http://www.181.fm/winamp.pls?station=181-thebox', 'http://listen.sky.fm/public1/urbanjamz.pls', 'http://www.181.fm/winamp.pls?station=181-rnb&style=&description=True%20R&B', 'http://listen.sky.fm/public1/classicrap.pls', 'http://www.smoothbeats.com/listen.pls', 'http://www.truehiphopfm.de/playlists/playlist.php?type=pls', ); const chn_oldmusic: array[0..0] of string = ( '80''s ( absolute )', 'Classical ( adagio.fm )', '80''s ( 1980s.fm )', 'New Wave ( soma )', 'New Wave ( nigel )', '60''s ( sky )', '70''s ( sky )', '80''s ( sky )', '90''s ( star.181.fm )', 'Classic Hits ( 181.fm )', '80''s ( awesome.181.fm )', '80''s ( lite.181.fm )', '90''s ( alternative.181.fm )', '80''s ( 977music )', '90''s ( 977music )', '50''s-80''s ( rautemusik )', 'Classical ( sky )', 'Baroque ( 1.fm )', 'Opera ( 1.fm )', 'Classical ( 1.fm )', 'Disco ( 1.fm )', '80''s ( flashback )', '80''s ( asf )', '80''s ( chaos )' ); const pls_oldmusic: array[0..0] of string = ( 'http://network.absoluteradio.co.uk/core/audio/mp3/live.pls?service=a8', 'http://loudcity.com/stations/adagio-fm/files/show/aacplus-hi.pls', 'http://loudcity.com/stations/1980s-fm/files/show/aacplus-hi.pls', 'http://somafm.com/u80s.pls', 'http://stream.radionigel.com:8010/listen.pls', 'http://listen.sky.fm/public1/oldies.pls', 'http://listen.sky.fm/public1/hit70s.pls', 'http://listen.sky.fm/public1/the80s.pls', 'http://www.181.fm/winamp.pls?station=181-star90s', 'http://www.181.fm/winamp.pls?station=181-greatoldies', 'http://www.181.fm/winamp.pls?station=181-awesome80s', 'http://www.181.fm/winamp.pls?station=181-lite80s', 'http://www.181.fm/winamp.pls?station=181-90salt', 'http://www.977music.com/977hi.pls', 'http://www.977music.com/itunes/90s.pls', 'http://goldies-high.rautemusik.fm/listen.pls', 'http://listen.sky.fm/public1/classical.pls', 'http://www.1.fm/baroque.pls', 'http://www.1.fm/opera.pls', 'http://www.1.fm/classical.pls', 'http://www.1.fm/disco.pls', 'http://www.1.fm/fa128k.pls', 'http://www.atlanticsoundfactory.com/asfbb.pls', 'http://www.chaos-radio.net/stream/listen.m3u' ); const chn_misc: array[0..0] of string = ( 'Nature ( sky )', 'Relaxation ( sky )', 'Blues ( bellyup4blues )', 'Salsa ( La X )', 'Tango ( tangorosario )', // 'Latino ( romanticafm )', 'Folk ( liveireland )', 'Jazz Acid ( soma )', 'Jazz Nu ( soma )', 'Country ( soma )', 'Country ( 977music )', 'Jazz Vocal ( 1.fm )', 'Jazz Smooth ( 977music )', 'Jazz Smooth ( swissgroove )', 'Jazz Smooth ( 1.fm )', 'Jazz Smooth ( smoothjazz )', 'Jazz Smooth ( 181.fm )', 'Easy Listening ( 181.fm )', 'Easy Listening ( slowradio )', 'Country ( 181.fm )', 'Country Classic ( 181.fm )', 'Country ( 1.fm )', 'Blues ( 1.fm )', 'Reggae ( 1.fm )', 'Beatles tribute ( sky )', 'Reggae ( sky )', 'Easy Listening ( sky )', 'Jazz Vocal Smooth ( sky )', 'Jazz Classics ( sky )', 'Jazz Smooth ( sky )', 'Jazz Uptempo ( sky )', 'Jazz Bebop ( sky )', 'Flamenco ( sky )', 'Piano Trio ( sky )', 'Piano Solo ( sky )', 'World ( sky )', 'Jazz Smooth 24''7 ( sky )', 'Jazz Piano ( sky )', 'Bossanova ( sky )', 'Soundtracks ( sky )', 'Gospel ( sky )', 'Salsa ( sky )', 'Jazz Nu ( sky )', 'American Classics ( sky )', 'Jpop/Anime ( kawaii )', 'Jpop/Anime ( armitage''s )', 'Jpop/Anime ( Anime Academy )', 'Jpop/Anime ( AnimeNfo )', 'Games ( VGamp )', 'Arabic ( darvish )', 'Soundtracks ( cinemix )', 'Soundtracks ( streamingsoundtracks )', 'World ( soma )', 'Chiptune ( DI )', 'Jpop ( sky )', 'Romantica ( sky )', ); const pls_misc: array[0..0] of string = ( 'http://listen.sky.fm/public1/nature.pls', 'http://listen.sky.fm/public1/relaxation.pls', 'http://64.62.252.134:5100/listen.pls', 'http://laxestereo.com/proserv1.pls', 'http://200.69.237.185:8000/listen.pls', // 'http://208.53.170.26:8910/listen.pls', 'http://www.liveireland.com/live.pls', 'http://somafm.com/secretagent.pls', 'http://somafm.com/sonicuniverse.pls', 'http://somafm.com/bootliquor.pls', 'http://www.977music.com/977hicountry.pls', 'http://www.1.fm/ajazz128k.pls', 'http://www.977music.com/itunes/jazz.pls', 'http://www.swissgroove.ch/listen.m3u', 'http://www.1.fm/jazz.pls', 'http://smoothjazz.com/streams/smoothjazz_128.pls', 'http://www.181.fm/winamp.pls?station=181-breeze', 'http://www.181.fm/winamp.pls?station=181-heart', 'http://streams.slowradio.com/index.php?id=winamp', 'http://www.181.fm/winamp.pls?station=181-kickincountry', 'http://www.181.fm/winamp.pls?station=181-highway', 'http://www.1.fm/country.pls', 'http://www.1.fm/blues.pls', 'http://www.1.fm/reggae.pls', 'http://listen.sky.fm/public1/beatles.pls', 'http://listen.sky.fm/public1/rootsreggae.pls', 'http://listen.sky.fm/public1/lovemusic.pls', 'http://listen.sky.fm/public1/vocalsmoothjazz.pls', 'http://listen.sky.fm/public1/jazzclassics.pls', 'http://listen.sky.fm/public1/smoothjazz.pls', 'http://listen.sky.fm/public1/uptemposmoothjazz.pls', 'http://listen.sky.fm/public1/bebop.pls', 'http://listen.sky.fm/public1/guitar.pls', 'http://listen.sky.fm/public1/classicalpianotrios.pls', 'http://listen.sky.fm/public1/solopiano.pls', 'http://listen.sky.fm/public1/world.pls', 'http://listen.sky.fm/public1/smoothjazz247.pls', 'http://listen.sky.fm/public1/pianojazz.pls', 'http://listen.sky.fm/public1/bossanova.pls', 'http://listen.sky.fm/public1/soundtracks.pls', 'http://listen.sky.fm/public1/christian.pls', 'http://listen.sky.fm/public1/salsa.pls', 'http://listen.sky.fm/public1/jazz.pls', 'http://listen.sky.fm/public1/americansongbook.pls', 'http://kawaii-radio.net/listen.m3u', 'http://albionys.net:8005/listen.pls', 'http://www.animeacademyradio.net/listen.m3u', 'http://www.animenfo.com/radio/listen.m3u', 'http://vgamp.com/listen128.pls', 'http://207.200.96.228:8078/listen.pls', 'http://loudcity.com/stations/cinemix/files/show/mp3-High.pls' 'http://loudcity.com/stations/streamingsoundtracks-com/files/show/aacplus-hi.asx', 'http://somafm.com/suburbsofgoa.pls', 'http://listen.di.fm/public3/chiptunes.pls', 'http://listen.sky.fm/public1/jpop.pls', 'http://listen.sky.fm/public1/romantica.pls', ); const chn_brasil: array[0..0] of string = ( 'Popular ( gaucha )', 'Mpb ( novabrasil )', 'Popular ( bandeirantes )', 'Ecletic ( metropolitana )', 'Ecletic ( jbfm )', 'Jazz Smooth ( jbfm )', 'Rock Classic ( cidadeclassicrock )', 'Rock Nacional ( cidaderockbrasil )', 'Rock Metal ( cidadewebmetal )', 'Mpb ( mpbfm )', 'Caipira ( violaviva )', 'Ecletic ( interativa )', 'Ecletic ( radiofusion )', 'Ecletic ( radiozone )', 'Psy ( radiodaweb )', 'Rock ( cidadewebrock )', 'Ecletic ( giga )', 'Ecletic ( circuitomix )', 'Ecletic ( ritmobrasil )', 'Ecletic ( megasom )', 'Ecletic ( tribunafm )', 'Noticias ( jovenpanam )', 'Noticias ( cbn.sp )', 'Noticias ( cbn.rj )', 'Noticias ( cbn.brasilia )', 'Noticias ( cbn.bh )', 'Popular ( tupi.rj )', 'Popular ( tupi.fm )', 'Rock Classic ( kissfm )', 'Ecletic ( redeblitz )', 'Ecletic ( jovempanfm )', 'Ecletic ( radiorox )', 'Ecletic ( hits.transamerica )', 'Ecletic ( pop.transamerica )', 'Ecletic ( light.transamerica )', 'Ecletic ( japan.transamerica )', 'Ecletic ( mixfm )', 'Ecletic ( totalshare )', 'Ecletic ( beat98 )', 'Ecletic ( globo.fm )', 'Popular ( globo.am.sp )', 'Popular ( globo.am.rj )', 'Popular ( globo.am.mg )', 'Rock ( sporttv )', 'Ecletic ( multishow )', 'Classicos ( gnt )', 'Japan/Anime ( radioblast )', 'Funk ( estacaofunk )', 'Ecletic ( paradiso )', 'Pagode ( pagofunk )', 'Mpb ( brasilmpb )', 'Rock ( poprock )', 'Folk ( valkyria )', ); const pls_brasil: array[0..0] of string = ( 'mms://gruporbs-gaucha-fm-rs.wm.llnwd.net/gruporbs_Gaucha_FM_RS?channel=232', 'http://cdn.upx.net.br/listen/00086_1.wmx', 'mms://servidor25.crossdigital.com.br:8000/bandeirantesam', 'http://metropolitanafm.uol.com.br/ao-vivo/sao-paulo01.asx', 'mms://200.222.115.52/OiFM_JBFM', 'mms://200.222.115.50/CidadeWebRock_JBSmoothJazz', 'mms://200.222.115.52/CidadeWebRock_ClassicRock', 'mms://200.222.115.52/CidadeWebRock_RockBrasil', 'mms://200.222.115.52/CidadeWebRock_Metal', 'http://www.mpbfm.com.br/radinho.asx', 'http://base2.streamingbrasil.com.br:8116/listen.pls', 'http://www.interativafm.net/interativa.m3u', 'http://www.radiofusion.com.br/listen.m3u', 'http://www.radiozone.com.br/player/winamp.m3u', 'http://www.radiodaweb.com/aovivo.m3u', 'mms://200.222.115.50/cidadewebrock_cidadewebrock128', 'http://wms2.corptv.com.br:8000/listen.pls', 'http://www.circuitomix.com.br/circuitomix.pls', 'http://www.ritmobrasil.com/RitmoBrasil.pls', 'http://www.radiowebtv.com/server/megasom/megasom.m3u', 'mms://200.203.183.10/TribunaFM', 'mms://p.mm.uol.com.br/ampan', 'http://cbn.globoradio.globo.com/playlist/asxAoVivo.php?praca=SP', 'http://cbn.globoradio.globo.com/playlist/asxAoVivo.php?praca=RJ', 'http://cbn.globoradio.globo.com/playlist/asxAoVivo.php?praca=BSB', 'http://cbn.globoradio.globo.com/playlist/asxAoVivo.php?praca=BH', 'mms://dedicado.tupi.am:8000/tupiaudio', 'http://www.crosshost.com.br/cbs/tupifm/listen.pls', 'http://www.crosshost.com.br/cbs/kiss/ouvir.m3u', 'http://www.redeblitz.com.br/playerblitz/playlist.asx', 'http://jovempanfm.virgula.uol.com.br/estudio/jpsp.asx', 'mms://200.222.115.51/radiorox_radiorox', 'mms://wmedia.telium.com.br/transsphits', 'mms://wmedia.telium.com.br/transsppop64', 'mms://wmedia.telium.com.br/transsplight', 'mms://transastream.dyndns.org/transapop', 'http://p.mm.uol.com.br/mixfm', 'http://totalshare.com.br/radio/player-winamp.m3u', 'http://beat98.globoradio.globo.com/playlist/asxAoVivo.php?praca=Beat98', 'http://wmsgr.globo.com/webmedia/ObterPathMidia?usuario=sgr01&tipo=live&path=/sgr_off_globofmrj_live.wma&midiaId=505114&ext.asx&output=ASX', 'http://wmsgr.globo.com/webmedia/ObterPathMidia?usuario=sgr01&tipo=live&path=/sgr_off_globoamsp_live.wma&midiaId=511329&ext.asx&output=ASX', 'http://wmsgr.globo.com/webmedia/ObterPathMidia?usuario=sgr01&tipo=live&path=/sgr_off_globoamrj_live.wma&midiaId=505105&ext.asx&output=ASX', 'http://wmsgr.globo.com/webmedia/ObterPathMidia?usuario=sgr01&tipo=live&path=/sgr_off_globoambh_live.wma&midiaId=519058&ext.asx&output=ASX', 'http://wmsgr.globo.com/webmedia/ObterPathMidia?usuario=sgr01&tipo=live&path=/sgr_off_sportv_live.wma&midiaId=511317&ext=.asx&output=ASX', 'http://wmsgr.globo.com/webmedia/ObterPathMidia?usuario=sgr01&tipo=live&path=/sgr_off_multishow_live.wma&midiaId=581681&ext.asx&output=ASX', 'http://wmsgr.globo.com/webmedia/ObterPathMidia?usuario=sgr01&tipo=live&path=/sgr_off_gnt_live.wma&midiaId=510705&ext.asx&output=ASX', 'http://ouvir.radioblast.com.br/', 'http://player.redefx.com.br/pesadao/ouvir.wmx', 'mms://p.mm.uol.com.br/paradisofm', 'http://www.radiopagofunk.com.br/aovivo.asx', 'http://174.36.195.11/~paineldj/centova/tunein.php/brasilmpb/playlist.pls', 'mms://200.203.124.65/poprock', 'http://69.162.90.148:7814/listen.pls', ); implementation end.
unit uCefUIBrowserProcessMessageReceiverCommon; interface uses System.SysUtils, System.Generics.Collections, System.Classes, // uCEFApplication, uCefTypes, uCefInterfaces, uCefChromium, // uCefUIBrowserProcessMessageReceiver ; type TCefUIBrowserProcessMessageReceiverCommon = class(TCefUIBrowserProcessMessageReceiver) protected procedure Receive(Sender: TObject; const ABrowser: ICefBrowser; ASourceProcess: TCefProcessId; const AMessage: ICefProcessMessage; out AResult: Boolean); override; public constructor Create; end; implementation uses uCEFProcessMessage, uCEFMiscFunctions, // uCefUtilConst, uCefWaitEventList, uCefUtilFunc, uCefUIFunc; { TCefUIBrowserProcessMessageReceiverCommon } constructor TCefUIBrowserProcessMessageReceiverCommon.Create; begin inherited Create(MYAPP_CEF_MESSAGE_NAME) end; procedure TCefUIBrowserProcessMessageReceiverCommon.Receive(Sender: TObject; const ABrowser: ICefBrowser; ASourceProcess: TCefProcessId; const AMessage: ICefProcessMessage; out AResult: Boolean); var arg: ICefListValue; event: TCefWaitEventItem; eventId: Integer; z: string; begin AResult := False; arg := AMessage.ArgumentList; if arg.GetType(IDX_TYPE) = VTYPE_INT then begin AResult := True; case arg.GetInt(IDX_TYPE) of VAL_CLICK_XY: CefUIFocusClickAndCallbackAsync(False, ABrowser, arg); VAL_FOCUSCLICK_XY: CefUIFocusClickAndCallbackAsync(True, ABrowser, arg); VAL_KEY_PRESS: CefUIKeyPressAsync(ABrowser, arg); else AResult := False; end; end else begin z := 'msgRecv:' + AMessage.Name + ' '; eventId := arg.GetInt(IDX_EVENT); z := z + 'bid:' + ABrowser.Identifier.ToString + ' eid:' + IntToStr(eventId) + ' '; event := CefWaitEventGet(eventId); if Assigned(event) then begin z := z + 'tick:' + IntToStr(event.TickDif()) + ' res:' + CefListValueToJsonStr(arg); event.Res := arg.Copy(); event.Event.SetEvent(); AResult := True; end; CefLog('frame', 138, 1, z); end; end; initialization CefUIBrowserProcessMessageReceiverAdd(TCefUIBrowserProcessMessageReceiverCommon.Create()) end.
unit LandmarksConverter; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Laz2_DOM, laz2_XMLRead, laz2_XMLWrite, math; type TLandmark = record Name, Description: String; Lat, Lon, Alt: Double; // Note: Alt may be NaN // ToDo: Add more available fields end; { Abstract class for each landmarks converter } TBaseLandmarksConverter = class private InFileName, OutFileName: String; InXML: TXMLDocument; function GetFileExtension: String; virtual; abstract; procedure ProcessLandmark(Landmark: TLandmark); virtual; abstract; public constructor Create(AnInFileName: String); destructor Destroy; override; property FileExtension: String read GetFileExtension; procedure Convert(AnOutFileName: String); end; { Base abstract class for XML converter } TXMLLandmarksConverter = class(TBaseLandmarksConverter) private OutXML: TXMLDocument; public constructor Create(AnInFileName: String); destructor Destroy; override; end; { KML converter } TKMLLandmarksConverter = class(TXMLLandmarksConverter) private //RootElement: TDOMNode; function GetFileExtension: String; override; procedure ProcessLandmark(Landmark: TLandmark); override; public constructor Create(AnInFileName: String); destructor Destroy; override; end; { GPX converter } TGPXLandmarksConverter = class(TXMLLandmarksConverter) private RootElement: TDOMNode; function GetFileExtension: String; override; procedure ProcessLandmark(Landmark: TLandmark); override; public constructor Create(AnInFileName: String); destructor Destroy; override; end; implementation { TGPXLandmarksConverter } function TGPXLandmarksConverter.GetFileExtension: String; begin Result := 'gpx'; end; procedure TGPXLandmarksConverter.ProcessLandmark(Landmark: TLandmark); var FixedFormat: TFormatSettings; WPTNode, EleNode, NameNode, DescNode: TDOMNode; begin FixedFormat.DecimalSeparator := '.'; WPTNode := OutXML.CreateElement('wpt'); TDOMElement(WPTNode).SetAttribute('lat', FloatToStr(Landmark.Lat, FixedFormat)); TDOMElement(WPTNode).SetAttribute('lon', FloatToStr(Landmark.Lon, FixedFormat)); RootElement.AppendChild(WPTNode); if not IsNan(Landmark.Alt) then begin EleNode := OutXML.CreateElement('ele'); EleNode.TextContent := FloatToStr(Landmark.Alt, FixedFormat); WPTNode.AppendChild(EleNode); end; if Landmark.Name <> '' then begin NameNode := OutXML.CreateElement('name'); NameNode.TextContent := Landmark.Name; WPTNode.AppendChild(NameNode); end; if Landmark.Description <> '' then begin DescNode := OutXML.CreateElement('desc'); DescNode.TextContent := Landmark.Description; WPTNode.AppendChild(DescNode); end; end; constructor TGPXLandmarksConverter.Create(AnInFileName: String); var GPXNode: TDOMNode; begin inherited; GPXNode := OutXML.CreateElement('gpx'); with (TDOMElement(GPXNode)) do begin SetAttribute('xmlns', 'http://www.topografix.com/GPX/1/1'); SetAttribute('version', '1.1'); SetAttribute('creator', ''); // ToDo: add this SetAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); SetAttribute('xsi:schemaLocation', 'http://www.topografix.com/GPX/1/1 ' + 'http://www.topografix.com/GPX/1/1/gpx.xsd') end; OutXML.AppendChild(GPXNode); RootElement := GPXNode; end; destructor TGPXLandmarksConverter.Destroy; begin inherited Destroy; end; { TBaseLandmarksConverter } constructor TBaseLandmarksConverter.Create(AnInFileName: String); begin Self.InFileName := AnInFileName; ReadXMLFile(InXML, Self.InFileName); end; destructor TBaseLandmarksConverter.Destroy; begin InXML.Free; end; procedure TBaseLandmarksConverter.Convert(AnOutFileName: String); var FixedFormat: TFormatSettings; LandmarkNodes: TDOMNodeList; Idx: Integer; Landmark: TLandmark; AltNode: TDOMNode; begin OutFileName := AnOutFileName; FixedFormat.DecimalSeparator := '.'; LandmarkNodes := InXML.DocumentElement.GetElementsByTagName('lm:landmark'); for Idx := 0 to LandmarkNodes.Count-1 do begin with LandmarkNodes[Idx] do begin Landmark.Name := FindNode('lm:name').TextContent; Landmark.Description := FindNode('lm:description').TextContent; with FindNode('lm:coordinates') do begin Landmark.Lat := StrToFloat(FindNode('lm:latitude').TextContent, FixedFormat); Landmark.Lon := StrToFloat(FindNode('lm:longitude').TextContent, FixedFormat); AltNode := FindNode('lm:altitude'); if Assigned(AltNode) then Landmark.Alt := StrToFloat(AltNode.TextContent, FixedFormat) else Landmark.Alt := NaN; end; ProcessLandmark(Landmark); end; end; LandmarkNodes.Free; end; { TXMLLandmarksConverter } constructor TXMLLandmarksConverter.Create(AnInFileName: String); begin inherited; OutXML := TXMLDocument.Create; end; destructor TXMLLandmarksConverter.Destroy; begin WriteXMLFile(OutXML, OutFileName); OutXML.Free; inherited; end; { TKMLLandmarksConverter } function TKMLLandmarksConverter.GetFileExtension: String; begin Result := 'kml'; end; procedure TKMLLandmarksConverter.ProcessLandmark(Landmark: TLandmark); var FixedFormat: TFormatSettings; PlacemarkElement, Element, PlacemarksRootElement: TDOMNode; CoordsStr: String; begin FixedFormat.DecimalSeparator := '.'; PlacemarkElement := OutXML.CreateElement('Placemark'); { Name } Element := OutXML.CreateElement('name'); TDOMDocument(Element).AppendChild(OutXML.CreateTextNode(Landmark.Name)); PlacemarkElement.AppendChild(Element); { Description } if Landmark.Description <> '' then begin Element := OutXML.CreateElement('description'); //TDOMDocument(Element).AppendChild(OutXML.CreateTextNode(Landmark.Description)); TDOMDocument(Element).AppendChild(OutXML.CreateCDATASection(Landmark.Description)); PlacemarkElement.AppendChild(Element); end; { Coordinates } Element := PlacemarkElement.AppendChild(OutXML.CreateElement('Point')); Element := Element.AppendChild(OutXML.CreateElement('coordinates')); CoordsStr := FloatToStr(Landmark.Lon, FixedFormat) + ',' + FloatToStr(Landmark.Lat, FixedFormat); if not IsNan(Landmark.Alt) then // Altitude is optional CoordsStr := CoordsStr + ',' + FloatToStr(Landmark.Alt, FixedFormat); Element := Element.AppendChild(OutXML.CreateTextNode(CoordsStr)); //RootElement.AppendChild(PlacemarkElement); PlacemarksRootElement := OutXML.GetElementsByTagName('Folder').Item[0]; PlacemarksRootElement.AppendChild(PlacemarkElement); end; constructor TKMLLandmarksConverter.Create(AnInFileName: String); var KMLNode, DocumentNode, FolderNode: TDOMNode; begin inherited; KMLNode := OutXML.CreateElement('kml'); TDOMElement(KMLNode).SetAttribute('xmlns', 'http://earth.google.com/kml/2.0'); OutXML.AppendChild(KMLNode); DocumentNode := OutXML.CreateElement('Document'); KMLNode.AppendChild(DocumentNode); FolderNode := OutXML.CreateElement('Folder'); DocumentNode.AppendChild(FolderNode); // RootElement := FolderNode; end; destructor TKMLLandmarksConverter.Destroy; begin //RootElement.Free; inherited; end; end.