text
stringlengths
14
6.51M
unit uMainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, IPPeerClient, REST.Backend.PushTypes, System.JSON, REST.Backend.EMSPushDevice, System.PushNotification, Data.Bind.Components, Data.Bind.ObjectScope, REST.Backend.BindSource, REST.Backend.PushDevice, REST.Backend.EMSProvider, FMX.ScrollBox, FMX.Memo; type TMainForm = class(TForm) ToolBar1: TToolBar; Label1: TLabel; EMSProvider1: TEMSProvider; PushEvents1: TPushEvents; Memo1: TMemo; Switch1: TSwitch; procedure PushEvents1DeviceRegistered(Sender: TObject); procedure PushEvents1DeviceTokenReceived(Sender: TObject); procedure PushEvents1DeviceTokenRequestFailed(Sender: TObject; const AErrorMessage: string); procedure PushEvents1PushReceived(Sender: TObject; const AData: TPushData); procedure Switch1Switch(Sender: TObject); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; implementation uses System.Threading; {$R *.fmx} procedure TMainForm.PushEvents1DeviceRegistered(Sender: TObject); begin Memo1.Lines.Add('Device Registered'); Memo1.Lines.Add(''); end; procedure TMainForm.PushEvents1DeviceTokenReceived(Sender: TObject); begin Memo1.Lines.Add('Device Token Received'); Memo1.Lines.Add(''); end; procedure TMainForm.PushEvents1DeviceTokenRequestFailed(Sender: TObject; const AErrorMessage: string); begin Memo1.Lines.Add('Device Token Request Failed'); Memo1.Lines.Add(AErrorMessage); Memo1.Lines.Add(''); end; procedure TMainForm.PushEvents1PushReceived(Sender: TObject; const AData: TPushData); begin Memo1.Lines.Add('Device push received'); Memo1.Lines.Add(AData.Message); Memo1.Lines.Add(''); end; procedure TMainForm.Switch1Switch(Sender: TObject); begin TTask.Run( procedure begin PushEvents1.Active := Switch1.IsChecked; end); end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Janela Cadastro de Abonos para o Ponto Eletrônico 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 (alberteije@gmail.com) @version 2.0 ******************************************************************************* } unit UPontoAbono; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UTelaCadastro, DB, DBClient, Menus, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, PontoAbonoVO, PontoAbonoController, Tipos, Atributos, Constantes, LabeledCtrls, JvToolEdit, Mask, JvExMask, JvBaseEdits, Math, StrUtils, ActnList, Generics.Collections, RibbonSilverStyleActnCtrls, ActnMan, ToolWin, ActnCtrls, Controller; type [TFormDescription(TConstantes.MODULO_PONTO_ELETRONICO, 'Abonos')] TFPontoAbono = class(TFTelaCadastro) DSPontoAbonoUtilizacao: TDataSource; CDSPontoAbonoUtilizacao: TClientDataSet; CDSPontoAbonoUtilizacaoID: TIntegerField; CDSPontoAbonoUtilizacaoID_PONTO_ABONO: TIntegerField; CDSPontoAbonoUtilizacaoDATA_UTILIZACAO: TDateField; CDSPontoAbonoUtilizacaoOBSERVACAO: TStringField; PanelMestre: TPanel; EditIdColaborador: TLabeledCalcEdit; EditColaborador: TLabeledEdit; EditInicioUtilizacao: TLabeledDateEdit; EditQuantidade: TLabeledCalcEdit; EditDataCadastro: TLabeledDateEdit; EditUtilizado: TLabeledCalcEdit; EditSaldo: TLabeledCalcEdit; MemoObservacao: TLabeledMemo; PageControlItens: TPageControl; tsItens: TTabSheet; PanelItens: TPanel; GridParcelas: TJvDBUltimGrid; procedure FormCreate(Sender: TObject); procedure GridDblClick(Sender: TObject); procedure EditIdColaboradorKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } 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 ConfigurarLayoutTela; end; var FPontoAbono: TFPontoAbono; implementation uses ULookup, Biblioteca, UDataModule, PontoAbonoUtilizacaoVO, ViewPessoaColaboradorVO, ViewPessoaColaboradorController; {$R *.dfm} {$REGION 'Infra'} procedure TFPontoAbono.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TPontoAbonoVO; ObjetoController := TPontoAbonoController.Create; inherited; end; procedure TFPontoAbono.LimparCampos; begin inherited; CDSPontoAbonoUtilizacao.EmptyDataSet; end; procedure TFPontoAbono.ConfigurarLayoutTela; begin PanelEdits.Enabled := True; if StatusTela = stNavegandoEdits then begin PanelMestre.Enabled := False; PanelItens.Enabled := False; end else begin PanelMestre.Enabled := True; PanelItens.Enabled := True; end; end; {$ENDREGION} {$REGION 'Controles CRUD'} function TFPontoAbono.DoInserir: Boolean; begin Result := inherited DoInserir; ConfigurarLayoutTela; if Result then begin EditIdColaborador.SetFocus; end; end; function TFPontoAbono.DoEditar: Boolean; begin Result := inherited DoEditar; ConfigurarLayoutTela; if Result then begin EditIdColaborador.SetFocus; end; end; function TFPontoAbono.DoExcluir: Boolean; begin if inherited DoExcluir then begin try TController.ExecutarMetodo('PontoAbonoController.TPontoAbonoController', 'Exclui', [IdRegistroSelecionado], 'DELETE', 'Boolean'); Result := TController.RetornoBoolean; except Result := False; end; end else begin Result := False; end; if Result then TController.ExecutarMetodo('PontoAbonoController.TPontoAbonoController', 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista'); end; function TFPontoAbono.DoSalvar: Boolean; begin Result := inherited DoSalvar; if Result then begin try if not Assigned(ObjetoVO) then ObjetoVO := TPontoAbonoVO.Create; TPontoAbonoVO(ObjetoVO).IdColaborador := EditIdColaborador.AsInteger; TPontoAbonoVO(ObjetoVO).Quantidade := EditQuantidade.AsInteger; TPontoAbonoVO(ObjetoVO).Utilizado := EditUtilizado.AsInteger; TPontoAbonoVO(ObjetoVO).Saldo := EditSaldo.AsInteger; TPontoAbonoVO(ObjetoVO).DataCadastro := EditDataCadastro.Date; TPontoAbonoVO(ObjetoVO).InicioUtilizacao := EditInicioUtilizacao.Date; TPontoAbonoVO(ObjetoVO).Observacao := MemoObservacao.Text; if StatusTela = stInserindo then begin TController.ExecutarMetodo('PontoAbonoController.TPontoAbonoController', 'Insere', [TPontoAbonoVO(ObjetoVO)], 'PUT', 'Lista'); end else if StatusTela = stEditando then begin if TPontoAbonoVO(ObjetoVO).ToJSONString <> StringObjetoOld then begin TController.ExecutarMetodo('PontoAbonoController.TPontoAbonoController', 'Altera', [TPontoAbonoVO(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 'Campos Transientes'} procedure TFPontoAbono.EditIdColaboradorKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var Filtro: String; begin if Key = VK_F1 then begin if EditIdColaborador.Value <> 0 then Filtro := 'ID = ' + EditIdColaborador.Text else Filtro := 'ID=0'; try EditIdColaborador.Clear; EditColaborador.Clear; if not PopulaCamposTransientes(Filtro, TViewPessoaColaboradorVO, TViewPessoaColaboradorController) then PopulaCamposTransientesLookup(TViewPessoaColaboradorVO, TViewPessoaColaboradorController); if CDSTransiente.RecordCount > 0 then begin EditIdColaborador.Text := CDSTransiente.FieldByName('ID').AsString; EditColaborador.Text := CDSTransiente.FieldByName('NOME').AsString; end else begin Exit; EditQuantidade.SetFocus; end; finally CDSTransiente.Close; end; end; end; {$ENDREGION} {$REGION 'Controle de Grid'} procedure TFPontoAbono.GridDblClick(Sender: TObject); begin inherited; ConfigurarLayoutTela; end; procedure TFPontoAbono.GridParaEdits; begin inherited; if not CDSGrid.IsEmpty then begin ObjetoVO := TPontoAbonoVO(TController.BuscarObjeto('PontoAbonoController.TPontoAbonoController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET')); end; if Assigned(ObjetoVO) then begin EditIdColaborador.AsInteger := TPontoAbonoVO(ObjetoVO).IdColaborador; EditColaborador.Text := TPontoAbonoVO(ObjetoVO).ColaboradorNome; EditQuantidade.AsInteger := TPontoAbonoVO(ObjetoVO).Quantidade; EditUtilizado.AsInteger := TPontoAbonoVO(ObjetoVO).Utilizado; EditSaldo.AsInteger := TPontoAbonoVO(ObjetoVO).Saldo; EditDataCadastro.Date := TPontoAbonoVO(ObjetoVO).DataCadastro; EditInicioUtilizacao.Date := TPontoAbonoVO(ObjetoVO).InicioUtilizacao; MemoObservacao.Text := TPontoAbonoVO(ObjetoVO).Observacao; // Preenche as grids internas com os dados das Listas que vieram no objeto TController.TratarRetorno<TPontoAbonoUtilizacaoVO>(TPontoAbonoVO(ObjetoVO).ListaPontoAbonoUtilizacaoVO, True, True, CDSPontoAbonoUtilizacao); // Limpa as listas para comparar posteriormente se houve inclusões/alterações e subir apenas o necessário para o servidor TPontoAbonoVO(ObjetoVO).ListaPontoAbonoUtilizacaoVO.Clear; // Serializa o objeto para consultar posteriormente se houve alterações FormatSettings.DecimalSeparator := '.'; StringObjetoOld := ObjetoVO.ToJSONString; FormatSettings.DecimalSeparator := ','; end; ConfigurarLayoutTela; end; {$ENDREGION} end.
(* Author: Tomas Giedraitis Date: 2016 March 12 Description: Find the sum and average of five predefined numbers Version: 1.0 - original version *) program SumAverage; const total_no = 5; var no1, no2, no3, no4, no5 : integer; sum : integer; avg : real; begin { Main } no1 := 45; no2 := 7; no3 := 68; no4 := 2; no5 := 34; sum := no1 + no2 + no3 + no4 + no5; avg := sum / total_no; writeln('Number of integers = ', total_no); writeln('Number1 = ', no1); writeln('Number2 = ', no2); writeln('Number3 = ', no3); writeln('Number4 = ', no4); writeln('Number5 = ', no5); writeln('Sum = ', sum); writeln('Average =', avg); end. { Main }
unit Ldmenus; interface Uses Forms,Menus,BmpBtn,classes,Controls; type TMenuButtonItem = class (TMenuItem) protected fButtonCaption:string; fButtonBMP:string; procedure WriteVisible(v:boolean); procedure WriteEnabled(v:boolean); procedure WriteButtonCaption(v:string); procedure WriteButtonBMP(v:string); procedure WriteHint(v:string); procedure WriteOnClick(v:TNotifyEvent); procedure WriteButtonPresent(v:boolean); function ReadVisible:boolean; function ReadEnabled:boolean; function ReadButtonCaption:string; function ReadButtonBMP:string; function ReadHint:string; function ReadButtonPresent:boolean; public Button:TBmpBtn; constructor Create(AC:TComponent);override; destructor Destroy;override; published property ButtonPresent:boolean Read ReadButtonPresent Write WriteButtonPresent; property ButtonCaption:string read fButtonCaption Write WriteButtonCaption; property ButtonBMP:string Read ReadButtonBMP Write WriteButtonBMP; property Visible:boolean Read ReadVisible Write WriteVisible; property Enabled:boolean Read ReadEnabled Write WriteEnabled; property OnClick:TNotifyEvent Write WriteOnClick; property Hint:string Read ReadHint Write WriteHint; end; procedure Register; implementation constructor TMenuButtonItem.Create(AC:TComponent); var i:integer; begin inherited Create(AC); Button:=NIL; fButtonCaption:=''; fButtonBMP:=''; end; destructor TMenuButtonItem.Destroy; begin { if Button<>NIL then Button.free;} inherited destroy; end; {-------------------------Read----------------------} function TMenuButtonItem.ReadButtonPresent:boolean; begin if Button<>nil then ReadButtonPresent:=Button.Visible else ReadButtonPresent:=false; end; function TMenuButtonItem.ReadVisible:boolean; begin ReadVisible:=inherited Visible; end; function TMenuButtonItem.ReadEnabled:boolean; begin ReadEnabled:=inherited Enabled; end; function TMenuButtonItem.ReadButtonBMP:string; begin if Button<>nil then ReadButtonBMP:=Button.FileName else ReadButtonBMP:=''; end; function TMenuButtonItem.ReadHint:string; begin ReadHint:=inherited hint; end; function TMenuButtonItem.ReadButtonCaption:string; begin ButtonCaption:=Button.FileName; end; {-------------------------Write----------------------} procedure TMenuButtonItem.WriteVisible(v:boolean); begin inherited visible:=v; if Button<>NIL then Button.Visible:=v; end; procedure TMenuButtonItem.WriteEnabled(v:boolean); begin inherited Enabled:=v; if Button<>NIL then Button.Enabled:=v; end; procedure TMenuButtonItem.WriteButtonPresent(v:boolean); begin if v then begin Button:=TBmpBtn.Create(self); Button.Parent:=TWinControl(Owner); Button.Visible:=v; Button.ToolbarButton:=TRUE; Button.Caption:=fButtonCaption; Button.FileName:=fButtonBMP; Button.NumGlyphs:=3; Button.Hint:=Hint; end else begin if Button<>NIL then Button.Free; Button:=NIL end end; procedure TMenuButtonItem.WriteButtonCaption(v:string); begin fButtonCaption:=v; if Button<>NIL then Button.Caption:=v; end; procedure TMenuButtonItem.WriteButtonBMP(v:string); begin fButtonBMP:=v; if Button<>NIL then Button.FileName:=v; end; procedure TMenuButtonItem.WriteHint(v:string); begin inherited hint:=v; if Button<>NIL then Button.Hint:=v; end; procedure TMenuButtonItem.WriteOnClick(v:TNotifyEvent); begin inherited OnClick:=v; if Button<>NIL then Button.OnClick:=v; end; {-------------------------End Read/write properties-------------} procedure Register; {---------------------} begin RegisterComponents('MenuButtonItem', [TMenuButtonItem]); end; end.
unit Model.Components.Query.Interfaces; interface uses Data.DB; type IModelComponentsQueryInterfaces = interface ['{4920C789-0953-4161-82DE-8498A42BB7F4}'] function Active : Boolean; function Close : IModelComponentsQueryInterfaces; function DataSet : TDataSet; function ExecSQL : IModelComponentsQueryInterfaces; function Open : IModelComponentsQueryInterfaces; function ParamByName(aParam:string;aValue:Variant): IModelComponentsQueryInterfaces; function FiledByName(aField:string):Variant; function SQLAdd(aSQL:string) : IModelComponentsQueryInterfaces; function SQLClear : IModelComponentsQueryInterfaces; end; IModelComponentsQueryFactory = interface ['{4C4213D1-1256-4F1D-89FF-A2C1289129AE}'] Function Query:IModelComponentsQueryInterfaces; end; implementation end.
unit SmileyTestAppMainForm; interface uses Windows, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, uSmiley, ExtCtrls, AppEvnts; type TSmileyTestForm = class(TForm) Button1: TButton; Button2: TButton; Button3: TButton; Label1: TLabel; ApplicationEvents1: TApplicationEvents; Panel1: TPanel; Label2: TLabel; procedure Button1Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure ApplicationEvents1Hint(Sender: TObject); private { Private declarations } MySmiley: TSmiley; public { Public declarations } end; var SmileyTestForm: TSmileyTestForm; implementation {$R *.dfm} uses frmChoose ; procedure TSmileyTestForm.ApplicationEvents1Hint(Sender: TObject); begin Label1.Caption := Application.Hint; end; procedure TSmileyTestForm.Button1Click(Sender: TObject); begin MySmiley := TSmiley.Create(Panel1); // Centers the TSmiley in the Panel // Uses TRectHelper in SysUtils MySmiley.Left := Panel1.ClientRect.CenterPoint.X - (MySmiley.Width div 2); MySmiley.Top := Panel1.ClientRect.CenterPoint.Y - (MySmiley.Height div 2); MySmiley.Parent := Panel1; Button3.Enabled := True; Button2.Enabled := True; Button1.Enabled := False; end; procedure TSmileyTestForm.Button2Click(Sender: TObject); begin MySmiley.Increment; end; procedure TSmileyTestForm.Button3Click(Sender: TObject); var TempChooseDlg: TChooseDlg; begin TempChooseDlg := TChooseDlg.Create(Self); try TempChooseDlg.Mood := MySmiley.Mood; TempChooseDlg.ShowModal; if MySmiley <> nil then begin MySmiley.ClickMood := TempChooseDlg.Mood; end; finally TempChooseDlg.Free; end; end; procedure TSmileyTestForm.FormClose(Sender: TObject; var Action: TCloseAction); begin MySmiley.Free; end; end.
{******************************************************} { rsSuperMemo Component } { Copyright 1998 RealSoft Development } { support: www.realsoftdev.com } {******************************************************} unit Rsmemo; interface {$I REALSOFT.INC} uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, Menus; type TrsSuperMemo = class(TMemo) private FOnReturn: TNotifyEvent; FLocator : boolean; FLocColor : TColor; FOldColor : TColor; FShowGray : boolean; FEnterToTab : boolean; procedure SetShowGray(AValue : Boolean); protected procedure DoEnter; override; procedure DoExit; override; procedure Loaded; override; procedure KeyPress(var Key: Char); override; procedure CMSetEnabled(var Message: TMessage); message CM_ENABLEDCHANGED; procedure WMSetColor(var Message: TMessage); message CM_COLORCHANGED; procedure WMPaint(var Message: TWMPaint); message WM_PAINT; public constructor Create(AOwner: TComponent); override; published property Locator : boolean read FLocator write FLocator default false; property LocColor : TColor read FLocColor write FLocColor default clAqua; property ShowGray : boolean read FShowGray write SetShowGray default true; property EnterToTab : boolean read FEnterToTab write FEnterToTab default false; property OnReturn : TNotifyEvent read FOnReturn write FOnReturn; end; procedure Register; implementation procedure Register; begin RegisterComponents('RSD', [TrsSuperMemo]); end; {***************************} { rsCustomComboBox } {***************************} constructor TrsSuperMemo.Create(AOwner: TComponent); begin inherited Create(AOwner); FLocator:= false; FLocColor:= clAqua; FShowGray:= true; FOnReturn:= nil; FEntertoTab:= false; ControlStyle := ControlStyle - [csSetCaption]; end; procedure TrsSuperMemo.Loaded; {$IFDEF LOCATOR} var F: TWinControl; {$ENDIF} begin inherited Loaded; FOldColor:= Color; {$IFDEF LOCATOR} F := GetParentForm( Self ); if F.Tag > 32767 then FLocator:= true; {$ENDIF} end; procedure TrsSuperMemo.KeyPress(var Key: Char); var F: TWinControl; begin {Handle enter like TAB} if not WantReturns then if (Key = #13) then begin if FEnterToTab then begin F := GetParentForm( Self ); SendMessage(F.Handle, WM_NEXTDLGCTL, 0, 0); end; Key := #0; if assigned(FOnReturn) then FOnReturn(Self); end; inherited KeyPress(Key); end; procedure TrsSuperMemo.DoEnter; begin if FLocator = true then Color:= FLocColor; inherited DoEnter; end; procedure TrsSuperMemo.DoExit; begin if FLocator = true then Color:= FOldColor; inherited DoExit; end; procedure TrsSuperMemo.CMSetEnabled(var Message: TMessage); begin inherited; Invalidate; end; procedure TrsSuperMemo.WMSetColor(var Message: TMessage); begin inherited; if (Color <> clBtnFace) and (Color <> LocColor) then FOldColor:= Color; end; procedure TrsSuperMemo.WMPaint(var Message: TWMPaint); var Gray: boolean; begin Gray:= (not Enabled) and (ShowGray) and (not Focused); if Gray then Color:= clbtnFace; if (not Gray) and (not (Color = LocColor)) then Color:= clWindow; inherited; end; procedure TrsSuperMemo.SetShowGray(AValue : Boolean); begin FShowGray:= AValue; Invalidate; end; end.
unit MqttService; interface {$I mormot.defines.inc} uses sysutils, classes, mormot.core.base, mormot.core.os, mormot.core.rtti, mormot.core.data, mormot.core.text, mormot.core.unicode, mormot.core.datetime, mormot.core.buffers, mormot.core.threads, mormot.core.log, mormot.net.sock, mormot.net.http, mormot.net.client, mormot.net.server, mormot.net.async_rw; type ERtspOverHttp = class(ESynException); TMQTTConnection = class(TAsyncConnection) private FClientId:RawByteString; FWillTopic,FWillMessage:RawByteString; FSubTitle:TShortStringDynArray; protected function DoParsePacket(Sender: TAsyncConnections;MsgType:Byte;Payload:RawByteString):integer; function OnRead(Sender: TAsyncConnections): TPollAsyncSocketOnRead; override; procedure BeforeDestroy(Sender: TAsyncConnections); override; procedure WriteSelfAck2(Sender: TAsyncConnections;p:RawByteString); procedure WritePublic(Sender: TAsyncConnections;t,c:RawByteString); public constructor Create(const aRemoteIP: RawUtf8); override; published property ClientId:RawByteString read FClientId; property SubTitle:TShortStringDynArray read FSubTitle; end; TMQTTServer = class(TAsyncServer) protected function ConnectionCreate(aSocket: TNetSocket; const aRemoteIp: RawUtf8; out aConnection: TAsyncConnection): boolean; override; procedure OnClientClose(connection: TObject); override; procedure OnClientsLogs(Level: TSynLogInfo; const Fmt: RawUtf8; const Args: array of const; Instance: TObject = nil); public constructor Create(const aHttpPort: RawUtf8; aLog: TSynLogClass; const aOnStart, aOnStop: TOnNotifyThread; aOptions: TAsyncConnectionsOptions = []); reintroduce; destructor Destroy; override; procedure WritePublic(t,c:RawByteString); end; implementation uses MqttUtils; { TPostConnection } function TMQTTConnection.DoParsePacket(Sender: TAsyncConnections;MsgType:Byte;Payload:RawByteString):Integer; var identistrid:RawByteString; i,ret:integer; t:RawByteString; msg:TMQTTMessageType; FFlag:byte; begin Result := 0; msg := TMQTTMessageType(MsgType shr 4); if not Loined then if msg<>mtCONNECT then begin Result := -1; exit; end; case msg of mtCONNECT: begin if Payload[1]<>#0 then begin Result := -1; exit; end; Delete(Payload,1,1); if Payload[1]=MQTT_VERSIONLEN3_CHAR then begin if length(Payload)<11 then exit; if (Payload[8]<>MQTT_VERSION3_CHAR) then exit; if not CompareMemSmall(@Payload[2],PAnsiChar(MQTT_PROTOCOLV3),MQTT_VERSIONLEN3) then exit; CanIdleLen := (ord(Payload[10]) shl 8) or ord(Payload[11]); FFlag := ord(Payload[9]); Delete(Payload,1,11); end else if (Payload[1]=MQTT_VERSIONLEN311_CHAR) then begin if length(Payload)<9 then exit; if (Payload[6]<>MQTT_VERSION4_CHAR) then exit; if not CompareMemSmall(@Payload[2],PAnsiChar(MQTT_PROTOCOLV311),length(MQTT_PROTOCOLV311)) then exit; CanIdleLen := (ord(Payload[8]) shl 8) or ord(Payload[9]) ; FFlag := ord(Payload[7]); Delete(Payload,1,9); end else begin Result := -1; exit; end; CanIdleLen := fCanIdleLen + 3; ret:=mqtt_readstr(@Payload[1],length(Payload),FClientID); if ret = 0 then begin Result := -1; exit; end; Delete(Payload,1,ret); if (FFlag and $4)<>0 then begin ret:=mqtt_readstr(@Payload[1],length(Payload),FWillTopic); if ret = 0 then begin Result := -1; exit; end; Delete(Payload,1,ret); ret:=mqtt_readstr(@Payload[1],length(Payload),FWillMessage); if ret = 0 then begin Result := -1; exit; end; Delete(Payload,1,ret); end; if (FFlag and $80)<>0 then begin ret:=mqtt_readstr(@Payload[1],length(Payload),identistrid); if ret = 0 then begin Result := -1; exit; end; Delete(Payload,1,ret); end; if (FFlag and $40)<>0 then begin ret:=mqtt_readstr(@Payload[1],length(Payload),identistrid); if ret = 0 then begin Result := -1; exit; end; Delete(Payload,1,ret); end; WriteSelfAck2(Sender,mqtt_get_conack(0)); Loined := true; end; mtPINGREQ: begin if ((MsgType and $f)<>0) or (Payload<>'') then begin Result := -1; //error found close it exit; end; WriteSelfAck2(Sender,#$D0#0); //1010 0000 0 end; mtPUBLISH: begin if ((MsgType and 3)=3) or (length(Payload)<4) then begin Result := -1; exit; end; ret := mqtt_readstr(@Payload[1],length(Payload),t); if ret=0 then begin Result := -2; exit; end; Delete(Payload,1,ret); if (MsgType and 3)>0 then begin if length(Payload)<3 then begin Result := -3; exit; end; identistrid := Payload[1] + Payload[2]; Delete(Payload,1,2); end; if length(Payload)=0 then begin Result := -4; exit; end; WritePublic(Sender,t,Payload); if (MsgType and 3)>0 then WriteSelfAck2(Sender,#$40#02+identistrid); end; mtSUBSCRIBE: begin if ((MsgType and 3)<>2) or (length(Payload)<5) then begin Result := -1; //error found close it exit; end; identistrid := Payload[1] + Payload[2]; Delete(Payload,1,2); ret := mqtt_AddTopic(Payload,FSubTitle); if ret>0 then begin t := ''; for i := 0 to ret-1 do t := t + #2; WriteSelfAck2(Sender,mqtt_get_subAck(identistrid,t)); Result := 1; end; end; mtUNSUBSCRIBE: begin if ((MsgType and 3)<>2) or (length(Payload)<5) then begin Result := -1; //error found close it exit; end; identistrid := Payload[1] + Payload[2]; Delete(Payload,1,2); ret := mqtt_DelTopic(Payload,FSubTitle); if ret>0 then WriteSelfAck2(Sender,#$b0#02+identistrid); end; end; end; function TMQTTConnection.OnRead( Sender: TAsyncConnections): TPollAsyncSocketOnRead; var alen,lenwid:integer; Payload,bak:RawByteString; MsgType:Byte; begin result := sorContinue; if fSlot.readbuf='' then exit; bak := fSlot.readbuf; while length(fSlot.readbuf)>=2 do begin alen := mqtt_getframelen(@fSlot.readbuf[2],length(fSlot.readbuf)-1,lenwid); if (alen = -3) or ((alen+lenwid+1)>length(fSlot.readbuf)) then //part data, wait for recv begin exit; end else if alen < 0 then begin Sender.Log.Add.Log(sllCustom1, 'Len is Err ip=%id=%OnRead %',[RemoteIP,FClientId,BinToHex(fSlot.readbuf)], self); fSlot.readbuf := ''; result := sorClose; //error exit; end; MsgType := ord(fSlot.readbuf[1]); if Loined then begin if alen>2048 then begin Sender.Log.Add.Log(sllCustom1, 'Len is big ip=%OnRead %',[RemoteIP,BinToHex(fSlot.readbuf)], self); fSlot.readbuf := ''; result := sorClose; //error exit; end; end else begin if alen>1024 then begin Sender.Log.Add.Log(sllCustom1, 'Len is big ip=%OnRead %',[RemoteIP,BinToHex(fSlot.readbuf)], self); fSlot.readbuf := ''; result := sorClose; //error exit; end; end; if alen>0 then Payload := Copy(fSlot.readbuf,lenwid+2,alen) else Payload := ''; Delete(fSlot.readbuf,1,alen + lenwid + 1); if DoParsePacket(Sender,MsgType,Payload)<0 then begin Sender.Log.Add.Log(sllCustom1, 'Jiexi is Err ip=%id=%OnRead %',[RemoteIP,FClientId,BinToHex(bak)], self); fSlot.readbuf := ''; result := sorClose; //error exit; end; end; end; procedure TMQTTConnection.WritePublic(Sender: TAsyncConnections; t,c: RawByteString); begin TMQTTServer(sender).WritePublic(t,c); end; procedure TMQTTConnection.WriteSelfAck2(Sender: TAsyncConnections; p: RawByteString); var aconn: TAsyncConnection; begin aconn := Sender.ConnectionFindLocked(self.Handle); if aconn <> nil then try Sender.Write(aconn, p); finally Sender.Unlock; end else begin Sender.Log.Add.Log(sllDebug, 'OnRead % ',[Handle], self); end; end; procedure TMQTTConnection.BeforeDestroy(Sender: TAsyncConnections); begin inherited BeforeDestroy(Sender); // if FWillTopic<>'' then // WritePublic(Sender,FWillTopic,FWillMessage); end; constructor TMQTTConnection.Create(const aRemoteIP: RawUtf8); begin inherited; FClientId:= ''; end; { TRtspOverHttpServer } constructor TMQTTServer.Create( const aHttpPort: RawUtf8; aLog: TSynLogClass; const aOnStart, aOnStop: TOnNotifyThread; aOptions: TAsyncConnectionsOptions); begin fLog := aLog; inherited Create(aHttpPort, aOnStart, aOnStop, TMQTTConnection, 'MQTTSvr', aLog, aOptions,4); ServerSocket.OnLog := OnClientsLogs; end; destructor TMQTTServer.Destroy; var log: ISynLog; begin log := fLog.Enter(self, 'Destroy'); inherited Destroy; end; function TMQTTServer.ConnectionCreate(aSocket: TNetSocket; const aRemoteIp: RawUtf8; out aConnection: TAsyncConnection): boolean; begin aConnection := TMQTTConnection.Create(aRemoteIp); aConnection.CanIdleLen := 3; // connected in 3 sec, if not inherited ConnectionAdd(aSocket, aConnection) then begin aConnection.Free; aConnection := nil; Log.Add.Log(sllCustom1, 'inherited %.ConnectionAdd(%) failed', [ConnectionCount], self); Result := false; exit; end; Log.Add.Log(sllCustom1, 'Open Connection Count:%', [ConnectionCount], self); result := true; end; procedure TMQTTServer.OnClientClose(connection: TObject); begin Log.Add.Log(sllCustom1, 'Close Connection Count:%', [ConnectionCount], self); end; procedure TMQTTServer.OnClientsLogs(Level: TSynLogInfo; const Fmt: RawUtf8; const Args: array of const; Instance: TObject); begin Log.Add.Log(Level, Fmt, Args, Instance); end; procedure TMQTTServer.WritePublic(t,c: RawByteString); var i:integer; aconn: TMQTTConnection; frame:RawByteString; begin frame := #$30 + mqtt_get_lenth(length(t)+length(c)+2) + mqtt_get_strlen(length(t)) + t + c; Lock; try for i := 0 to ConnectionCount-1 do begin aconn := Connection[i] as TMQTTConnection; //if aconn=self then Continue; if mqtt_compareTitle(t,aconn.FSubTitle) then Write(aconn, frame); end; finally Unlock; end; end; end.
unit Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Data.DB, Vcl.ComCtrls, Data.Bind.EngExt, Vcl.Bind.DBEngExt, System.Rtti, System.Bindings.Outputs, Vcl.Bind.Editors, Data.Bind.Components, Vcl.ExtCtrls, Model; type TForm3 = class(TForm) MCPDbGrid: TDBGrid; SelectMCPButton: TButton; Log_MCPDataGrid: TDBGrid; SelectLogBtn: TButton; MasterTree: TTreeView; DetailsPanel: TPanel; Memo1: TMemo; procedure SelectMCPButtonClick(Sender: TObject); procedure SelectLogBtnClick(Sender: TObject); procedure MasterTreeChange(Sender: TObject; Node: TTreeNode); procedure FormTree(Parent: TTreeNode; Value: TRecordInfo); procedure MasterTreeCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean); private { Private declarations } public { Public declarations } end; var Form3: TForm3; implementation {$R *.dfm} uses DataModule, Mappings; procedure TForm3.MasterTreeChange(Sender: TObject; Node: TTreeNode); var recordInfo: TRecordInfo; i: Integer; begin if Node.Data <> nil then begin for i := 0 to DetailsPanel.ComponentCount - 1 do begin DetailsPanel.Components[i].Free; end; recordInfo := TRecordInfo(Node.Data); recordInfo.GetView(DetailsPanel); end; end; procedure TForm3.MasterTreeCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean); var recordInfo: TRecordInfo; begin if Node.Data = nil then begin Exit; end; recordInfo := TRecordInfo(Node.Data); if recordInfo is TRecordContainer and recordInfo.HaveChanges() then begin Sender.Canvas.Font.Color := clPurple; end else if recordInfo.State = stAdded then begin Sender.Canvas.Font.Color := clGreen; end else if recordInfo.State = stDeleted then begin Sender.Canvas.Font.Color := clGray; end else if recordInfo.State = stModified then begin Sender.Canvas.Font.Color := clRed; end else if recordInfo.State = stChildModified then begin Sender.Canvas.Font.Color := clPurple; end; end; procedure TForm3.SelectLogBtnClick(Sender: TObject); var Node: TTreeNode; recordInfo: TRecordInfo; item: TRecordInfo; begin MCPDataModule.SelectZ_MCPQuery.ParamByName('z_mcp_id').AsInteger := MCPDataModule.SelectLog_MCPQuery.FieldByName('z_mcp_id').AsInteger; MCPDataModule.SelectZ_MCPQuery.ParamByName('mcp_id').AsInteger := MCPDataModule.SelectMCPQuery.FieldByName('id').AsInteger; MCPDataModule.SelectZ_MCPQuery.Open; MasterTree.Items.Clear; Node := MasterTree.Items.AddFirst(nil, ''); recordInfo := TMappingsFactory.MapMCP(MCPDataModule.SelectZ_MCPQuery.Fields); Node.Text := recordInfo.DisplayText; Node.Data := recordInfo; for item in recordInfo.Items do begin FormTree(Node, item); end; Memo1.Clear; Memo1.Lines.AddStrings(TMappingsFactory.GetChanges(recordInfo)); MCPDataModule.SelectZ_MCPQuery.Close; end; procedure TForm3.SelectMCPButtonClick(Sender: TObject); begin MCPDataModule.SelectLog_MCPQuery.Close; MCPDataModule.SelectLog_MCPQuery.ParamByName('log_id').AsInteger := MCPDataModule.SelectMCPQuery.FieldByName('log_id').AsInteger; MCPDataModule.SelectLog_MCPQuery.Open; end; procedure TForm3.FormTree(Parent: TTreeNode; Value: TRecordInfo); var Node: TTreeNode; item: TRecordInfo; begin Node := MasterTree.Items.AddChildObject(Parent, Value.DisplayText, Value); for item in Value.Items do begin FormTree(Node, item); end; end; end.
unit uGlobals; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, Math, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ShlObj, System.ImageList, Vcl.ImgList, DBGridEh, System.IOUtils, ShellExec, FlexCel.Core, FlexCel.XLSAdapter, FlexCel.Render, FlexCel.PDF, Vcl.ExtCtrls, System.Actions, Vcl.ActnList, Vcl.ComCtrls, Vcl.DBCtrls, Vcl.StdCtrls; type TfrmGlobals = class(TForm) imgList16: TImageList; imgList32: TImageList; procedure FormCreate(Sender: TObject); end; type TOpenManner = (omRead, omEdit, omNew); type TDogScope = (dgsActive, dgsArchive); type TFileDates = record Created: TDateTime; Modified: TDateTime; Accessed: TDateTime; end; procedure TurnContainerChildsToRO(const container: TComponent); procedure TurnContainerChildsToRW(const container: TComponent); procedure GetMyDocsFolder; procedure MakePDFFromXF(const xf: TXlsFile; const xfName: string; openAfterCreate: boolean = true); procedure ClearGridFilters(var grid: TDBGridEh); procedure SetAccessRestrictions(var frm: TFormClass); procedure ShowMessageDIP; function SelectDirectory(var Path: string; const Title: string): boolean; //function GetFileDate(const FName: string; var Dates: TFileDates) // : boolean; overload; function GetFileDate(const FName: string; var FileDate: TDateTime) : boolean; //overload; function GetDocPagesCount(const FileName: string; var PagesCount: integer): boolean; var frmGlobals: TfrmGlobals; // gv = Global Variable // gvActiveGrig: TDBGridEh; gvOrgID: integer; // current Org ID gvOwnerID: integer; // current Owner ID gvDogID: integer; // current Dog ID gvOpenManner: TOpenManner; gvIsRusOrg: boolean; // Rissian company or not gvLastShownFormName: string; // except of TfrmCommRecEditor kind gvMyDocuments: string; // gvChangedFields: TStringList; gvLastMonitorNum: integer; // for multiple monotors case gvDogScope: TDogScope; gvUserInfo: packed record OSName, NameFull, NameShort, RightsS, SMTP, Phone: string; RightsN, Shop, LNOM: integer; end; const // gc = Global Constant // access rights gcARAdmin = 0; // Administrator gcARBuyer = 1; // Buyer gcARView = 2; // Read only // Contracts visibility scope gcDogScopeActive = ' <> '; // ' in (''О'',''С'',''П'')'; gcDogScopeArchive = ' = '; // ' = ''А'''; // Russian counrty code gcCountyRusCode = 643; // field names gcFldOrgID = 'KORG'; gcFldDogID = 'NOM_DOC'; gcFldDogRegNum = 'NOM_REG'; gcFldDogState = 'SOST_DOG'; gcFldDogType = 'PRDPK'; gcFldRefDogID = 'N_ISHDOG'; gcFldECopy = 'DOC_ECOPY_PATH'; gcFldOwnerID = 'DOG_OWNER'; gcFldEBSPayCode = 'KODEBS'; gcWhere = 'WHERE '; // labeling gcDogAlone = 'Договор'; gcOrgAlone = 'Организация'; gcAccessTypeEdit = ' - Редактирование'; gcAccessTypeNewRecord = ' - Новая запись'; gcAccessTypeRO = ' - Просмотр'; // info messages gcIMMandatoryField = 'Это поле обязательное и не может быть пустым.'; // mandatory fields for record editing gcMFOrg = 'NAM=dbeNAM,STRANA=dblKSTR,GOR=dbeGOR,UL=dbeUL,TIPORG=dblTIPORG,' + 'VED=dblVED'; gcMFDog = 'DOG_OWNER=dblDogOwner,PRDPK=dblDogType,DOG=dbeDogNum' + ',DTOFOR=dbdDateOfor,DTFINISH=dbdDTFINISH' + ',K_BUSINESS_UNIT=dblContractedBU,KOD_ISP_KD=dblRespBU,KOD_ISP_FO=dblRespFO' + ',ID_RETENTION=dblRetention,SODER=dbmContent'; gcMFEBSPayRecord = 'TIP_DOG=dbcDogType,KODEBS=dbeEBSCode' + ',DESCRIPTION=dbmDescr,DESCRIPTION_R=dbmDescrRus'; { DONE : add mandatory fields for EBS pay record } gcDefOwnerID = 23320; implementation {$R *.dfm} const gcIMStillBuild = 'Developement is in progress. This feature will available later.'; procedure ShowMessageDIP; begin ShowMessage(gcIMStillBuild); end; procedure TurnContainerChildsToRO(const container: TComponent); var i: integer; begin for i := 0 to pred(container.Owner.ComponentCount) do if TControl(container.Owner.Components[i]).Parent = container then if container.Owner.Components[i] is TDBGridEh then TDBGridEh(container.Owner.Components[i]).ReadOnly := true else if not((container.Owner.Components[i] is TPageControl) or (container.Owner.Components[i] is TDBText) or (container.Owner.Components[i] is TLabel) or (container.Owner.Components[i] is TLabeledEdit)) then TControl(container.Owner.Components[i]).Enabled := False; end; procedure TurnContainerChildsToRW(const container: TComponent); var i: integer; begin for i := 0 to pred(container.Owner.ComponentCount) do if TControl(container.Owner.Components[i]).Parent = container then if container.Owner.Components[i] is TDBGridEh then TDBGridEh(container.Owner.Components[i]).ReadOnly := False else TControl(container.Owner.Components[i]).Enabled := true; end; procedure GetMyDocsFolder; begin gvMyDocuments := IncludeTrailingBackslash(tpath.GetDocumentsPath); end; procedure MakePDFFromXF(const xf: TXlsFile; const xfName: string; openAfterCreate: boolean = true); var PDF: TFlexCelPdfExport; pdfName: string; begin PDF := TFlexCelPdfExport.Create(xf, true); try pdfName := ChangeFileExt(xfName, '.pdf'); PDF.Export(pdfName); if openAfterCreate then ShellExecute(0, EmptyStr, pdfName, EmptyStr, EmptyStr, SW_SHOWMAXIMIZED); finally PDF.Free; end; end; procedure TfrmGlobals.FormCreate(Sender: TObject); begin // initialize global vars // gvActiveGrig := nil; gvOpenManner := omRead; gvIsRusOrg := False; // Rissian company or not gvLastShownFormName := EmptyStr; gvOrgID := 0; gvOwnerID := gcDefOwnerID; // SMZ by default gvDogID := 0; gvMyDocuments := EmptyStr; gvLastMonitorNum := 0; gvDogScope := dgsActive; end; procedure ClearGridFilters(var grid: TDBGridEh); var i: integer; begin for i := 0 to pred(grid.Columns.Count) do begin grid.Columns[i].STFilter.Clear; // grid.Columns[i].Title.SortIndex := 0; // grid.Columns[i].Title.SortMarker := smNoneEh; end; grid.Refresh; end; procedure SetAccessRestrictions(var frm: TFormClass); procedure RestrictActionWithRole(const actName: string; var fc: TFormClass; const ARole: integer = gcARAdmin; const AType: integer = 1); var actn: TComponent; begin actn := TForm(fc).FindComponent(actName); if actn <> nil then if AType > 0 then TAction(actn).Visible := (gvUserInfo.RightsN = ARole) else TAction(actn).Visible := (gvUserInfo.RightsN <> ARole); end; begin try if TForm(frm).Name = 'frmMain' then begin RestrictActionWithRole('actOrgNew', frm); RestrictActionWithRole('actJournals', frm, gcARBuyer, 0); RestrictActionWithRole('actRefs', frm, gcARBuyer, 0); RestrictActionWithRole('actTools', frm); end else if TForm(frm).Name = 'frmOrgList' then begin RestrictActionWithRole('actOrgNew', frm); RestrictActionWithRole('actOrgDelete', frm); end else if TForm(frm).Name = 'frmDogs' then begin RestrictActionWithRole('actDogNew', frm); RestrictActionWithRole('actDogNewAddon', frm); RestrictActionWithRole('actDeleteDog', frm); end; finally if gvUserInfo.RightsN = gcARAdmin then gvOpenManner := omEdit else gvOpenManner := omRead; end; end; function SelectDirectory(var Path: string; const Title: string): boolean; var lpItemID: PItemIDList; BrowseInfo: TBrowseInfo; DisplayName: array [0 .. MAX_PATH] of char; TempPath: array [0 .. MAX_PATH] of char; begin FillChar(BrowseInfo, sizeof(TBrowseInfo), #0); BrowseInfo.hwndOwner := 0; BrowseInfo.pszDisplayName := @DisplayName; BrowseInfo.lpszTitle := PChar(Title); BrowseInfo.ulFlags := BIF_RETURNONLYFSDIRS or BIF_USENEWUI or BIF_STATUSTEXT; // BIF_BROWSEINCLUDEFILES or BIF_EDITBOX or BIF_VALIDATE ; lpItemID := SHBrowseForFolder(BrowseInfo); Result := lpItemID <> nil; if Result then begin SHGetPathFromIDList(lpItemID, TempPath); Path := TempPath; GlobalFreePtr(lpItemID); end; end; //function GetFileDate(const FName: string; var Dates: TFileDates) // : boolean; overload; //var // fad: TWin32FileAttributeData; // SystemTime, LocalTime: TSystemTime; //begin // if not GetFileAttributesEx(PChar(FName), GetFileExInfoStandard, @fad) then // Result := False // else // begin // Result := true; // FileTimeToSystemTime(fad.ftLastWriteTime, SystemTime); // SystemTimeToTzSpecificLocalTime(nil, SystemTime, LocalTime); // Dates.Modified := SystemTimeToDateTime(LocalTime); // FileTimeToSystemTime(fad.ftCreationTime, SystemTime); // SystemTimeToTzSpecificLocalTime(nil, SystemTime, LocalTime); // Dates.Created := SystemTimeToDateTime(LocalTime); // FileTimeToSystemTime(fad.ftLastAccessTime, SystemTime); // SystemTimeToTzSpecificLocalTime(nil, SystemTime, LocalTime); // Dates.Accessed := SystemTimeToDateTime(LocalTime); // end; //end; function GetFileDate(const FName: string; var FileDate: TDateTime) : boolean; //overload; var fad: TWin32FileAttributeData; SystemTime, LocalTime: TSystemTime; begin if not GetFileAttributesEx(PChar(FName), GetFileExInfoStandard, @fad) then Result := False else begin Result := true; FileTimeToSystemTime(fad.ftLastWriteTime, SystemTime); SystemTimeToTzSpecificLocalTime(nil, SystemTime, LocalTime); FileDate := SystemTimeToDateTime(LocalTime); end; end; function GetDocPagesCount(const FileName: string; var PagesCount: integer): boolean; function CalcTIFFPages(f: TStream): integer; function ReadLongIntel(aBuffer: array of byte): cardinal; var tmp: cardinal; begin Result := 0; tmp := longint(aBuffer[3]); tmp := tmp shl 24; Result := Result or tmp; tmp := longint(aBuffer[2]); Result := Result or (tmp shl 16); tmp := longint(aBuffer[1]); Result := Result or (tmp shl 8); tmp := longint(aBuffer[0]); Result := Result or tmp; end; function ReadToByteIntel(aBuffer: array of byte): longint; var tmp: longint; begin Result := 0; tmp := longint(aBuffer[1]); Result := Result or (tmp shl 8); tmp := longint(aBuffer[0]); Result := Result or tmp; end; var Buffer: array [0 .. 65000] of byte; IFDOffset: integer; i: integer; bread: cardinal; begin Result := 0; f.Read(Buffer, 8); if not((Buffer[0] = $49) and (Buffer[1] = $49)) then // non-Intel raise Exception.Create('Not Intel(Motorolla)'); for i := 4 to 7 do Buffer[i - 4] := Buffer[i]; IFDOffset := ReadLongIntel(Buffer); while IFDOffset <> 0 do begin inc(Result); f.Seek(IFDOffset, soFromBeginning); f.Read(Buffer, 2); for i := 1 to ReadToByteIntel(Buffer) do begin f.Read(Buffer, 12); end; bread := f.Read(Buffer, 4); if bread <> 4 then break; IFDOffset := ReadLongIntel(Buffer); end; end; var s: TStream; begin Result := False; s := TFileStream.Create(FileName, fmShareDenyWrite); try PagesCount := CalcTIFFPages(s); Result := PagesCount > 0; finally FreeAndNil(s); end; end; end.
unit CommonfrmOptions; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.FreeOTFE.org/ // // ----------------------------------------------------------------------------- // interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, CommonSettings, OTFEFreeOTFEBase_U, ExtCtrls, SDUForms, SDUStdCtrls, CommonfmeOptions_Base, CommonfmeOptions_PKCS11; type TfrmOptions = class(TSDUForm) pbOK: TButton; pbCancel: TButton; cbSettingsLocation: TComboBox; lblSettingsLocation: TLabel; ckAssociateFiles: TSDUCheckBox; pcOptions: TPageControl; imgNoSaveWarning: TImage; tsPKCS11: TTabSheet; fmeOptions_PKCS11: TfmeOptions_PKCS11; procedure pbOKClick(Sender: TObject); procedure pbCancelClick(Sender: TObject); procedure ControlChanged(Sender: TObject); procedure FormShow(Sender: TObject); protected FOrigAssociateFiles: boolean; function SettingsLocationDisplay(loc: TSettingsSaveLocation): string; procedure PopulateSaveLocation(); procedure EnableDisableControls(); virtual; function GetSettingsLocation(): TSettingsSaveLocation; function DoOKClicked(): boolean; virtual; procedure AllTabs_InitAndReadSettings(config: TSettings); virtual; procedure AllTabs_WriteSettings(config: TSettings); public OTFEFreeOTFEBase: TOTFEFreeOTFEBase; procedure ChangeLanguage(langCode: string); virtual; abstract; end; implementation {$R *.DFM} uses ShlObj, // Required for CSIDL_PROGRAMS {$IFDEF FREEOTFE_MAIN} FreeOTFESettings, {$ENDIF} {$IFDEF FREEOTFE_EXPLORER} FreeOTFEExplorerSettings, {$ENDIF} SDUi18n, SDUGeneral, SDUDialogs; {$IFDEF _NEVER_DEFINED} // This is just a dummy const to fool dxGetText when extracting message // information // This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to // picks up SDUGeneral.SDUCRLF const SDUCRLF = ''#13#10; {$ENDIF} const SHELL_VERB = 'Open'; CONTROL_MARGIN = 10; function TfrmOptions.GetSettingsLocation(): TSettingsSaveLocation; var retval: TSettingsSaveLocation; sl: TSettingsSaveLocation; begin retval := Settings.OptSaveSettings; for sl:=low(sl) to high(sl) do begin if (SettingsLocationDisplay(sl) = cbSettingsLocation.Items[cbSettingsLocation.ItemIndex]) then begin retval := sl; break; end; end; Result := retval; end; function TfrmOptions.SettingsLocationDisplay(loc: TSettingsSaveLocation): string; var retval: string; begin retval := ''; case loc of slNone: retval := SAVELOCATION_DO_NOT_SAVE; slExeDir: retval := SDUParamSubstitute( SAVELOCATION_EXE_DIR, [Application.Title] ); slProfile: retval := SAVELOCATION_USER_PROFILE; slRegistry: retval := SAVELOCATION_REGISTRY; slCustom: retval := SAVELOCATION_CUSTOMISED; end; Result := retval; end; procedure TfrmOptions.pbOKClick(Sender: TObject); begin if DoOKClicked() then begin ModalResult := mrOK; end end; function TfrmOptions.DoOKClicked(): boolean; var allOK: boolean; oldSettingsLocation: TSettingsSaveLocation; newSettingsLocation: TSettingsSaveLocation; msgSegment: string; vistaProgFilesDirWarn: boolean; programFilesDir: string; filename: string; prevSDUDialogsStripSingleCRLF: boolean; i: integer; j: integer; currTabSheet: TTabSheet; deleteOldLocation: boolean; begin allOK := TRUE; // Decode settings save location oldSettingsLocation := Settings.OptSaveSettings; newSettingsLocation := GetSettingsLocation(); if allOK then begin // If user tried to save settings under C:\Program Files\... while // running under Vista, let the user know that Vista's security // system screws this up (it maps the save to somewhere in the user's // profile) vistaProgFilesDirWarn:= FALSE; if ( SDUOSVistaOrLater() and (newSettingsLocation = slExeDir) ) then begin programFilesDir := SDUGetSpecialFolderPath(SDU_CSIDL_PROGRAM_FILES); filename := Settings.GetSettingsFilename(newSettingsLocation); vistaProgFilesDirWarn := (Pos( uppercase(programFilesDir), uppercase(filename) ) > 0); end; allOK := not(vistaProgFilesDirWarn); if not(allOK) then begin prevSDUDialogsStripSingleCRLF := SDUDialogsStripSingleCRLF; // Don't do special processing on this message SDUDialogsStripSingleCRLF := FALSE; // Don't do special processing on this message SDUMessageDlg( SDUParamSubstitute(_('Under Windows Vista, you cannot save your settings file anywhere under:'+SDUCRLF+ SDUCRLF+ '%1'+SDUCRLF+ SDUCRLF+ 'due to Vista''s security/mapping system.'), [programFilesDir])+SDUCRLF+ SDUCRLF+ _('Please either select another location for storing your settings (e.g. your user profile), or move the FreeOTFE executable such that it is not stored underneath the directory shown above.'), mtWarning ); SDUDialogsStripSingleCRLF := prevSDUDialogsStripSingleCRLF; // Don't do special processing on this message end; end; if allOK then begin // For each tab, scan it's controls; if it's one of our frames, get it to // process... for i:=0 to (pcOptions.PageCount - 1) do begin currTabSheet := pcOptions.Pages[i]; for j:=0 to (currTabSheet.Controlcount - 1) do begin if (currTabSheet.Controls[j] is TfmeOptions_Base) then begin if not(TfmeOptions_Base(currTabSheet.Controls[j]).CheckSettings()) then begin pcOptions.ActivePage := pcOptions.Pages[i]; allOK := FALSE; break; end; end; end; // Break out of loop early if problem detected if not(allOK) then begin break; end; end; end; if allOK then begin Settings.OptSaveSettings := newSettingsLocation; AllTabs_WriteSettings(Settings); if (Settings.OptSaveSettings <> slNone) then begin allOK := Settings.Save(); end; end; if allOK then begin // If settings aren't going to be saved, and they weren't saved previously, // warn user if ( (oldSettingsLocation = newSettingsLocation) and (newSettingsLocation = slNone) ) then begin allOK := (SDUMessageDlg( _('You have not specified a location where FreeOTFE should save its settings to.')+SDUCRLF+ SDUCRLF+ _('Although the settings entered will take effect, they will revert back to their defaults when FreeOTFE is exited.')+SDUCRLF+ SDUCRLF+ _('Do you wish to select a location in order to make your settings persistant?'), mtWarning, [mbYes, mbNo], 0 ) = mrNo); end // If the save settings location has been changed, and we previously // saved settings to a file, ask the user if they want to delete their // old settings file else if ( (oldSettingsLocation <> newSettingsLocation) and (oldSettingsLocation <> slNone) ) then begin if (newSettingsLocation = slNone) then begin msgSegment := _('You have opted not to save your settings'); end else begin msgSegment := _('You have changed the location where your settings will be saved'); end; // If settings were previously stored in a file, prompt user if they want // to delete it deleteOldLocation := TRUE; if ( (oldSettingsLocation = slExeDir) or (oldSettingsLocation = slProfile) or (oldSettingsLocation = slCustom) ) then begin deleteOldLocation := (SDUMessageDlg( msgSegment+SDUCRLF+ SDUCRLF+ _('Would you like FreeOTFE to delete your previous settings file?')+SDUCRLF+ SDUCRLF+ _('Note: If you select "No" here, FreeOTFE may pick up your old settings the next time you start FreeOTFE'), mtConfirmation, [mbYes, mbNo], 0 ) = mrYes); end; if deleteOldLocation then begin if not(Settings.DestroySettingsFile(oldSettingsLocation)) then begin if ( (oldSettingsLocation = slExeDir) or (oldSettingsLocation = slProfile) or (oldSettingsLocation = slCustom) )then begin SDUMessageDlg( SDUParamSubstitute(_('Your previous settings file stored at:'+SDUCRLF+ SDUCRLF+ '%1'+SDUCRLF+ SDUCRLF+ 'could not be deleted. Please remove this file manually.'), [Settings.GetSettingsFilename(oldSettingsLocation)]), mtInformation ); end else if (oldSettingsLocation = slRegistry) then begin SDUMessageDlg( SDUParamSubstitute(_('Your previous settings file stored in the Windows registry under:'+SDUCRLF+ SDUCRLF+ '%1'+SDUCRLF+ SDUCRLF+ 'could not be deleted. Please delete this registry key manually.'), [Settings.RegistryKey()]), mtInformation ); end; end; end else begin if ( (oldSettingsLocation = slExeDir) or (oldSettingsLocation = slProfile) or (oldSettingsLocation = slCustom) )then begin SDUMessageDlg( SDUParamSubstitute(_('Your previous settings will remain stored at:'+SDUCRLF+ SDUCRLF+ '%1'), [Settings.GetSettingsFilename(oldSettingsLocation)]), mtInformation ); end else if (oldSettingsLocation = slRegistry) then begin SDUMessageDlg( SDUParamSubstitute(_('Your previous settings will remain stored in the Windows registry under:'+SDUCRLF+ SDUCRLF+ '%1'), [Settings.RegistryKey()]), mtInformation ); end; end; end; end; if allOK then begin if (ckAssociateFiles.checked <> FOrigAssociateFiles) then begin if ckAssociateFiles.checked then begin SDUFileExtnRegCmd( VOL_FILE_EXTN, SHELL_VERB, '"'+ParamStr(0)+'" /mount /volume "%1"' ); SDUFileExtnRegIcon( VOL_FILE_EXTN, ParamStr(0), 0 ); end else begin SDUFileExtnUnregIcon(VOL_FILE_EXTN); SDUFileExtnUnregCmd( VOL_FILE_EXTN, SHELL_VERB ); end; FOrigAssociateFiles := ckAssociateFiles.checked; end; end; Result := allOK; end; procedure TfrmOptions.PopulateSaveLocation(); var idx: integer; useIdx: integer; sl: TSettingsSaveLocation; begin // Populate and set settings location dropdown cbSettingsLocation.Items.Clear(); idx := -1; useIdx := -1; for sl := low(sl) to high(sl) do begin if ( (sl = slCustom) and (Settings.CustomLocation = '') ) then begin // Skip this one; no custom location set continue; end; inc(idx); cbSettingsLocation.Items.Add(SettingsLocationDisplay(sl)); if (Settings.OptSaveSettings = sl) then begin useIdx := idx; end; end; cbSettingsLocation.ItemIndex := useIdx; end; procedure TfrmOptions.AllTabs_InitAndReadSettings(config: TSettings); var i: integer; j: integer; currTabSheet: TTabSheet; maxWidth: integer; begin PopulateSaveLocation(); // For each tab, scan it's controls; if it's one of our frames, get it to // process... for i:=0 to (pcOptions.PageCount - 1) do begin currTabSheet := pcOptions.Pages[i]; for j:=0 to (currTabSheet.Controlcount - 1) do begin if (currTabSheet.Controls[j] is TfmeOptions_Base) then begin TfmeOptions_Base(currTabSheet.Controls[j]).Align := alClient; TfmeOptions_Base(currTabSheet.Controls[j]).Initialize(); TfmeOptions_Base(currTabSheet.Controls[j]).ReadSettings(config); end; end; end; // Center "assocate with .vol files" checkbox ckAssociateFiles.Caption := SDUParamSubstitute( _('Associate %1 with ".vol" &files'), [Application.Title] ); SDUCenterControl(ckAssociateFiles, ccHorizontal); // Reposition the "Settings location" controls, bearing in mind the label // can change width depending on the language used and whether it's in bold // or not // Setup for worst case scenario - the label is in bold (widest) lblSettingsLocation.font.style := [fsBold]; // Determine full width of label, combobox and warning image maxWidth := ( cbSettingsLocation.width + CONTROL_MARGIN + lblSettingsLocation.width + CONTROL_MARGIN + imgNoSaveWarning.width ); lblSettingsLocation.left := (self.width - maxWidth) div 2; cbSettingsLocation.left := ( lblSettingsLocation.left+ lblSettingsLocation.width+ CONTROL_MARGIN ); imgNoSaveWarning.left := ( cbSettingsLocation.left+ cbSettingsLocation.width+ CONTROL_MARGIN ); // Call enable/disable controls to put the label in bold/clear the bold EnableDisableControls(); end; procedure TfrmOptions.AllTabs_WriteSettings(config: TSettings); var i: integer; j: integer; currTabSheet: TTabSheet; begin // For each tab, scan it's controls; if it's one of our frames, get it to // process... for i:=0 to (pcOptions.PageCount - 1) do begin currTabSheet := pcOptions.Pages[i]; for j:=0 to (currTabSheet.Controlcount - 1) do begin if (currTabSheet.Controls[j] is TfmeOptions_Base) then begin TfmeOptions_Base(currTabSheet.Controls[j]).WriteSettings(config); end; end; end; end; procedure TfrmOptions.FormShow(Sender: TObject); begin // Special handling... fmeOptions_PKCS11.OTFEFreeOTFE := OTFEFreeOTFEBase; AllTabs_InitAndReadSettings(Settings); // Push the PKCS#11 tab to the far end; the "General" tab should be the // leftmost one tsPKCS11.PageIndex := (pcOptions.PageCount - 1); FOrigAssociateFiles := SDUFileExtnIsRegCmd( VOL_FILE_EXTN, SHELL_VERB, ExtractFilename(ParamStr(0)) ); ckAssociateFiles.checked := FOrigAssociateFiles; EnableDisableControls(); end; procedure TfrmOptions.EnableDisableControls(); var i: integer; j: integer; currTabSheet: TTabSheet; begin // For each tab, scan it's controls; if it's one of our frames, get it to // process... for i:=0 to (pcOptions.PageCount - 1) do begin currTabSheet := pcOptions.Pages[i]; for j:=0 to (currTabSheet.Controlcount - 1) do begin if (currTabSheet.Controls[j] is TfmeOptions_Base) then begin TfmeOptions_Base(currTabSheet.Controls[j]).EnableDisableControls(); end; end; end; if (GetSettingsLocation() = slNone) then begin imgNoSaveWarning.visible := TRUE; lblSettingsLocation.font.style := [fsBold]; end else begin imgNoSaveWarning.visible := FALSE; lblSettingsLocation.font.style := []; end; // Adjust "Save settings to:" label lblSettingsLocation.Left := ( cbSettingsLocation.left - lblSettingsLocation.Width - CONTROL_MARGIN ); end; procedure TfrmOptions.pbCancelClick(Sender: TObject); begin // Reset langugage used, in case it was changed by the user SDUSetLanguage(Settings.OptLanguageCode); ModalResult := mrCancel; end; procedure TfrmOptions.ControlChanged(Sender: TObject); begin EnableDisableControls(); end; END.
unit Main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ImgList, Menus, ToolWin, ComCtrls, StdCtrls, ExtCtrls; type TBuilderForm = class(TForm) MainMenu: TMainMenu; MenuImages: TImageList; miFile: TMenuItem; miCreateFont: TMenuItem; miSaveAs: TMenuItem; sep1: TMenuItem; miExit: TMenuItem; Tools: TToolBar; tbCreateFont: TToolButton; tbSaveAs: TToolButton; tbSep1: TToolButton; FontPanel: TScrollBox; FontImage: TImage; miFont: TMenuItem; miBorders: TMenuItem; miAbout: TMenuItem; labFontPreview: TLabel; FontDialog: TFontDialog; Status: TStatusBar; tbSep2: TToolButton; SaveDialog: TSaveDialog; miManual: TMenuItem; sep2: TMenuItem; tbManual: TToolButton; tbSep3: TToolButton; procedure miAboutClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure miCreateFontClick(Sender: TObject); procedure miExitClick(Sender: TObject); procedure miSaveAsClick(Sender: TObject); procedure miManualClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure SetMenuState(st : Boolean); end; type TCharRect = packed record X, Y : Word; Width : Word; end; var BuilderForm: TBuilderForm; CharsInfo : array [0..255] of TCharRect; FontSize : Longword = 0; FontBitmap : TBitmap; implementation uses Manual, About, Zlib; {$R *.dfm} procedure CreateFont(Font : TFont); var i, j : Integer; CharRect : TRect; CurrentWidth, MaxWidth : Integer; CurrentHeight : Integer; CharHeight, CharWidth : Integer; begin BuilderForm.Status.Panels[0].Text := 'Создание шрифта...'; Application.ProcessMessages; FontBitmap.Width := 0; FontBitmap.Height := 0; FontBitmap.PixelFormat := pf24bit; FontBitmap.Canvas.Font := Font; FontBitmap.Canvas.Brush.Style := bsSolid; FontBitmap.Canvas.Brush.Color := clBlack; MaxWidth := 0; CurrentHeight := 0; CharHeight := FontBitmap.Canvas.TextHeight('A'); FontSize := CharHeight; for i := 0 to 255 do begin if (i mod 20) = 0 then begin CurrentHeight := FontBitmap.Height; FontBitmap.Height := CurrentHeight + CharHeight; CurrentWidth := 0; end; CharWidth := FontBitmap.Canvas.TextWidth(Chr(i)); if CurrentWidth + CharWidth > MaxWidth then begin FontBitmap.Width := CurrentWidth + CharWidth; MaxWidth := CurrentWidth + CharWidth; end; SetRect(CharRect, CurrentWidth, CurrentHeight, CurrentWidth + CharWidth, CurrentHeight + CharHeight); CharsInfo[i].X := CurrentWidth; CharsInfo[i].Y := CurrentHeight; CharsInfo[i].Width := CharWidth; FontBitmap.Canvas.TextRect(CharRect, CurrentWidth, CurrentHeight, Chr(i)); CurrentWidth := CurrentWidth + CharWidth; end; if BuilderForm.miBorders.Checked then begin FontBitmap.Monochrome := True; FontBitmap.PixelFormat := pf24bit; for j := 0 to FontBitmap.Height - 1 do for i := 0 to FontBitmap.Width - 1 do if FontBitmap.Canvas.Pixels[i, j] = clWhite then FontBitmap.Canvas.Pixels[i, j] := clBlack else FontBitmap.Canvas.Pixels[i, j] := Font.Color; end; BuilderForm.Status.Panels[0].Text := 'Шрифт создан.'; end; procedure TBuilderForm.miAboutClick(Sender: TObject); begin AboutForm.ShowModal; end; procedure TBuilderForm.FormCreate(Sender: TObject); begin FontBitmap := TBitmap.Create; end; procedure TBuilderForm.FormDestroy(Sender: TObject); begin FontBitmap.Free; end; procedure TBuilderForm.miCreateFontClick(Sender: TObject); begin if FontDialog.Execute then begin SetMenuState(False); CreateFont(FontDialog.Font); FontImage.Picture.Bitmap := FontBitmap; SetMenuState(True); end; end; procedure TBuilderForm.miExitClick(Sender: TObject); begin Close; end; procedure TBuilderForm.SetMenuState(st: Boolean); begin miCreateFont.Enabled := st; miSaveAs.Enabled := st; miBorders.Enabled := st; tbCreateFont.Enabled := st; tbSaveAs.Enabled := st; end; procedure TBuilderForm.miSaveAsClick(Sender: TObject); var dst : TFileStream; zcs : TCompressionStream; wrkC, wrk : Cardinal; r, g, b : Byte; wrkW : Word; i, j : Integer; begin SaveDialog.FileName := FontDialog.Font.Name + ',' + IntToStr(FontSize); if SaveDialog.Execute then begin SetMenuState(False); Status.Panels[0].Text := 'Сохранение ' + SaveDialog.FileName; Application.ProcessMessages; try dst := TFileStream.Create(SaveDialog.FileName, fmCreate); except Application.MessageBox(PChar('Невозможно создать файл!'), PChar('Ошибка'), MB_ICONSTOP); Status.Panels[0].Text := 'Ошибка сохранения.'; SetMenuState(True); Exit; end; try wrkC := $5F464645; dst.Write(wrkC, 4); wrkC := FontBitmap.Width; dst.Write(wrkC, 4); wrkC := FontBitmap.Height; dst.Write(wrkC, 4); wrkC := FontBitmap.Width * FontBitmap.Height * 2; dst.Write(wrkC, 4); wrkC := FontSize; dst.Write(wrkC, 4); for i := 0 to 255 do begin wrkW := CharsInfo[i].X; dst.Write(wrkW, 2); wrkW := CharsInfo[i].Y; dst.Write(wrkW, 2); wrkW := CharsInfo[i].Width; dst.Write(wrkW, 2); end; wrkC := $61746164; dst.Write(wrkC, 4); zcs := TCompressionStream.Create(clMax, dst); for j := 0 to FontBitmap.Height - 1 do for i := 0 to FontBitmap.Width- 1 do begin wrk := FontBitmap.Canvas.Pixels[i, j]; r := GetRValue(wrk); g := GetGValue(wrk); b := GetBValue(wrk); wrkW := (Round(b / 255 * $1F) or (Round(g / 255 * $3F) shl 5) or (Round(r / 255 * $1F) shl 11)); zcs.WriteBuffer(wrkW, 2); end; except Application.MessageBox(PChar('Невозможно сохранить файл!'), PChar('Ошибка'), MB_ICONSTOP); Status.Panels[0].Text := 'Ошибка сохранения.'; if Assigned(zcs) then zcs.Free; dst.Free; SetMenuState(True); Exit; end; zcs.Free; dst.Free; Status.Panels[0].Text := 'Файл сохранен.'; SetMenuState(True); end; end; procedure TBuilderForm.miManualClick(Sender: TObject); begin ManualForm.Show; end; end.
unit uCaixaView; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uFormView, Vcl.ExtCtrls, Vcl.ComCtrls, uFuncao, uData, Vcl.StdCtrls, System.Actions, Vcl.ActnList, Vcl.DBCtrls, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Imaging.pngimage, Vcl.Grids, Vcl.DBGrids, StrUtils; type TCaixaView = class(TFormView) pgcCaixa: TPageControl; tabCaixa: TTabSheet; tabMovimento: TTabSheet; pnlCaixa: TPanel; aclCaixa: TActionList; actAbrir: TAction; actCancelar: TAction; pnlSenha: TPanel; imgSenha: TImage; lblCaixa: TLabel; edtSenha: TEdit; btnAbrir: TButton; btnCancelar: TButton; actReceber: TAction; actMovimentar: TAction; actAtualizar: TAction; actPesquisar: TAction; actFechar: TAction; grdOs: TDBGrid; actConsultar: TAction; pnlPendentes: TPanel; qryOs: TFDQuery; dtsOs: TDataSource; actImprimir: TAction; pnlAcoes: TPanel; pnlReceber: TPanel; imgReceber: TImage; pnlMovimentar: TPanel; imgMovimentar: TImage; pnlFechar: TPanel; imgFechar: TImage; pnlAtualizar: TPanel; imgAtualizar: TImage; pnlConsultar: TPanel; imgConsultar: TImage; pnlPesquisar: TPanel; imgPesquisar: TImage; pnlImprimir: TPanel; imgImprimir: TImage; pnlCaixa0: TPanel; pnlCaixa1: TPanel; qryCaixa: TFDQuery; dtsCaixa: TDataSource; txtidcaixa: TDBText; txtdtcaixa: TDBText; lblidcaixa: TLabel; Label1: TLabel; txtlogin: TDBText; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; lblstatus: TLabel; Label8: TLabel; txtstatus: TDBText; qryAux: TFDQuery; pnlMovimentoInferior: TPanel; pnlSalvar: TPanel; imgSalvar: TImage; pnlVoltar: TPanel; imgVoltar: TImage; actVoltar: TAction; actSalvar: TAction; imgPendentes: TImage; pnlOsConsulta: TPanel; txtnome: TDBText; lblNome: TLabel; lblfone: TLabel; txtfone: TDBText; lblTotal: TLabel; txttotal: TDBText; lbldtservico: TLabel; txtdtservico: TDBText; Label6: TLabel; txtmoeda: TDBText; pnlOS: TPanel; pnlConsultaOS: TPanel; pnlSuperior: TPanel; edtOs: TEdit; imgOS: TImage; Label7: TLabel; Label9: TLabel; Label10: TLabel; Label11: TLabel; Label12: TLabel; txtdesconto: TDBText; txtacrescimo: TDBText; txtvalor: TDBText; Label13: TLabel; Label14: TLabel; Label15: TLabel; Label16: TLabel; Label17: TLabel; Label18: TLabel; Label19: TLabel; txtdescricao: TDBText; txtcomplemento: TDBText; txtserie: TDBText; lblserie: TLabel; Label21: TLabel; txtmodelo: TDBText; lblmodelo: TLabel; Label22: TLabel; txtversao: TDBText; lblversao: TLabel; Label23: TLabel; imgCaixa: TImage; txtdtcadast: TDBText; Label20: TLabel; lbldtcadast: TLabel; lblidservico: TLabel; Label26: TLabel; txtidservico: TDBText; pnlAutenticar: TPanel; imgAutenticar: TImage; actAutenticar: TAction; qryOsidservico: TIntegerField; qryOsdtservico: TDateField; qryOsidstatus: TIntegerField; qryOsstatus: TWideStringField; qryOsidcliente: TIntegerField; qryOsnome: TWideStringField; qryOsfone: TWideStringField; qryOsidmoeda: TIntegerField; qryOsmoeda: TWideStringField; qryOsdescricao: TWideStringField; qryOscomplemento: TWideStringField; qryOsserie: TWideStringField; qryOsmodelo: TWideStringField; qryOsversao: TWideStringField; qryOsvalor: TFMTBCDField; qryOsacrescimo: TFMTBCDField; qryOsacrescimoperc: TFloatField; qryOsdesconto: TFMTBCDField; qryOsdescontoperc: TFloatField; qryOstotal: TFMTBCDField; qryOsuscadast: TWideStringField; qryOsdtcadast: TSQLTimeStampField; qryOsusmodifi: TWideStringField; qryOsdtmodifi: TSQLTimeStampField; qryOsguidservico: TWideStringField; pnlMovimentoSuperior: TPanel; pnlMovimentoValor: TPanel; Label24: TLabel; lblMovimento: TLabel; edtReferencia: TEdit; cbbMovimento: TComboBox; Label25: TLabel; edtDescricao: TEdit; lblValor: TLabel; edtValor: TEdit; mmoDescricao: TMemo; lblObs: TLabel; procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure actAbrirExecute(Sender: TObject); procedure actCancelarExecute(Sender: TObject); procedure FormShow(Sender: TObject); procedure edtOsKeyPress(Sender: TObject; var Key: Char); procedure actReceberExecute(Sender: TObject); procedure actMovimentarExecute(Sender: TObject); procedure actAtualizarExecute(Sender: TObject); procedure actPesquisarExecute(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); override; procedure actConsultarExecute(Sender: TObject); procedure actFecharExecute(Sender: TObject); procedure actImprimirExecute(Sender: TObject); procedure actSalvarExecute(Sender: TObject); procedure actVoltarExecute(Sender: TObject); procedure actAutenticarExecute(Sender: TObject); procedure dtsOsDataChange(Sender: TObject; Field: TField); procedure edtValorKeyPress(Sender: TObject; var Key: Char); private FCaixa: Integer; FOs: Integer; procedure setCaixa(const Value: Integer); procedure setOs(const Value: Integer); { Private declarations } public { Public declarations } procedure CarregarCaixa; property Caixa: Integer read FCaixa write setCaixa; property Os: Integer read FOs write setOs; end; var CaixaView: TCaixaView; implementation {$R *.dfm} uses uPesquisaView, uMainView; procedure TCaixaView.FormCreate(Sender: TObject); begin inherited; pgcCaixa.ActivePage := tabMovimento; tabCaixa.TabVisible := False; tabMovimento.TabVisible := False; pgcCaixa.ActivePage := tabCaixa; MainView.imlLogin.GetBitmap(5, imgSenha.Picture.Bitmap); Caixa := GetCaixa(MainView.Usuario.getIdusuario); imgReceber.Picture.Bitmap := nil; MainView.imlCaixa.GetBitmap(5, imgReceber.Picture.Bitmap); imgReceber.Hint := actReceber.Hint; imgReceber.OnClick := actReceberExecute; pnlReceber.Hint := actReceber.Hint; pnlReceber.Caption := actReceber.Caption; pnlReceber.OnClick := actReceberExecute; imgMovimentar.Picture.Bitmap := nil; MainView.imlCaixa.GetBitmap(4, imgMovimentar.Picture.Bitmap); imgMovimentar.Hint := actMovimentar.Hint; imgMovimentar.OnClick := actMovimentarExecute; pnlMovimentar.Hint := actMovimentar.Hint; pnlMovimentar.Caption := actMovimentar.Caption; pnlMovimentar.OnClick := actMovimentarExecute; imgFechar.Picture.Bitmap := nil; MainView.imlCaixa.GetBitmap(0, imgFechar.Picture.Bitmap); imgFechar.Hint := actFechar.Hint; imgFechar.OnClick := actFecharExecute; pnlFechar.Hint := actFechar.Hint; pnlFechar.Caption := actFechar.Caption; pnlFechar.OnClick := actFecharExecute; imgAtualizar.Picture.Bitmap := nil; MainView.imlCaixa.GetBitmap(6, imgAtualizar.Picture.Bitmap); imgAtualizar.Hint := actAtualizar.Hint; imgAtualizar.OnClick := actAtualizarExecute; pnlAtualizar.Hint := actAtualizar.Hint; pnlAtualizar.Caption := actAtualizar.Caption; pnlAtualizar.OnClick := actAtualizarExecute; imgConsultar.Picture.Bitmap := nil; MainView.imlCaixa.GetBitmap(7, imgConsultar.Picture.Bitmap); imgConsultar.Hint := actConsultar.Hint; imgConsultar.OnClick := actConsultarExecute; pnlConsultar.Hint := actConsultar.Hint; pnlConsultar.Caption := actConsultar.Caption; pnlConsultar.OnClick := actConsultarExecute; imgImprimir.Picture.Bitmap := nil; MainView.imlCaixa.GetBitmap(3, imgImprimir.Picture.Bitmap); imgImprimir.Hint := actImprimir.Hint; imgImprimir.OnClick := actImprimirExecute; pnlImprimir.Hint := actImprimir.Hint; pnlImprimir.Caption := actImprimir.Caption; pnlImprimir.OnClick := actImprimirExecute; imgPesquisar.Picture.Bitmap := nil; MainView.imlCaixa.GetBitmap(8, imgPesquisar.Picture.Bitmap); imgPesquisar.Hint := actPesquisar.Hint; imgPesquisar.OnClick := actPesquisarExecute; pnlPesquisar.Hint := actPesquisar.Hint; pnlPesquisar.Caption := actPesquisar.Caption; pnlPesquisar.OnClick := actPesquisarExecute; imgSalvar.Picture.Bitmap := nil; MainView.imlCaixa.GetBitmap(9, imgSalvar.Picture.Bitmap); imgSalvar.Hint := actSalvar.Hint; imgSalvar.OnClick := actSalvarExecute; pnlSalvar.Hint := actSalvar.Hint; pnlSalvar.Caption := actSalvar.Caption; pnlSalvar.OnClick := actSalvarExecute; imgVoltar.Picture.Bitmap := nil; MainView.imlCaixa.GetBitmap(10, imgVoltar.Picture.Bitmap); imgVoltar.Hint := actVoltar.Hint; imgVoltar.OnClick := actVoltarExecute; pnlVoltar.Hint := actVoltar.Hint; pnlVoltar.Caption := actVoltar.Caption; pnlVoltar.OnClick := actVoltarExecute; imgAutenticar.Picture.Bitmap := nil; MainView.imlCaixa.GetBitmap(2, imgAutenticar.Picture.Bitmap); imgAutenticar.Hint := actAutenticar.Hint; imgAutenticar.OnClick := actAutenticarExecute; pnlAutenticar.Hint := actAutenticar.Hint; pnlAutenticar.Caption := actAutenticar.Caption; pnlAutenticar.OnClick := actAutenticarExecute; end; procedure TCaixaView.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then begin if edtOs.Focused then actConsultarExecute(Sender) else if not (mmoDescricao.Focused) then Perform(WM_NEXTDLGCTL, 0, 0); end else if (Key = VK_ESCAPE) and (pgcCaixa.ActivePage = tabCaixa) then actCancelarExecute(Sender) else if (Key = VK_ESCAPE) and (pgcCaixa.ActivePage = tabMovimento) then actVoltarExecute(Sender) else inherited; end; procedure TCaixaView.FormShow(Sender: TObject); begin inherited; actAtualizarExecute(Sender); end; procedure TCaixaView.FormActivate(Sender: TObject); var Tamanho: Integer; begin inherited; CarregarCaixa; if Caixa > 0 then pgcCaixa.ActivePage := tabCaixa else begin if edtSenha.CanFocus then edtSenha.SetFocus; end; Tamanho := Trunc((Screen.Width - 30) / 8); pnlReceber.Width := Tamanho; pnlMovimentar.Width := Tamanho; pnlFechar.Width := Tamanho; pnlAtualizar.Width := Tamanho; pnlConsultar.Width := Tamanho; pnlImprimir.Width := Tamanho; pnlPesquisar.Width := Tamanho; pnlAutenticar.Width := Tamanho; end; procedure TCaixaView.actAbrirExecute(Sender: TObject); begin inherited; if (Trim(edtSenha.Text) <> EmptyStr) and (MainView.Usuario.getSenha = Trim(edtSenha.Text)) then begin if MainView.Mensagem.Pergunta('Confirma a abertura do caixa?') then begin Caixa := uFuncao.SetCaixa(MainView.Usuario.getIdusuario); FormActivate(Sender); end end else begin Caixa := 0; MainView.Mensagem.Aviso('Senha inválida!', True, edtSenha); end; end; procedure TCaixaView.actCancelarExecute(Sender: TObject); begin inherited; if pgcCaixa.ActivePage = tabCaixa then Close; end; procedure TCaixaView.actReceberExecute(Sender: TObject); begin inherited; booClose := True; pgcCaixa.ActivePage := tabCaixa; if edtOs.CanFocus then edtOs.SetFocus; end; procedure TCaixaView.actMovimentarExecute(Sender: TObject); begin inherited; booClose := False; pgcCaixa.ActivePage := tabMovimento; end; procedure TCaixaView.actFecharExecute(Sender: TObject); var AQuery: TFDQuery; begin inherited; AQuery := TFDQuery.Create(nil); if Caixa > 0 then begin if MainView.Mensagem.Pergunta('Deseja realmente fechar o caixa Nº ' +Caixa.ToString()+ ' ?') then begin AQuery.Connection := qryAux.Connection; AQuery.SQL.Clear; AQuery.SQL.Add('UPDATE '); AQuery.SQL.Add(' CAIXAS '); AQuery.SQL.Add('SET '); AQuery.SQL.Add(' status = :status, '); AQuery.SQL.Add(' usmodifi = :usmodifi, '); AQuery.SQL.Add(' dtmodifi = :dtmodifi '); AQuery.SQL.Add('WHERE '); AQuery.SQL.Add(' idcaixa = :idcaixa '); AQuery.ParamByName('status').AsString := 'FECHADO'; AQuery.ParamByName('usmodifi').AsString := MainView.Usuario.getLogin(); AQuery.ParamByName('dtmodifi').AsDateTime := Now; AQuery.ParamByName('idcaixa').AsInteger := Caixa; AQuery.ExecSQL; Caixa := 0; edtOs.Clear; qryOs.Close; FormActivate(Sender); end; end; FreeAndNil(AQuery); end; procedure TCaixaView.actAtualizarExecute(Sender: TObject); begin inherited; qryOs.Close; qryOs.SQL.Clear; qryOs.SQL.Add('SELECT'); qryOs.SQL.Add(' * '); qryOs.SQL.Add('FROM'); qryOs.SQL.Add(' vw_servicos'); qryOs.SQL.Add('WHERE'); qryOs.SQL.Add(' idstatus = 5'); qryOs.SQL.Add('ORDER BY idservico DESC'); qryOs.Open; if grdOs.CanFocus then grdOs.SetFocus; end; procedure TCaixaView.actConsultarExecute(Sender: TObject); begin inherited; qryOs.Close; if Trim(edtOs.Text) <> '' then begin qryOs.SQL.Clear; qryOs.SQL.Add('SELECT * FROM vw_servicos WHERE idservico =:idservico'); qryOs.ParamByName('idservico').AsInteger := Trim(edtOs.Text).ToInteger(); qryOs.Open; if qryOs.FieldByName('idstatus').AsInteger <> 5 then begin MainView.Mensagem.Aviso('O status '+qryOs.FieldByName('status').AsString+' não é permitido para recebimento em caixa!', False); qryOs.Close; actAtualizarExecute(Sender); end; edtOs.Clear; end else begin actAtualizarExecute(Sender); if edtOs.CanFocus then edtOs.SetFocus; end; end; procedure TCaixaView.actImprimirExecute(Sender: TObject); begin inherited; ShowMessage('actImprimirExecute'); end; procedure TCaixaView.actPesquisarExecute(Sender: TObject); begin inherited; PesquisaView := Pesquisa('Pesquisa de Ordem de Serviços', 'os'); PesquisaView.ShowModal; if Trim(PesquisaView.Retorno) <> '' then begin edtOs.Text := PesquisaView.Retorno; actConsultarExecute(nil); end; end; procedure TCaixaView.actAutenticarExecute(Sender: TObject); var AQuery: TFDQuery; begin inherited; AQuery := TFDQuery.Create(nil); if OS > 0 then begin if MainView.Mensagem.Pergunta('Deseja autenticar a OS Nº ' +OS.ToString()+ ' ?') then begin AQuery.Connection := qryAux.Connection; AQuery.SQL.Clear; AQuery.SQL.Add('INSERT INTO '); AQuery.SQL.Add(' caixasmovimentos ( '); AQuery.SQL.Add(' idcaixa, '); AQuery.SQL.Add(' movimento, '); AQuery.SQL.Add(' referencia, '); AQuery.SQL.Add(' descricao, '); AQuery.SQL.Add(' valor, '); AQuery.SQL.Add(' idservico, '); AQuery.SQL.Add(' uscadast, '); AQuery.SQL.Add(' dtcadast, '); AQuery.SQL.Add(' guidcaixa) '); AQuery.SQL.Add(' VALUES( '); AQuery.SQL.Add(' :idcaixa, '); AQuery.SQL.Add(' :movimento, '); AQuery.SQL.Add(' :referencia, '); AQuery.SQL.Add(' :descricao, '); AQuery.SQL.Add(' :valor, '); AQuery.SQL.Add(' :idservico, '); AQuery.SQL.Add(' :uscadast, '); AQuery.SQL.Add(' :dtcadast, '); AQuery.SQL.Add(' :guidcaixa) '); AQuery.ParamByName('idcaixa').AsInteger := qryCaixa.FieldByName('idcaixa').AsInteger; AQuery.ParamByName('movimento').AsString := 'E'; AQuery.ParamByName('referencia').AsString := OS.ToString+''+FormatDateTime('ddmmyyyy', Now)+''; AQuery.ParamByName('descricao').AsString := 'RECEBIMENTO DA OS Nº '+OS.ToString() +' NO CAIXA Nº '+Caixa.ToString(); AQuery.ParamByName('valor').AsFloat := qryOs.FieldByName('total').AsFloat; AQuery.ParamByName('idservico').AsInteger := qryOs.FieldByName('idservico').AsInteger; AQuery.ParamByName('uscadast').AsString := MainView.Usuario.getLogin(); AQuery.ParamByName('dtcadast').AsDateTime := Now; AQuery.ParamByName('guidcaixa').AsString := qryCaixa.FieldByName('guidcaixa').AsString; AQuery.ExecSQL; AQuery.SQL.Clear; AQuery.SQL.Add('UPDATE '); AQuery.SQL.Add(' servicos '); AQuery.SQL.Add('SET '); AQuery.SQL.Add(' idstatus = :idstatus, '); AQuery.SQL.Add(' usmodifi = :usmodifi, '); AQuery.SQL.Add(' dtmodifi = :dtmodifi '); AQuery.SQL.Add('WHERE '); AQuery.SQL.Add(' idservico = :idservico '); AQuery.ParamByName('idstatus').AsInteger := 6; AQuery.ParamByName('usmodifi').AsString := MainView.Usuario.getLogin(); AQuery.ParamByName('dtmodifi').AsDateTime := Now; AQuery.ParamByName('idservico').AsInteger := OS; AQuery.ExecSQL; OS := 0; edtOs.Clear; qryOs.Close; MainView.Mensagem.Aviso('Atenticação realizada com sucesso!', False); actAtualizarExecute(Sender); end; end; FreeAndNil(AQuery); end; procedure TCaixaView.actSalvarExecute(Sender: TObject); var AQuery: TFDQuery; begin inherited; AQuery := TFDQuery.Create(nil); edtValor.Text := IfThen(Trim(edtValor.Text) = '', '0', Trim(edtValor.Text)); if (Caixa > 0) and (StrToFloat(edtValor.Text) > 0) then begin if MainView.Mensagem.Pergunta('Salvar movimento no caixa Nº ' +Caixa.ToString()+ ' ?') then begin AQuery.Connection := qryAux.Connection; AQuery.SQL.Clear; AQuery.SQL.Add('INSERT INTO '); AQuery.SQL.Add(' caixasmovimentos ( '); AQuery.SQL.Add(' idcaixa, '); AQuery.SQL.Add(' movimento, '); AQuery.SQL.Add(' referencia, '); AQuery.SQL.Add(' descricao, '); AQuery.SQL.Add(' valor, '); AQuery.SQL.Add(' obs, '); AQuery.SQL.Add(' uscadast, '); AQuery.SQL.Add(' dtcadast, '); AQuery.SQL.Add(' guidcaixa) '); AQuery.SQL.Add(' VALUES( '); AQuery.SQL.Add(' :idcaixa, '); AQuery.SQL.Add(' :movimento, '); AQuery.SQL.Add(' :referencia, '); AQuery.SQL.Add(' :descricao, '); AQuery.SQL.Add(' :valor, '); AQuery.SQL.Add(' :obs, '); AQuery.SQL.Add(' :uscadast, '); AQuery.SQL.Add(' :dtcadast, '); AQuery.SQL.Add(' :guidcaixa) '); AQuery.ParamByName('idcaixa').AsInteger := qryCaixa.FieldByName('idcaixa').AsInteger; AQuery.ParamByName('movimento').AsString := Copy(cbbMovimento.Text, 1, 1); AQuery.ParamByName('referencia').AsString := edtReferencia.Text; AQuery.ParamByName('descricao').AsString := edtDescricao.Text; AQuery.ParamByName('valor').AsFloat := StrToFloat(edtValor.Text); AQuery.ParamByName('obs').AsString := mmoDescricao.Lines.Text; AQuery.ParamByName('uscadast').AsString := MainView.Usuario.getLogin(); AQuery.ParamByName('dtcadast').AsDateTime := Now; AQuery.ParamByName('guidcaixa').AsString := qryCaixa.FieldByName('guidcaixa').AsString; AQuery.ExecSQL; MainView.Mensagem.Aviso('Movimento salvo com sucesso!', False); actVoltarExecute(Sender); actAtualizarExecute(Sender); end; end; FreeAndNil(AQuery); end; procedure TCaixaView.actVoltarExecute(Sender: TObject); begin inherited; booClose := True; pgcCaixa.ActivePage := tabCaixa; if grdOs.CanFocus then grdOs.SetFocus; end; procedure TCaixaView.CarregarCaixa; begin pgcCaixa.Visible := Caixa > 0; pgcCaixa.Repaint; pnlSenha.Visible := Caixa <= 0; pnlSenha.Top := Trunc((MainView.Height / 2) - (pnlSenha.Height / 2)); pnlSenha.Left := Trunc((MainView.Width / 2) - (pnlSenha.Width / 2)); pnlSenha.Repaint; edtSenha.Text := '123'; end; procedure TCaixaView.dtsOsDataChange(Sender: TObject; Field: TField); begin inherited; if Sender <> nil then Os := qryOs.FieldByName('idservico').AsInteger; end; procedure TCaixaView.edtOsKeyPress(Sender: TObject; var Key: Char); begin inherited; ApenasNumeros(Sender, Key); end; procedure TCaixaView.edtValorKeyPress(Sender: TObject; var Key: Char); begin inherited; FormatoNumeros(Sender, Key); end; procedure TCaixaView.setCaixa(const Value: Integer); begin FCaixa := Value; CarregarCaixa; qryCaixa.Close; qryCaixa.SQL.Clear; qryCaixa.SQL.Add('SELECT * FROM vw_caixas WHERE idcaixa=:idcaixa'); qryCaixa.ParamByName('idcaixa').AsInteger := FCaixa; qryCaixa.Open; end; procedure TCaixaView.setOs(const Value: Integer); begin FOs := Value; end; initialization RegisterClass(TCaixaView); end.
unit automat; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Dialogs; type TZustand = 0..1; TAutomat = class altGen: array of TZustand; neueGen: array of TZustand; regel: array[0..7] of TZustand; nummer: byte; constructor Create; procedure regel_setzen(nr: byte); procedure breite_setzen(br: cardinal); function breite_geben: cardinal; procedure startgeneration; procedure neue_gen_berechnen; end; implementation constructor TAutomat.Create; begin self.nummer := 0; Randomize; end; procedure TAutomat.regel_setzen(nr: byte); var i: cardinal; begin self.nummer := nr; for i := 0 to 7 do begin regel[i] := nr mod 2; nr := nr div 2; end; end; procedure TAutomat.breite_setzen(br: cardinal); begin SetLength(self.neueGen, br); SetLength(self.altGen, br); end; function TAutomat.breite_geben: cardinal; begin result:= length(self.altGen); end; procedure TAutomat.startgeneration; var i: cardinal; begin for i := 0 to Length(self.neueGen) - 1 do begin self.neueGen[i] := Random(2); end; end; procedure TAutomat.neue_gen_berechnen; var i, regelpos: cardinal; begin self.altGen := self.neueGen; for i := 0 to Length(self.neueGen) - 1 do begin regelpos := altGen[(i - 1) mod Length(self.neueGen)] * 4 + altgen[i mod Length(self.neueGen)] * 2 + altgen[(i + 1) mod Length(self.neueGen)]; neueGen[i] := self.regel[regelpos]; end; end; end.
unit HS4D.Get; interface uses System.Net.URLClient, System.Net.HttpClient, System.Net.HttpClientComponent, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, Vcl.ExtCtrls, Vcl.Imaging.jpeg, Vcl.Graphics, HS4D.Interfaces; type THSD4Get = class(TInterfacedObject, iHS4DGet) private FParent : iHS4D; FFileName : string; procedure GetImageByUrl(URL: string; APicture: TPicture); public constructor Create(Parent : iHS4D); destructor Destroy; override; class function New (aParent : iHS4D): iHS4DGet; function Get(var aImage : TImage) : iHS4DGet; function FileName(aName : string) : iHS4DGet; end; implementation uses System.Classes; { THSD4Get } constructor THSD4Get.Create(Parent: iHS4D); begin FParent:= Parent; end; destructor THSD4Get.Destroy; begin inherited; end; function THSD4Get.FileName(aName: string): iHS4DGet; begin Result:= Self; FFileName:= aName; end; function THSD4Get.Get(var aImage : TImage) : iHS4DGet; begin result:= self; if pos('http', FFileName) > 0 then begin GetImageByUrl(FFileName, aImage.Picture); end else begin aImage.Picture.LoadFromFile(FFileName); end; end; procedure THSD4Get.GetImageByUrl(URL: string; APicture: TPicture); var Jpeg: TJPEGImage; Strm: TMemoryStream; vIdHTTP : TIdHTTP; begin Jpeg := TJPEGImage.Create; Strm := TMemoryStream.Create; vIdHTTP := TIdHTTP.Create(nil); try vIdHTTP.Get(URL, Strm); if (Strm.Size > 0) then begin Strm.Position := 0; Jpeg.LoadFromStream(Strm); APicture.Assign(Jpeg); end; finally Strm.Free; Jpeg.Free; vIdHTTP.Free; end; end; class function THSD4Get.New(aParent : iHS4D): iHS4DGet; begin result:= Self.Create(aParent); end; end.
unit ConsoleFuncs; interface uses Windows, SysUtils, BWUtil, Token; type TDrawnText = record X: DWORD; Y: DWORD; Text: PChar; Format: DWORD; end; procedure DispText(Args: PChar); procedure DrawText(Args: PChar); procedure DoAbout; var DrawnTextArr: array of TDrawnText; implementation procedure DispText(Args: PChar); begin BWTextOut(#6'~~'#7'~~'#3'~~'#1' Command Worked!'); end; procedure AddDrawnText(dX, dY: DWORD; dText: PChar; dFormat: DWORD); begin SetLength(DrawnTextArr, Length(DrawnTextArr) + 1); with DrawnTextArr[Length(DrawnTextArr) - 1] do begin X := dX; Y := dY; Text := dText; Format := dFormat; end; end; function HexifyText(Text: string): string; var CurChar: Integer; TempInt: Integer; WorkingStr: string; HexNumeric: set of Char; EscapedChars: set of Char; begin HexNumeric := ['0'..'9', 'A'..'F', 'a'..'f']; EscapedChars := ['|','#']; CurChar := 1; WorkingStr := Text; Result := ''; while CurChar <= Length(WorkingStr) do begin if WorkingStr[CurChar] <> '#' then Result := Result + WorkingStr[CurChar] else begin if not (WorkingStr[CurChar + 1] in EscapedChars) then // if its not a character that must be escaped begin TempInt := CurChar + 1; while (WorkingStr[TempInt] in HexNumeric) and (TempInt <= Length(WorkingStr)) do Inc(TempInt); Dec(TempInt); // TempInt will be one past the last hex char otherwise Result := Result + Chr(StrToInt('$' + Copy(WorkingStr, CurChar+1, TempInt - CurChar))); if TempInt < Length(WorkingStr) then CurChar := TempInt else break; if WorkingStr[CurChar + 1] = '|' then Inc(CurChar); end end; Inc(CurChar); end; Result := Result + #0; end; procedure DrawText(Args: PChar); var X, Y: Integer; TextStr: string; Text: PChar; Size: Integer; Format: DWORD; begin // Should be called with: X,Y,Text,[Size] // Hex chars may be used with #X (| to force end of a hex string) // '##' = '#', '#|' = '|' (so we can end hex strings on purpose) if NumToken(Args,',') >= 2 then begin X := StrToInt(GetToken(Args,',',1)); Y := StrToInt(GetToken(Args,',',2)); TextStr := HexifyText(GetToken(Args,',',3)); Text := AllocMem(Length(TextStr) + 1); StrPCopy(Text,TextStr); if NumToken(Args,',') = 2 then AddDrawnText(X, Y, Text, bwtf_Normal) else begin Size := StrToInt(GetToken(Args,',',4)); case Size of 1: Format := bwtf_Mini; 2: Format := bwtf_Normal; 3: Format := bwtf_Large; 4: Format := bwtf_UltraLarge; else Format := bwtf_Normal; end; AddDrawnText(X,Y,Text,Format); end; end; end; procedure DoAbout; begin end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Controller relacionado às tabelas [DAV_CABECALHO e DAV_DETALHE] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (t2ti.com@gmail.com) @version 2.0 ******************************************************************************* } unit DAVController; interface uses Classes, Dialogs, SysUtils, DBClient, DB, Windows, Forms, Controller, Rtti, Atributos, VO, DavCabecalhoVO, Generics.Collections, Biblioteca, DavDetalheAlteracaoVO; type TDAVController = class(TController) private class var FDataSet: TClientDataSet; public class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False); class function ConsultaLista(pFiltro: String): TObjectList<TDavCabecalhoVO>; class function ConsultaObjeto(pFiltro: String): TDavCabecalhoVO; class procedure Insere(pObjeto: TDavCabecalhoVO); class function Altera(pObjeto: TDavCabecalhoVO): Boolean; // Método chamado pelo PAF para gravar as informações do ECF class function AlteraPaf(pObjeto: TDavCabecalhoVO): Boolean; class function Exclui(pId: Integer): Boolean; class function GetDataSet: TClientDataSet; override; class procedure SetDataSet(pDataSet: TClientDataSet); override; class procedure TratarListaRetorno(pListaObjetos: TObjectList<TVO>); end; implementation uses T2TiORM, DavDetalheVO; class procedure TDAVController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean); var Retorno: TObjectList<TDavCabecalhoVO>; begin try Retorno := TT2TiORM.Consultar<TDavCabecalhoVO>(pFiltro, pPagina, pConsultaCompleta); TratarRetorno<TDavCabecalhoVO>(Retorno); finally end; end; class function TDAVController.ConsultaLista(pFiltro: String): TObjectList<TDavCabecalhoVO>; begin try Result := TT2TiORM.Consultar<TDavCabecalhoVO>(pFiltro, '-1', True); finally end; end; class function TDAVController.ConsultaObjeto(pFiltro: String): TDavCabecalhoVO; begin try Result := TT2TiORM.ConsultarUmObjeto<TDavCabecalhoVO>(pFiltro, True); finally end; end; class procedure TDAVController.Insere(pObjeto: TDavCabecalhoVO); var DavDetalheEnumerator: TEnumerator<TDavDetalheVO>; UltimoID: Integer; begin try UltimoID := TT2TiORM.Inserir(pObjeto); pObjeto.Id := UltimoID; pObjeto.NumeroDav := StringOfChar('0',10-Length(UltimoID.ToString)) + UltimoID.ToString; pObjeto.HashRegistro := '0'; pObjeto.HashRegistro := MD5String(pObjeto.ToJSONString); TT2TiORM.Alterar(pObjeto); // Detalhes try DavDetalheEnumerator := pObjeto.ListaDavDetalheVO.GetEnumerator; with DavDetalheEnumerator do begin while MoveNext do begin Current.IdDavCabecalho := pObjeto.Id; Current.NumeroDav := pObjeto.NumeroDav; Current.HashRegistro := '0'; Current.HashRegistro := MD5String(Current.ToJSONString); TT2TiORM.Inserir(Current); end; end; finally FreeAndNil(DavDetalheEnumerator); end; Consulta('ID = ' + IntToStr(UltimoID), '0'); finally end; end; class function TDAVController.Altera(pObjeto: TDavCabecalhoVO): Boolean; var DavDetalheEnumerator: TEnumerator<TDavDetalheVO>; DavDetalheAlteracao: TDavDetalheAlteracaoVO; UltimoIdDetalhe: Integer; begin try pObjeto.HashRegistro := '0'; pObjeto.HashRegistro := MD5String(pObjeto.ToJSONString); Result := TT2TiORM.Alterar(pObjeto); // Detalhes try DavDetalheEnumerator := pObjeto.ListaDavDetalheVO.GetEnumerator; with DavDetalheEnumerator do begin while MoveNext do begin Current.IdDavCabecalho := pObjeto.Id; Current.NumeroDav := pObjeto.NumeroDav; Current.HashRegistro := '0'; Current.HashRegistro := MD5String(Current.ToJSONString); if Current.Id > 0 then begin UltimoIdDetalhe := Current.Id; Result := TT2TiORM.Alterar(Current) end else UltimoIdDetalhe := TT2TiORM.Inserir(Current); try // Alteração - Para Registro D4 do PAF. DavDetalheAlteracao := TDavDetalheAlteracaoVO.Create; if Current.Cancelado = 'S' then DavDetalheAlteracao.TipoAlteracao := 'E' else if Current.Id > 0 then DavDetalheAlteracao.TipoAlteracao := 'A' else DavDetalheAlteracao.TipoAlteracao := 'I'; DavDetalheAlteracao.IdDavDetalhe := UltimoIdDetalhe; DavDetalheAlteracao.DataAlteracao := Date; DavDetalheAlteracao.HoraAlteracao := FormatDateTime('hh:mm:ss', Now); DavDetalheAlteracao.Objeto := Current.ToJsonString; TT2TiORM.Inserir(DavDetalheAlteracao) finally FreeAndNil(DavDetalheAlteracao); end; end; end; finally FreeAndNil(DavDetalheEnumerator); end; finally end; end; class function TDAVController.AlteraPaf(pObjeto: TDavCabecalhoVO): Boolean; var DavDetalheEnumerator: TEnumerator<TDavDetalheVO>; DavDetalheAlteracao: TDavDetalheAlteracaoVO; UltimoIdDetalhe: Integer; begin try pObjeto.HashRegistro := '0'; pObjeto.HashRegistro := MD5String(pObjeto.ToJSONString); Result := TT2TiORM.Alterar(pObjeto); // Detalhes try DavDetalheEnumerator := pObjeto.ListaDavDetalheVO.GetEnumerator; with DavDetalheEnumerator do begin while MoveNext do begin Current.IdDavCabecalho := pObjeto.Id; Current.NumeroDav := pObjeto.NumeroDav; Current.HashRegistro := '0'; Current.HashRegistro := MD5String(Current.ToJSONString); if Current.Id > 0 then begin UltimoIdDetalhe := Current.Id; Result := TT2TiORM.Alterar(Current) end else UltimoIdDetalhe := TT2TiORM.Inserir(Current); end; end; finally FreeAndNil(DavDetalheEnumerator); end; finally end; end; class function TDAVController.Exclui(pId: Integer): Boolean; begin try raise Exception.Create('Não é permitido excluir uma DAV.'); finally end; end; class function TDAVController.GetDataSet: TClientDataSet; begin Result := FDataSet; end; class procedure TDAVController.SetDataSet(pDataSet: TClientDataSet); begin FDataSet := pDataSet; end; class procedure TDAVController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>); begin try TratarRetorno<TDavCabecalhoVO>(TObjectList<TDavCabecalhoVO>(pListaObjetos)); finally FreeAndNil(pListaObjetos); end; end; initialization Classes.RegisterClass(TDAVController); finalization Classes.UnRegisterClass(TDAVController); end.
unit Unit1; { ------------------------------------------------------------------------------ Record/Buffer Exchange Server Demo Indy 10.5.5 It just shows how to send/receive Record/Buffer. No error handling. **** GENERIC RECORD HANDLING ***** Instruction : select correct means corresponding recordtype for client send = server get and server send = client get version march 2012 & April 2012 ------------------------------------------------------------------------------- } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, IdContext, StdCtrls, IdBaseComponent, IdComponent, IdCustomTCPServer, IdTCPServer, IdSync, Unit_Indy_Classes, Unit_Indy_Functions; type TForm1 = class(TForm) IdTCPServer1: TIdTCPServer; CheckBox1: TCheckBox; Memo1: TMemo; Button1: TButton; procedure FormCreate(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure ClientConnected; procedure ClientDisconnected; procedure IdTCPServer1Execute(AContext: TIdContext); procedure RecordReceived; procedure IdTCPServer1Connect(AContext: TIdContext); procedure IdTCPServer1Disconnect(AContext: TIdContext); procedure FormDestroy(Sender: TObject); procedure Button1Click(Sender: TObject); private procedure ShowCannotGetBufferErrorMessage; procedure ShowCannotSendBufferErrorMessage; { Private declarations } public { Public declarations } end; var Form1: TForm1; MyRecord: TMyThreadSafeRecord; MyErrorMessage: string; implementation {$R *.dfm} uses Unit_DelphiCompilerversionDLG; procedure TForm1.Button1Click(Sender: TObject); begin OKRightDlgDelphi.Show; end; procedure TForm1.CheckBox1Click(Sender: TObject); begin IdTCPServer1.Active := CheckBox1.Checked; end; procedure TForm1.ClientConnected; begin Memo1.Lines.Add('A Client connected'); end; procedure TForm1.ClientDisconnected; begin Memo1.Lines.Add('A Client disconnected'); end; procedure TForm1.FormCreate(Sender: TObject); begin IdTCPServer1.Bindings.Add.IP := '127.0.0.1'; IdTCPServer1.Bindings.Add.Port := 6000; MyRecord := TMyThreadSafeRecord.Create; end; procedure TForm1.FormDestroy(Sender: TObject); begin IdTCPServer1.Active := False; MyRecord.Free; end; procedure TForm1.IdTCPServer1Connect(AContext: TIdContext); begin TIdNotify.NotifyMethod(ClientConnected); end; procedure TForm1.IdTCPServer1Disconnect(AContext: TIdContext); begin TIdNotify.NotifyMethod(ClientDisconnected); end; procedure TForm1.IdTCPServer1Execute(AContext: TIdContext); var LBuffer: TBytes; MyLRecord: TMyRecord; aINDYCMD: TGenericRecord<TMyRecord>; LSize: LongInt; begin Memo1.Lines.Add('svr start execute !'); aINDYCMD := TGenericRecord<TMyRecord>.Create; AContext.Connection.IOHandler.ReadTimeout := 9000; if (ReceiveBuffer(AContext, LBuffer) = False) then begin TIdNotify.NotifyMethod(ShowCannotGetBufferErrorMessage); Exit; end else begin end; aINDYCMD.value := aINDYCMD.ByteArrayToMyRecord(LBuffer); // MyRecord.Lock; // MyRecord.value := aINDYCMD.value; TIdNotify.NotifyMethod(RecordReceived); // MyRecord.Unlock; MyLRecord.FileName := 'SERVERSIDE-TXT'; MyLRecord.Details := 'OK'; MyLRecord.FileSize := random(123); MyLRecord.Recordsize := random(10) - 5; MyLRecord.FileDate := now; aINDYCMD.value := MyLRecord; LBuffer := aINDYCMD.MyRecordToByteArray(aINDYCMD.value); if (SendBuffer(AContext, LBuffer) = False) then begin TIdNotify.NotifyMethod(ShowCannotSendBufferErrorMessage); Exit; end; Memo1.Lines.Add('svr end execute !'); end; procedure TForm1.RecordReceived; begin Memo1.Lines.Add('Details ' + MyRecord.value.Details); Memo1.Lines.Add('FileName = ' + MyRecord.value.FileName); Memo1.Lines.Add('FileSize = ' + INtToStr(MyRecord.value.FileSize)); Memo1.Lines.Add('Date = ' + DateToStr(MyRecord.value.FileDate)); Memo1.Lines.Add('Time = ' + TimeToStr(MyRecord.value.FileDate)); Memo1.Lines.Add('RecordSize = ' + INtToStr(MyRecord.value.Recordsize)); end; procedure TForm1.ShowCannotGetBufferErrorMessage; begin Memo1.Lines.Add ('Cannot get record/buffer from client, Unknown error occured'); end; procedure TForm1.ShowCannotSendBufferErrorMessage; begin Memo1.Lines.Add('Cannot send record/buffer to client, Unknown error occured'); end; end.
unit frmCR3SwitcherUnit; //for runtime switching between CR3 targets {$mode delphi} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls, Menus, maps; type { TfrmCR3Switcher } TfrmCR3Switcher = class(TForm) btnSetCR3: TButton; edtNewCR3: TEdit; Label1: TLabel; lbCR3List: TListBox; MenuItem1: TMenuItem; pmCR3List: TPopupMenu; procedure btnSetCR3Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure lbCR3ListDblClick(Sender: TObject); procedure lbCR3ListSelectionChange(Sender: TObject; User: boolean); procedure MenuItem1Click(Sender: TObject); private fOnCR3Change: TNotifyEvent; fCR3: qword; public procedure addCR3ToList(v: qword); property CR3: qword read fCR3 write fCR3; property OnCR3Change: TNotifyEvent read fOnCR3Change write fOnCR3Change; end; implementation { TfrmCR3Switcher } uses CEFuncProc, vmxfunctions; resourcestring rsDBVMCR3Log = 'DBVM CR3 Log'; rsDescribeDBVMRoutine = 'DBVM will record all CR3 values it encounters up to 512 unique ones). How long should it wait? (In seconds)'; rsLongwaitWarning = 'Are you sure you wish to wait %d seconds?'; procedure TfrmCR3Switcher.FormCreate(Sender: TObject); begin loadformposition(self); end; procedure TfrmCR3Switcher.addCR3ToList(v: qword); var i: integer; begin i:=lbCR3List.Items.IndexOf(inttohex(v,8)); if i<>-1 then lbCR3List.Items.Move(i,0) else lbCR3List.Items.Insert(0,inttohex(v,8)); end; procedure TfrmCR3Switcher.btnSetCR3Click(Sender: TObject); var newcr3: qword; begin newcr3:=0; if edtNewCR3.text<>'' then begin try newcr3:=StrToInt64('$'+edtNewCR3.text); except showmessage('invalid value'); exit; end; end; fcr3:=newcr3; fOnCR3Change(self); //add to the list if not there already, and if it is, bring to the top addCR3ToList(newcr3); end; procedure TfrmCR3Switcher.FormDestroy(Sender: TObject); begin SaveFormPosition(self); end; procedure TfrmCR3Switcher.FormShow(Sender: TObject); begin edtNewCR3.ClientWidth:=canvas.TextWidth(' DDDDDDDDDDDDDDDD '); if autosize then begin autosize:=false; clientheight:=edtNewCR3.Height*12; end; end; procedure TfrmCR3Switcher.lbCR3ListDblClick(Sender: TObject); begin if lbCR3List.ItemIndex<>-1 then begin edtNewCR3.Text:=lbCR3List.Items[lbCR3List.ItemIndex]; btnSetCR3.Click; end; end; procedure TfrmCR3Switcher.lbCR3ListSelectionChange(Sender: TObject; User: boolean); begin if lbCR3List.ItemIndex<>-1 then edtNewCR3.Text:=lbCR3List.Items[lbCR3List.ItemIndex]; end; procedure TfrmCR3Switcher.MenuItem1Click(Sender: TObject); var v: string; t: integer; cr3log: array [0..511] of qword; i: integer; begin v:='5'; if InputQuery(rsDBVMCR3Log, rsDescribeDBVMRoutine, v) then begin t:=strtoint(v); if (t<60) or (MessageDlg(Format(rsLongwaitWarning, [t]), mtConfirmation, [mbyes, mbno], 0)=mryes) then begin if dbvm_log_cr3values_start then begin sleep(t*1000); if dbvm_log_cr3values_stop(@cr3log[0]) then begin lbCR3List.Items.BeginUpdate; try lbCR3List.Clear; for i:=0 to 511 do begin if cr3log[i]=0 then break; lbCR3List.Items.Add(inttohex(cr3log[i],8)); end; finally lbCR3List.Items.EndUpdate; end; end; end; end; end; end; initialization {$I frmCR3SwitcherUnit.lrs} end.
(** * $Id: dco.util.ThreadedConsumer.pas 840 2014-05-24 06:04:58Z QXu $ * * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either * express or implied. See the License for the specific language governing rights and limitations under the License. *) unit dco.util.ThreadedConsumer; interface uses System.Classes, dutil.util.container.Queue; type /// <summary>The consumer class keeps to *consume* the elements of a queue in a first-in-first-out manner.</summary> TThreadedConsumer<T> = class(TThread) private type TThreadedMethod = procedure(const Elem: T)of object; private FElems: IQueue<T>; FHandleMethod: TThreadedMethod; protected procedure Execute; override; public constructor Create(const Elems: IQueue<T>; const HandleMethod: TThreadedMethod); destructor Destroy; override; end; implementation uses System.Generics.Defaults; constructor TThreadedConsumer<T>.Create(const Elems: IQueue<T>; const HandleMethod: TThreadedMethod); begin assert(Elems <> nil); assert(Assigned(HandleMethod)); inherited Create({CreateSuspended=}True); NameThreadForDebugging(ClassName, ThreadID); FElems := Elems; FHandleMethod := HandleMethod; end; destructor TThreadedConsumer<T>.Destroy; begin Terminate; FElems.Put(Default(T)); // Put a poison pill WaitFor; FHandleMethod := nil; FElems := nil; inherited; end; procedure TThreadedConsumer<T>.Execute; var Comparer: IEqualityComparer<T>; Elem: T; begin Comparer := TEqualityComparer<T>.Default; Elem := FElems.Take; while not Comparer.Equals(Elem, Default(T)) do begin if not Terminated then try FHandleMethod(Elem); except end; Elem := FElems.Take; end; end; end.
unit PetrolRegion; interface uses Registrator, Classes, BaseObjects, ParentedObjects; type TPetrolRegionType = (prtNGP, prtNGO, prtNGR); TPetrolRegion = class; TPetrolRegions = class; TPetrolRegion = class(TRegisteredIDObject, IParentChild) private FRegionType: TPetrolRegionType; FSubRegions: TPetrolRegions; FMainPetrolRegionID: integer; protected procedure AssignTo(Dest: TPersistent); override; function _AddRef: integer; stdcall; function _Release: Integer; stdcall; function GetChildren: TIDObjects; function GetParent: TIDObject; function GetMe: TIDObject; function GetChildAsParent(const Index: integer): IParentChild; function GetSubRegions: TPetrolRegions; virtual; function GetMainPetrolRegion: TPetrolRegion; virtual; public property MainPetrolRegion: TPetrolRegion read GetMainPetrolRegion; property MainPetrolRegionID: integer read FMainPetrolRegionID write FMainPetrolRegionID; property RegionType: TPetrolRegionType read FRegionType write FRegionType; property SubRegions: TPetrolRegions read GetSubregions; function GetNextWellPassportNumber: integer; constructor Create(ACollection: TIDObjects); override; end; TPetrolRegions = class(TRegisteredIDObjects) private FPlainList: TPetrolRegions; function GetItems(Index: integer): TPetrolRegion; function GetPlaintList: TPetrolRegions; public property PlainList: TPetrolRegions read GetPlaintList; procedure MakeRegionTypedList(ALst: TStrings; ARegionType: TPetrolRegionType; NeedsRegistering: boolean = true; NeedsClearing: boolean = true); property Items[Index: integer]: TPetrolRegion read GetItems; constructor Create; override; end; TNewPetrolRegion = class(TPetrolRegion) private FOldRegionID: Integer; protected procedure AssignTo(Dest: TPersistent); override; function GetSubRegions: TPetrolRegions; override; function GetMainPetrolRegion: TPetrolRegion; override; public property OldRegionID: Integer read FOldRegionID write FOldRegionID; constructor Create(ACollection: TIDObjects); override; end; TNewPetrolRegions = class(TPetrolRegions) private function GetItems(Index: integer): TNewPetrolRegion; public property Items[Index: integer]: TNewPetrolRegion read GetItems; constructor Create; override; end; implementation uses Facade, PetrolRegionDataPoster, SysUtils; { TPetrolRegion } procedure TPetrolRegion.AssignTo(Dest: TPersistent); var o : TPetrolRegion; begin inherited; o := Dest as TPetrolRegion; o.RegionType := RegionType; o.MainPetrolRegionID := MainPetrolRegionID; end; constructor TPetrolRegion.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'ÍÃÏ, ÍÃÎ, ÍÃÐ'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TPetrolRegionDataPoster]; end; function TPetrolRegion.GetChildAsParent( const Index: integer): IParentChild; begin Result := SubRegions.Items[Index]; end; function TPetrolRegion.GetChildren: TIDObjects; begin Result := SubRegions; end; function TPetrolRegion.GetMainPetrolRegion: TPetrolRegion; begin Result := TMainFacade.GetInstance.AllPetrolRegions.ItemsByID[MainPetrolRegionID] as TPetrolRegion; end; function TPetrolRegion.GetMe: TIDObject; begin Result := Self; end; function TPetrolRegion.GetNextWellPassportNumber: integer; var vResult: OleVariant; begin Result := 0; if TMainFacade.GetInstance.DBGates.Server.ExecuteQuery('select max (v.vch_passport_num) from vw_well_coord v where v.petrol_region_id = ' + IntToStr(ID) + ' and v.num_region_type = 3') > 0 then begin vResult := TMainFacade.GetInstance.DBGates.Server.QueryResult; try Result := vResult[0, 0] + 1; except end; end end; function TPetrolRegion.GetParent: TIDObject; begin Result := MainPetrolRegion; end; function TPetrolRegion.GetSubregions: TPetrolRegions; var i: integer; begin if not Assigned(FSubRegions) then begin FSubRegions := TPetrolRegions.Create; FSubRegions.OwnsObjects := true; FSubRegions.Owner := Self; TMainFacade.GetInstance.AllPetrolRegions.OwnsObjects := false; for i := 0 to TMainFacade.GetInstance.AllPetrolRegions.Count - 1 do if TMainFacade.GetInstance.AllPetrolRegions.Items[i].MainPetrolRegionID = ID then begin FSubRegions.Add(TMainFacade.GetInstance.AllPetrolRegions.Items[i], false, false); TMainFacade.GetInstance.AllPetrolRegions.Items[i].ReassignCollection(FSubRegions); end; end; Result := FSubRegions; end; function TPetrolRegion._AddRef: integer; begin Result := -1; end; function TPetrolRegion._Release: Integer; begin Result := -1; end; { TPetrolRegions } constructor TPetrolRegions.Create; begin inherited; FObjectClass := TPetrolRegion; Poster := TMainFacade.GetInstance.DataPosterByClassType[TPetrolRegionDataPoster]; end; function TPetrolRegions.GetItems(Index: integer): TPetrolRegion; begin Result := inherited Items[Index] as TPetrolRegion; end; function TPetrolRegions.GetPlaintList: TPetrolRegions; var i: integer; begin if not Assigned(FPlainList) then begin FPlainList := TPetrolRegions.Create; FPlainList.OwnsObjects := false; FPlainList.AddObjects(Self, false, False); for i := 0 to Count - 1 do FPlainList.AddObjects(Items[i].SubRegions.PlainList, false, false); end; Result := FPlainList; end; procedure TPetrolRegions.MakeRegionTypedList(ALst: TStrings; ARegionType: TPetrolRegionType; NeedsRegistering, NeedsClearing: boolean); var i: integer; begin if NeedsClearing then Clear; for i := 0 to Count - 1 do if Items[i].RegionType = ARegionType then ALst.AddObject(Items[i].List, Items[i]) end; { TNewPetrolRegion } procedure TNewPetrolRegion.AssignTo(Dest: TPersistent); var o : TNewPetrolRegion; begin inherited; o := Dest as TNewPetrolRegion; o.OldRegionID := OldRegionID; end; constructor TNewPetrolRegion.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Íîâûé ÍÃÏ, ÍÃÎ, ÍÃÐ'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TNewPetrolRegionDataPoster]; end; function TNewPetrolRegion.GetMainPetrolRegion: TPetrolRegion; begin Result := TMainFacade.GetInstance.AllNewPetrolRegions.ItemsByID[MainPetrolRegionID] as TNewPetrolRegion; end; function TNewPetrolRegion.GetSubRegions: TPetrolRegions; var i: integer; begin if not Assigned(FSubRegions) then begin FSubRegions := TNewPetrolRegions.Create; FSubRegions.OwnsObjects := true; FSubRegions.Owner := Self; TMainFacade.GetInstance.AllNewPetrolRegions.OwnsObjects := false; for i := 0 to TMainFacade.GetInstance.AllNewPetrolRegions.Count - 1 do if TMainFacade.GetInstance.AllNewPetrolRegions.Items[i].MainPetrolRegionID = ID then begin FSubRegions.Add(TMainFacade.GetInstance.AllNewPetrolRegions.Items[i], false, false); TMainFacade.GetInstance.AllNewPetrolRegions.Items[i].ReassignCollection(FSubRegions); end; end; Result := FSubRegions; end; { TNewPetrolRegions } constructor TNewPetrolRegions.Create; begin inherited; FObjectClass := TNewPetrolRegion; Poster := TMainFacade.GetInstance.DataPosterByClassType[TNewPetrolRegionDataPoster]; end; function TNewPetrolRegions.GetItems(Index: integer): TNewPetrolRegion; begin Result := inherited Items[index] as TNewPetrolRegion; end; end.
unit TextEditor.CompletionProposal.Trigger; interface uses System.Classes; const DEFAULT_INTERVAL = 300; type TTextEditorCompletionProposalTrigger = class(TPersistent) strict private FActive: Boolean; FChars: string; FInterval: Integer; public constructor Create; procedure Assign(ASource: TPersistent); override; published property Active: Boolean read FActive write FActive default False; property Chars: string read FChars write FChars; property Interval: Integer read FInterval write FInterval default DEFAULT_INTERVAL; end; implementation constructor TTextEditorCompletionProposalTrigger.Create; begin inherited; FActive := False; FChars := '.'; FInterval := DEFAULT_INTERVAL; end; procedure TTextEditorCompletionProposalTrigger.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TTextEditorCompletionProposalTrigger) then with ASource as TTextEditorCompletionProposalTrigger do begin Self.FActive := FActive; Self.FChars := FChars; Self.FInterval := FInterval; end else inherited Assign(ASource); end; end.
unit TNT_Scene; // Gestion de la scene // ------------------- // La scene est constituée de modeles (tableau) et d'entitees (liste chainée) // Plusieurs obj peuvent partager le meme modele (d'ou la differenciation) interface uses OpenGL12, TNT_Entity, TNT_Model, TNT_Camera; type TScene = class public Entities: TEntity; Models: array of TModel; constructor Create; procedure LoadFromFile(FileName: String); procedure Render(TimeElapsed: Single); function LoadModel(ModelName: String): Integer; procedure Add(Entity: TEntity); procedure Remove(Entity: TEntity); procedure FlushModels; procedure FlushEntities(EntityType: TEntitySet); destructor Destroy; override; end; implementation uses TNT_3D, TNT_File, TNT_Console; constructor TScene.Create; begin inherited Create; Console.Log('Creating scene...'); glClearColor(0, 0, 0, 0); glClearDepth(1); glBlendFunc(GL_SRC_ALPHA, GL_ONE); glEnable(GL_CULL_FACE); glEnable(GL_TEXTURE_2D); end; procedure TScene.LoadFromFile(FileName: String); var F: TFile; Str: String; c: Char; begin F := TFile.Open(FileName); repeat Str := ''; repeat c := F.ReadChar; Str := Str + c; until c=#10; if Copy(Str,1,3) <> 'end' then with Console do begin Lines[Cursor] := PROMPT + Copy(Str, 1, Length(Str)-2); Execute; end; until Copy(Str,1,3) = 'end'; F.Close; end; procedure TScene.Render(TimeElapsed: Single); var Entity: TEntity; begin TNT.Tris := 0; Entity := Entities; while Entity <> nil do with Entity do begin if not Dead then begin Animate(TimeElapsed); if Visible then Render; end else Destroy; Entity := Next; end; end; function TScene.LoadModel(ModelName: String): Integer; begin Console.Log('Loading model ' + ModelName); Result := Length(Models); SetLength(Models, Result+1); Models[Result] := TModel.Create(ModelName); end; procedure TScene.Add(Entity: TEntity); var Next: PEntity; begin Console.Log('Add entity: ' + Entity.ClassName); Next := @Entities; while (Next^ <> nil) and (Next^.Typ < Entity.Typ) do Next := @Next^.Next; Entity.Next := Next^; Next^ := Entity; end; procedure TScene.Remove(Entity: TEntity); var Next: PEntity; begin Console.Log('Remove entity: ' + Entity.ClassName); Next := @Entities; while (Next^ <> nil) and (Next^ <> Entity) do Next := @Next^.Next; if Next <> nil then Next^ := Entity.Next; end; procedure TScene.FlushModels; var i: Integer; begin Console.Log('Flushing models'); for i := 0 to Length(Models)-1 do Models[i].Free; Models := nil; end; procedure TScene.FlushEntities(EntityType: TEntitySet); var Entity, Temp: TEntity; begin Console.Log('Flushing entities'); Entity := Entities; while Entity <> nil do begin Temp := Entity; Entity := Entity.Next; if Temp.Typ in EntityType then Temp.Free; end; end; destructor TScene.Destroy; begin FlushModels; FlushEntities([TYPE_CAMERA, TYPE_LIGHT, TYPE_SKYBOX, TYPE_LANDSCAPE, TYPE_OBJECT, TYPE_PARTICLES, TYPE_HUD]); inherited Destroy; end; end.
unit CBSKrimskyDisplay; interface uses Windows, Messages, ExtCtrls, StdCtrls, SysUtils, Variants, Classes, Graphics, Controls, CBSKrimsky, CBSKrimskyEntry, DB, DBCtrls, dialogs; const GridBorder = 4; CM_CTDATAChange = WM_APP+400; type TGridOrientation = (goHorizontal, goVertical, goSquare); //TCBSKrimskyDataDisplay individual panel that shows Vertical or Horizontal data in cell TCBSKrimskyDataDisplay = class(TPanel) public constructor Create(AOwner: TComponent);override; destructor Destroy; override; end; //TCBSKrimskyCell- Individual Cell in grid TCustomKrimskyCell = class(TPanel) private FCellData: TKrimskyCellData; VerticalDisplay, HorizontalDisplay: TCBSKrimskyDataDisplay; VerticalLabel, HorizontalLabel: TLabel; FBoxIsSelected: Boolean; FGridType: TCBSGridType; procedure SetCellData(Value: TKrimskyCellData); procedure DisplayClick(Sender: TObject); procedure SetBoxIsSelected(const Value: Boolean); function GetBoxPosition: TBoxPosition; procedure SetBoxPosition(const Value: TBoxPosition); function GetIsEmpty: Boolean; procedure SetGridType(const Value: TCBSGridType); protected procedure Paint; override; public property GridType: TCBSGridType read FGridType write SetGridType; property CellData: TKrimskyCellData read FCellData write SetCellData; property BoxPosition: TBoxPosition read GetBoxPosition write SetBoxPosition; property BoxIsSelected: Boolean read FBoxIsSelected write SetBoxIsSelected; property IsEmpty: Boolean read GetIsEmpty; constructor Create(AOwner: TComponent; ACTData: TCBSCTGridData); destructor Destroy; override; end; TCBSKrimskyCell = class(TCustomKrimskyCell); //TCustomKrimsky - the full single grid with all cells TCustomKrimsky = class(TPanel) private FCurrentCellData: TKrimskyCellData; FGridType: TCBSGridType; FGridSize: Integer; procedure SetCurrentCellData(Value: TKrimskyCellData); procedure SetGridType(const Value: TCBSGridType); procedure SetGridSize(const Value: Integer); procedure SetCTData(const Value: TCBSCTGridData); protected procedure Paint; override; procedure CellsSelect(SendPosition: TBoxPosition); procedure DisplayClick(Sender: TObject); procedure CreateCells(ACTData: TCBSCTGridData); public Cells: array[TBoxPosition] of TCBSKrimskyCell; property CTData: TCBSCTGridData write SetCTData; property CurrentCellData: TKrimskyCellData read FCurrentCellData write SetCurrentCellData; property GridType: TCBSGridType read FGridType write SetGridType; property GridSize: Integer read FGridSize write SetGridSize; procedure CopyToAll(CopyOnlyToBlanks:Boolean=True); procedure ClearAll; constructor Create(AOwner: TComponent; ACTData: TCBSCTGridData); destructor Destroy; override; end; TCBSKrimskyGrid = class(TCustomKrimsky); //TCustomCTGrid - collection of 4 grids TCustomCTGrid = class(TPanel) private FCTData: TCBSCTGridData; FGridOrientation: TGridOrientation; FGridSize: Integer; FMinimumGrid: Integer; function GetDataField: Widestring; function GetDataSource: TDataSource; procedure SetDataField(const Value: Widestring); procedure SetDataSource(const Value: TDataSource); procedure SetGridOrientation(const Value: TGridOrientation); procedure SetGridSize(const Value: Integer); procedure SetMinimumGrid(const Value: Integer); procedure SetColor(const Value: TColor); function GetColor: TColor; procedure SetCTData(const Value: TCBSCTGridData); protected procedure Paint; override; property CTData: TCBSCTGridData read FCTData write SetCTData; procedure Change; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure Loaded; override; public Grids: array[TCBSGridType] of TCBSKrimskyGrid; procedure UpdateData; constructor Create(AOwner: TComponent);override; destructor Destroy; override; property MinimumGrid: Integer read FMinimumGrid write SetMinimumGrid default 160; published property DataField: Widestring read GetDataField write SetDataField; property DataSource: TDataSource read GetDataSource write SetDataSource; property GridOrientation: TGridOrientation read FGridOrientation write SetGridOrientation; property GridSize: Integer read FGridSize write SetGridSize; property Color read GetColor write SetColor; end; TCBSCTGrid = class(TCustomCTGrid) published property Top; property Left; property Height; property Width; property Visible; end; implementation { TCBSKrimsky } procedure TCustomKrimsky.CellsSelect(SendPosition: TBoxPosition); var I: TBoxPosition; begin for I := low(TBoxPosition) to high(TBoxPosition) do begin if I = SendPosition then continue else Cells[I].BoxIsSelected := False; Cells[I].Refresh; end; end; procedure TCustomKrimsky.ClearAll; begin CurrentCellData.ClearData; CopyToAll(False); end; procedure TCustomKrimsky.CopyToAll(CopyOnlyToBlanks:Boolean=True); var I: TBoxPosition; begin for I := low(TBoxPosition) to high(TBoxPosition) do begin if not Cells[I].BoxIsSelected then begin if not CopyOnlyToBlanks or (Cells[I].IsEmpty) then Cells[I].CellData := CurrentCellData; end; end; end; constructor TCustomKrimsky.Create(AOwner: TComponent; ACTData: TCBSCTGridData); begin inherited Create(AOwner as TComponent); FCurrentCellData := TKrimskyCellData.Create(Self, ACTData); if AOwner is TWinControl then Parent := TWinControl(AOwner); if AOwner is TCustomCTGrid then begin with AOwner as TCustomCTGrid do begin Height := 201; Width := 185; Top := 5; Left := 5; end; end else begin Height := 201; Width := 185; Top := 5; Left := 5; end; VerticalAlignment := taAlignTop; CreateCells(ACTData); end; procedure TCustomKrimsky.CreateCells(ACTData: TCBSCTGridData); var I: TBoxPosition; TempData: TKrimskyCellData; begin for I := Low(TBoxPosition) to high(TBoxPosition) do begin Cells[I] := TCBSKrimskyCell.Create(Self, ACTData); Cells[I].Color := Self.Color; Cells[I].Parent := Self; Cells[I].BoxPosition := I; Cells[I].BoxIsSelected := False; Cells[I].GridType := GridType; end; end; destructor TCustomKrimsky.Destroy; begin inherited; end; procedure TCustomKrimsky.DisplayClick(Sender: TObject); begin ShowMessage('In Grid'); end; procedure TCustomKrimsky.Paint; var AWinControl: TWinControl; ACanvas: TCanvas; Third, Header: Integer; I: TBoxPosition; begin inherited; AWinControl := TWinControl(Self); ACanvas := TCanvas.Create; try ACanvas.Handle := GetDC(AWinControl.Handle); try //drawing part //draw divider lines Header := (Self.Font.Size*2); Third := trunc(Self.Width/3); ACanvas.MoveTo(Third, Header ); ACanvas.LineTo(Third, Self.ClientHeight); ACanvas.MoveTo(Third*2,Header); ACanvas.LineTo(Third*2, Self.ClientHeight); Third := trunc((Self.Height-Header)/3); ACanvas.MoveTo(0, Third+Header); ACanvas.LineTo(Self.Width, Third+Header); ACanvas.MoveTo(0, (2*Third)+Header); ACanvas.LineTo(Self.ClientWidth, 2*Third+Header); // size and display cells for I := UL to LR do begin Third := trunc(Self.Width/3); Cells[I].Width := Third-4; case I of UL, CL, LL: Cells[I].Left := 2; UC, CC, LC: Cells[I].Left := Third+2; UR, CR, LR: Cells[I].Left := Third+Third+2; end; Third := trunc((Self.Height-Header)/3); Cells[I].Height := Third-4; case I of UL, UC, UR: Cells[I].Top := Header+2; CL, CC, CR: Cells[I].Top := Third+Header+2; LL, LC, LR: Cells[I].Top := Third+Third+Header+2; end; end; finally ReleaseDC(AWinControl.Handle, ACanvas.Handle); ACanvas.Handle := 0; end; finally ACanvas.Free; end; end; procedure TCustomKrimsky.SetCTData(const Value: TCBSCTGridData); var I: TBoxPosition; begin for I := low(TBoxPosition) to high(TBoxPosition) do Cells[I].CellData.CTData := Value; end; procedure TCustomKrimsky.SetCurrentCellData(Value: TKrimskyCellData); begin FCurrentCellData.UpdateData(Value); end; procedure TCustomKrimsky.SetGridSize(const Value: Integer); begin FGridSize := Value; Self.ClientHeight := FGridSize; Self.ClientWidth := FGridSize; end; procedure TCustomKrimsky.SetGridType(const Value: TCBSGridType); var I: TBoxPosition; begin case Value of CGTsc: Caption := 'SC Dist'; CGTscprime: Caption := 'SC Near'; CGTcc: Caption := 'CC Dist'; CGTccprime: Caption := 'CC Near'; end; if FGridType = Value then exit; FGridType := Value; for I := low(TBoxPosition) to high(TBoxPosition) do Cells[I].GridType := Value; end; { TCustomKrimskyCell } constructor TCustomKrimskyCell.Create(AOwner: TComponent; ACTData: TCBSCTGridData); begin inherited Create(AOwner); if AOwner is TWinControl then Parent := TWinControl(AOwner); FCellData := TKrimskyCellData.Create(Self, ACTData); // randomize; VerticalDisplay := TCBSKrimskyDataDisplay.Create(Self); HorizontalDisplay := TCBSKrimskyDataDisplay.Create(Self); VerticalDisplay.Visible := False; HorizontalDisplay.Visible := False; VerticalLabel := TLabel.Create(Self); HorizontalLabel := TLabel.Create(Self); VerticalLabel.Parent := Self; HorizontalLabel.Parent := Self; VerticalLabel.Alignment := taCenter; HorizontalLabel.Alignment := taCenter; BevelOuter := bvNone; OnClick := DisplayClick; OnDblClick := DisplayClick; HorizontalDisplay.OnClick := DisplayClick; VerticalDisplay.OnClick := DisplayClick; HorizontalLabel.OnClick := DisplayClick; VerticalLabel.OnClick := DisplayClick; HorizontalDisplay.OnDblClick := DisplayClick; VerticalDisplay.OnDblClick := DisplayClick; HorizontalLabel.OnDblClick := DisplayClick; VerticalLabel.OnDblClick := DisplayClick; end; destructor TCustomKrimskyCell.Destroy; begin //FCellData.Free; inherited; end; procedure TCustomKrimskyCell.DisplayClick(Sender: TObject); var EntryForm: TKrimskyDataEntryForm; ExitCode: Integer; begin if not BoxIsSelected then begin BoxIsSelected := True; TCustomKrimsky(Parent).CellsSelect(BoxPosition); if IsEmpty then CellData := TCustomKrimsky(Parent).CurrentCellData; end else begin EntryForm := TKrimskyDataEntryForm.Create(nil); try with Self do begin EntryForm.GridType := GridType; EntryForm.VertDirection := CellData.Vertical.Direction; EntryForm.VertPrism := CellData.Vertical.Prism; EntryForm.HorizDirection := CellData.Horizontal.Direction; EntryForm.HorizPrism := CellData.Horizontal.Prism; ExitCode := EntryForm.ShowModal; if not (ExitCode = mrCancel) then begin CellData.Vertical.Direction := EntryForm.VertDirection; CellData.Vertical.Prism := EntryForm.VertPrism; CellData.Horizontal.Direction := EntryForm.HorizDirection; CellData.Horizontal.Prism := EntryForm.HorizPrism; TCustomKrimsky(Parent).CurrentCellData := CellData; end; if ExitCode = mrYesToAll then begin TCustomKrimsky(Parent).CopyToAll; end; if ExitCode = mrNoToAll then begin TCustomKrimsky(Parent).CopyToAll(False); end; end; finally FreeAndNil(EntryForm); end; end; Refresh; end; function TCustomKrimskyCell.GetBoxPosition: TBoxPosition; begin Result := FCellData.BoxPosition; end; function TCustomKrimskyCell.GetIsEmpty: Boolean; begin Result := ((CellData.Horizontal.KrimskyData = '') and (CellData.Vertical.KrimskyData = '')); end; procedure TCustomKrimskyCell.Paint; begin inherited; if BoxIsSelected then Color := clHighlight else Color := TCustomKrimsky(Parent).Color; HorizontalDisplay.Width := Self.Width -4; HorizontalDisplay.Height := trunc((Self.Height-6)/2); HorizontalDisplay.Left := 2; HorizontalDisplay.Top := 2; VerticalDisplay.Width := HorizontalDisplay.Width; VerticalDisplay.Height := HorizontalDisplay.Height; VerticalDisplay.Left := HorizontalDisplay.Left; VerticalDisplay.Top := HorizontalDisplay.Height+4; VerticalDisplay.Caption := CellData.Vertical.KrimskyData; HorizontalDisplay.Caption := CellData.Horizontal.KrimskyData; HorizontalLabel.Width := Self.Width -4; HorizontalLabel.Height := trunc((Self.Height-6)/2); HorizontalLabel.Left := 2; HorizontalLabel.Top := 2; VerticalLabel.Width := HorizontalLabel.Width; VerticalLabel.Height := HorizontalLabel.Height; VerticalLabel.Left := HorizontalLabel.Left; VerticalLabel.Top := HorizontalLabel.Height+4; VerticalLabel.Caption := CellData.Vertical.KrimskyData; HorizontalLabel.Caption := CellData.Horizontal.KrimskyData; end; procedure TCustomKrimskyCell.SetCellData(Value: TKrimskyCellData); begin FCellData.UpdateData(Value); VerticalDisplay.Caption := FCellData.Vertical.KrimskyData; HorizontalDisplay.Caption := FCellData.Horizontal.KrimskyData; VerticalLabel.Caption := FCellData.Vertical.KrimskyData; HorizontalLabel.Caption := FCellData.Horizontal.KrimskyData; end; procedure TCustomKrimskyCell.SetGridType(const Value: TCBSGridType); begin FGridType := Value; if Assigned(FCellData) then FCellData.GridType := Value; end; procedure TCustomKrimskyCell.SetBoxPosition(const Value: TBoxPosition); begin FCellData.BoxPosition := Value; end; procedure TCustomKrimskyCell.SetBoxIsSelected(const Value: Boolean); begin FBoxIsSelected := Value; end; { TCBSKrimskyDataPoint } constructor TCBSKrimskyDataDisplay.Create(AOwner: TComponent); begin inherited; if AOwner is TWincontrol then Parent := TWincontrol(AOwner); VerticalAlignment := taVerticalCenter; // OnClick := DisplayClick; end; destructor TCBSKrimskyDataDisplay.Destroy; begin inherited; end; { TCustomCTGrid } procedure TCustomCTGrid.Change; begin inherited; end; constructor TCustomCTGrid.Create(AOwner: TComponent); var I: TCBSGridType; begin inherited; MinimumGrid := 160; Top := 5; Left := 5; Visible := False; if AOwner is TWinControl then Parent := TWinControl(AOwner); FCTData := TCBSCTGridData.Create(Self); for I := low(TCBSGridType) to high(TCBSGridType) do begin Grids[I] := TCBSKrimskyGrid.Create(Self, FCTData); Grids[I].Color := Self.Color; Grids[I].Parent := Self; Grids[I].GridType := I; end; GridSize := MinimumGrid; GridOrientation := goHorizontal; VerticalAlignment := taAlignTop; Visible := True; end; destructor TCustomCTGrid.Destroy; begin inherited; end; function TCustomCTGrid.GetColor: TColor; begin Result := inherited Color; end; function TCustomCTGrid.GetDataField: Widestring; begin Result := FCTData.DataField; end; function TCustomCTGrid.GetDataSource: TDataSource; begin Result := FCTData.DataSource; end; procedure TCustomCTGrid.KeyDown(var Key: Word; Shift: TShiftState); begin inherited; end; procedure TCustomCTGrid.KeyPress(var Key: Char); begin inherited; end; procedure TCustomCTGrid.Loaded; begin inherited; end; procedure TCustomCTGrid.Paint; var I: TCBSGridType; X: Integer; begin inherited; case GridOrientation of goHorizontal: begin Height := GridSize + GridBorder + 16; Width := ((GridSize + GridBorder) * 4) + GridBorder; end; goVertical: begin Width := (GridSize + GridBorder *2); Height := ((GridSize + GridBorder) * 4) + GridBorder + 16; end; goSquare: begin Width := ((GridSize + GridBorder) * 2) + GridBorder; Height := ((GridSize + GridBorder) * 2) + GridBorder + 16; end; end; X:=0; for I := low(TCBSGridType) to high(TCBSGridType) do begin if Assigned(Grids[I]) then begin case GridOrientation of goHorizontal: begin Grids[I].Top := 16; Grids[I].Left := GridBorder + (X * (GridSize + GridBorder)); end; goVertical: begin Grids[I].Top := 16 + GridBorder + (X * (GridSize + GridBorder)); Grids[I].Left := GridBorder; end; goSquare: ; end; end; Inc(X); end; end; procedure TCustomCTGrid.SetColor(const Value: TColor); var I: TCBSGridType; begin inherited Color := Value; for I := low(TCBSGridType) to high(TCBSGridType) do Grids[I].Color := Value; end; procedure TCustomCTGrid.SetCTData(const Value: TCBSCTGridData); var I: TCBSGridType; begin if FCTData = Value then exit; FCTData := Value; for I := low(TCBSGridType) to high(TCBSGridType) do Grids[I].CTData := Value; end; procedure TCustomCTGrid.SetDataField(const Value: Widestring); begin FCTData.DataField := Value; end; procedure TCustomCTGrid.SetDataSource(const Value: TDataSource); begin FCTData.DataSource := Value; end; procedure TCustomCTGrid.SetGridOrientation(const Value: TGridOrientation); begin FGridOrientation := Value; end; procedure TCustomCTGrid.SetGridSize(const Value: Integer); var I: TCBSGridType; begin // Make sure that grid doesn't get too small if Value < MinimumGrid then FGridSize := MinimumGrid else FGridSize := Value; for I := low(TCBSGridType) to high(TCBSGridType) do Grids[I].GridSize := FGridSize; Refresh; end; procedure TCustomCTGrid.SetMinimumGrid(const Value: Integer); begin FMinimumGrid := Value; end; procedure TCustomCTGrid.UpdateData; begin FCTData.UpdateData(Self); end; { TDBKrimskyGrid } end.
unit Tidy; interface uses Windows, Classes, Forms, Dialogs, SysUtils, StrUtils, Fonctions; type TTidyWarningError = record Line, Column : integer; Text : string; end; type TTidy = class(TObject) private Dir : string; function BuildCommand : string; public Input, Output : TStringlist; OptionsFile, Options : string; Infos : array of string; Warnings, Errors : array of TTidyWarningError; constructor Create(DirTidy : string); destructor Destroy; override; function Execute : integer; end; const TidyPath = 'Tidy\Tidy.exe'; ErrorsFile = 'Tidy\Tidy_Err.dat'; InputFile = 'Tidy\Tidy_In.dat'; implementation function ExecuteCommand(Cmd : string) : boolean; var StartInfo : TStartupInfo; ProcessInfo : TProcessInformation; Fin : Boolean; begin Result := True; FillChar(StartInfo, SizeOf(StartInfo), #0); StartInfo.cb := SizeOf(StartInfo); StartInfo.dwFlags := STARTF_USESHOWWINDOW; StartInfo.wShowWindow := SW_HIDE; if CreateProcess(nil, PChar(Cmd), nil, nil, False, 0, nil, nil, StartInfo, ProcessInfo) then begin Fin := False; repeat case WaitForSingleObject(ProcessInfo.hProcess, 200) of WAIT_OBJECT_0 : Fin := True; WAIT_TIMEOUT : ; end; Application.ProcessMessages; until Fin; end else Result := false; end; constructor TTidy.Create(DirTidy : string); begin inherited Create; Dir := DirTidy; OptionsFile := ''; Options := ''; Input := TStringList.Create; Output := TStringList.Create; SetLength(Infos, 0); SetLength(Warnings, 0); SetLength(Errors, 0); end; destructor TTidy.Destroy; begin Input.Free; Output.Free; inherited Destroy; end; function TTidy.BuildCommand : string; begin Result := '"' + Dir + TidyPath + '" -f "' + Dir + ErrorsFile + '"'; if FileExists(Dir + OptionsFile) then Result := Result + ' -config "' + Dir + OptionsFile + '"' else Result := Result + ' -' + Options; Result := Result + ' "' + Dir + InputFile + '"'; end; function TTidy.Execute : integer; var ErrorsList : TStringList; i : integer; begin Result := 0; if Input.Text = '' then begin Result := 1; Exit; end; if not (FileExists(Dir + TidyPath)) then begin Result := 2; exit; end; ErrorsList := TStringList.Create; Input.SaveToFile(Dir + InputFile); Input.Clear; ErrorsList.Clear; Output.Clear; if ExecuteCommand(BuildCommand) then begin { Option write-back:yes ou -m > Ecrit dans le fichier d'entrée Ca évite d'avoir à créer un nouveau fichier } if FileExists(Dir + InputFile) then Output.LoadFromFile(Dir + InputFile); DeleteFile(Dir + InputFile); if FileExists(Dir + ErrorsFile) then ErrorsList.LoadFromFile(Dir + ErrorsFile); DeleteFile(Dir + ErrorsFile); SetLength(Infos, 0); for i := 0 to ErrorsList.Count - 1 do begin if ErrorsList[i] = '' then Break; if LeftStr(ErrorsList[i], 5) = 'Info:' then begin SetLength(Infos, length(Infos) + 1); Infos[length(Infos) - 1] := RightStr(ErrorsList[i], length(ErrorsList[i]) - 6); end end; SetLength(Warnings, 0); for i := 0 to ErrorsList.Count - 1 do begin if ErrorsList[i] = '' then Break; if pos('- Warning:', ErrorsList[i]) <> 0 then begin SetLength(Warnings, length(Warnings) + 1); Warnings[length(Warnings) - 1].line := ExtractNumber(ErrorsList[i], pos('line ', ErrorsList[i]) + 5); Warnings[length(Warnings) - 1].column := ExtractNumber(ErrorsList[i], pos('column ', ErrorsList[i]) + 7); Warnings[length(Warnings) - 1].text := RightStr(ErrorsList[i], length(ErrorsList[i]) - pos('Warning: ', ErrorsList[i]) - 8); end end; SetLength(Errors, 0); for i := 0 to ErrorsList.Count - 1 do begin if ErrorsList[i] = '' then Break; if pos('- Error:', ErrorsList[i]) <> 0 then begin SetLength(Errors, length(Errors) + 1); Errors[length(Errors) - 1].line := ExtractNumber(ErrorsList[i], pos('line ', ErrorsList[i]) + 5); Errors[length(Errors) - 1].column := ExtractNumber(ErrorsList[i], pos('column ', ErrorsList[i]) + 7); Errors[length(Errors) - 1].text := RightStr(ErrorsList[i], length(ErrorsList[i]) - pos('Error: ', ErrorsList[i]) - 6); end end; end else Result := 3; ErrorsList.Free; end; end.
unit RulersWnd; {*******************************************************} { } { On screen rulers } { Program main window (rulers) } { } { Copyright (c) 2007, Anton A. Drachev } { anton@drachev.com } { } { Distributed "AS IS" under BSD-like license } { Full text of license can be found in } { "License.txt" file attached } { } {*******************************************************} interface uses Classes, GDIPAPI, GDIPOBJ, AlphaWnd, SysUtils, Windows, Messages, Guide, ShellApi; type TRulersWnd = class(TAlphaWnd) private whitepen: TGPPen; nid: NotifyIconData; blackpen: TGPPen; g: TGuide; protected procedure OnCreate; override; function ProcessMsg(msg: PMess): boolean; override; procedure CreatNew(); public constructor Create(); overload; destructor Destroy(); override; end; implementation uses Globals; const FRAME_THICKNESS = 25; WM_TRAY = WM_USER + $01; function min(a, b: smallint): smallint; begin if a < b then Result:=a else Result:=b; end; const fontsize = 9; { TRulersWnd } constructor TRulersWnd.Create(); var rect: TRect; brsh: TGPSolidBrush; tmp, i, j: integer; p: TPointF; s: string; Font: TGPFont; Graph: TGPGraphics; begin Create(CS_DBLCLKS, WS_POPUP, WS_EX_TOOLWINDOW, 0, 'Rulers Window', 'TRulersWndClass', Parent); GetWindowRect(GetDesktopWindow(), rect); Width:=rect.Right; Height:=rect.Bottom; Left:=0; Top:=0; Font:=TGPFont.Create('Arial', fontsize, FontStyleRegular, UnitPixel); Bitmap:=TGPBitmap.Create(Width, Height, $26200A); // Magic number ;) Graph:=TGPGraphics.Create(Bitmap); Graph.SetTextRenderingHint(TextRenderingHintSystemDefault); brsh:=TGPSolidBrush.Create(MakeColor(255,255,255)); blackpen:=TGPPen.Create(TGPSolidBrush.Create(MakeColor(0,0,0))); whitepen:=TGPPen.Create(TGPSolidBrush.Create(MakeColor(255, 255, 255))); Graph.Clear(0); Graph.FillRectangle(brsh, 0, 0, 15, Height); Graph.FillRectangle(brsh, 0, 0, Width, 15); Graph.DrawLine(blackpen, 15, 16, 15, Height); Graph.DrawLine(blackpen, 16, 15, Width, 15); brsh:=TGPSolidBrush.Create(MakeColor(0, 0, 0)); p.X:=0; for i := 0 to Round(Height / 50) do begin tmp:=i * 50; s:=IntToStr(i * 50); for j := 1 to Length(s) do begin p.Y:=tmp + j * fontsize - 8; Graph.DrawString(s[j], -1, Font, p, brsh); end; Graph.DrawLine(blackpen, 0, tmp, 15, tmp); end; for i := 0 to Round(Height / 5) do begin tmp:=i * 5; if i mod 2 = 1 then p.X:=11 else p.X:=9; Graph.DrawLine(blackpen, p.X, tmp, 15, tmp); end; p.Y:=0; for i := 0 to Round(Width / 50) do begin tmp:=i * 50; p.X:=tmp; Graph.DrawLine(blackpen, tmp, 0, tmp, 15); Graph.DrawString(IntToStr(i * 50), -1, Font, p, brsh); end; for i := 0 to Round(Width / 5) do begin tmp:=i * 5; if i mod 2 = 1 then p.Y:=11 else p.Y:=9; Graph.DrawLine(blackpen, tmp, p.Y, tmp, 15); end; Graph.FillRectangle(TGPSolidBrush.Create(MakeColor(255, 255, 255)), 0, 0, 16, 16); g:=nil; Graph.Free(); Redraw(); Invalidate(); fillchar(nid, Sizeof(nid), 0); nid.cbSize:=Sizeof(nid); nid.Wnd:=Handle; nid.hIcon:=Loadicon(HInstance, 'MAINICON'); nid.uFlags:=NIF_ICON or NIF_TIP or NIF_MESSAGE; nid.szTip:='Rulers'; nid.uCallbackMessage:=WM_TRAY; Shell_NotifyIcon(NIM_ADD, @nid); Bitmap:=nil; end; procedure TRulersWnd.OnCreate; begin inherited; end; procedure TRulersWnd.CreatNew; var p: TPoint; begin GetCursorPos(p); if (p.X < 20) and (p.Y > 18) then begin SetCursor(sizeHCursor); g:=TGuide.Create(true, Height); g.Left:=p.X - 6; end else if (p.Y < 20) and (p.X > 18) then begin SetCursor(sizeVCursor); g:=TGuide.Create(false, Width); g.Top:=p.Y - 6; end else ; end; destructor TRulersWnd.Destroy; begin Shell_NotifyIcon(NIM_DELETE, @nid); end; function TRulersWnd.ProcessMsg(msg: PMess): boolean; begin Result:=True; case msg.Msg of WM_NCHITTEST: msg.Result:=HTCAPTION; WM_ENTERSIZEMOVE: begin CreatNew(); msg.Result:=0; end; WM_EXITSIZEMOVE: begin if g <> nil then PostMessage(g.Handle, WM_EXITSIZEMOVE, 0, 0); g:=nil; msg.Result:=0; end; WM_MOVING: begin if g <> nil then begin if g.Vertical then g.Left:=PRect(msg.LParam).Left + g.Left else g.Top:=PRect(msg.LParam).Top + g.Top; end; PRect(msg.LParam).Top:=Top; PRect(msg.LParam).Bottom:=Top + Height; PRect(msg.LParam).Left:=Left; PRect(msg.LParam).Right:=Left + Width; msg.Result:=0; end; WM_CLOSE, WM_NCMBUTTONUP: begin running:=false; msg.Result:=0; end; WM_NCRBUTTONDOWN: begin if isControl then RemoveAllGuides(); msg.Result:=0; end; WM_SETCURSOR: begin SetCursor(LoadCursor(0, IDC_ARROW)); msg.Result:=0; end; WM_TRAY: begin case msg.LParam of WM_MOUSEMOVE:; WM_LBUTTONDOWN: BringToFrontAll(); WM_MBUTTONUP: begin running:=false; PostMessage(Handle, WM_TRAY, 0, 0) end; WM_RBUTTONDOWN: begin Inc(displayMode); if displayMode > 2 then displayMode:=0; NotifyAll(); end; //else begin // Inc(displayMode); //end; end; msg.Result:=0; end else Result:=false; end; end; end.
unit LUX.GPU.OpenGL.Viewer; 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.Platform.Win, Winapi.Windows, Winapi.OpenGL, Winapi.OpenGLext, LUX, LUX.M4, LUX.GPU.OpenGL, LUX.GPU.OpenGL.FMX, LUX.GPU.OpenGL.Buffer.Unifor, LUX.GPU.OpenGL.Camera; type TGLViewer = class(TFrame) private { private 宣言 } procedure _OnMouseDown( Sender_:TObject; Button_:TMouseButton; Shift_:TShiftState; X_,Y_:Single ); inline; procedure _OnMouseMove( Sender_:TObject; Shift_:TShiftState; X_,Y_:Single ); inline; procedure _OnMouseUp( Sender_:TObject; Button_:TMouseButton; Shift_:TShiftState; X_,Y_:Single ); inline; procedure _OnMouseWheel( Sender_:TObject; Shift_:TShiftState; WheelDelta_:Integer; var Handled_:Boolean ); inline; protected _Form :TCommonCustomForm; _WND :HWND; _DC :HDC; _Viewer :TGLUnifor<TSingleM4>; _Camera :TGLCamera; ///// イベント _OnPaint :TProc; ///// アクセス function GetRootForm :TForm; function GetRootWND :HWND; function GetPixSiz :System.Types.TSize; ///// メソッド procedure DoAbsoluteChanged; override; procedure ParentChanged; override; procedure Paint; override; procedure Resize; override; procedure AncestorVisibleChanged( const Visible_: Boolean ); override; procedure FitWindow; procedure CreateWindow; procedure CreateDC; procedure DestroyDC; public { public 宣言 } constructor Create( AOwner_:TComponent ); override; destructor Destroy; override; ///// プロパティ property Form :TCommonCustomForm read _Form ; property WND :HWND read _WND ; property DC :HDC read _DC ; property PixSiz :System.Types.TSize read GetPixSiz ; property Camera :TGLCamera read _Camera write _Camera; ///// イベント property OnPaint :TProc read _OnPaint write _OnPaint; ///// メソッド procedure Repaint; procedure RecreateDC; procedure BeginGL; procedure EndGL; procedure BeginRender; procedure EndRender; function MakeScreenShot :FMX.Graphics.TBitmap; end; implementation //############################################################### ■ {$R *.fmx} //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private /////////////////////////////////////////////////////////////////////// メソッド procedure TGLViewer._OnMouseDown( Sender_:TObject; Button_:TMouseButton; Shift_:TShiftState; X_,Y_:Single ); begin _Form.MouseCapture; MouseDown( Button_, Shift_, X_, Y_ ); MouseClick( Button_, Shift_, X_, Y_ ); end; procedure TGLViewer._OnMouseMove( Sender_:TObject; Shift_:TShiftState; X_,Y_:Single ); begin MouseMove( Shift_, X_, Y_ ); end; procedure TGLViewer._OnMouseUp( Sender_:TObject; Button_:TMouseButton; Shift_:TShiftState; X_,Y_:Single ); begin MouseUp( Button_, Shift_, X_, Y_ ); _Form.ReleaseCapture; end; procedure TGLViewer._OnMouseWheel( Sender_:TObject; Shift_:TShiftState; WheelDelta_:Integer; var Handled_:Boolean ); begin MouseWheel( Shift_, WheelDelta_, Handled_ ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TGLViewer.GetRootForm :TForm; begin Result := Self.Root.GetObject as TForm; end; function TGLViewer.GetRootWND :HWND; begin Result := WindowHandleToPlatform( GetRootForm.Handle ).Wnd; end; function TGLViewer.GetPixSiz :System.Types.TSize; begin with Result do begin Width := Round( _Form.Width * Scene.GetSceneScale ); Height := Round( _Form.Height * Scene.GetSceneScale ); end; end; /////////////////////////////////////////////////////////////////////// メソッド procedure TGLViewer.DoAbsoluteChanged; begin inherited; FitWindow; end; procedure TGLViewer.ParentChanged; begin inherited; _Form.Visible := Self.ParentedVisible; end; procedure TGLViewer.Paint; begin BeginRender; with GetPixSiz do glViewport( 0, 0, Width, Height ); if Assigned( _Camera ) then _Camera.Render; _OnPaint; EndRender; end; procedure TGLViewer.Resize; begin inherited; if not ( csLoading in Self.ComponentState ) then FitWindow; end; procedure TGLViewer.AncestorVisibleChanged( const Visible_: Boolean ); begin inherited; _Form.Visible := Visible_; end; //------------------------------------------------------------------------------ procedure TGLViewer.CreateWindow; begin _Form := TCommonCustomForm.Create( Self ); with _Form do begin BorderStyle := TFmxFormBorderStyle.None; OnMouseDown := _OnMouseDown ; OnMouseMove := _OnMouseMove ; OnMouseUp := _OnMouseUp ; OnMouseWheel := _OnMouseWheel; HandleNeeded; _WND := WindowHandleToPlatform( Handle ).Wnd; end; SetWindowLong( _WND, GWL_STYLE, WS_CHILD or WS_CLIPSIBLINGS ); Winapi.Windows.SetParent( _WND, GetRootWND ); end; procedure TGLViewer.FitWindow; var R :TRectF; begin R := TRectF.Create( LocalToAbsolute( TPointF.Zero ) * Scene.GetSceneScale, Width, Height ); _Form.Bounds := R.Round; if Height < Width then _Viewer[ 0 ] := TSingleM4.Scale( Height / Width, 1, 1 ) else if Width < Height then _Viewer[ 0 ] := TSingleM4.Scale( 1, Width / Height, 1 ) else _Viewer[ 0 ] := TSingleM4.Identify; end; //------------------------------------------------------------------------------ procedure TGLViewer.CreateDC; begin _DC := GetDC( _WND ); _OpenGL_.ApplyPixelFormat( _DC ); end; procedure TGLViewer.DestroyDC; begin ReleaseDC( _WND, _DC ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TGLViewer.Create( AOwner_:TComponent ); begin inherited; HitTest := False; _OnPaint := procedure begin end; CreateWindow; CreateDC; _Viewer := TGLUnifor<TSingleM4>.Create( GL_DYNAMIC_DRAW ); _Viewer.Count := 1; end; destructor TGLViewer.Destroy; begin _Viewer.DisposeOf; DestroyDC; inherited; end; /////////////////////////////////////////////////////////////////////// メソッド procedure TGLViewer.Repaint; begin Paint; end; //------------------------------------------------------------------------------ procedure TGLViewer.RecreateDC; begin DestroyDC; _Form.RecreateResources; CreateDC; end; //------------------------------------------------------------------------------ procedure TGLViewer.BeginGL; begin _OpenGL_.EndGL; wglMakeCurrent( _DC, _OpenGL_.RC ); end; procedure TGLViewer.EndGL; begin wglMakeCurrent( _DC, 0 ); _OpenGL_.BeginGL; end; //------------------------------------------------------------------------------ procedure TGLViewer.BeginRender; begin BeginGL; glClearColor( 0, 0, 0, 0 ); glClear( GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT ); _Viewer.Use( 0{BinP} ); end; procedure TGLViewer.EndRender; begin _Viewer.Unuse( 0{BinP} ); glFlush; EndGL; SwapBuffers( _DC ); end; //------------------------------------------------------------------------------ function TGLViewer.MakeScreenShot :FMX.Graphics.TBitmap; var Cs :TArray<TAlphaColor>; C, B :PAlphaColor; Bs :TBitmapData; S, Y :Integer; begin Result := FMX.Graphics.TBitmap.Create; with Result do begin SetSize( GetPixSiz ); SetLength( Cs, Height * Width ); C := @Cs[ 0 ]; BeginGL; glReadBuffer( GL_FRONT ); glReadPixels( 0, 0, Width, Height, GL_BGRA, GL_UNSIGNED_BYTE, C ); EndGL; Map( TMapAccess.Write, Bs ); S := SizeOf( TAlphaColor ) * Width; for Y := Height-1 downto 0 do begin B := Bs.GetScanline( Y ); System.Move( C^, B^, S ); Inc( C, Width ); end; Unmap( Bs ); end; end; end. //######################################################################### ■
unit Ssepan.Laz.utility; {$mode objfpc}{$H+} interface uses Classes, SysUtils; implementation procedure x() ; var y:String; begin WriteLn('x'); end; function z():Boolean ; var q:String; begin WriteLn('z'); z:=True; end; //''' <summary> //''' Use for Marquee-style progress bar, or when percentages must be indicated. //''' Picture. //''' </summary> //''' <param name="sStatusMessage"></param> //''' <param name="errorMessage"></param> //''' <param name="objImage"></param> //''' <param name="isMarqueeProgressBarStyle"></param> //''' <param name="fProgressBarValue"></param> //Public Procedure StartProgressBarWithPicture(sStatusMessage : String, sErrorMessage : String, objImage : TImage, isMarqueeProgressBarStyle : Boolean, fProgressBarValue : Float);//,ctlProgressBar : TProgressBar,ctlActionIconTTImage) //var //begin // {$ctlProgressBar.Pulse = isMarqueeProgressBarStyle // 'set to blocks if actual percentage was used. // $ctlProgressBar.Value = fProgressBarValue // 'set to value if percentage used. // 'if Style is not Marquee, then we are marking either a count or percentage // If fProgressBarValue > 1 Then '$ctlProgressBar.Maximum // '$ctlProgressBar.Step = 1 // $ctlProgressBar.Value = 1 // Endif // // $ctlStatusMessage.Text = sStatusMessage // $ctlErrorMessage.Text = sErrorMessage // $ctlErrorMessage.ToolTip = sErrorMessage // // $ctlProgressBar.Visible = True // // $ctlActionIcon.Picture = objImage // $ctlActionIcon.Tooltip = sStatusMessage // $ctlActionIcon.Visible = True // // 'give the app time to draw the eye-candy, even if its only for an instant // Wait //Catch 'ex As Exception // Debug Log.FormatError(Error.Text, Error.Where, Error.BackTrace) // // Error.Propagate 'Throw } // // //End; //Sub end.
unit UAttributes.Rtti; interface uses System.Generics.Collections; type //mover para helper TAttributesInspector<T: class> = class public class function GetAttr<Attr: TCustomAttribute>(): TList<Attr>; end; implementation uses Rtti; { TAttributesInspector } class function TAttributesInspector<T>.GetAttr<Attr>(): TList<Attr>; var rttiContext: TRttiContext; rttiType: TRttiType; attribute: TCustomAttribute; begin rttiContext := TRttiContext.Create(); Result:= TList<Attr>.Create(); try rttiType := rttiContext.GetType(T); for attribute in rttiType.GetAttributes do if attribute is Attr then Result.Add( Attr(attribute) ); finally rttiContext.Free(); end; // try to recover and return the DisplayLabel end; end.
{***********************************************} {* Connect 4 - Classes and Data Structures *} {* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *} {* *} {* Author: Nathan Bartram *} {* Contact: nathan_bartram@hotmail.co.uk *} {* Licence: GPL *} {* *} {***********************************************} unit Game; {$mode objfpc}{$H+} interface uses SysUtils, IniFiles; type TGrid = array[0..8,0..7] of byte; type TTinyPoint = record x: byte; y: byte; end; type TWinDirection = record Start: TTinyPoint; Parts: byte; end; type TMovesHistory = record StartPlayer: boolean; Move: array[1..42] of TTinyPoint; end; type TWinPosition = class private _HorizontalWin: boolean; _VerticalWin: boolean; _LeftDiagonalWin: boolean; _RightDiagonalWin: boolean; function TinyPoint(x,y: byte): TTinyPoint; public Horizontal: TWinDirection; Vertical: TWinDirection; LeftDiagonal: TWinDirection; RightDiagonal: TWinDirection; constructor Create; procedure ClearData; property IsHorizontalWin: boolean read _HorizontalWin write _HorizontalWin; property IsVerticalWin: boolean read _VerticalWin write _VerticalWin; property IsLeftDiagonalWin: boolean read _LeftDiagonalWin write _LeftDiagonalWin; property IsRightDiagonalWin: boolean read _RightDiagonalWin write _RightDiagonalWin; end; type TSettings = class private Config: TMemIniFile; _PlayerStart: byte; // 0 = random, 1 = player1, 2 = player2. _ShowToolBar: boolean; _NewCoinPosition: byte;// 0 = random, 1 = left, 2 = centre, 3 = right. _ShowCoinPreview: boolean; _ShowStatusBar: boolean; _FormLeft: integer; _FormTop: integer; _BotLevel: integer; _IsPlayer1Bot: boolean; _IsPlayer2Bot: boolean; _Player1Name: string; _Player2Name: string; _Skin: string; public constructor Create; destructor Free; procedure Read; procedure Write; property PlayerStart: byte read _PlayerStart write _PlayerStart; property ShowToolBar: boolean read _ShowToolBar write _ShowToolBar; property NewCoinPosition: byte read _NewCoinPosition write _NewCoinPosition; property ShowCoinPreview: boolean read _ShowCoinPreview write _ShowCoinPreview; property ShowStatusBar: boolean read _ShowStatusBar write _ShowStatusBar; property FormLeft: integer read _FormLeft write _FormLeft; property FormTop: integer read _FormTop write _FormTop; property BotLevel: integer read _BotLevel write _BotLevel; property IsPlayer1Bot: boolean read _IsPlayer1Bot write _IsPlayer1Bot; property IsPlayer2Bot: boolean read _IsPlayer2Bot write _IsPlayer2Bot; property Player1Name: string read _Player1Name write _Player1Name; property Player2Name: string read _Player2Name write _Player2Name; property Skin: string read _Skin write _Skin; end; type { TGame } TGame = class private MovesGrid: TGrid; // 0 = no move, 1 = player1, 2 = player2. PlayerGo: boolean; // false = player1, true = player2. NumberOfMoves: byte; // Counts moves made, needed for NewCoin in main unit. MovesHistory: TMovesHistory; function GetPlayerNumber: byte; overload; // Functions used by bot function MinMax(Depth: integer;Player: boolean;CurrentGrid:TGrid): integer; function GetScore(x,y: byte;player:boolean;CurrentGrid:TGrid):integer; function GetDropLocation(x: byte;Grid:TGrid): byte; overload; function IsWin(x,y:byte;player:boolean;CurrentGrid: TGrid): boolean; overload; function GetPlayerNumber(p:boolean): byte; overload; function ChooseBest(ResultList: array of integer): integer; public Settings: TSettings; WinPosition: TWinPosition; constructor Create; destructor Free; function GetNumberOfMoves: byte; procedure IncNumberOfMoves; procedure DecNumberOfMoves; procedure ResetNumberOfMoves; function GetDropLocation(x: byte): byte; overload;// Returns y value of new drop location. procedure SetMove(x, y: byte); // Sets move in MovesGrid. function GetPlayerGo: boolean; procedure SwitchPlayer; function IsWin: boolean; overload; procedure NewGame; function IsGridFull: boolean; procedure UndoMove; procedure RedoMove; procedure GetMoveFromList(const MoveNumber: byte; out x, y :byte); function GetLastMoveX: byte; function GetLastMoveY: byte; procedure SaveGame(const FileName: string); procedure LoadGame(const FileName: string); function IsCurrentPlayerBot: boolean; function IsOtherPlayerBot: boolean; function IsStartPlayerBot: boolean; function GetFirstPlayer: boolean; function GetBotMove: byte; end; implementation //---TGame--------------------------------------------------------------------// constructor TGame.Create; begin Settings:=TSettings.Create; WinPosition:=TWinPosition.Create; end; //----------------------------------------------------------------------------// destructor TGame.Free; begin Settings.Free; WinPosition.Free; end; //----------------------------------------------------------------------------// function TGame.GetNumberOfMoves: byte; begin Result:=NumberOfMoves; end; //----------------------------------------------------------------------------// procedure TGame.IncNumberOfMoves; begin Inc(NumberOfMoves); end; //----------------------------------------------------------------------------// procedure TGame.DecNumberOfMoves; begin Dec(NumberOfMoves); end; //----------------------------------------------------------------------------// procedure TGame.ResetNumberOfMoves; begin NumberOfMoves:=0; end; //----------------------------------------------------------------------------// function TGame.GetDropLocation(x: byte): byte; overload; var i: byte; begin for i:=6 downto 0 do if MovesGrid[x,i]=0 then Break; Result:=i; end; //----------------------------------------------------------------------------// procedure TGame.SetMove(x, y: byte); begin MovesGrid[x,y]:=GetPlayerNumber; MovesHistory.Move[NumberOfMoves]:=WinPosition.TinyPoint(x,y); if NumberOfMoves<>42 then MovesHistory.Move[NumberOfMoves+1]:=WinPosition.TinyPoint(0,0); end; //----------------------------------------------------------------------------// function TGame.GetPlayerGo: boolean; begin Result:=PlayerGo; end; //----------------------------------------------------------------------------// procedure TGame.SwitchPlayer; begin PlayerGo:=not PlayerGo; end; //----------------------------------------------------------------------------// function TGame.IsWin: boolean; overload; var Count, i, j, PlayerNumber, XPos, YPos: byte; Found4InRow: boolean = false; begin WinPosition.ClearData; XPos:=GetLastMoveX; YPos:=GetLastMoveY; PlayerNumber:=GetPlayerNumber; Found4InRow:=false; // Check horizontal. for i := 1 to 4 do begin if MovesGrid[i ,YPos]=PlayerNumber then if MovesGrid[i+1,YPos]=PlayerNumber then if MovesGrid[i+2,YPos]=PlayerNumber then if MovesGrid[i+3,YPos]=PlayerNumber then begin j:=3; while MovesGrid[i+j,YPos]=PlayerNumber do Inc(j); WinPosition.Horizontal.Start:=WinPosition.TinyPoint(i,YPos); WinPosition.Horizontal.Parts:=j; WinPosition.IsHorizontalWin:=true; Found4InRow:=true; Break; end; end; // Check vertical. for i := 1 to 4 do begin if MovesGrid[XPos,i ]=PlayerNumber then if MovesGrid[XPos,i+1]=PlayerNumber then if MovesGrid[XPos,i+2]=PlayerNumber then if MovesGrid[XPos,i+3]=PlayerNumber then begin WinPosition.Vertical.Start:=WinPosition.TinyPoint(XPos,i); WinPosition.Vertical.Parts:=4; WinPosition.IsVerticalWin:=true; Found4InRow:=true; Break; end; end; // Check left diagonal. if (XPos<>0) and (YPos<>0) then Count:=0; repeat Count:=Count+1; XPos:=XPos-1; YPos:=YPos-1; until (XPos=0) or (YPos=0); for i := 1 to 4 do begin if MovesGrid[XPos+i ,YPos+i ]=PlayerNumber then if MovesGrid[XPos+i+1,YPos+i+1]=PlayerNumber then if MovesGrid[XPos+i+2,YPos+i+2]=PlayerNumber then if MovesGrid[XPos+i+3,YPos+i+3]=PlayerNumber then begin j:=3; while MovesGrid[XPos+i+j,YPos+i+j]=PlayerNumber do Inc(j); WinPosition.LeftDiagonal.Start:=WinPosition.TinyPoint(XPos+i,YPos+i); WinPosition.LeftDiagonal.Parts:=j; WinPosition.IsLeftDiagonalWin:=true; Found4InRow:=true; Break; end; end; // Check right diagonal. repeat Count:=Count-1; XPos:=XPos+1; YPos:=YPos+1; until count=0; repeat XPos:=XPos+1; YPos:=YPos-1; until (XPos=8) or (YPos=0); for i := 1 to 4 do begin if MovesGrid[XPos-i ,YPos+i ]=PlayerNumber then if MovesGrid[XPos-i-1,YPos+i+1]=PlayerNumber then if MovesGrid[XPos-i-2,YPos+i+2]=PlayerNumber then if MovesGrid[XPos-i-3,YPos+i+3]=PlayerNumber then begin j:=3; while MovesGrid[XPos-i-j,YPos+i+j]=PlayerNumber do Inc(j); WinPosition.RightDiagonal.Start:=WinPosition.TinyPoint(XPos-i,YPos+i); WinPosition.RightDiagonal.Parts:=j; WinPosition.IsRightDiagonalWin:=true; Found4InRow:=true; Break; end; end; Result:=Found4InRow; end; //----------------------------------------------------------------------------// procedure TGame.NewGame; var i, j: byte; begin for i:=0 to 8 do for j:=0 to 7 do MovesGrid[i,j]:=0; for i:=1 to 42 do MovesHistory.Move[i]:=WinPosition.TinyPoint(0,0); case Settings.PlayerStart of 0: if Random(2)=0 then PlayerGo:=true else PlayerGo:=false; 1: PlayerGo:=true; 2: PlayerGo:=false; end; MovesHistory.StartPlayer:=PlayerGo; NumberOfMoves:=0; WinPosition.ClearData; end; //----------------------------------------------------------------------------// function TGame.IsGridFull: boolean; var i: byte; begin for i:=1 to 7 do if MovesGrid[i,1]=0 then begin Result:=false; Exit; end; Result:=true; end; //----------------------------------------------------------------------------// procedure TGame.UndoMove; begin DecNumberOfMoves; MovesGrid[MovesHistory.Move[NumberOfMoves].x,MovesHistory.Move[NumberOfMoves].y]:=0; SwitchPlayer; end; //----------------------------------------------------------------------------// procedure TGame.RedoMove; var x, y: byte; begin GetMoveFromList(NumberOfMoves,x,y); MovesGrid[x,y]:=GetPlayerNumber; //SwitchPlayer; end; //----------------------------------------------------------------------------// procedure TGame.GetMoveFromList(const MoveNumber: byte; out x, y :byte); begin if MoveNumber>42 then begin x:=0; y:=x; end else begin x:=MovesHistory.Move[MoveNumber].x; y:=MovesHistory.Move[MoveNumber].y; end; end; //----------------------------------------------------------------------------// function TGame.GetLastMoveX: byte; begin Result:=MovesHistory.Move[NumberOfMoves].x; end; //----------------------------------------------------------------------------// function TGame.GetLastMoveY: byte; begin Result:=MovesHistory.Move[NumberOfMoves].y; end; //----------------------------------------------------------------------------// procedure TGame.SaveGame(const FileName: string); var DataFile: file of byte; i: byte; begin AssignFile(DataFile, ChangeFileExt(FileName,'.save')); Rewrite(DataFile); if MovesHistory.StartPlayer then Write(DataFile,1) else Write(DataFile,0); if IsWin or IsGridFull then Write(DataFile,NumberOfMoves+1) else Write(DataFile,NumberOfMoves); for i:=1 to 42 do begin Write(DataFile,MovesHistory.Move[i].x); Write(DataFile,MovesHistory.Move[i].y); end; CloseFile(DataFile); end; //----------------------------------------------------------------------------// procedure TGame.LoadGame(const FileName: string); var DataFile: file of byte; i, temp: byte; begin NewGame; AssignFile(DataFile, FileName); Reset(DataFile); Read(DataFile,temp); if temp=1 then PlayerGo:=true else PlayerGo:=false; MovesHistory.StartPlayer:=PlayerGo; Read(DataFile,NumberOfMoves); for i:=1 to 42 do begin Read(DataFile,MovesHistory.Move[i].x); Read(DataFile,MovesHistory.Move[i].y); if i<NumberOfMoves then MovesGrid[MovesHistory.Move[i].x,MovesHistory.Move[i].y]:=GetPlayerNumber; SwitchPlayer; end; CloseFile(DataFile); PlayerGo:=MovesHistory.StartPlayer; end; //----------------------------------------------------------------------------// function TGame.GetPlayerNumber: byte; overload; begin if PlayerGo then Result:=1 else Result:=2; end; //----------------------------------------------------------------------------// function TGame.IsCurrentPlayerBot: boolean; begin if PlayerGo and Settings.IsPlayer1Bot then Result:=true else if (not PlayerGo) and Settings.IsPlayer2Bot then Result:=true else Result:=false; end; //----------------------------------------------------------------------------// function TGame.IsOtherPlayerBot: boolean; begin if PlayerGo then Result:=Settings.IsPlayer1Bot else Result:=Settings.IsPlayer2Bot; end; //----------------------------------------------------------------------------// function TGame.IsStartPlayerBot: boolean; begin if MovesHistory.StartPlayer then Result:=Settings.IsPlayer2Bot else Result:=Settings.IsPlayer1Bot; end; //----------------------------------------------------------------------------// function TGame.GetFirstPlayer: boolean; begin Result:=MovesHistory.StartPlayer; end; //----------------------------------------------------------------------------// function TGame.GetBotMove: byte; var TempGrid: TGrid; MoveResults: array[1..7] of integer; i, y: integer; begin TempGrid:=MovesGrid; for i:=1 to 7 do // Check for win begin y:=GetDropLocation(i,TempGrid); if y=0 then Continue else begin TempGrid[i,y]:=GetPlayerNumber(PlayerGo); If IsWin(i,y,PlayerGo,TempGrid) then begin Result:=i; Exit; end; TempGrid[i,y]:=0; end; end; for i:=1 to 7 do // check for lose begin y:=GetDropLocation(i,TempGrid); if y=0 then Continue else begin TempGrid[i,y]:=GetPlayerNumber(not PlayerGo); If IsWin(i,y,not PlayerGo,TempGrid) then begin Result:=i; Exit; end; TempGrid[i,y]:=0; end; end; TempGrid:=MovesGrid; for i:=1 to 7 do // Start Minmax begin y:=GetDropLocation(i,TempGrid); if y=0 then Continue else begin TempGrid[i,y]:=GetPlayerNumber(PlayerGo); MoveResults[i]:=MinMax(Settings.BotLevel,not PlayerGo,TempGrid); TempGrid[i,y]:=0; end; end; Result:=ChooseBest(MoveResults); for i:=1 to 7 do write(MoveResults[i],' '); writeln; end; //---Bot Functions------------------------------------------------------------// function TGame.MinMax(Depth: integer; Player: boolean; CurrentGrid:TGrid): integer; var MoveStats: array[1..7] of integer; x, y: byte; temp: integer; begin for x:=1 to 7 do begin y:=GetDropLocation(x,CurrentGrid); if y=0 then begin MoveStats[x]:=0; Continue; end else begin CurrentGrid[x,y]:=GetPlayerNumber(Player); if IsWin(x,y,Player,CurrentGrid) then begin if Player=PlayerGo then MoveStats[x]:=42 else MoveStats[x]:=-42; end else if Depth=0 then begin MoveStats[x]:=GetScore(x,y,player,CurrentGrid); if Player<>PlayerGo then MoveStats[x]:=MoveStats[x]*-1; end else if Depth<>0 then MoveStats[x]:=MinMax(Depth-1,not Player,CurrentGrid); end; CurrentGrid[x,y]:=0; end; temp:=MoveStats[1]; if Player=PlayerGo then begin for x:=2 to 7 do if temp<MoveStats[x] then temp:=MoveStats[x]; end else begin for x:=2 to 7 do if temp>MoveStats[x] then temp:=MoveStats[x]; end; Result:=temp; end; //----------------------------------------------------------------------------// function TGame.ChooseBest(ResultList: array of integer): integer; var x, y, i, count: integer; Duplicate: array[0..6] of integer = (-1,-1,-1,-1,-1,-1,-1); begin count:=0; x:=ResultList[0]; for i:=0 to 6 do begin y:=GetDropLocation(i+1); if y=0 then ResultList[i]:=-100000; if x<ResultList[i] then x:=ResultList[i]; end; for i:=0 to 6 do if x=ResultList[i] then begin Duplicate[i]:=ResultList[i]; Inc(count); Result:=i+1; end; if count>1 then begin y:=Random(Count)+1; for i:=0 to 6 do begin if Duplicate[i]=x then Dec(y); if y=0 then begin Result:=i+1; Exit; end; end; end; end; //----------------------------------------------------------------------------// function TGame.IsWin(x,y:byte;player:boolean;CurrentGrid:TGrid): boolean; overload; var Count, i, PlayerNumber, XPos, YPos: byte; begin XPos:=x; YPos:=y; PlayerNumber:=GetPlayerNumber(player); Result:=false; // Check horizontal. for i := 1 to 4 do begin if CurrentGrid[i ,YPos]=PlayerNumber then if CurrentGrid[i+1,YPos]=PlayerNumber then if CurrentGrid[i+2,YPos]=PlayerNumber then if CurrentGrid[i+3,YPos]=PlayerNumber then begin Result:=true; Exit; end; end; // Check vertical. for i := 1 to 4 do begin if CurrentGrid[XPos,i ]=PlayerNumber then if CurrentGrid[XPos,i+1]=PlayerNumber then if CurrentGrid[XPos,i+2]=PlayerNumber then if CurrentGrid[XPos,i+3]=PlayerNumber then begin Result:=true; Exit; end; end; // Check left diagonal. if (XPos<>0) and (YPos<>0) then Count:=0; repeat Count:=Count+1; XPos:=XPos-1; YPos:=YPos-1; until (XPos=0) or (YPos=0); for i := 1 to 4 do begin if CurrentGrid[XPos+i ,YPos+i ]=PlayerNumber then if CurrentGrid[XPos+i+1,YPos+i+1]=PlayerNumber then if CurrentGrid[XPos+i+2,YPos+i+2]=PlayerNumber then if CurrentGrid[XPos+i+3,YPos+i+3]=PlayerNumber then begin Result:=true; Exit; end; end; // Check right diagonal. repeat Count:=Count-1; XPos:=XPos+1; YPos:=YPos+1; until count=0; repeat XPos:=XPos+1; YPos:=YPos-1; until (XPos=8) or (YPos=0); for i := 1 to 4 do begin if CurrentGrid[XPos-i ,YPos+i ]=PlayerNumber then if CurrentGrid[XPos-i-1,YPos+i+1]=PlayerNumber then if CurrentGrid[XPos-i-2,YPos+i+2]=PlayerNumber then if CurrentGrid[XPos-i-3,YPos+i+3]=PlayerNumber then begin Result:=true; Exit; end; end; end; //----------------------------------------------------------------------------// function TGame.GetScore(x,y: byte;player:boolean;CurrentGrid:TGrid):integer; var PlayerNumber, i, count, temp: Integer; begin // when end of tree is reached and no win or lose, then gen score based on adjacent moves PlayerNumber:=GetPlayerNumber(player); count:=0; // Check horizontal for i:=x-1 downto 1 do if CurrentGrid[i,y]=PlayerNumber then Inc(count) else Break; for i:=x+1 to 7 do if CurrentGrid[i,y]=PlayerNumber then Inc(count) else Break; // Check vertical for i:=y-1 downto 1 do if CurrentGrid[x,i]=PlayerNumber then Inc(count) else Break; for i:=y+1 to 6 do if CurrentGrid[x,i]=PlayerNumber then Inc(count) else Break; // Check left diagonal for i:=x-1 downto 1 do begin temp:=y-(x-i); if temp<>0 then if CurrentGrid[i,temp]=PlayerNumber then Inc(count) else Break; end; for i:=x+1 to 7 do begin temp:=y+(x-i); if temp<>7 then if CurrentGrid[i,temp]=PlayerNumber then Inc(count) else Break; end; // Check right diagonal for i:=x-1 downto 1 do begin temp:=y+(x-i); if temp<>7 then if CurrentGrid[i,temp]=PlayerNumber then Inc(count) else Break; end; for i:=x+1 to 7 do begin temp:=y-(x-i); if temp<>0 then if CurrentGrid[i,temp]=PlayerNumber then Inc(count) else Break; end; Result:=count; end; //----------------------------------------------------------------------------// function TGame.GetDropLocation(x: byte;Grid:TGrid): byte; overload; var i: byte; begin for i:=6 downto 0 do if Grid[x,i]=0 then Break; Result:=i; end; //----------------------------------------------------------------------------// function TGame.GetPlayerNumber(p:boolean): byte; overload; begin if p then Result:=1 else Result:=2; end; //---Bot Functions------------------------------------------------------------// //---TSettings----------------------------------------------------------------// constructor TSettings.Create; begin Config:=TMemIniFile.Create('Config.ini',false); Read; end; //----------------------------------------------------------------------------// destructor TSettings.Free; begin Config.Free; end; //----------------------------------------------------------------------------// procedure TSettings.Write; begin try Config.WriteInteger('Settings','PlayerStart',PlayerStart); Config.WriteInteger('Settings','NewCoinPosition',NewCoinPosition); Config.WriteBool('Settings','ShowCoinPreview',ShowCoinPreview); Config.WriteBool('View','ShowToolBar',ShowToolBar); Config.WriteBool('View','ShowStatusBar',ShowStatusBar); Config.WriteInteger('View','FormLeft',FormLeft); Config.WriteInteger('View','FormTop',FormTop); Config.WriteInteger('Settings','BotLevel',BotLevel); Config.WriteBool('Player','IsPlayer1Bot',IsPlayer1Bot); Config.WriteBool('Player','IsPlayer2Bot',IsPlayer2Bot); Config.WriteString('Player','Player1Name',Player1Name); Config.WriteString('Player','Player2Name',Player2Name); Config.WriteString('View','Skin',Skin); except // Do nothing. end; end; //----------------------------------------------------------------------------// procedure TSettings.Read; begin try PlayerStart:=Config.ReadInteger('Settings','PlayerStart',1); NewCoinPosition:=Config.ReadInteger('Settings','NewCoinPosition',1); ShowCoinPreview:=Config.ReadBool('Settings','ShowCoinPreview',true); ShowToolBar:=Config.ReadBool('View','ShowToolBar',true); ShowStatusBar:=Config.ReadBool('View','ShowStatusBar',true); FormLeft:=Config.ReadInteger('View','FormLeft',-1000); FormTop:=Config.ReadInteger('View','FormTop',-1000); BotLevel:=Config.ReadInteger('Settings','BotLevel',4); IsPlayer1Bot:=Config.ReadBool('Player','IsPlayer1Bot',false); IsPlayer2Bot:=Config.ReadBool('Player','IsPlayer2Bot',true); Player1Name:=Config.ReadString('Player','Player1Name','Player 1'); Player2Name:=Config.ReadString('Player','Player2Name','Player 2'); Skin:=Config.ReadString('View','Skin','Crystal'); except // Do Nothing. end; end; //----------------------------------------------------------------------------// //---TWinPosition-------------------------------------------------------------// function TWinPosition.TinyPoint(x, y: byte): TTinyPoint; begin Result.x:=x; Result.y:=y; end; //----------------------------------------------------------------------------// procedure TWinPosition.ClearData; begin Horizontal.Start:=TinyPoint(0,0); Horizontal.Parts:=0; Vertical.Start:=TinyPoint(0,0); Vertical.Parts:=0; LeftDiagonal.Start:=TinyPoint(0,0); LeftDiagonal.Parts:=0; RightDiagonal.Start:=TinyPoint(0,0); RightDiagonal.Parts:=0; _HorizontalWin:=false; _VerticalWin:=false; _LeftDiagonalWin:=false; _RightDiagonalWin:=false; end; //----------------------------------------------------------------------------// constructor TWinPosition.Create; begin ClearData; end; //----------------------------------------------------------------------------// end.
unit uDB; interface uses Windows, uOSMCommon, Variants, SysUtils, Classes, Contnrs, uInterfaces, uModule, SQLite3, SQLiteObj, DBF; implementation uses Math; const storageClassGUID: TGUID = '{91D72ED8-8FB3-4F62-A87C-650DFA1B9432}'; dbfReaderClassGUID: TGUID = '{616CDC46-28E6-46FB-876F-623C867011D7}'; type TStorageChild = class(TOSManObject) protected fOnClose: TNotifyEvent; procedure close(); virtual; abstract; end; TQueryResult = class(TStorageChild, IQueryResult) protected fQry: TSQLiteStmt; procedure close(); override; public function get_eos(): WordBool; destructor destroy; override; published //maxBufSize - number of rows to read function read(const maxBufSize: integer): OleVariant; //"true" if end of stream reached, "false" otherwise property eos: WordBool read get_eos; //returns SafeArray of string variants function getColNames(): OleVariant; //internal proc. Do not use procedure sqlExecInt(const paramNames, paramValues: OleVariant); end; TStoredIdList = class(TStorageChild, IStoredIdList) protected fStorage: OleVariant; fQryAdd: OleVariant; fQryIsIn: OleVariant; fQryDelete: OleVariant; fTableName: WideString; fTableCreated: boolean; function get_tableName: WideString; procedure dbOpenCheck(); procedure createTable(); procedure deleteTable(); procedure close(); override; public destructor destroy; override; published function isIn(const id: int64): boolean; procedure add(const id: int64); procedure remove(const id: int64); property tableName: WideString read get_tableName; end; TStorage = class(TOSManObject, IStorage) protected fDBName: WideString; fDB: TSQLiteDB; fChildList: TObjectList; fReadOnly: boolean; fCRTreeLoaded: boolean; procedure exec(const sql: WideString); procedure onCloseQuery(child: TObject); procedure initDBMode(); procedure close(); public function get_dbName(): WideString; procedure set_dbName(const newName: WideString); function get_readOnly(): boolean; procedure set_readOnly(roFlag: boolean); destructor destroy; override; published //returns opaque Query object function sqlPrepare(const sqlProc: WideString): OleVariant; //sqlQuery - opaque Query object //paramsNames,paramValues - query parameters. SafeArray of variants. //returns IQueryResult object //It can do batch execution if length(ParamValues)==k*length(paramsNames) and k>=1. //In such case only last resultset returned function sqlExec(const sqlQuery: OleVariant; const paramNames, paramValues: OleVariant): OleVariant; //creates IStoredIdList object function createIdList(): OleVariant; //initialize new storage - create database schema (tables, indexes, triggers...) procedure initSchema(); //set this property before open to use db in readonly mode property readOnly: boolean read get_readOnly write set_readOnly; //database resource locator (file name, server name, etc). property dbName: WideString read get_dbName write set_dbName; end; TDBFReader = class(TOSManObject, IResourceInputStream, IStorageUser) protected fStorage: Variant; fDBF: TDBF; public function get_storage: OleVariant; procedure set_storage(const newStorage: OleVariant); published //URL - fs file name procedure open(const URL: WideString); //maxBufSize - file codepage //result undefined function read(const maxBufSize: integer): OleVariant; function get_eos(): WordBool; //"true" if end of stream reached, "false" otherwise property eos: WordBool read get_eos; property storage: OleVariant read get_storage write set_storage; end; { TStorage } procedure TStorage.close; begin if assigned(fChildList) then begin while (fChildList.Count > 0) do TStorageChild(fChildList[fChildList.Count - 1]).close(); end; if assigned(fDB) then begin if fDB.IsInTransaction then fDB.Commit(); FreeAndNil(fDB); end; fCRTreeLoaded := false; end; function TStorage.createIdList: OleVariant; var sil: TStoredIdList; begin if not assigned(fDB) then raise EInOutError.Create(toString() + '.createIdList: can not create IdList on closed database'); sil := TStoredIdList.Create(); sil.fStorage := self as IDispatch; sil.fOnClose := onCloseQuery; sil.createTable(); result := sil as IDispatch; if not assigned(fChildList) then fChildList := TObjectList.Create(false); fChildList.add(sil); end; destructor TStorage.destroy; begin if assigned(fDB) then begin close(); end; FreeAndNil(fChildList); inherited; end; procedure TStorage.exec(const sql: WideString); var q: TSQLiteStmt; begin q := nil; try q := fDB.CreateStmt(sql); q.exec(); finally if assigned(q) then FreeAndNil(q); end; end; function TStorage.get_dbName: WideString; begin result := fDBName; end; function TStorage.get_readOnly: boolean; begin result := fReadOnly; end; procedure TStorage.initDBMode; begin exec('PRAGMA page_size=4096'); exec('PRAGMA encoding="UTF-8";'); exec('PRAGMA journal_mode=off;'); exec('PRAGMA synchronous=0 ;'); if not readOnly then begin exec('PRAGMA locking_mode=exclusive ;'); exec('PRAGMA default_cache_size = 32768'); end; exec('PRAGMA temp_store=1;'); exec('PRAGMA fullfsync=0;'); exec('PRAGMA recursive_triggers = 0'); exec('PRAGMA cache_size = 32768'); fCRTreeLoaded := true; try exec('SELECT load_extension("'+getOSManPath()+'crtree.dll")'); except fCRTreeLoaded := false; end; fDB.StartTransaction; end; procedure TStorage.initSchema; begin exec('DROP TABLE IF EXISTS users'); exec('CREATE TABLE IF NOT EXISTS users (' + 'id INTEGER PRIMARY KEY AUTOINCREMENT,' + 'name VARCHAR(40) NOT NULL)'); exec('DROP TABLE IF EXISTS nodes_attr'); exec('CREATE TABLE IF NOT EXISTS nodes_attr (' + 'id INTEGER PRIMARY KEY AUTOINCREMENT,' + 'version INTEGER DEFAULT 1 NOT NULL,' + 'timestamp BIGINT DEFAULT 20000101000011,' + 'userid INTEGER DEFAULT 0,' + 'changeset BIGINT)'); exec('DROP TABLE IF EXISTS nodes_latlon'); if fCRTreeLoaded then exec('CREATE VIRTUAL TABLE nodes_latlon USING crtree_i32(id,minlat,maxlat,minlon,maxlon)') else exec('CREATE VIRTUAL TABLE nodes_latlon USING rtree_i32(id,minlat,maxlat,minlon,maxlon)'); exec('DROP VIEW IF EXISTS nodes'); exec('CREATE VIEW IF NOT EXISTS nodes AS SELECT nodes_latlon.id as id,' + 'nodes_latlon.minlat as lat, nodes_latlon.minlon as lon,' + 'nodes_attr.version as version, nodes_attr.timestamp as timestamp,' + 'nodes_attr.userid as userid, nodes_attr.changeset as changeset ' + 'FROM nodes_attr, nodes_latlon WHERE nodes_attr.id=nodes_latlon.id'); exec('DROP TRIGGER IF EXISTS nodes_ii'); exec('CREATE TRIGGER IF NOT EXISTS nodes_ii INSTEAD OF INSERT ON nodes BEGIN ' + 'INSERT INTO nodes_attr (id, version, timestamp, userid, changeset) ' + 'VALUES (NEW.id,NEW.version, NEW.timestamp, NEW.userid, NEW.changeset);' + 'INSERT INTO nodes_latlon(id,minlat,maxlat,minlon,maxlon)' + 'VALUES (NEW.id, NEW.lat, NEW.lat, NEW.lon, NEW.lon);' + 'END;'); exec('DROP TRIGGER IF EXISTS nodes_iu'); exec('CREATE TRIGGER IF NOT EXISTS nodes_iu INSTEAD OF UPDATE ON nodes BEGIN ' + 'UPDATE nodes_attr SET id=NEW.id, version=NEW.version, timestamp=NEW.timestamp, userid=NEW.userid, changeset=NEW.changeset WHERE id=OLD.id;' + 'UPDATE nodes_latlon SET id=NEW.id,minlat=NEW.lat,maxlat=NEW.lat,minlon=NEW.lon,maxlon=NEW.lon WHERE id=OLD.id;' + 'UPDATE objtags SET objid=NEW.id*4 WHERE objid=4*OLD.id;' + 'END;'); exec('DROP TRIGGER IF EXISTS nodes_id'); exec('CREATE TRIGGER IF NOT EXISTS nodes_id INSTEAD OF DELETE ON nodes BEGIN ' + 'DELETE FROM nodes_attr WHERE id=OLD.id;' + 'DELETE FROM nodes_latlon WHERE id=OLD.id;' + 'DELETE FROM objtags WHERE objid=4*OLD.id;' + 'END;'); exec('DROP VIEW IF EXISTS strnodes'); exec('CREATE VIEW IF NOT EXISTS strnodes AS ' + 'SELECT nodes_attr.id AS id, minlat AS lat, minlon AS lon, version AS version, ' + 'timestamp AS timestamp, userid as userid, users.name AS username, changeset as changeset ' + 'FROM nodes_attr,nodes_latlon,users ' + 'WHERE nodes_attr.id=nodes_latlon.id AND nodes_attr.userid=users.id'); exec('CREATE TRIGGER IF NOT EXISTS strnodes_ii INSTEAD OF INSERT ON strnodes BEGIN ' + 'DELETE FROM nodes_latlon WHERE id=NEW.id;' + 'DELETE FROM objtags WHERE objid=0+NEW.id*4;' + 'INSERT OR IGNORE INTO users (id, name) VALUES (NEW.userid, NEW.username);' + 'INSERT OR REPLACE INTO nodes_attr (id,version,timestamp,userid,changeset) ' + 'VALUES (NEW.id,NEW.version,NEW.timestamp,NEW.userid,NEW.changeset);' + 'INSERT INTO nodes_latlon(id,minlat,maxlat,minlon,maxlon)' + 'VALUES (NEW.id,NEW.lat,NEW.lat,NEW.lon,NEW.lon);' + 'END;'); exec('DROP TABLE IF EXISTS tags'); exec('CREATE TABLE IF NOT EXISTS tags(' + 'id INTEGER NOT NULL CONSTRAINT tags_pk PRIMARY KEY AUTOINCREMENT,' + 'tagname VARCHAR(50) CONSTRAINT tags_tagname_c COLLATE BINARY,' + 'tagvalue VARCHAR(150) CONSTRAINT tags_tagvalue_c COLLATE BINARY' + ')'); exec('CREATE UNIQUE INDEX IF NOT EXISTS tags_tagname_tagvalue_i ' + 'ON tags(tagname,tagvalue)'); exec('DROP TABLE IF EXISTS objtags'); exec('CREATE TABLE IF NOT EXISTS objtags(' + 'objid BIGINT NOT NULL /* =id*4 + (0 for node, 1 for way, 2 for relation) */,' + 'tagid BIGINT NOT NULL,' + 'CONSTRAINT objtags_pk PRIMARY KEY (objid,tagid)' + ')'); exec('CREATE INDEX objtags_tagid_i ON objtags(tagid)'); exec('DROP VIEW IF EXISTS strobjtags'); exec('CREATE VIEW strobjtags AS ' + 'SELECT objid AS ''objid'',tagname AS ''tagname'',tagvalue AS ''tagvalue'' ' + 'FROM objtags,tags WHERE objtags.tagid=tags.id'); exec('CREATE TRIGGER strobjtags_ii INSTEAD OF INSERT ON strobjtags BEGIN ' + 'INSERT OR IGNORE INTO tags (tagname, tagvalue) ' + 'VALUES (NEW.tagname,NEW.tagvalue);' + 'INSERT OR IGNORE INTO objtags(objid,tagid) ' + 'VALUES (NEW.objid,(SELECT id FROM tags WHERE tags.tagname=NEW.tagname AND tags.tagvalue=NEW.tagvalue));' + 'END;'); exec('DROP TABLE IF EXISTS waynodes'); exec('CREATE TABLE IF NOT EXISTS waynodes (' + 'wayid INTEGER NOT NULL,' + 'nodeidx INTEGER NOT NULL,' + 'nodeid INTEGER NOT NULL,' + 'PRIMARY KEY (wayid,nodeidx))'); exec('CREATE INDEX IF NOT EXISTS waynodes_nodeid_i ON waynodes (nodeid)'); exec('DROP TABLE IF EXISTS ways'); exec('CREATE TABLE IF NOT EXISTS ways (' + 'id INTEGER PRIMARY KEY AUTOINCREMENT,' + 'version INTEGER DEFAULT 1 NOT NULL,' + 'timestamp BIGINT DEFAULT 20000101000012,' + 'userid INTEGER DEFAULT 0,' + 'changeset BIGINT)'); exec('CREATE TRIGGER IF NOT EXISTS ways_bu BEFORE UPDATE ON ways BEGIN ' + 'UPDATE objtags SET objid=1+4*NEW.id WHERE objid=1+4*OLD.id;' + 'UPDATE waynodes SET wayid=NEW.id WHERE wayid=OLD.id;' + 'END'); exec('CREATE TRIGGER ways_bd BEFORE DELETE ON ways BEGIN ' + 'DELETE FROM objtags WHERE objid=1+4*OLD.id;' + 'DELETE FROM waynodes WHERE wayid=OLD.id;' + 'END'); exec('DROP VIEW IF EXISTS strways'); exec('CREATE VIEW IF NOT EXISTS strways AS ' + 'SELECT ways.id AS id, version AS version, ' + 'timestamp AS timestamp, userid as userid, users.name AS username, changeset as changeset ' + 'FROM ways,users WHERE ways.userid=users.id'); exec('CREATE TRIGGER IF NOT EXISTS strways_ii INSTEAD OF INSERT ON strways BEGIN ' + 'DELETE FROM objtags WHERE objid=1+NEW.id*4;' + 'DELETE FROM waynodes WHERE wayid=NEW.id;' + 'INSERT OR IGNORE INTO users (id, name) VALUES (NEW.userid, NEW.username);' + 'INSERT OR REPLACE INTO ways (id,version,timestamp,userid,changeset) ' + 'VALUES(NEW.id,NEW.version,NEW.timestamp,NEW.userid,NEW.changeset);' + 'END;'); exec('DROP TABLE IF EXISTS relationmembers'); exec('CREATE TABLE IF NOT EXISTS relationmembers(' + 'relationid INTEGER NOT NULL,' + 'memberidxtype INTEGER NOT NULL,/*=index*4+(0 for node, 1 for way, 2 for relation)*/' + 'memberid INTEGER NOT NULL,' + 'memberrole VARCHAR(20) DEFAUlT '''',' + 'PRIMARY KEY (relationid,memberidxtype))'); exec('CREATE INDEX IF NOT EXISTS relationmembers_memberid_i ON relationmembers(memberid)'); exec('DROP VIEW IF EXISTS strrelationmembers'); exec('CREATE VIEW IF NOT EXISTS strrelationmembers AS ' + 'SELECT relationid AS relationid, ' + '(memberidxtype>>2) AS memberidx,' + '(CASE (memberidxtype & 3) WHEN 0 THEN ''node'' WHEN 1 THEN ''way'' WHEN 2 THEN ''relation'' ELSE '''' END) AS membertype,' + 'memberid AS memberid,' + 'memberrole AS memberrole ' + 'FROM relationmembers'); exec('CREATE TRIGGER IF NOT EXISTS strrelationmembers_ii INSTEAD OF INSERT ON strrelationmembers BEGIN ' + 'INSERT OR REPLACE INTO relationmembers (relationid,memberidxtype,memberid,memberrole) ' + 'VALUES(NEW.relationid,' + 'NEW.memberidx*4+(CASE NEW.membertype WHEN ''node'' THEN 0 WHEN ''way'' THEN 1 WHEN ''relation'' THEN 2 ELSE 3 END),' + 'NEW.memberid,' + 'NEW.memberrole);' + 'END;'); exec('DROP TABLE IF EXISTS relations'); exec('CREATE TABLE IF NOT EXISTS relations (' + 'id INTEGER PRIMARY KEY AUTOINCREMENT,' + 'version INTEGER DEFAULT 1 NOT NULL,' + 'timestamp BIGINT DEFAULT 20000101000013,' + 'userid INTEGER DEFAULT 0,' + 'changeset BIGINT)'); exec('CREATE TRIGGER IF NOT EXISTS relations_bu BEFORE UPDATE ON relations BEGIN ' + 'UPDATE objtags SET objid=2+4*NEW.id WHERE objid=2+4*OLD.id;' + 'UPDATE relationmembers SET relationid=NEW.id WHERE relationid=OLD.id;' + 'END'); exec('CREATE TRIGGER relations_bd BEFORE DELETE ON relations BEGIN ' + 'DELETE FROM objtags WHERE objid=2+4*OLD.id;' + 'DELETE FROM relationmembers WHERE relationid=OLD.id;' + 'END'); exec('DROP VIEW IF EXISTS strrelations'); exec('CREATE VIEW IF NOT EXISTS strrelations AS ' + 'SELECT relations.id AS id, version AS version, ' + 'timestamp AS timestamp, userid as userid, users.name AS username, changeset as changeset ' + 'FROM relations,users WHERE relations.userid=users.id'); exec('CREATE TRIGGER IF NOT EXISTS strrelations_ii INSTEAD OF INSERT ON strrelations BEGIN ' + 'DELETE FROM objtags WHERE objid=2+NEW.id*4;' + 'DELETE FROM relationmembers WHERE relationid=NEW.id;' + 'INSERT OR IGNORE INTO users (id, name) VALUES (NEW.userid, NEW.username);' + 'INSERT OR REPLACE INTO relations (id,version,timestamp,userid,changeset) ' + 'VALUES(NEW.id,NEW.version,NEW.timestamp,NEW.userid,NEW.changeset);' + 'END;'); end; procedure TStorage.onCloseQuery(child: TObject); begin fChildList.Remove(child); end; procedure TStorage.set_dbName(const newName: WideString); var newDB: TSQLiteDB; begin if newName = '' then begin close(); fDBName := newName; exit; end; newDB := TSQLiteDB.Create(); try if readOnly then newDB.open(newName, SQLITE_OPEN_READONLY) else newDB.open(newName); newDB.setBusyTimeout(30000); except FreeAndNil(newDB); raise; end; if assigned(fDB) then close(); fDB := newDB; fDBName := newName; initDBMode(); end; procedure TStorage.set_readOnly(roFlag: boolean); begin if (roFlag <> fReadOnly) and assigned(fDB) then begin raise EInOutError.Create(toString + '.set_readOnly: can not change on opened database'); end; fReadOnly := roFlag; end; function TStorage.sqlExec(const sqlQuery: OleVariant; const paramNames, paramValues: OleVariant): OleVariant; var n, v: OleVariant; begin if not assigned(fDB) then raise EInOutError.Create(toString() + '.sqlExec: can not execute query on closed database'); n := varFromJsObject(paramNames); v := varFromJsObject(paramValues); if (not VarIsArray(n)) and VarIsStr(n) and ('' <> n) then begin n := VarArrayOf([n]); if not VarIsArray(v) then begin v := VarArrayOf([v]); end; end; try sqlQuery.sqlExecInt(n, v); except on E:Exception do begin E.Message:=toString()+':'+E.Message; raise; end; end; result := sqlQuery; end; function TStorage.sqlPrepare(const sqlProc: WideString): OleVariant; var q: TSQLiteStmt; qr: TQueryResult; begin if not assigned(fDB) then raise EInOutError.Create(toString() + '.sqlPrepare: can not prepare query on closed database'); q := fDB.CreateStmt(sqlProc); qr := TQueryResult.Create(); qr.fQry := q; qr.fOnClose := onCloseQuery; result := qr as IDispatch; if not assigned(fChildList) then fChildList := TObjectList.Create(false); fChildList.add(qr); end; { TQueryResult } destructor TQueryResult.destroy; begin close(); inherited; end; function TQueryResult.get_eos: WordBool; begin result := (not assigned(fQry)) or (not fQry.HasNext); end; function TQueryResult.getColNames: OleVariant; var i: integer; begin result := VarArrayCreate([0, fQry.ColCount - 1], varVariant); for i := 0 to fQry.ColCount - 1 do begin VarArrayPut(Variant(result), fQry.ColName[i], [i]); end; end; function TQueryResult.read(const maxBufSize: integer): OleVariant; var nc, rc, ci: integer; pv: POleVariant; begin if assigned(fQry) then nc := fQry.ColCount else nc := 0; result := VarArrayCreate([0, nc * maxBufSize - 1], varVariant); if not assigned(fQry) then exit; rc := 0; pv := VarArrayLock(result); try while fQry.HasNext and (rc < maxBufSize) do begin for ci := 0 to nc - 1 do begin pv^ := fQry.Column[ci]; inc(pv); end; fQry.Next(); inc(rc); end; finally varArrayUnlock(result); end; if rc < maxBufSize then VarArrayRedim(result, nc * rc - 1); end; procedure TQueryResult.sqlExecInt(const paramNames, paramValues: OleVariant); var nLock, vLock: boolean; n, v: TVarRecArray; nl, vl, k, i: integer; begin nLock := false; vLock := false; setLength(n, 0); setLength(v, 0); try if (VarArrayDimCount(paramNames) = 1) or (VarArrayDimCount(paramValues) = 1) then begin //bind parameters before exec if ((varType(paramNames) and varTypeMask) <> varVariant) or ((varType(paramValues) and varTypeMask) <> varVariant) then raise EConvertError.Create(toString() + '.sqlExecInt: array of variants expected'); n := VarArrayLockVarRec(paramNames); nLock := true; v := VarArrayLockVarRec(paramValues); vLock := true; nl := length(n); vl := length(v); if not ((nl = vl) or //same size or empty ((nl > 0)and (vl > nl) and ((vl mod nl) = 0)) //not empty and vl=k*nl ) then raise ERangeError.Create(toString() + '.sqlExecInt: invalid arrays lengths'); if nl = vl then begin //simple params. one call. fQry.Bind(n, v); fQry.exec(); end else begin //batch query k := vl div nl; for i := 0 to k - 1 do begin fQry.Bind(n, copy(v, i * nl, nl)); fQry.exec(); end; end; end else //empty params, no bind fQry.exec(); finally if nLock then VarArrayUnlockVarRec(paramNames, n); if vLock then VarArrayUnlockVarRec(paramValues, v); end; end; procedure TQueryResult.close; begin if assigned(fQry) then FreeAndNil(fQry); if assigned(fOnClose) then begin fOnClose(self); fOnClose := nil; end; end; { TDBFReader } function TDBFReader.get_storage: OleVariant; begin result := fStorage; end; function TDBFReader.get_eos: WordBool; begin result := not assigned(fDBF); end; procedure TDBFReader.open(const URL: WideString); begin if assigned(fDBF) then raise EInOutError.Create(toString() + ': Open must be called only once'); fDBF := TDBF.Create(nil); fDBF.tableName := URL; //bug - not Unicode aware fDBF.open; fDBF.CodePage := NONE; end; function TDBFReader.read(const maxBufSize: integer): OleVariant; var nCol, i: integer; sAnsi: AnsiString; sQry, sInsQry, sTableName, sFieldName, sWide: WideString; vQry, vParNames, vParValues: OleVariant; begin if not assigned(fDBF) then begin raise EInOutError.Create(toString() + ': file must be opened before read'); end; if not varIsType(fStorage, varDispatch) then raise EInOutError.Create(toString() + ': storage not assigned'); nCol := fDBF.FieldCount; sTableName := ChangeFileExt(ExtractFileName(fDBF.tableName), ''); sQry := 'DROP TABLE IF EXISTS "' + sTableName + '"'; vQry := fStorage.sqlPrepare(sQry); fStorage.sqlExec(vQry, 0, 0); sQry := 'CREATE TABLE "' + sTableName + '" ('; sInsQry := 'INSERT INTO "' + sTableName + '" ('; for i := 1 to nCol do begin sFieldName := fDBF.GetFieldName(i); sQry := sQry + '"' + sFieldName + '" '; case fDBF.GetFieldType(i) of bfBoolean, bfNumber: sQry := sQry + 'INTEGER'; bfDate, bfFloat: sQry := sQry + 'FLOAT'; bfString: sQry := sQry + 'TEXT'; bfUnkown: sQry := sQry + 'BLOB'; end; sInsQry := sInsQry + '"' + sFieldName + '"'; if i < nCol then begin sQry := sQry + ','; sInsQry := sInsQry + ','; end else begin sQry := sQry + ')'; sInsQry := sInsQry + ')' end; end; vParNames := VarArrayCreate([0, nCol - 1], varVariant); vParValues := VarArrayCreate([0, nCol - 1], varVariant); sInsQry := sInsQry + ' VALUES ('; for i := 1 to nCol do begin sInsQry := sInsQry + ':field' + inttostr(i - 1); vParNames[i - 1] := ':field' + inttostr(i - 1); if i < nCol then begin sInsQry := sInsQry + ','; end else begin sInsQry := sInsQry + ')' end; end; vQry := fStorage.sqlPrepare(sQry); fStorage.sqlExec(vQry, 0, 0); vQry := fStorage.sqlPrepare(sInsQry); fDBF.First; while not fDBF.Eof do begin for i := 1 to nCol do begin sAnsi := fDBF.GetFieldData(i); setLength(sWide, length(sAnsi) + 1); setLength(sWide, MultiByteToWideChar(maxBufSize, 0, pchar(sAnsi), length(sAnsi), PWideChar(sWide), length(sWide))); vParValues[i - 1] := sWide; end; fStorage.sqlExec(vQry, vParNames, vParValues); fDBF.Next; end; FreeAndNil(fDBF); end; procedure TDBFReader.set_storage(const newStorage: OleVariant); begin varCopyNoInd(fStorage, newStorage); end; { TStoredIdList } procedure TStoredIdList.add(const id: int64); begin dbOpenCheck(); if VarIsEmpty(fQryAdd) then begin createTable(); fQryAdd := fStorage.sqlPrepare( 'INSERT INTO ' + tableName + '(id) VALUES (:id)'); end; fStorage.sqlExec(fQryAdd, ':id', id); end; procedure TStoredIdList.createTable; var q: OleVariant; begin if fTableCreated then exit; dbOpenCheck(); q := fStorage.sqlPrepare( 'CREATE TEMPORARY TABLE ' + tableName + '(id INTEGER PRIMARY KEY ON CONFLICT IGNORE)'); fStorage.sqlExec(q, 0, 0); fTableCreated := true; end; procedure TStoredIdList.remove(const id: int64); begin dbOpenCheck(); if VarIsEmpty(fQryDelete) then begin createTable(); fQryDelete := fStorage.sqlPrepare( 'DELETE FROM ' + tableName + ' WHERE id=:id'); end; fStorage.sqlExec(fQryDelete, ':id', id); end; procedure TStoredIdList.deleteTable; var q: OleVariant; begin if not fTableCreated then exit; fTableCreated := false; dbOpenCheck(); try q := fStorage.sqlPrepare('DELETE FROM ' + tableName); fStorage.sqlExec(q, 0, 0); q := fStorage.sqlPrepare('DROP TABLE ' + tableName); fStorage.sqlExec(q, 0, 0); except end; end; destructor TStoredIdList.destroy; begin close(); inherited; end; function TStoredIdList.get_tableName: WideString; begin if fTableName = '' then fTableName := 'idlist' + inttostr(getUID); result := fTableName; end; function TStoredIdList.isIn(const id: int64): boolean; var i: integer; begin dbOpenCheck(); if VarIsEmpty(fQryIsIn) then begin createTable(); fQryIsIn := fStorage.sqlPrepare('SELECT COUNT(1) FROM ' + tableName + ' WHERE id=:id'); end; i := fStorage.sqlExec(fQryIsIn, ':id', id).read(1)[0]; result := i > 0; end; procedure TStoredIdList.close(); begin fQryAdd := unassigned; fQryIsIn := unassigned; fQryDelete := unassigned; deleteTable(); fStorage := unassigned; if assigned(fOnClose) then fOnClose(self); fOnClose := nil; end; procedure TStoredIdList.dbOpenCheck; begin if VarIsEmpty(fStorage) then raise EInOutError.Create(toString() + ': can not operate on closed db'); end; initialization OSManRegister(TStorage, storageClassGUID); OSManRegister(TDBFReader, dbfReaderClassGUID); end.
unit ucGoURL; {access a file through a web browser } (* Permission is hereby granted, on 1-Nov-2003, free of charge, to any person obtaining a copy of this file (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. Author of original version of this file: Michael Ax *) interface type TtpBrowserMode=(bmRegistryDefault,bmShellExecute,bmNetScapeDDE); procedure BrowseURL(const URL:string); procedure BrowserGotoURL(const URL:string;Mode:TtpBrowserMode); procedure BrowserNetscapeGotoURL(Value:string); implementation uses ucShell, ucstring, DDEMan, Windows, Registry; procedure BrowseURL(const URL:string); begin BrowserGotoURL(URL,bmRegistryDefault); end; procedure BrowserGotoURL(const URL:string;Mode:TtpBrowserMode); //use ShellExecute or DDE to display the URL //accepts 'default' mode where it guesses the mode from the registry const cHTMLViewer='SOFTWARE\Classes\htmlfile\shell\open\ddeexec\Application'; cDefaultKey=''; cIEKey='IExplore'; begin if Mode=bmRegistryDefault then with TRegistry.Create do try Mode:=bmShellExecute; //pick a default RootKey:= HKEY_LOCAL_MACHINE; if OpenKey(cHTMLViewer, False) then if ReadString(cDefaultKey)<>cIEKey then Mode:=bmNetScapeDDE; finally free; end; case Mode of bmShellExecute: WinShellOpen(URL); bmNetScapeDDE: BrowserNetscapeGotoURL(URL); end; end; procedure BrowserNetscapeGotoURL(Value:string); //use DDE and Netscape to display the URL const cNetScapePath='SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\NetScape.exe'; cDefaultKey=''; cNetScape='NetScape'; cActivate='WWW_Activate'; cOpenURL='WWW_OpenURL'; cWakeUp='0xFFFFFFFF'; cRequest=',,'+cWakeUp+',0x3,,,'; begin with TDDEClientConv.Create(nil) do try // specify the location of netscape.exe with TRegistry.Create do try RootKey:= HKEY_LOCAL_MACHINE; if OpenKey(cNetScapePath, False) then begin ServiceApplication:= '"'+ReadString(cDefaultKey)+'"'; SetLink(cNetScape,cActivate); //start netscape RequestData(cWakeUp); //wake it up SetLink(cNetScape,cOpenURL); //tell it what we'll tell it RequestData(Value+cRequest); //get the value CloseLink; //break the connection end; finally free; end; finally free; end; end; end.
unit URParams; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, tc, UTime; type TFRParams = class(TForm) Button1: TButton; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; LineBox: TComboBox; Panel1: TPanel; FromBox: TComboBox; ToBox: TComboBox; Button2: TButton; procedure FormActivate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); public Item : RItem; Model : TModel; procedure RefreshLineBox; procedure RefreshFromBox; procedure RefreshToBox; procedure SetLine(value : integer); function GetLine : integer; procedure SetTime(value : time); function GetTime : time; procedure SetFrom(value : integer); function GetFrom : integer; procedure SetTo(value : integer); function GetTo : integer; procedure Load; procedure Save; property pLine : integer read GetLine write SetLine; property pTime : time read GetTime write SetTime; property pFrom : integer read GetFrom write SetFrom; property pTo : integer read GetTo write SetTo; end; var FRParams: TFRParams; implementation var FTime : TFTime; {$R *.DFM} procedure TFRParams.FormActivate(Sender: TObject); begin Load; end; procedure TFRParams.Button1Click(Sender: TObject); var l : TAssembleLine; begin if (pLine = -1) or (pFrom = -1) or (pTo = -1) then begin MessageDlg('Такая перенастройка невозможна!', mtError, [mbOk], 0); exit; end; l := Model.Lines.List[Model.Lines.FindByNumber(pLine)] as TAssembleLine; if (L.FReconfigure.GetReconfTime(pFrom, pTo) = -1) then begin MessageDlg('Выбранная линия не может быть так перенастроена!' , mtError, [mbOk], 0); exit; end; Save; ModalResult := mrOk; end; procedure TFRParams.Load; begin pTime := Item.rTime; pFrom := Item.rFrom; pTo := Item.rTo; pLine := Item.rLine; end; procedure TFRParams.Save; begin Item.rTime := pTime; Item.rFrom := pFrom; Item.rTo := pTo; Item.rLine := pLine; end; function TFRParams.GetFrom: integer; begin with FromBox do if ItemIndex = -1 then result := -1 else result := (Items.Objects[ItemIndex] as TMaterial).Number; end; function TFRParams.GetLine: integer; begin with LineBox do if ItemIndex = -1 then result := -1 else result := (Items.Objects[ItemIndex] as TAssembleLine).Number; end; function TFRParams.GetTime: time; begin result := FTime.Number; end; function TFRParams.GetTo: integer; begin with ToBox do if ItemIndex = -1 then result := -1 else result := (Items.Objects[ItemIndex] as TMaterial).Number; end; procedure TFRParams.SetFrom(value: integer); begin RefreshFromBox; FromBox.ItemIndex := Model.Materials.FindByNumber(value); end; procedure TFRParams.SetLine(value: integer); begin RefreshLineBox; LineBox.ItemIndex := Model.Lines.FindByNumber(value); end; procedure TFRParams.SetTime(value: time); begin FTime.Number := value; end; procedure TFRParams.SetTo(value: integer); begin RefreshToBox; ToBox.ItemIndex := Model.Materials.FindByNumber(value); end; procedure TFRParams.FormCreate(Sender: TObject); begin Panel1.BorderStyle := bsNone; FTime := TFTime.CreateEmbedded(self, Panel1); FTime.Show; end; procedure TFRParams.RefreshLineBox; var i : integer; begin LineBox.Clear; with Model.Lines do for i := Low(List) to high(List) do LineBox.Items.AddObject(List[i].Name, List[i]); end; procedure TFRParams.RefreshFromBox; var i : integer; begin FromBox.Clear; with Model.Materials do for i := Low(List) to high(List) do FromBox.Items.AddObject(List[i].Name, List[i]); end; procedure TFRParams.RefreshToBox; var i : integer; begin ToBox.Clear; with Model.Materials do for i := Low(List) to high(List) do ToBox.Items.AddObject(List[i].Name, List[i]); end; end.
unit uServerSocket; interface uses Windows, SysUtils, classes, Forms, scktcomp; type TServerSocket = class(TObject) private { Private declarations } ServerSocket : TClientSocket; Connecting : Boolean; strReceive : string; On_strReceive: Boolean; procedure OnRead(Sender: TObject; Socket: TCustomWinSocket); function wait_for_connect: Boolean; public { Public declarations } constructor Create(AOwner: TComponent); virtual; destructor Destroy; override; function Connect(const IPAddress: string; portNumber: integer) : Boolean; function Receive(var str_Receive: string; TimeOut: integer) : Boolean; function Send(strToSend: string) : Boolean; function Close : Boolean; end; implementation constructor TServerSocket.Create(AOwner: TComponent); begin ServerSocket := TClientSocket.Create(AOwner); ServerSocket.OnRead := OnRead; Connecting := False; strReceive := ''; On_strReceive := False; end; destructor TServerSocket.Destroy; begin ServerSocket.Free; end; procedure TServerSocket.OnRead(Sender: TObject; Socket: TCustomWinSocket); begin On_strReceive := True; strReceive := ServerSocket.Socket.ReceiveText; end; function TServerSocket.Connect(const IpAddress: string; portNumber: integer) : Boolean; begin ServerSocket.Address := IpAddress; ServerSocket.Port := portNumber; ServerSocket.ClientType := ctNonBlocking; ServerSocket.Open; Connecting := True; result := True; end; function TServerSocket.wait_for_connect: Boolean; var i: integer; begin result := ServerSocket.Active; if (Connecting = false) then exit; for i := 1 to 200 do begin if (ServerSocket.Active) = False then begin Application.ProcessMessages; Sleep(50); end else begin Connecting := False; result := True; exit; end; end; end; function TServerSocket.Send(StrToSend: string) : Boolean; begin Result := wait_for_connect; if (result = False) then exit; ServerSocket.Socket.SendText(StrToSend); Result := True; end; function TServerSocket.Receive(var str_receive: string; TimeOut: integer) : Boolean; var i: integer; begin Result := wait_for_connect; if (result = False) then exit; if TimeOut < 1 then TimeOut := 1; for i := 1 to TimeOut*20 do begin if (On_strReceive = False) then begin Application.ProcessMessages; Sleep(10); end else begin str_Receive := strReceive; strReceive := ''; On_strReceive := False; result := True; exit; end; end; end; function TServerSocket.Close : Boolean; begin ServerSocket.Active := False; result := True; end; end.
{ Copyright (C) 2013-2018 Tim Sinaeve tim.sinaeve@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit DataGrabber.Data.ResultSet; { A (decorator) class composed of a dataset with some extra information. } interface uses System.SysUtils, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Spring.Collections, Spring.Collections.Lists, DataGrabber.Interfaces; type TResultSet = class(TInterfacedObject, IResultSet) private FDataSet : TFDMemTable; // reference to a returned TFDMemTable instance FData : IData; FConstantFields : IList<TField>; FEmptyFields : IList<TField>; FNonEmptyFields : IList<TField>; FHiddenFields : IList<TField>; FFavoriteFields : IList<TField>; FConstantFieldsVisible : Boolean; FEmptyFieldsVisible : Boolean; FHiddenFieldCount : Integer; {$REGION 'property access methods'} function GetConstantFields: IList<TField>; function GetConstantFieldsVisible: Boolean; function GetEmptyFields: IList<TField>; function GetEmptyFieldsVisible: Boolean; function GetHiddenFields: IList<TField>; function GetNonEmptyFields: IList<TField>; function GetShowFavoriteFieldsOnly: Boolean; procedure SetConstantFieldsVisible(const Value: Boolean); procedure SetEmptyFieldsVisible(const Value: Boolean); procedure SetShowFavoriteFieldsOnly(const Value: Boolean); function GetDataSet: TFDDataSet; function GetData: IData; {$ENDREGION} protected procedure UpdateFieldLists; function ShowAllFields: Boolean; procedure InitFields(ADataSet: TDataSet); procedure InitField(AField: TField); public constructor Create( AData : IData; AFDDataSetReference : IFDDataSetReference ); procedure AfterConstruction; override; procedure BeforeDestruction; override; property DataSet: TFDDataSet read GetDataSet; property ConstantFields: IList<TField> read GetConstantFields; property EmptyFields: IList<TField> read GetEmptyFields; property NonEmptyFields: IList<TField> read GetNonEmptyFields; property HiddenFields: IList<TField> read GetHiddenFields; property ConstantFieldsVisible: Boolean read GetConstantFieldsVisible write SetConstantFieldsVisible; property EmptyFieldsVisible: Boolean read GetEmptyFieldsVisible write SetEmptyFieldsVisible; property ShowFavoriteFieldsOnly: Boolean read GetShowFavoriteFieldsOnly write SetShowFavoriteFieldsOnly; end; TResultSets = class(TList<IResultSet>) end; implementation uses Spring; {$REGION 'construction and destruction'} procedure TResultSet.AfterConstruction; begin inherited AfterConstruction; FConstantFields := TCollections.CreateObjectList<TField>(False); FEmptyFields := TCollections.CreateObjectList<TField>(False); FNonEmptyFields := TCollections.CreateObjectList<TField>(False); FFavoriteFields := TCollections.CreateObjectList<TField>(False); FHiddenFields := TCollections.CreateObjectList<TField>(False); FConstantFieldsVisible := True; FEmptyFieldsVisible := True; UpdateFieldLists; end; procedure TResultSet.BeforeDestruction; begin FData := nil; FreeAndNil(FDataSet); inherited BeforeDestruction; end; constructor TResultSet.Create(AData: IData; AFDDataSetReference: IFDDataSetReference); begin inherited Create; Guard.CheckNotNull(AData, 'AData'); Guard.CheckNotNull(AFDDataSetReference, 'AFDDataSetReference'); FData := AData; FDataSet := TFDMemTable.Create(nil);; FDataSet.Data := AFDDataSetReference; end; {$ENDREGION} {$REGION 'property access methods'} function TResultSet.GetData: IData; begin Result := FData; end; function TResultSet.GetDataSet: TFDDataSet; begin Result := FDataSet; end; function TResultSet.GetConstantFields: IList<TField>; begin Result := FConstantFields; end; function TResultSet.GetEmptyFields: IList<TField>; begin Result := FEmptyFields; end; function TResultSet.GetHiddenFields: IList<TField>; begin Result := FHiddenFields; end; function TResultSet.GetNonEmptyFields: IList<TField>; begin Result := FNonEmptyFields; end; function TResultSet.GetEmptyFieldsVisible: Boolean; begin Result := FEmptyFieldsVisible; end; procedure TResultSet.SetEmptyFieldsVisible(const Value: Boolean); begin if Value <> EmptyFieldsVisible then begin FEmptyFieldsVisible := Value; UpdateFieldLists; InitFields(DataSet); end; end; function TResultSet.GetShowFavoriteFieldsOnly: Boolean; begin Result := False; end; procedure TResultSet.SetShowFavoriteFieldsOnly(const Value: Boolean); begin // TODO end; function TResultSet.GetConstantFieldsVisible: Boolean; begin Result := FConstantFieldsVisible; end; procedure TResultSet.SetConstantFieldsVisible(const Value: Boolean); begin if Value <> ConstantFieldsVisible then begin FConstantFieldsVisible := Value; UpdateFieldLists; InitFields(DataSet); end; end; {$ENDREGION} {$REGION 'protected methods'} procedure TResultSet.InitField(AField: TField); var B : Boolean; begin B := True; // if ShowFavoriteFieldsOnly then // B := FFavoriteFields.Contains(AField); if B and not ConstantFieldsVisible then B := not FConstantFields.Contains(AField); if B and not EmptyFieldsVisible then B := not FEmptyFields.Contains(AField); if not B and not FHiddenFields.Contains(AField) then FHiddenFields.Add(AField); B := not FHiddenFields.Contains(AField); AField.Visible := B; end; procedure TResultSet.InitFields(ADataSet: TDataSet); var Field : TField; begin FHiddenFieldCount := 0; for Field in ADataSet.Fields do begin InitField(Field); end; end; function TResultSet.ShowAllFields: Boolean; var F : TField; begin Result := False; DataSet.DisableControls; try FConstantFieldsVisible := True; FEmptyFieldsVisible := True; for F in DataSet.Fields do begin if not F.Visible then begin F.Visible := True; Result := True; end; end; FHiddenFields.Clear; FHiddenFieldCount := 0; finally DataSet.EnableControls; end; end; procedure TResultSet.UpdateFieldLists; var S : string; T : string; F : TField; LIsEmpty : Boolean; LIsConst : Boolean; begin DataSet.DisableControls; FConstantFields.Clear; FEmptyFields.Clear; FNonEmptyFields.Clear; try if DataSet.FindFirst then begin for F in DataSet.Fields do begin // constant fields DataSet.FindFirst; S := F.AsString; LIsConst := True; LIsEmpty := F.IsNull or F.AsString.IsEmpty; while (LIsConst or LIsEmpty) and DataSet.FindNext do begin T := F.AsString; LIsConst := LIsConst and (S = T); LIsEmpty := LIsEmpty and (F.IsNull or T.IsEmpty); end; if LIsConst then FConstantFields.Add(F); if LIsEmpty then FEmptyFields.Add(F) else FNonEmptyFields.Add(F); end; end; finally DataSet.EnableControls; end; end; {$ENDREGION} end.
unit REPViewCommand; {$writeableconst on} interface uses REPWorldCanvas, Console, Windows, Classes, Controls; type TMouseDownParams = record Sender : TObject; Button : TMouseButton; Shift : TShiftState; x, y : integer; WC : TREPWorldCanvas; lWGS, bWGS : Double; end; TViewCmd = class private fIsTransparent : boolean; SavedCommand : TViewCmd; // Used only if command is transparent PrevPageIndex : integer; fCmdPhase : integer; LastMouseDown : record Point : TPoint; Sender : TObject end; procedure SetCmdPhase(v : integer); function ReactOnCtrl(Sender : TObject; var X, Y : integer; Shift : TShiftState) : boolean; protected procedure ShowControls; virtual; public function Name : String; virtual; function HelpStr : String; virtual; property IsTransparent : boolean read fIsTransparent; constructor Create; property CmdPhase : integer read fCmdPhase write SetCmdPhase; procedure CallOnMouseDown( Sender: TObject; Button: TMouseButton; Shift: TShiftState; x, y : integer; lWGS, bWGS : Double; WC : TREPWorldCanvas ); procedure OnMouseDown(Params : TMouseDownParams); virtual; procedure OnMouseMove(Sender: TObject; Shift: TShiftState; var X, Y: Integer; WC : TREPWorldCanvas); virtual; procedure OnMouseUp(Sender: TObject; Shift: TShiftState; X, Y: Integer; WC : TREPWorldCanvas); virtual; {$ifndef DBLCLICKTOSUPERZOOM} procedure OnDblClick(Sender: TObject; X, Y: Integer; WC : TREPWorldCanvas); virtual; {$endif} procedure CleanPaintBox(WC : TREPWorldCanvas); procedure CleanAllPaintBoxes; procedure DrawActualState(WC : TREPWorldCanvas); overload; virtual; procedure DrawActualState; overload; procedure SavePreviousCommand(PreviousCommand : TViewCmd); procedure RestorePreviousCommand; end; procedure ChangeCmd(NewCmd : TViewCmd); const ActiveCmd : TViewCmd = nil; OnChangeCmd : TNotifyEvent = nil; implementation procedure ProcessMouseDown(bWGS, lWGS : Double); begin { TODO : Opravit implementaci } { LastDown_wgs84B := bWGS; LastDown_wgs84L := lWGS; } end; procedure ChangeCmd(NewCmd : TViewCmd); begin if Assigned(NewCmd) then begin NewCmd.SavePreviousCommand(ActiveCmd); ActiveCmd := NewCmd; //DisplayCmdName(ActiveCmd.Name); //DisplayCmdHint(ActiveCmd.HelpStr); if Assigned(OnChangeCmd) then OnChangeCmd(nil); {$ifdef ONEBUTTONDOWN} CommandSelected(NewCmd.ClassName); {$endif} end; end; // **************************************************************************** // TViewCmd // **************************************************************************** constructor TViewCmd.Create; var i : integer; begin inherited; fIsTransparent := false; SavedCommand := nil; CmdPhase := 0; LastMouseDown.Sender := nil; end; // ***************************************************************************** // **** TViewCmd // ***************************************************************************** procedure TViewCmd.RestorePreviousCommand; begin if Assigned(SavedCommand) then ChangeCmd(SavedCommand); end; procedure TViewCmd.SavePreviousCommand(PreviousCommand : TViewCmd); begin if PreviousCommand = nil then Exit; if IsTransparent then begin if PreviousCommand.IsTransparent then begin SavedCommand := PreviousCommand.SavedCommand; PreviousCommand.Free; end else SavedCommand := PreviousCommand end else PreviousCommand.Free; end; {$ifndef DBLCLICKTOSUPERZOOM} procedure TViewCmd.OnDblClick(Sender: TObject; X, Y: Integer; WC : TREPWorldCanvas); begin // Blank end; {$endif} procedure TViewCmd.ShowControls; begin // if Assigned(CommandsParamsControlOwner) then ... end; procedure TViewCmd.DrawActualState(WC : TREPWorldCanvas); begin end; procedure TViewCmd.DrawActualState; begin CleanAllPaintBoxes; // DoForEachWorldCanvas(DrawActualState); // DrawGeovecDynamics; // DrawPrintFence; end; procedure TViewCmd.CleanAllPaintBoxes; begin // DoForEachWorldCanvas(CleanPaintBox); end; procedure TViewCmd.CleanPaintBox(WC : TREPWorldCanvas); begin // if Assigned(WC) then WC.PaintBox.Refresh; end; procedure TViewCmd.OnMouseUp(Sender: TObject; Shift: TShiftState; X, Y: Integer; WC : TREPWorldCanvas); begin // This method is intentionally blank end; procedure TViewCmd.CallOnMouseDown( Sender: TObject; Button: TMouseButton; Shift: TShiftState; x, y : integer; lWGS, bWGS : Double; WC : TREPWorldCanvas ); var Params : TMouseDownParams; begin if IsTransparent and (CmdPhase = 0) and (Button = mbRight) then RestorePreviousCommand else begin { if ReactOnCtrl(Sender, X, Y, Shift) then begin lWGS := PrimaryWorldCanvas.CanvasDef.WUfromEIndex(x); bWGS := PrimaryWorldCanvas.CanvasDef.WUfromNIndex(y); PrimaryWorldCanvas.CanvasDef.GeodeticSystem.ConvertStoreCoorsToGS(MBRGeoSystem, lWGS, bWGS, lWGS, bWGS); end; } Params.Sender := Sender; Params.Button := Button; Params.Shift := Shift; Params.x := x; Params.y := y; Params.lWGS := lWGS; Params.bWGS := bWGS; Params.WC := wc; LastMouseDown.Point.X := Params.x; LastMouseDown.Point.Y := Params.y; LastMouseDown.Sender := Params.Sender; OnMouseDown(Params); end; end; procedure TViewCmd.SetCmdPhase(v : integer); begin {$ifdef CustomMouseCursors} ChangeViewCursors(GetCursor); {$endif} fCmdPhase := v; if Self = ActiveCmd then DisplayCmdHint(HelpStr); end; function TViewCmd.Name : String; begin Result := ''; end; function TViewCmd.HelpStr : String; begin Result := ''; end; procedure TViewCmd.OnMouseDown; begin LastMouseDown.Point.X := Params.x; LastMouseDown.Point.Y := Params.y; LastMouseDown.Sender := Params.Sender; ProcessMouseDown(Params.bWGS, Params.lWGS); end; procedure TViewCmd.OnMouseMove(Sender: TObject; Shift: TShiftState; var X, Y: Integer; WC : TREPWorldCanvas); begin ReactOnCtrl(Sender, X, Y, Shift); end; function TViewCmd.ReactOnCtrl(Sender : TObject; var X, Y : integer; Shift : TShiftState) : boolean; // Jestlize je stisknuto Ctrl, chceme kreslit pouze vodorovne nebo svisle begin Result := false; end; end.
unit AppRender; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ExtCtrls, Graphics, Math, AppList; type TAppRender = class private fBgColor: TColor; fNodeSize: Integer; fNodeColor: TColor; fTextStyle: TTextStyle; fPaintBox: TPaintBox; public constructor Create(PaintBox: TPaintBox); procedure Update(MyList: TMyList); property BgColor: TColor read fBgColor write fBgColor; property NodeColor: TColor read fNodeColor write fNodeColor; end; implementation constructor TAppRender.Create(PaintBox: TPaintBox); begin fBgColor := clWhite; fNodeSize := 30; fNodeColor := clAqua; with fTextStyle do begin Alignment := taCenter; Layout := tlCenter; SingleLine := True; Clipping := False; ExpandTabs := False; ShowPrefix := False; Wordbreak := False; Opaque := False; // ? SystemFont := False; RightToLeft := False; end; fPaintBox := PaintBox; end; procedure TAppRender.Update(MyList: TMyList); var Iter: TMyNode; tr: TRect; sx, sy, r: Integer; nx, ny: Integer; th, ca: Single; begin with fPaintBox do begin Canvas.Brush.Style := bsSolid; Canvas.Brush.Color := fBgColor; Canvas.Clear(); if MyList.Size > 0 then begin // Выполняем предварительные вычисления sx := Canvas.Width div 2; sy := Canvas.Height div 2; // Центральный угол для каждой вершины th := 2 * pi / MyList.Size; // Подбираем радиус r := Max(Abs(Round((2.5 * fNodeSize) / (2 * Sin(th / 2)))), 90); if MyList.Size = 1 then r := 90; // Рисуем кольцо, на котором будем размещать узлы Canvas.Ellipse(sx-r, sy-r, sx+r, sy+r); Canvas.Brush.Color := fNodeColor; Iter := MyList.Root; // Рисуем узлы списка. Корневой узел списка всегда // будет расположена на 180 градусов, то есть слева. ca := pi; repeat nx := sx + Round(r * Cos(ca)); ny := sy + Round(r * Sin(ca)); tr.Left := nx-fNodeSize; tr.Top := ny-5; tr.Right := nx+fNodeSize; tr.Bottom := ny+5; Canvas.Ellipse(nx-fNodeSize, ny-fNodeSize, nx+fNodeSize, ny+fNodeSize); Canvas.TextRect(tr, 0, 0, IntToStr(Iter.Key), fTextStyle); Iter := Iter.Next; ca += th; until (Iter = MyList.Root); end; end; end; end.
unit FormDrzewoPostojow; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ComCtrls, JvUIB, JvUIBLib; type TFrmDrzewoPostojow = class(TForm) TrvPostoje: TTreeView; BtnZamknij: TBitBtn; EdtZnajdz: TEdit; LblZnajdz: TLabel; BtnZnajdz: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure BtnZamknijClick(Sender: TObject); procedure BtnZnajdzClick(Sender: TObject); private { Private declarations } procedure AssignLanguage; procedure DisplayUlice; procedure DisplayPostoje(Root: TTreeNode; UlicaId: Integer); public { Public declarations } end; implementation uses RT_SQL; {$R *.DFM} { TFrmDrzewoPostojow } { Private declarations } procedure TFrmDrzewoPostojow.AssignLanguage; begin Caption := ''; end; procedure TFrmDrzewoPostojow.DisplayUlice; var Node: TTreeNode; S: String; begin TrvPostoje.Items.BeginUpdate; try TrvPostoje.Items.Clear; with TSQL.Instance.CreateQuery do try SQL.Text := 'SELECT ID,NAZWA,POCZATEK,KONIEC FROM ULICA ORDER BY NAZWA'; Open; while not Eof do begin S := Format('%s od %s do %s', [ Fields.ByNameAsString['NAZWA'], Fields.ByNameAsString['POCZATEK'], Fields.ByNameAsString['KONIEC'] ]); if Fields.ByNameAsString['KONIEC'] = '' then S := S + 'końca'; Node := TrvPostoje.Items.Add(nil, S); DisplayPostoje(Node, Fields.ByNameAsInteger['ID']); Next; end; finally Free; end; finally TrvPostoje.Items.EndUpdate; end; end; procedure TFrmDrzewoPostojow.DisplayPostoje(Root: TTreeNode; UlicaId: Integer); begin with TSQL.Instance.CreateQuery do try SQL.Text := Format('SELECT POSTOJ.NAZWA FROM POSTOJNAULICY INNER JOIN POSTOJ ON (POSTOJNAULICY.POSTOJID = POSTOJ.ID) WHERE POSTOJNAULICY.ULICAID=%d ORDER BY POSTOJNAULICY.INDEKS;', [ UlicaId ]); Open; while not Eof do begin TrvPostoje.Items.AddChild(Root, Fields.ByNameAsString['NAZWA']); Next; end; finally Free; end; end; { Public declarations } procedure TFrmDrzewoPostojow.FormCreate(Sender: TObject); begin AssignLanguage; end; procedure TFrmDrzewoPostojow.FormDestroy(Sender: TObject); begin // end; procedure TFrmDrzewoPostojow.FormShow(Sender: TObject); begin DisplayUlice; TrvPostoje.Items.EndUpdate; end; procedure TFrmDrzewoPostojow.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin // end; procedure TFrmDrzewoPostojow.BtnZamknijClick(Sender: TObject); begin Close; end; procedure TFrmDrzewoPostojow.BtnZnajdzClick(Sender: TObject); var I: Integer; begin for I := 0 to TrvPostoje.Items.Count - 1 do begin if AnsiCompareText(Copy(TrvPostoje.Items[I].Text, 1, Length(EdtZnajdz.Text)), EdtZnajdz.Text) = 0 then begin TrvPostoje.Selected := TrvPostoje.Items[I]; TrvPostoje.SetFocus; Break; end; end; end; end.
unit Generator; interface uses Classes, SysUtils, PxDTDFile; procedure GenerateUnit(UnitName: String; DTDFile: TDTDFile; Output: TStrings); implementation function CapitalizeFirstLetter(S: String): String; begin Result := S; Result[1] := UpCase(Result[1]); end; function HasObjects(Element: TDTDElement): Boolean; var I: Integer; begin Result := False; for I := 0 to Element.Elements.Count - 1 do if Element.Elements[I].Elements.Count > 0 then begin Result := True; Break; end; end; procedure CreateForwardDeclarations(DTDFile: TDTDFile; Output: TStrings); var I: Integer; begin for I := 0 to DTDFile.Elements.Count - 1 do if DTDFile.Elements[I].Elements.Count > 0 then begin Output.Add(' TXml' + CapitalizeFirstLetter(DTDFile.Elements[I].Name) + ' = class;'); if DTDFile.Elements[I] <> DTDFile.Root then Output.Add(' TXml' + CapitalizeFirstLetter(DTDFile.Elements[I].Name) + 'List = class;'); end; Output.Add(''); end; procedure CreateRootElementInterface(Element: TDTDElement; Output: TStrings); var I: Integer; begin Output.Add(' TXml' + CapitalizeFirstLetter(Element.Name) + ' = class(TObject)'); Output.Add(' private'); for I := 0 to Element.Elements.Count - 1 do begin if Element.Elements[I].Elements.Count = 0 then Output.Add(' F' + CapitalizeFirstLetter(Element.Elements[I].Name) + ': String;') else Output.Add(' F' + CapitalizeFirstLetter(Element.Elements[I].Name) + ': TXml' + CapitalizeFirstLetter(Element.Elements[I].Name) + 'List;') end; Output.Add(' protected'); Output.Add(' procedure LoadFromXml(XmlReader: TPxXmlReader);'); Output.Add(' public'); if HasObjects(Element) then begin Output.Add(' constructor Create;'); Output.Add(' destructor Destroy; override;'); end; for I := 0 to Element.Elements.Count - 1 do if Element.Elements[I].Elements.Count = 0 then Output.Add(' property ' + CapitalizeFirstLetter(Element.Elements[I].Name) + ': String read F' + CapitalizeFirstLetter(Element.Elements[I].Name) + ' write F' + CapitalizeFirstLetter(Element.Elements[I].Name) + ';') else Output.Add(' property ' + CapitalizeFirstLetter(Element.Elements[I].Name) + ': TXml' + CapitalizeFirstLetter(Element.Elements[I].Name) + 'List read F' + CapitalizeFirstLetter(Element.Elements[I].Name) +';'); Output.Add(' end;'); Output.Add(''); end; procedure CreateElementListInterface(Element: TDTDElement; Output: TStrings); begin Output.Add(' TXml' + CapitalizeFirstLetter(Element.Name) + 'List = class(TList)'); Output.Add(' private'); Output.Add(' function GetItem(Index: Integer): TXml' + CapitalizeFirstLetter(Element.Name) + ';'); Output.Add(' public'); Output.Add(' property Items[Index: Integer]: TXml' + CapitalizeFirstLetter(Element.Name) + ' read GetItem; default;'); Output.Add(' end;'); Output.Add(''); end; procedure CreateElementInterface(Element: TDTDElement; Output: TStrings); var I: Integer; begin Output.Add(' TXml' + CapitalizeFirstLetter(Element.Name) + ' = class(TObject)'); Output.Add(' private'); for I := 0 to Element.Elements.Count - 1 do begin if Element.Elements[I].Elements.Count = 0 then Output.Add(' F' + CapitalizeFirstLetter(Element.Elements[I].Name) + ': String;') else Output.Add(' F' + CapitalizeFirstLetter(Element.Elements[I].Name) + ': TXml' + CapitalizeFirstLetter(Element.Elements[I].Name) + 'List;') end; Output.Add(' protected'); Output.Add(' procedure LoadFromXml(XmlReader: TPxXmlReader);'); Output.Add(' public'); if HasObjects(Element) then begin Output.Add(' constructor Create;'); Output.Add(' destructor Destroy; override;'); end; for I := 0 to Element.Elements.Count - 1 do if Element.Elements[I].Elements.Count = 0 then Output.Add(' property ' + CapitalizeFirstLetter(Element.Elements[I].Name) + ': String read F' + CapitalizeFirstLetter(Element.Elements[I].Name) + ' write F' + CapitalizeFirstLetter(Element.Elements[I].Name) + ';') else Output.Add(' property ' + CapitalizeFirstLetter(Element.Elements[I].Name) + ': TXml' + CapitalizeFirstLetter(Element.Elements[I].Name) + 'List read F' + CapitalizeFirstLetter(Element.Elements[I].Name) +';'); Output.Add(' end;'); Output.Add(''); end; procedure CreateRootElementImplementation(Element: TDTDElement; Output: TStrings); var I: Integer; begin Output.Add('{ TXml' + CapitalizeFirstLetter(Element.Name) + ' } '); Output.Add(''); Output.Add('{ Protected declarations }'); Output.Add(''); // // LoadFromXml // Output.Add('procedure TXml' + CapitalizeFirstLetter(Element.Name) + '.LoadFromXml(XmlReader: TPxXmlReader);'); if HasObjects(Element) then begin Output.Add('var'); for I := 0 to Element.Elements.Count - 1 do if Element.Elements[I].Elements.Count > 0 then Output.Add(' ' + CapitalizeFirstLetter(Element.Elements[I].Name) + ': TXml' + CapitalizeFirstLetter(Element.Elements[I].Name) + ';'); end; Output.Add('begin'); Output.Add(' while XmlReader.Next <> xrtEof do'); Output.Add(' case XmlReader.TokenType of'); Output.Add(' xrtElementBegin:'); Output.Add(' begin'); for I := 0 to Element.Elements.Count - 1 do begin if I = 0 then Output.Add(' if XmlReader.Name = ''' + Element.Elements[I].Name + ''' then') else Output.Add(' else if XmlReader.Name = ''' + Element.Elements[I].Name + ''' then'); Output.Add(' begin'); Output.Add(' ' + CapitalizeFirstLetter(Element.Elements[I].Name) + ' := TXml' + CapitalizeFirstLetter(Element.Elements[I].Name) + '.Create;'); Output.Add(' ' + CapitalizeFirstLetter(Element.Elements[I].Name) + '.LoadFromXml(XmlReader);'); Output.Add(' Self.' + CapitalizeFirstLetter(Element.Elements[I].Name) + '.Add(' + CapitalizeFirstLetter(Element.Elements[I].Name) + ');'); Output.Add(' end'); end; Output.Add(' end;'); Output.Add(' xrtElementEnd:'); Output.Add(' if XmlReader.Name = ''' + Element.Name + ''' then'); Output.Add(' Break'); Output.Add(' end;'); Output.Add('end;'); Output.Add(''); if HasObjects(Element) then begin Output.Add('{ Public declarations }'); Output.Add(''); // // Constructor // Output.Add('constructor TXml' + CapitalizeFirstLetter(Element.Name) + '.Create;'); Output.Add('begin'); Output.Add(' inherited Create;'); for I := 0 to Element.Elements.Count - 1 do if Element.Elements[I].Elements.Count > 0 then Output.Add(' F' + CapitalizeFirstLetter(Element.Elements[I].Name) + ' := TXml' + CapitalizeFirstLetter(Element.Elements[I].Name) + 'List.Create;'); Output.Add('end;'); Output.Add(''); // // Destructor // Output.Add('destructor TXml' + CapitalizeFirstLetter(Element.Name) + '.Destroy;'); Output.Add('var'); Output.Add(' I: Integer;'); Output.Add('begin'); for I := 0 to Element.Elements.Count - 1 do if Element.Elements[I].Elements.Count > 0 then begin Output.Add(' for I := 0 to ' + CapitalizeFirstLetter(Element.Elements[I].Name) + '.Count - 1 do'); Output.Add(' ' + CapitalizeFirstLetter(Element.Elements[I].Name) + '[I].Free;'); Output.Add(' FreeAndNil(F' + CapitalizeFirstLetter(Element.Elements[I].Name) + ');'); end; Output.Add(' inherited Destroy;'); Output.Add('end;'); end; Output.Add(''); end; procedure CreateElementImplementation(Element: TDTDElement; Output: TStrings); var I: Integer; IfStarted: Boolean; begin Output.Add('{ TXml' + CapitalizeFirstLetter(Element.Name) + ' } '); Output.Add(''); Output.Add('{ Protected declarations }'); Output.Add(''); // // LoadFromXml // Output.Add('procedure TXml' + CapitalizeFirstLetter(Element.Name) + '.LoadFromXml(XmlReader: TPxXmlReader);'); Output.Add('begin'); Output.Add(' while XmlReader.Next <> xrtEof do'); Output.Add(' case XmlReader.TokenType of'); if HasObjects(Element) then begin Output.Add(' xrtElementBegin:'); Output.Add(' begin'); IfStarted := False; for I := 0 to Element.Elements.Count - 1 do if Element.Elements[I].Elements.Count > 0 then begin if not IfStarted then Output.Add(' if XmlReader.Name = ''' + Element.Elements[I].Name + ''' then') else Output.Add(' else if XmlReader.Name = ''' + Element.Elements[I].Name + ''' then'); IfStarted := True; Output.Add(' begin'); begin Output.Add(' ' + CapitalizeFirstLetter(Element.Elements[I].Name) + ' := TXml' + CapitalizeFirstLetter(Element.Elements[I].Name) + '.Create;'); Output.Add(' ' + CapitalizeFirstLetter(Element.Elements[I].Name) + '.LoadFromXml(XmlReader);'); Output.Add(' Self.' + CapitalizeFirstLetter(Element.Elements[I].Name) + '.Add(' + CapitalizeFirstLetter(Element.Elements[I].Name) + ');'); end; Output.Add(' end'); end; Output.Add(' end;'); end; Output.Add(' xrtText:'); Output.Add(' begin'); IfStarted := False; for I := 0 to Element.Elements.Count - 1 do if Element.Elements[I].Elements.Count = 0 then begin if not IfStarted then Output.Add(' if XmlReader.ElementName = ''' + Element.Elements[I].Name + ''' then') else Output.Add(' else if XmlReader.ElementName = ''' + Element.Elements[I].Name + ''' then'); IfStarted := True; Output.Add(' F' + CapitalizeFirstLetter(Element.Elements[I].Name) + ' := XmlReader.Value'); end; Output.Add(' end;'); Output.Add(' xrtElementEnd:'); Output.Add(' if XmlReader.Name = ''' + Element.Name + ''' then'); Output.Add(' Break;'); Output.Add(' end;'); Output.Add('end;'); Output.Add(''); if HasObjects(Element) then begin Output.Add('{ Public declarations }'); Output.Add(''); // // Constructor // Output.Add('constructor TXml' + CapitalizeFirstLetter(Element.Name) + '.Create;'); Output.Add('begin'); Output.Add(' inherited Create;'); for I := 0 to Element.Elements.Count - 1 do if Element.Elements[I].Elements.Count > 0 then Output.Add(' F' + CapitalizeFirstLetter(Element.Elements[I].Name) + ' := TXml' + CapitalizeFirstLetter(Element.Elements[I].Name) + 'List.Create;'); Output.Add('end;'); Output.Add(''); // // Destructor // Output.Add('destructor TXml' + CapitalizeFirstLetter(Element.Name) + '.Destroy;'); Output.Add('var'); Output.Add(' I: Integer;'); Output.Add('begin'); for I := 0 to Element.Elements.Count - 1 do if Element.Elements[I].Elements.Count > 0 then begin Output.Add(' for I := 0 to ' + CapitalizeFirstLetter(Element.Elements[I].Name) + '.Count - 1 do'); Output.Add(' ' + CapitalizeFirstLetter(Element.Elements[I].Name) + '[I].Free;'); Output.Add(' FreeAndNil(F' + CapitalizeFirstLetter(Element.Elements[I].Name) + ');'); end; Output.Add(' inherited Destroy;'); Output.Add('end;'); Output.Add(''); end; end; procedure CreateElementListImplementation(Element: TDTDElement; Output: TStrings); begin Output.Add('{ TXml' + CapitalizeFirstLetter(Element.Name) + 'List } '); Output.Add(''); Output.Add('{ Private declarations }'); Output.Add(''); Output.Add('function TXml' + CapitalizeFirstLetter(Element.Name) + 'List.GetItem(Index: Integer): TXml' + CapitalizeFirstLetter(Element.Name) + ';'); Output.Add('begin'); Output.Add(' Result := TObject(Get(Index)) as TXml' + CapitalizeFirstLetter(Element.Name) + ';'); Output.Add('end;'); Output.Add(''); end; procedure CreateMainLoadFunctionInterface(DTDFile: TDTDFile; Output: TStrings); begin Output.Add('function Load' + CapitalizeFirstLetter(DTDFile.Root.Name) + '(FileName: String): TXml' + CapitalizeFirstLetter(DTDFile.Root.Name) + ';'); Output.Add(''); end; procedure CreateMainLoadFunctionImplementation(DTDFile: TDTDFile; Output: TStrings); begin Output.Add('function Load' + CapitalizeFirstLetter(DTDFile.Root.Name) + '(FileName: String): TXml' + CapitalizeFirstLetter(DTDFile.Root.Name) + ';'); Output.Add('var'); Output.Add(' XmlReader: TPxXmlReader;'); Output.Add('begin'); Output.Add(' Result := nil;'); Output.Add(''); Output.Add(' XmlReader := TPxXmlReader.Create;'); Output.Add(' try'); Output.Add(' XmlReader.Open(FileName);'); Output.Add(' while XmlReader.Next <> xrtEof do'); Output.Add(' case XmlReader.TokenType of'); Output.Add(' xrtElementBegin:'); Output.Add(' begin'); Output.Add(' if XmlReader.Name = ''' + DTDFile.Root.Name + ''' then'); Output.Add(' begin'); Output.Add(' Result := TXml' + CapitalizeFirstLetter(DTDFile.Root.Name) + '.Create;'); Output.Add(' Result.LoadFromXml(XmlReader);'); Output.Add(' end'); Output.Add(' else'); Output.Add(' raise Exception.CreateFmt(''Error: unknown element %s'', [XmlReader.Name]);'); Output.Add(' end;'); Output.Add(' end;'); Output.Add(' finally'); Output.Add(' XmlReader.Free;'); Output.Add(' end;'); Output.Add('end;'); Output.Add(''); end; procedure GenerateUnit(UnitName: String; DTDFile: TDTDFile; Output: TStrings); var I: Integer; begin Output.Add('unit ' + UnitName + ';'); Output.Add(''); Output.Add('interface'); Output.Add(''); Output.Add('uses'); Output.Add(' Classes, SysUtils, PxXmlReader;'); Output.Add(''); Output.Add('type'); Output.Add(''); Output.Add(' { Forward declarations }'); Output.Add(''); CreateForwardDeclarations(DTDFile, Output); Output.Add(' { Element''s Interface }'); Output.Add(''); for I := 0 to DTDFile.Elements.Count - 1 do if DTDFile.Elements[I] = DTDFile.Root then CreateRootElementInterface(DTDFile.Elements[I], Output) else if DTDFile.Elements[I].Elements.Count > 0 then begin CreateElementInterface(DTDFile.Elements[I], Output); CreateElementListInterface(DTDFile.Elements[I], Output); end; CreateMainLoadFunctionInterface(DTDFile, Output); Output.Add('implementation'); Output.Add(''); for I := 0 to DTDFile.Elements.Count - 1 do if DTDFile.Elements[I] = DTDFile.Root then CreateRootElementImplementation(DTDFile.Elements[I], Output) else if DTDFile.Elements[I].Elements.Count > 0 then begin CreateElementImplementation(DTDFile.Elements[I], Output); CreateElementListImplementation(DTDFile.Elements[I], Output); end; Output.Add('{ *** }'); Output.Add(''); CreateMainLoadFunctionImplementation(DTDFile, Output); Output.Add('end.'); end; end.
unit Vector2OperatorsTestCase; {$mode objfpc}{$H+} {$CODEALIGN LOCALMIN=16} interface uses Classes, SysUtils, fpcunit, testregistry, BaseTestCase, native, BZVectorMath; type { TVector2OperatorsTestCase } TVector2OperatorsTestCase = class(TVectorBaseTestCase) published procedure TestCompare; // these two test ensure we have data to play procedure TestCompareFalse; // with and tests the compare function. procedure TestAddVector; procedure TestAddSingle; procedure TestSubVector; procedure TestSubSingle; procedure TestMulVector; procedure TestMulSingle; procedure TestDivVector; procedure TestDivSingle; procedure TestDiv2i; procedure TestNegate; procedure TestEqualVector; procedure TestUnEqualVector; end; implementation {%region%====[ TVector2OperatorsTestCase ]======================================} {Test IsEqual and we have same values for each class ttpe} procedure TVector2OperatorsTestCase.TestCompare; begin AssertTrue('Test Values do not match'+ntt3.ToString+' --> '+vtt3.ToString, Compare(ntt1,vtt1)); end; procedure TVector2OperatorsTestCase.TestCompareFalse; begin AssertFalse('Test Values should not match'+ntt3.ToString+' --> '+vtt3.ToString, Compare(ntt1,vtt2)); end; procedure TVector2OperatorsTestCase.TestAddVector; begin ntt3 := ntt2 + ntt1; vtt3 := vtt1 + vtt2; AssertTrue('Vector + Vector no match'+ntt3.ToString+' --> '+vtt3.ToString, Compare(ntt3,vtt3)); end; procedure TVector2OperatorsTestCase.TestAddSingle; begin ntt3 := ntt1 + fs1; vtt3 := vtt1 + fs1; AssertTrue('Vector + Single no match'+ntt3.ToString+' --> '+vtt3.ToString, Compare(ntt3,vtt3)); end; procedure TVector2OperatorsTestCase.TestSubVector; begin ntt3 := ntt2 - ntt1; vtt3 := vtt2 - vtt1; AssertTrue('Vector - Vector no match'+ntt3.ToString+' --> '+vtt3.ToString, Compare(ntt3,vtt3)); end; procedure TVector2OperatorsTestCase.TestSubSingle; begin ntt3 := ntt1 - fs1; vtt3 := vtt1 - fs1; AssertTrue('Vector - Single no match'+ntt3.ToString+' --> '+vtt3.ToString, Compare(ntt3,vtt3)); end; procedure TVector2OperatorsTestCase.TestMulVector; begin ntt3 := ntt2 * ntt1; vtt3 := vtt2 * vtt1; AssertTrue('Vector x Vector no match'+ntt3.ToString+' --> '+vtt3.ToString, Compare(ntt3,vtt3)); end; procedure TVector2OperatorsTestCase.TestMulSingle; begin ntt3 := ntt1 * fs1; vtt3 := vtt1 * fs1; AssertTrue('Vector x Single no match'+ntt3.ToString+' --> '+vtt3.ToString, Compare(ntt3,vtt3)); end; procedure TVector2OperatorsTestCase.TestDivVector; begin ntt3 := ntt2 / ntt1; vtt3 := vtt2 / vtt1; AssertTrue('Vector / Vector no match'+ntt3.ToString+' --> '+vtt3.ToString, Compare(ntt3,vtt3)); end; procedure TVector2OperatorsTestCase.TestDivSingle; begin ntt3 := ntt1 / fs1; vtt3 := vtt1 / fs1; AssertTrue('Vector / Single no match'+ntt3.ToString+' --> '+vtt3.ToString, Compare(ntt3,vtt3,1e-5)); end; procedure TVector2OperatorsTestCase.TestDiv2i; var at2i: TBZVector2i; begin at2i.Create(2,2); nt2i.V := at2i.V; ntt3 := ntt1 / nt2i; vtt3 := vtt1 / at2i; AssertTrue('Vector / 2i no match'+ntt3.ToString+' --> '+vtt3.ToString, Compare(ntt3,vtt3)); end; procedure TVector2OperatorsTestCase.TestNegate; begin ntt3 := -ntt1; vtt3 := -vtt1; AssertTrue('Vector Negate no match'+ntt3.ToString+' --> '+vtt3.ToString, Compare(ntt3,vtt3,1e-5)); end; procedure TVector2OperatorsTestCase.TestEqualVector; begin nb := ntt1 = ntt1; vb := vtt1 = vtt1; AssertTrue('Vectors should be equal'+ntt1.ToString+' --> '+vtt1.ToString, not(nb xor vb)); end; procedure TVector2OperatorsTestCase.TestUnEqualVector; begin nb := ntt1 <> ntt2; vb := vtt1 <> vtt2; AssertTrue('Vectors should be equal'+vtt1.ToString+' --> '+vtt2.ToString, not(nb xor vb)); end; {%endregion%} initialization RegisterTest(REPORT_GROUP_VECTOR2F, TVector2OperatorsTestCase); end.
PROGRAM e910; USES Crt; TYPE Product = record code: Integer; name: String; currentStock: Integer; minStock: Integer; price: Real; end; ProductsFileT = file of Product; procedure PrintProduct(var rec: Product); begin with rec do WriteLn(code: 10, name: 20, currentStock: 10, minStock: 10, price: 10); end; procedure ReadProduct(var rec: Product); begin with rec do begin Write('Enter code: '); ReadLn(code); Write('Enter name: '); ReadLn(name); Write('Enter currentStock: '); ReadLn(currentStock); Write('Enter minStock: '); ReadLn(minStock); Write('Enter price: '); ReadLn(price); WriteLn(); end; end; procedure CreateAndFillFile(var productsFile: ProductsFileT); var rec: Product; begin Rewrite(productsFile); ReadProduct(rec); while rec.code <> 0 do begin Write(productsFile, rec); ReadProduct(rec); end; Close(productsFile); end; procedure List(var productsFile: ProductsFileT); var rec: Product; begin Reset(productsFile); while NOT EOF(productsFile) do begin Read(productsFile, rec); if rec.currentStock < rec.minStock then PrintProduct(rec); end; Close(productsFile); end; procedure IncrementProducts(var productsFile: ProductsFileT); var rec: Product; begin Reset(productsFile); while NOT EOF(productsFile) do begin Read(productsFile, rec); if rec.currentStock < rec.minStock then begin Seek(productsFile, filepos(productsFile) - 1); rec.price := rec.price * 0.15; Write(productsFile, rec); end; end; Close(productsFile); end; VAR productsFile: ProductsFileT; fileName: String; option: Byte; BEGIN Write('Enter the file name: '); ReadLn(fileName); Assign(productsFile, fileName); ClrScr; WriteLn('1. Create file'); WriteLn('2. List products with stock under min stock'); WriteLn('3. Increment 15%'); WriteLn(); Write('Option: '); ReadLn(option); case option of 1: CreateAndFillFile(productsFile); 2: List(productsFile); 3: IncrementProducts(productsFile); end; END.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.Scene3D.Renderer; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$m+} interface uses Classes, SysUtils, Math, PasMP, Vulkan, PasVulkan.Types, PasVulkan.Math, PasVulkan.Framework, PasVulkan.Application, PasVulkan.Resources, PasVulkan.FrameGraph, PasVulkan.TimerQuery, PasVulkan.Collections, PasVulkan.CircularDoublyLinkedList, PasVulkan.VirtualReality, PasVulkan.Scene3D, PasVulkan.Scene3D.Renderer.Globals, PasVulkan.Scene3D.Renderer.SMAAData, PasVulkan.Scene3D.Renderer.SkyCubeMap, PasVulkan.Scene3D.Renderer.MipmappedArray2DImage, PasVulkan.Scene3D.Renderer.ImageBasedLighting.EnvMapCubeMaps, PasVulkan.Scene3D.Renderer.Charlie.BRDF, PasVulkan.Scene3D.Renderer.GGX.BRDF, PasVulkan.Scene3D.Renderer.SheenE.BRDF, PasVulkan.Scene3D.Renderer.Lens.Color, PasVulkan.Scene3D.Renderer.Lens.Dirt, PasVulkan.Scene3D.Renderer.Lens.Star; type TpvScene3DRenderer=class; TpvScene3DRendererBaseObject=class; TpvScene3DRendererBaseObjects=class(TpvObjectGenericList<TpvScene3DRendererBaseObject>); TpvScene3DRendererBaseObjectCircularDoublyLinkedListNode=class(TpvCircularDoublyLinkedListNode<TpvScene3DRendererBaseObject>); { TpvScene3DRendererBaseObject } TpvScene3DRendererBaseObject=class private fParent:TpvScene3DRendererBaseObject; fRenderer:TpvScene3DRenderer; fChildrenLock:TPasMPCriticalSection; fChildren:TpvScene3DRendererBaseObjectCircularDoublyLinkedListNode; fOwnCircularDoublyLinkedListNode:TpvScene3DRendererBaseObjectCircularDoublyLinkedListNode; public constructor Create(const aParent:TpvScene3DRendererBaseObject); reintroduce; destructor Destroy; override; procedure AfterConstruction; override; procedure BeforeDestruction; override; published property Parent:TpvScene3DRendererBaseObject read fParent; property Renderer:TpvScene3DRenderer read fRenderer; end; { TpvScene3DRenderer } TpvScene3DRenderer=class(TpvScene3DRendererBaseObject) private fScene3D:TpvScene3D; fVulkanDevice:TpvVulkanDevice; fVulkanPipelineCache:TpvVulkanPipelineCache; fCountInFlightFrames:TpvSizeInt; fAntialiasingMode:TpvScene3DRendererAntialiasingMode; fShadowMode:TpvScene3DRendererShadowMode; fTransparencyMode:TpvScene3DRendererTransparencyMode; fDepthOfFieldMode:TpvScene3DRendererDepthOfFieldMode; fLensMode:TpvScene3DRendererLensMode; fGlobalIlluminatonMode:TpvScene3DRendererGlobalIlluminatonMode; fMinLogLuminance:TpvFloat; fMaxLogLuminance:TpvFloat; fMaxMSAA:TpvInt32; fMaxShadowMSAA:TpvInt32; fShadowMapSize:TpvInt32; fVirtualRealityHUDWidth:TpvInt32; fVirtualRealityHUDHeight:TpvInt32; fBufferDeviceAddress:boolean; fMeshFragTypeName:TpvUTF8String; fMeshFragShadowTypeName:TpvUTF8String; fOptimizedNonAlphaFormat:TVkFormat; fUseDepthPrepass:boolean; fUseDemote:boolean; fUseNoDiscard:boolean; fUseOITAlphaTest:boolean; fShadowMapSampleCountFlagBits:TVkSampleCountFlagBits; fCountCascadedShadowMapMSAASamples:TpvSizeInt; fSurfaceSampleCountFlagBits:TVkSampleCountFlagBits; fCountSurfaceMSAASamples:TpvSizeInt; private fSkyCubeMap:TpvScene3DRendererSkyCubeMap; fGGXBRDF:TpvScene3DRendererGGXBRDF; fCharlieBRDF:TpvScene3DRendererCharlieBRDF; fSheenEBRDF:TpvScene3DRendererSheenEBRDF; fLensColor:TpvScene3DRendererLensColor; fLensDirt:TpvScene3DRendererLensDirt; fLensStar:TpvScene3DRendererLensStar; fImageBasedLightingEnvMapCubeMaps:TpvScene3DRendererImageBasedLightingEnvMapCubeMaps; fShadowMapSampler:TpvVulkanSampler; fGeneralSampler:TpvVulkanSampler; fSSAOSampler:TpvVulkanSampler; fSMAAAreaTexture:TpvVulkanTexture; fSMAASearchTexture:TpvVulkanTexture; fEmptySSAOReflectionProbeTexture:TpvVulkanTexture; { fLensColorTexture:TpvVulkanTexture; fLensDirtTexture:TpvVulkanTexture; fLensStarTexture:TpvVulkanTexture;} fVulkanFlushQueue:TpvVulkanQueue; fVulkanFlushCommandPool:TpvVulkanCommandPool; fVulkanFlushCommandBuffers:array[0..MaxInFlightFrames-1] of TpvVulkanCommandBuffer; fVulkanFlushCommandBufferFences:array[0..MaxInFlightFrames-1] of TpvVulkanFence; fVulkanFlushSemaphores:array[0..MaxInFlightFrames-1] of TpvVulkanSemaphore; public constructor Create(const aScene3D:TpvScene3D;const aVulkanDevice:TpvVulkanDevice=nil;const aVulkanPipelineCache:TpvVulkanPipelineCache=nil;const aCountInFlightFrames:TpvSizeInt=0); reintroduce; destructor Destroy; override; class procedure SetupVulkanDevice(const aVulkanDevice:TpvVulkanDevice); static; class function CheckBufferDeviceAddress(const aVulkanDevice:TpvVulkanDevice):boolean; static; procedure Prepare; procedure AcquirePersistentResources; procedure ReleasePersistentResources; procedure Flush(const aInFlightFrameIndex:TpvInt32;var aWaitSemaphore:TpvVulkanSemaphore;const aWaitFence:TpvVulkanFence=nil); published property Scene3D:TpvScene3D read fScene3D; property VulkanDevice:TpvVulkanDevice read fVulkanDevice; property VulkanPipelineCache:TpvVulkanPipelineCache read fVulkanPipelineCache; property CountInFlightFrames:TpvSizeInt read fCountInFlightFrames; property AntialiasingMode:TpvScene3DRendererAntialiasingMode read fAntialiasingMode write fAntialiasingMode; property ShadowMode:TpvScene3DRendererShadowMode read fShadowMode write fShadowMode; property TransparencyMode:TpvScene3DRendererTransparencyMode read fTransparencyMode write fTransparencyMode; property DepthOfFieldMode:TpvScene3DRendererDepthOfFieldMode read fDepthOfFieldMode write fDepthOfFieldMode; property LensMode:TpvScene3DRendererLensMode read fLensMode write fLensMode; property GlobalIlluminatonMode:TpvScene3DRendererGlobalIlluminatonMode read fGlobalIlluminatonMode write fGlobalIlluminatonMode; property MinLogLuminance:TpvFloat read fMinLogLuminance write fMinLogLuminance; property MaxLogLuminance:TpvFloat read fMaxLogLuminance write fMaxLogLuminance; property MaxMSAA:TpvInt32 read fMaxMSAA write fMaxMSAA; property MaxShadowMSAA:TpvInt32 read fMaxShadowMSAA write fMaxShadowMSAA; property ShadowMapSize:TpvInt32 read fShadowMapSize write fShadowMapSize; property VirtualRealityHUDWidth:TpvInt32 read fVirtualRealityHUDWidth write fVirtualRealityHUDWidth; property VirtualRealityHUDHeight:TpvInt32 read fVirtualRealityHUDHeight write fVirtualRealityHUDHeight; property BufferDeviceAddress:boolean read fBufferDeviceAddress; property MeshFragTypeName:TpvUTF8String read fMeshFragTypeName; property MeshFragShadowTypeName:TpvUTF8String read fMeshFragShadowTypeName; property OptimizedNonAlphaFormat:TVkFormat read fOptimizedNonAlphaFormat; property UseDepthPrepass:boolean read fUseDepthPrepass; property UseDemote:boolean read fUseDemote; property UseNoDiscard:boolean read fUseNoDiscard; property UseOITAlphaTest:boolean read fUseOITAlphaTest; property ShadowMapSampleCountFlagBits:TVkSampleCountFlagBits read fShadowMapSampleCountFlagBits; property CountCascadedShadowMapMSAASamples:TpvSizeInt read fCountCascadedShadowMapMSAASamples; property SurfaceSampleCountFlagBits:TVkSampleCountFlagBits read fSurfaceSampleCountFlagBits; property CountSurfaceMSAASamples:TpvSizeInt read fCountSurfaceMSAASamples; published property SkyCubeMap:TpvScene3DRendererSkyCubeMap read fSkyCubeMap; property GGXBRDF:TpvScene3DRendererGGXBRDF read fGGXBRDF; property CharlieBRDF:TpvScene3DRendererCharlieBRDF read fCharlieBRDF; property SheenEBRDF:TpvScene3DRendererSheenEBRDF read fSheenEBRDF; property LensColor:TpvScene3DRendererLensColor read fLensColor write fLensColor; property LensDirt:TpvScene3DRendererLensDirt read fLensDirt write fLensDirt; property LensStar:TpvScene3DRendererLensStar read fLensStar write fLensStar; property ImageBasedLightingEnvMapCubeMaps:TpvScene3DRendererImageBasedLightingEnvMapCubeMaps read fImageBasedLightingEnvMapCubeMaps; property ShadowMapSampler:TpvVulkanSampler read fShadowMapSampler; property GeneralSampler:TpvVulkanSampler read fGeneralSampler; property SSAOSampler:TpvVulkanSampler read fSSAOSampler; property SMAAAreaTexture:TpvVulkanTexture read fSMAAAreaTexture; property SMAASearchTexture:TpvVulkanTexture read fSMAASearchTexture; property EmptySSAOReflectionProbeTexture:TpvVulkanTexture read fEmptySSAOReflectionProbeTexture; { property LensColorTexture:TpvVulkanTexture read fLensColorTexture; property LensDirtTexture:TpvVulkanTexture read fLensDirtTexture; property LensStarTexture:TpvVulkanTexture read fLensStarTexture;} end; implementation uses PasVulkan.Scene3D.Assets, PasVulkan.Scene3D.Renderer.Instance; { TpvScene3DRendererBaseObject } constructor TpvScene3DRendererBaseObject.Create(const aParent:TpvScene3DRendererBaseObject); begin inherited Create; fParent:=aParent; if assigned(fParent) then begin if fParent is TpvScene3DRenderer then begin fRenderer:=TpvScene3DRenderer(fParent); end else begin fRenderer:=fParent.fRenderer; end; end else begin fRenderer:=nil; end; if self is TpvScene3DRenderer then begin fRenderer:=TpvScene3DRenderer(self); end; fOwnCircularDoublyLinkedListNode:=TpvScene3DRendererBaseObjectCircularDoublyLinkedListNode.Create; fOwnCircularDoublyLinkedListNode.Value:=self; fChildrenLock:=TPasMPCriticalSection.Create; fChildren:=TpvScene3DRendererBaseObjectCircularDoublyLinkedListNode.Create; end; destructor TpvScene3DRendererBaseObject.Destroy; var Child:TpvScene3DRendererBaseObject; begin fChildrenLock.Acquire; try while fChildren.PopFromBack(Child) do begin FreeAndNil(Child); end; finally fChildrenLock.Release; end; FreeAndNil(fChildren); FreeAndNil(fChildrenLock); FreeAndNil(fOwnCircularDoublyLinkedListNode); inherited Destroy; end; procedure TpvScene3DRendererBaseObject.AfterConstruction; begin inherited AfterConstruction; if assigned(fParent) then begin fParent.fChildrenLock.Acquire; try fParent.fChildren.Add(fOwnCircularDoublyLinkedListNode); finally fParent.fChildrenLock.Release; end; end; end; procedure TpvScene3DRendererBaseObject.BeforeDestruction; begin if assigned(fParent) and not fOwnCircularDoublyLinkedListNode.IsEmpty then begin try fParent.fChildrenLock.Acquire; try if not fOwnCircularDoublyLinkedListNode.IsEmpty then begin fOwnCircularDoublyLinkedListNode.Remove; end; finally fParent.fChildrenLock.Release; end; finally fParent:=nil; end; end; inherited BeforeDestruction; end; { TpvScene3DRenderer } constructor TpvScene3DRenderer.Create(const aScene3D:TpvScene3D;const aVulkanDevice:TpvVulkanDevice;const aVulkanPipelineCache:TpvVulkanPipelineCache;const aCountInFlightFrames:TpvSizeInt); var InFlightFrameIndex:TpvSizeInt; begin inherited Create(nil); fScene3D:=aScene3D; if assigned(aVulkanDevice) then begin fVulkanDevice:=aVulkanDevice; end else begin fVulkanDevice:=pvApplication.VulkanDevice; end; if assigned(aVulkanPipelineCache) then begin fVulkanPipelineCache:=aVulkanPipelineCache; end else begin fVulkanPipelineCache:=pvApplication.VulkanPipelineCache; end; if aCountInFlightFrames>0 then begin fCountInFlightFrames:=aCountInFlightFrames; end else begin fCountInFlightFrames:=pvApplication.CountInFlightFrames; end; fAntialiasingMode:=TpvScene3DRendererAntialiasingMode.Auto; fShadowMode:=TpvScene3DRendererShadowMode.Auto; fTransparencyMode:=TpvScene3DRendererTransparencyMode.Auto; fDepthOfFieldMode:=TpvScene3DRendererDepthOfFieldMode.Auto; fLensMode:=TpvScene3DRendererLensMode.Auto; fGlobalIlluminatonMode:=TpvScene3DRendererGlobalIlluminatonMode.Auto; fMinLogLuminance:=-8.0; fMaxLogLuminance:=3.5; fMaxMSAA:=0; fMaxShadowMSAA:=0; fShadowMapSize:=0; fVirtualRealityHUDWidth:=2048; fVirtualRealityHUDHeight:=1152; fVulkanFlushQueue:=Renderer.VulkanDevice.UniversalQueue; fVulkanFlushCommandPool:=TpvVulkanCommandPool.Create(Renderer.VulkanDevice, Renderer.VulkanDevice.UniversalQueueFamilyIndex, TVkCommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT)); for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin fVulkanFlushCommandBuffers[InFlightFrameIndex]:=TpvVulkanCommandBuffer.Create(fVulkanFlushCommandPool,VK_COMMAND_BUFFER_LEVEL_PRIMARY); fVulkanFlushCommandBufferFences[InFlightFrameIndex]:=TpvVulkanFence.Create(Renderer.VulkanDevice); fVulkanFlushSemaphores[InFlightFrameIndex]:=TpvVulkanSemaphore.Create(Renderer.VulkanDevice); end; end; destructor TpvScene3DRenderer.Destroy; var InFlightFrameIndex:TpvSizeInt; begin for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin FreeAndNil(fVulkanFlushCommandBuffers[InFlightFrameIndex]); FreeAndNil(fVulkanFlushCommandBufferFences[InFlightFrameIndex]); FreeAndNil(fVulkanFlushSemaphores[InFlightFrameIndex]); end; FreeAndNil(fVulkanFlushCommandPool); inherited Destroy; end; class procedure TpvScene3DRenderer.SetupVulkanDevice(const aVulkanDevice:TpvVulkanDevice); begin if (aVulkanDevice.PhysicalDevice.DescriptorIndexingFeaturesEXT.descriptorBindingPartiallyBound=VK_FALSE) or (aVulkanDevice.PhysicalDevice.DescriptorIndexingFeaturesEXT.runtimeDescriptorArray=VK_FALSE) or (aVulkanDevice.PhysicalDevice.DescriptorIndexingFeaturesEXT.shaderSampledImageArrayNonUniformIndexing=VK_FALSE) then begin raise EpvApplication.Create('Application','Support for VK_EXT_DESCRIPTOR_INDEXING (descriptorBindingPartiallyBound + runtimeDescriptorArray + shaderSampledImageArrayNonUniformIndexing) is needed',LOG_ERROR); end; {if aVulkanDevice.PhysicalDevice.BufferDeviceAddressFeaturesKHR.bufferDeviceAddress=VK_FALSE then begin raise EpvApplication.Create('Application','Support for VK_KHR_buffer_device_address (bufferDeviceAddress) is needed',LOG_ERROR); end;} if aVulkanDevice.PhysicalDevice.AvailableExtensionNames.IndexOf(VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME)>=0 then begin aVulkanDevice.EnabledExtensionNames.Add(VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME); end; if aVulkanDevice.PhysicalDevice.AvailableExtensionNames.IndexOf(VK_KHR_MAINTENANCE1_EXTENSION_NAME)>=0 then begin aVulkanDevice.EnabledExtensionNames.Add(VK_KHR_MAINTENANCE1_EXTENSION_NAME); end; if aVulkanDevice.PhysicalDevice.AvailableExtensionNames.IndexOf(VK_KHR_MAINTENANCE2_EXTENSION_NAME)>=0 then begin aVulkanDevice.EnabledExtensionNames.Add(VK_KHR_MAINTENANCE2_EXTENSION_NAME); end; if aVulkanDevice.PhysicalDevice.AvailableExtensionNames.IndexOf(VK_KHR_MAINTENANCE3_EXTENSION_NAME)>=0 then begin aVulkanDevice.EnabledExtensionNames.Add(VK_KHR_MAINTENANCE3_EXTENSION_NAME); end; if aVulkanDevice.PhysicalDevice.AvailableExtensionNames.IndexOf(VK_EXT_POST_DEPTH_COVERAGE_EXTENSION_NAME)>=0 then begin aVulkanDevice.EnabledExtensionNames.Add(VK_EXT_POST_DEPTH_COVERAGE_EXTENSION_NAME); end; if aVulkanDevice.PhysicalDevice.AvailableExtensionNames.IndexOf(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME)>=0 then begin aVulkanDevice.EnabledExtensionNames.Add(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME); end; if aVulkanDevice.PhysicalDevice.AvailableExtensionNames.IndexOf(VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME)>=0 then begin aVulkanDevice.EnabledExtensionNames.Add(VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME); end; if aVulkanDevice.PhysicalDevice.AvailableExtensionNames.IndexOf(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME)>=0 then begin aVulkanDevice.EnabledExtensionNames.Add(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME); end; if aVulkanDevice.PhysicalDevice.AvailableExtensionNames.IndexOf(VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME)>=0 then begin aVulkanDevice.EnabledExtensionNames.Add(VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME); end; if aVulkanDevice.PhysicalDevice.AvailableExtensionNames.IndexOf(VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME)>=0 then begin aVulkanDevice.EnabledExtensionNames.Add(VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME); end; if ((aVulkanDevice.Instance.APIVersion and VK_API_VERSION_WITHOUT_PATCH_MASK)<VK_API_VERSION_1_2) and (aVulkanDevice.PhysicalDevice.AvailableExtensionNames.IndexOf(VK_KHR_SPIRV_1_4_EXTENSION_NAME)>=0) then begin aVulkanDevice.EnabledExtensionNames.Add(VK_KHR_SPIRV_1_4_EXTENSION_NAME); end; end; class function TpvScene3DRenderer.CheckBufferDeviceAddress(const aVulkanDevice:TpvVulkanDevice):boolean; begin result:=assigned(aVulkanDevice) and ((aVulkanDevice.PhysicalDevice.BufferDeviceAddressFeaturesKHR.bufferDeviceAddress<>VK_FALSE) and (aVulkanDevice.PhysicalDevice.BufferDeviceAddressFeaturesKHR.bufferDeviceAddressCaptureReplay<>VK_FALSE)); end; procedure TpvScene3DRenderer.Prepare; var SampleCounts:TVkSampleCountFlags; FormatProperties:TVkFormatProperties; begin if fShadowMapSize=0 then begin fShadowMapSize:=512; end; fShadowMapSize:=Max(16,fShadowMapSize); fBufferDeviceAddress:=fScene3D.UseBufferDeviceAddress; if fBufferDeviceAddress then begin fMeshFragTypeName:='matbufref'; end else begin fMeshFragTypeName:='matssbo'; end; FormatProperties:=fVulkanDevice.PhysicalDevice.GetFormatProperties(VK_FORMAT_B10G11R11_UFLOAT_PACK32); if //(fVulkanDevice.PhysicalDevice.Properties.deviceType=VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU) and ((FormatProperties.linearTilingFeatures and (TVkFormatFeatureFlags(VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) or TVkFormatFeatureFlags(VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) or TVkFormatFeatureFlags(VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) or TVkFormatFeatureFlags(VK_FORMAT_FEATURE_TRANSFER_DST_BIT) or TVkFormatFeatureFlags(VK_FORMAT_FEATURE_TRANSFER_SRC_BIT)))=(TVkFormatFeatureFlags(VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) or TVkFormatFeatureFlags(VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) or TVkFormatFeatureFlags(VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) or TVkFormatFeatureFlags(VK_FORMAT_FEATURE_TRANSFER_DST_BIT) or TVkFormatFeatureFlags(VK_FORMAT_FEATURE_TRANSFER_SRC_BIT))) and ((FormatProperties.optimalTilingFeatures and (TVkFormatFeatureFlags(VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) or TVkFormatFeatureFlags(VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) or TVkFormatFeatureFlags(VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) or TVkFormatFeatureFlags(VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) or TVkFormatFeatureFlags(VK_FORMAT_FEATURE_TRANSFER_DST_BIT) or TVkFormatFeatureFlags(VK_FORMAT_FEATURE_TRANSFER_SRC_BIT)))=(TVkFormatFeatureFlags(VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) or TVkFormatFeatureFlags(VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) or TVkFormatFeatureFlags(VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) or TVkFormatFeatureFlags(VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) or TVkFormatFeatureFlags(VK_FORMAT_FEATURE_TRANSFER_DST_BIT) or TVkFormatFeatureFlags(VK_FORMAT_FEATURE_TRANSFER_SRC_BIT))) then begin fOptimizedNonAlphaFormat:=VK_FORMAT_B10G11R11_UFLOAT_PACK32; end else begin fOptimizedNonAlphaFormat:=VK_FORMAT_R16G16B16A16_SFLOAT; end; fOptimizedNonAlphaFormat:=VK_FORMAT_R16G16B16A16_SFLOAT; case TpvVulkanVendorID(fVulkanDevice.PhysicalDevice.Properties.vendorID) of TpvVulkanVendorID.ImgTec, TpvVulkanVendorID.ARM, TpvVulkanVendorID.Qualcomm, TpvVulkanVendorID.Vivante:begin // Tile-based GPUs => Use no depth prepass, as it can be counterproductive for those fUseDepthPrepass:=false; end; else begin // Immediate-based GPUs => Use depth prepass, as for which it can bring an advantage fUseDepthPrepass:=true; end; end; fUseDemote:=fVulkanDevice.PhysicalDevice.ShaderDemoteToHelperInvocation; case TpvVulkanVendorID(fVulkanDevice.PhysicalDevice.Properties.vendorID) of TpvVulkanVendorID.Intel:begin // Workaround for Intel (i)GPUs, which've problems with discarding fragments in 2x2 fragment blocks at alpha-test usage fUseNoDiscard:=not fUseDemote; fUseOITAlphaTest:=true; end; else begin fUseNoDiscard:=false; fUseOITAlphaTest:=false; end; end; if fAntialiasingMode=TpvScene3DRendererAntialiasingMode.Auto then begin case TpvVulkanVendorID(fVulkanDevice.PhysicalDevice.Properties.vendorID) of TpvVulkanVendorID.AMD:begin if fVulkanDevice.PhysicalDevice.Properties.deviceType=VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU then begin fAntialiasingMode:=TpvScene3DRendererAntialiasingMode.FXAA; end else begin fAntialiasingMode:=TpvScene3DRendererAntialiasingMode.SMAA; end; end; TpvVulkanVendorID.NVIDIA:begin if fVulkanDevice.PhysicalDevice.Properties.deviceType=VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU then begin fAntialiasingMode:=TpvScene3DRendererAntialiasingMode.FXAA; end else begin fAntialiasingMode:=TpvScene3DRendererAntialiasingMode.SMAA; end; end; TpvVulkanVendorID.Intel:begin if fVulkanDevice.PhysicalDevice.Properties.deviceType=VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU then begin fAntialiasingMode:=TpvScene3DRendererAntialiasingMode.FXAA; end else begin fAntialiasingMode:=TpvScene3DRendererAntialiasingMode.SMAA; end; end; else begin if fVulkanDevice.PhysicalDevice.Properties.deviceType=VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU then begin fAntialiasingMode:=TpvScene3DRendererAntialiasingMode.DSAA; end else begin fAntialiasingMode:=TpvScene3DRendererAntialiasingMode.FXAA; end; end; end; //fAntialiasingMode:=TpvScene3DRendererAntialiasingMode.TAA; end; SampleCounts:=fVulkanDevice.PhysicalDevice.Properties.limits.framebufferColorSampleCounts and fVulkanDevice.PhysicalDevice.Properties.limits.framebufferDepthSampleCounts and fVulkanDevice.PhysicalDevice.Properties.limits.framebufferStencilSampleCounts; if fMaxShadowMSAA=0 then begin case TpvVulkanVendorID(fVulkanDevice.PhysicalDevice.Properties.vendorID) of TpvVulkanVendorID.AMD:begin fMaxShadowMSAA:=1; end; TpvVulkanVendorID.NVIDIA:begin if fVulkanDevice.PhysicalDevice.Properties.deviceType=VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU then begin fMaxShadowMSAA:=8; end else begin fMaxShadowMSAA:=1; end; end; TpvVulkanVendorID.Intel:begin fMaxShadowMSAA:=1; end; else begin fMaxShadowMSAA:=1; end; end; end; if fMaxMSAA=0 then begin case TpvVulkanVendorID(fVulkanDevice.PhysicalDevice.Properties.vendorID) of TpvVulkanVendorID.AMD:begin fMaxMSAA:=2; end; TpvVulkanVendorID.NVIDIA:begin if fVulkanDevice.PhysicalDevice.Properties.deviceType=VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU then begin fMaxMSAA:=8; end else begin fMaxMSAA:=2; end; end; TpvVulkanVendorID.Intel:begin fMaxMSAA:=2; end; else begin fMaxMSAA:=2; end; end; end; if fShadowMode=TpvScene3DRendererShadowMode.Auto then begin fShadowMode:=TpvScene3DRendererShadowMode.PCF; end; if fShadowMode in [TpvScene3DRendererShadowMode.PCF,TpvScene3DRendererShadowMode.DPCF,TpvScene3DRendererShadowMode.PCSS] then begin fMeshFragShadowTypeName:='pcfpcss'; end else begin fMeshFragShadowTypeName:='msm'; end; if fShadowMode=TpvScene3DRendererShadowMode.MSM then begin if (fMaxShadowMSAA>=64) and ((SampleCounts and TVkSampleCountFlags(VK_SAMPLE_COUNT_64_BIT))<>0) then begin fShadowMapSampleCountFlagBits:=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_64_BIT); fCountCascadedShadowMapMSAASamples:=64; end else if (fMaxShadowMSAA>=32) and ((SampleCounts and TVkSampleCountFlags(VK_SAMPLE_COUNT_32_BIT))<>0) then begin fShadowMapSampleCountFlagBits:=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_32_BIT); fCountCascadedShadowMapMSAASamples:=32; end else if (fMaxShadowMSAA>=16) and ((SampleCounts and TVkSampleCountFlags(VK_SAMPLE_COUNT_16_BIT))<>0) then begin fShadowMapSampleCountFlagBits:=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_16_BIT); fCountCascadedShadowMapMSAASamples:=16; end else if (fMaxShadowMSAA>=8) and ((SampleCounts and TVkSampleCountFlags(VK_SAMPLE_COUNT_8_BIT))<>0) then begin fShadowMapSampleCountFlagBits:=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_8_BIT); fCountCascadedShadowMapMSAASamples:=8; end else if (fMaxShadowMSAA>=4) and ((SampleCounts and TVkSampleCountFlags(VK_SAMPLE_COUNT_4_BIT))<>0) then begin fShadowMapSampleCountFlagBits:=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_4_BIT); fCountCascadedShadowMapMSAASamples:=4; end else if (fMaxShadowMSAA>=2) and ((SampleCounts and TVkSampleCountFlags(VK_SAMPLE_COUNT_2_BIT))<>0) then begin fShadowMapSampleCountFlagBits:=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_2_BIT); fCountCascadedShadowMapMSAASamples:=2; end else begin fShadowMapSampleCountFlagBits:=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT); fCountCascadedShadowMapMSAASamples:=1; end; end else begin fShadowMapSampleCountFlagBits:=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT); fCountCascadedShadowMapMSAASamples:=1; end; if fAntialiasingMode=TpvScene3DRendererAntialiasingMode.MSAA then begin if (fMaxMSAA>=64) and ((SampleCounts and TVkSampleCountFlags(VK_SAMPLE_COUNT_64_BIT))<>0) then begin fSurfaceSampleCountFlagBits:=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_64_BIT); fCountSurfaceMSAASamples:=64; end else if (fMaxMSAA>=32) and ((SampleCounts and TVkSampleCountFlags(VK_SAMPLE_COUNT_32_BIT))<>0) then begin fSurfaceSampleCountFlagBits:=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_32_BIT); fCountSurfaceMSAASamples:=32; end else if (fMaxMSAA>=16) and ((SampleCounts and TVkSampleCountFlags(VK_SAMPLE_COUNT_16_BIT))<>0) then begin fSurfaceSampleCountFlagBits:=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_16_BIT); fCountSurfaceMSAASamples:=16; end else if (fMaxMSAA>=8) and ((SampleCounts and TVkSampleCountFlags(VK_SAMPLE_COUNT_8_BIT))<>0) then begin fSurfaceSampleCountFlagBits:=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_8_BIT); fCountSurfaceMSAASamples:=8; end else if (fMaxMSAA>=4) and ((SampleCounts and TVkSampleCountFlags(VK_SAMPLE_COUNT_4_BIT))<>0) then begin fSurfaceSampleCountFlagBits:=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_4_BIT); fCountSurfaceMSAASamples:=4; end else if (fMaxMSAA>=2) and ((SampleCounts and TVkSampleCountFlags(VK_SAMPLE_COUNT_2_BIT))<>0) then begin fSurfaceSampleCountFlagBits:=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_2_BIT); fCountSurfaceMSAASamples:=2; end else begin fSurfaceSampleCountFlagBits:=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT); fCountSurfaceMSAASamples:=1; fAntialiasingMode:=TpvScene3DRendererAntialiasingMode.FXAA; end; end else begin fSurfaceSampleCountFlagBits:=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT); fCountSurfaceMSAASamples:=1; end; if fTransparencyMode=TpvScene3DRendererTransparencyMode.Auto then begin case TpvVulkanVendorID(fVulkanDevice.PhysicalDevice.Properties.vendorID) of TpvVulkanVendorID.AMD:begin if (fSurfaceSampleCountFlagBits=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT)) and (fVulkanDevice.EnabledExtensionNames.IndexOf(VK_EXT_POST_DEPTH_COVERAGE_EXTENSION_NAME)>0) then begin // >= RDNA, since VK_EXT_post_depth_coverage exists just from RDNA on. fTransparencyMode:=TpvScene3DRendererTransparencyMode.SPINLOCKOIT; end else begin if fVulkanDevice.PhysicalDevice.Properties.deviceType=VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU then begin fTransparencyMode:=TpvScene3DRendererTransparencyMode.WBOIT; end else begin fTransparencyMode:=TpvScene3DRendererTransparencyMode.LOOPOIT; end; end; end; TpvVulkanVendorID.NVIDIA:begin if fVulkanDevice.EnabledExtensionNames.IndexOf(VK_EXT_POST_DEPTH_COVERAGE_EXTENSION_NAME)>0 then begin if (fVulkanDevice.EnabledExtensionNames.IndexOf(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME)>0) and fVulkanDevice.PhysicalDevice.FragmentShaderPixelInterlock and (fCountSurfaceMSAASamples=1) then begin fTransparencyMode:=TpvScene3DRendererTransparencyMode.INTERLOCKOIT; end else begin fTransparencyMode:=TpvScene3DRendererTransparencyMode.SPINLOCKOIT; end; end else begin if fVulkanDevice.PhysicalDevice.Properties.deviceType=VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU then begin fTransparencyMode:=TpvScene3DRendererTransparencyMode.WBOIT; end else begin fTransparencyMode:=TpvScene3DRendererTransparencyMode.MBOIT; end; end; end; TpvVulkanVendorID.Intel:begin if (fSurfaceSampleCountFlagBits=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT)) and (fVulkanDevice.EnabledExtensionNames.IndexOf(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME)>0) and fVulkanDevice.PhysicalDevice.FragmentShaderPixelInterlock then begin fTransparencyMode:=TpvScene3DRendererTransparencyMode.INTERLOCKOIT; end else begin if fVulkanDevice.PhysicalDevice.Properties.deviceType=VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU then begin fTransparencyMode:=TpvScene3DRendererTransparencyMode.WBOIT; end else begin fTransparencyMode:=TpvScene3DRendererTransparencyMode.MBOIT; end; end; end; else begin if fVulkanDevice.PhysicalDevice.Properties.deviceType=VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU then begin fTransparencyMode:=TpvScene3DRendererTransparencyMode.Direct; end else begin fTransparencyMode:=TpvScene3DRendererTransparencyMode.WBOIT; end; end; end; end; if fDepthOfFieldMode=TpvScene3DRendererDepthOfFieldMode.Auto then begin case TpvVulkanVendorID(fVulkanDevice.PhysicalDevice.Properties.vendorID) of TpvVulkanVendorID.AMD:begin if fVulkanDevice.PhysicalDevice.Properties.deviceType=VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU then begin fDepthOfFieldMode:=TpvScene3DRendererDepthOfFieldMode.FullResHexagon; end else begin fDepthOfFieldMode:=TpvScene3DRendererDepthOfFieldMode.HalfResBruteforce; end; end; TpvVulkanVendorID.NVIDIA:begin if fVulkanDevice.PhysicalDevice.Properties.deviceType=VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU then begin fDepthOfFieldMode:=TpvScene3DRendererDepthOfFieldMode.FullResHexagon; end else begin fDepthOfFieldMode:=TpvScene3DRendererDepthOfFieldMode.HalfResBruteforce; end; end; TpvVulkanVendorID.Intel:begin if fVulkanDevice.PhysicalDevice.Properties.deviceType=VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU then begin fDepthOfFieldMode:=TpvScene3DRendererDepthOfFieldMode.None; end else begin fDepthOfFieldMode:=TpvScene3DRendererDepthOfFieldMode.FullResHexagon; end; end; else begin fDepthOfFieldMode:=TpvScene3DRendererDepthOfFieldMode.None; end; end; end; if fLensMode=TpvScene3DRendererLensMode.Auto then begin case TpvVulkanVendorID(fVulkanDevice.PhysicalDevice.Properties.vendorID) of TpvVulkanVendorID.AMD:begin if fVulkanDevice.PhysicalDevice.Properties.deviceType=VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU then begin fLensMode:=TpvScene3DRendererLensMode.DownUpsample; end else begin fLensMode:=TpvScene3DRendererLensMode.DownUpsample; end; end; TpvVulkanVendorID.NVIDIA:begin if fVulkanDevice.PhysicalDevice.Properties.deviceType=VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU then begin fLensMode:=TpvScene3DRendererLensMode.DownUpsample; end else begin fLensMode:=TpvScene3DRendererLensMode.DownUpsample; end; end; TpvVulkanVendorID.Intel:begin if fVulkanDevice.PhysicalDevice.Properties.deviceType=VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU then begin fLensMode:=TpvScene3DRendererLensMode.None; end else begin fLensMode:=TpvScene3DRendererLensMode.DownUpsample; end; end; else begin fLensMode:=TpvScene3DRendererLensMode.None; end; end; end; if fGlobalIlluminatonMode=TpvScene3DRendererGlobalIlluminatonMode.Auto then begin fGlobalIlluminatonMode:=TpvScene3DRendererGlobalIlluminatonMode.StaticEnvironmentMap;//CameraReflectionProbe;// end; end; procedure TpvScene3DRenderer.AcquirePersistentResources; var Stream:TStream; UniversalQueue:TpvVulkanQueue; UniversalCommandPool:TpvVulkanCommandPool; UniversalCommandBuffer:TpvVulkanCommandBuffer; UniversalFence:TpvVulkanFence; EmptySSAOCubeMapTextureData:TpvUInt8DynamicArray; begin fSkyCubeMap:=TpvScene3DRendererSkyCubeMap.Create(fVulkanDevice,fVulkanPipelineCache,fScene3D.PrimaryLightDirection,fOptimizedNonAlphaFormat); fGGXBRDF:=TpvScene3DRendererGGXBRDF.Create(fVulkanDevice,fVulkanPipelineCache); fCharlieBRDF:=TpvScene3DRendererCharlieBRDF.Create(fVulkanDevice,fVulkanPipelineCache); fSheenEBRDF:=TpvScene3DRendererSheenEBRDF.Create(fVulkanDevice,fVulkanPipelineCache); fLensColor:=TpvScene3DRendererLensColor.Create(fVulkanDevice,fVulkanPipelineCache); fLensDirt:=TpvScene3DRendererLensDirt.Create(fVulkanDevice,fVulkanPipelineCache); fLensStar:=TpvScene3DRendererLensStar.Create(fVulkanDevice,fVulkanPipelineCache); fImageBasedLightingEnvMapCubeMaps:=TpvScene3DRendererImageBasedLightingEnvMapCubeMaps.Create(fVulkanDevice,fVulkanPipelineCache,fSkyCubeMap.DescriptorImageInfo,fOptimizedNonAlphaFormat); case fShadowMode of TpvScene3DRendererShadowMode.MSM:begin fShadowMapSampler:=TpvVulkanSampler.Create(fVulkanDevice, TVkFilter.VK_FILTER_LINEAR, TVkFilter.VK_FILTER_LINEAR, TVkSamplerMipmapMode.VK_SAMPLER_MIPMAP_MODE_LINEAR, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, 0.0, false, 0.0, false, VK_COMPARE_OP_ALWAYS, 0.0, 0.0, VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE, false); end; TpvScene3DRendererShadowMode.PCF:begin fShadowMapSampler:=TpvVulkanSampler.Create(fVulkanDevice, TVkFilter.VK_FILTER_LINEAR, TVkFilter.VK_FILTER_LINEAR, TVkSamplerMipmapMode.VK_SAMPLER_MIPMAP_MODE_NEAREST, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, 0.0, false, 0.0, true, VK_COMPARE_OP_GREATER, 0.0, 0.0, VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE, false); end; else begin fShadowMapSampler:=TpvVulkanSampler.Create(fVulkanDevice, TVkFilter.VK_FILTER_NEAREST, TVkFilter.VK_FILTER_NEAREST, TVkSamplerMipmapMode.VK_SAMPLER_MIPMAP_MODE_NEAREST, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, 0.0, false, 0.0, false, VK_COMPARE_OP_ALWAYS, 0.0, 0.0, VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE, false); end; end; fGeneralSampler:=TpvVulkanSampler.Create(fVulkanDevice, TVkFilter.VK_FILTER_LINEAR, TVkFilter.VK_FILTER_LINEAR, TVkSamplerMipmapMode.VK_SAMPLER_MIPMAP_MODE_LINEAR, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, 0.0, false, 0.0, false, VK_COMPARE_OP_ALWAYS, 0.0, 0.0, VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK, false); fSSAOSampler:=TpvVulkanSampler.Create(fVulkanDevice, TVkFilter.VK_FILTER_LINEAR, TVkFilter.VK_FILTER_LINEAR, TVkSamplerMipmapMode.VK_SAMPLER_MIPMAP_MODE_LINEAR, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, 0.0, false, 0.0, false, VK_COMPARE_OP_ALWAYS, 0.0, 0.0, VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE, false); UniversalQueue:=fVulkanDevice.UniversalQueue; try UniversalCommandPool:=TpvVulkanCommandPool.Create(fVulkanDevice, fVulkanDevice.UniversalQueueFamilyIndex, TVkCommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT)); try UniversalCommandBuffer:=TpvVulkanCommandBuffer.Create(UniversalCommandPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY); try UniversalFence:=TpvVulkanFence.Create(fVulkanDevice); try case fAntialiasingMode of TpvScene3DRendererAntialiasingMode.SMAA:begin fSMAAAreaTexture:=TpvVulkanTexture.CreateFromMemory(fVulkanDevice, UniversalQueue, UniversalCommandBuffer, UniversalFence, UniversalQueue, UniversalCommandBuffer, UniversalFence, VK_FORMAT_R8G8_UNORM, VK_SAMPLE_COUNT_1_BIT, PasVulkan.Scene3D.Renderer.SMAAData.AREATEX_WIDTH, PasVulkan.Scene3D.Renderer.SMAAData.AREATEX_HEIGHT, 0, 0, 1, 0, [TpvVulkanTextureUsageFlag.General, TpvVulkanTextureUsageFlag.TransferDst, TpvVulkanTextureUsageFlag.TransferSrc, TpvVulkanTextureUsageFlag.Sampled], @PasVulkan.Scene3D.Renderer.SMAAData.AreaTexBytes[0], PasVulkan.Scene3D.Renderer.SMAAData.AREATEX_SIZE, false, false, 0, true, false); fSMAASearchTexture:=TpvVulkanTexture.CreateFromMemory(fVulkanDevice, UniversalQueue, UniversalCommandBuffer, UniversalFence, UniversalQueue, UniversalCommandBuffer, UniversalFence, VK_FORMAT_R8_UNORM, VK_SAMPLE_COUNT_1_BIT, PasVulkan.Scene3D.Renderer.SMAAData.SEARCHTEX_WIDTH, PasVulkan.Scene3D.Renderer.SMAAData.SEARCHTEX_HEIGHT, 0, 0, 1, 0, [TpvVulkanTextureUsageFlag.General, TpvVulkanTextureUsageFlag.TransferDst, TpvVulkanTextureUsageFlag.TransferSrc, TpvVulkanTextureUsageFlag.Sampled], @PasVulkan.Scene3D.Renderer.SMAAData.SearchTexBytes[0], PasVulkan.Scene3D.Renderer.SMAAData.SEARCHTEX_SIZE, false, false, 0, true, false); end; else begin end; end; EmptySSAOCubeMapTextureData:=nil; try SetLength(EmptySSAOCubeMapTextureData,2048*2048*6); FillChar(EmptySSAOCubeMapTextureData[0],length(EmptySSAOCubeMapTextureData)*SizeOf(TpvUInt8),#$ff); fEmptySSAOReflectionProbeTexture:=TpvVulkanTexture.CreateFromMemory(fVulkanDevice, UniversalQueue, UniversalCommandBuffer, UniversalFence, UniversalQueue, UniversalCommandBuffer, UniversalFence, VK_FORMAT_R8_UNORM, VK_SAMPLE_COUNT_1_BIT, 2048, 2048, 0, 6, 1, 0, [TpvVulkanTextureUsageFlag.General, TpvVulkanTextureUsageFlag.TransferDst, TpvVulkanTextureUsageFlag.TransferSrc, TpvVulkanTextureUsageFlag.Sampled], @EmptySSAOCubeMapTextureData[0], length(EmptySSAOCubeMapTextureData)*SizeOf(TpvUInt8), false, false, 0, true, false); finally EmptySSAOCubeMapTextureData:=nil; end; { case fLensMode of TpvScene3DRendererLensMode.DownUpsample:begin Stream:=TMemoryStream.Create; try Stream.Write(Scene3DLensColorData,Scene3DLensColorDataSize); Stream.Seek(0,soBeginning); fLensColorTexture:=TpvVulkanTexture.CreateFromImage(fVulkanDevice, UniversalQueue, UniversalCommandBuffer, UniversalFence, UniversalQueue, UniversalCommandBuffer, UniversalFence, Stream, false, true, false); fLensColorTexture.WrapModeU:=TpvVulkanTextureWrapMode.ClampToEdge; fLensColorTexture.WrapModeV:=TpvVulkanTextureWrapMode.ClampToEdge; fLensColorTexture.WrapModeW:=TpvVulkanTextureWrapMode.ClampToEdge; fLensColorTexture.UpdateSampler; finally FreeAndNil(Stream); end; Stream:=TMemoryStream.Create; try Stream.Write(Scene3DLensDirtData,Scene3DLensDirtDataSize); Stream.Seek(0,soBeginning); fLensDirtTexture:=TpvVulkanTexture.CreateFromImage(fVulkanDevice, UniversalQueue, UniversalCommandBuffer, UniversalFence, UniversalQueue, UniversalCommandBuffer, UniversalFence, Stream, false, true, false); fLensDirtTexture.WrapModeU:=TpvVulkanTextureWrapMode.ClampToEdge; fLensDirtTexture.WrapModeV:=TpvVulkanTextureWrapMode.ClampToEdge; fLensDirtTexture.WrapModeW:=TpvVulkanTextureWrapMode.ClampToEdge; fLensDirtTexture.UpdateSampler; finally FreeAndNil(Stream); end; Stream:=TMemoryStream.Create; try Stream.Write(Scene3DLensStarData,Scene3DLensStarDataSize); Stream.Seek(0,soBeginning); fLensStarTexture:=TpvVulkanTexture.CreateFromImage(fVulkanDevice, UniversalQueue, UniversalCommandBuffer, UniversalFence, UniversalQueue, UniversalCommandBuffer, UniversalFence, Stream, false, true, false); fLensStarTexture.WrapModeU:=TpvVulkanTextureWrapMode.ClampToEdge; fLensStarTexture.WrapModeV:=TpvVulkanTextureWrapMode.ClampToEdge; fLensStarTexture.WrapModeW:=TpvVulkanTextureWrapMode.ClampToEdge; fLensStarTexture.UpdateSampler; finally FreeAndNil(Stream); end; end; else begin end; end;//} finally FreeAndNil(UniversalFence); end; finally FreeAndNil(UniversalCommandBuffer); end; finally FreeAndNil(UniversalCommandPool); end; finally UniversalQueue:=nil; end; end; procedure TpvScene3DRenderer.ReleasePersistentResources; begin FreeAndNil(fShadowMapSampler); FreeAndNil(fSSAOSampler); FreeAndNil(fGeneralSampler); FreeAndNil(fSMAAAreaTexture); FreeAndNil(fSMAASearchTexture); FreeAndNil(fEmptySSAOReflectionProbeTexture); {FreeAndNil(fLensColorTexture); FreeAndNil(fLensDirtTexture); FreeAndNil(fLensStarTexture);} FreeAndNil(fLensColor); FreeAndNil(fLensDirt); FreeAndNil(fLensStar); FreeAndNil(fCharlieBRDF); FreeAndNil(fGGXBRDF); FreeAndNil(fSheenEBRDF); FreeAndNil(fImageBasedLightingEnvMapCubeMaps); FreeAndNil(fSkyCubeMap); end; procedure TpvScene3DRenderer.Flush(const aInFlightFrameIndex:TpvInt32;var aWaitSemaphore:TpvVulkanSemaphore;const aWaitFence:TpvVulkanFence=nil); begin if fScene3D.NeedFlush(aInFlightFrameIndex) then begin fVulkanFlushCommandBuffers[aInFlightFrameIndex].Reset(TVkCommandBufferResetFlags(VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT)); fVulkanFlushCommandBuffers[aInFlightFrameIndex].BeginRecording; fScene3D.Flush(aInFlightFrameIndex,fVulkanFlushCommandBuffers[aInFlightFrameIndex]); fVulkanFlushCommandBuffers[aInFlightFrameIndex].EndRecording; fVulkanFlushCommandBuffers[aInFlightFrameIndex].Execute(fVulkanFlushQueue, TVkPipelineStageFlags(VK_PIPELINE_STAGE_TRANSFER_BIT) or pvApplication.VulkanDevice.PhysicalDevice.PipelineStageAllShaderBits, aWaitSemaphore, fVulkanFlushSemaphores[aInFlightFrameIndex], aWaitFence, false); aWaitSemaphore:=fVulkanFlushSemaphores[aInFlightFrameIndex]; end; end; end.
unit hxObjectViewerFrame; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, hxBasicViewerFrame, hxHexEditor; type TCheckUserAbortEvent = procedure (Sender:TObject; var Aborted:boolean) of object; TExtractor = class private FHexEditor: THxHexEditor; FOffset: integer; FSize: integer; FTag: integer; FLastResult: boolean; FSignatures: TStringArray; FFileExt: string; FInfo: string; FEmbeddedClass: TClass; FOnCheckUserAbort: TCheckUserAbortEvent; function GetFirstFileExt: String; protected function CreateView({%H-}AOwner: TWinControl; AOffset: Integer; out AInfo: String): TControl; virtual; function FindView(AParent: TWinControl): TControl; procedure HideView(AParent: TWinControl); public constructor Create(AEmbeddedClass: TClass; AFileExt: String; const ASignatures: TStringArray); virtual; function CanExtract(AHexEditor: THxHexEditor; AOffset: integer; out ASize: Integer): boolean; function CheckAndShow(AHexEditor: THxHexEditor; AOffset: integer; AParent: TWinControl): TControl; function ExtractorFilter: String; function Find(AHexEditor: THxHexEditor; AStart, AEnd: integer): integer; procedure Reset; procedure SaveToStream(AStream: TStream); virtual; property FirstFileExt: string read GetFirstFileExt; { class methods } class function CheckSignature(AHexEditor: THxHexEditor; AOffset: Integer; AEmbeddedClass: TClass; const ASignature: String): boolean; virtual; class function FindOffset(AHexEditor: THxHexEditor; AOffset: Integer; AEmbeddedClass: TClass; const ASignatures: TStringArray): Integer; { properties } property Info: string read FInfo; property Signatures: TStringArray read FSignatures; property Size: integer read FSize; property OnCheckUserAbort: TCheckUserAbortEvent read FOnCheckUserAbort write FOnCheckUserAbort; end; TExtractorClass = class of TExtractor; TGraphicExtractor = class(TExtractor) protected class function CheckSignature(AHexEditor: THxHexEditor; AOffset: Integer; AEmbeddedClass: TClass; const ASignature: String): Boolean; override; function CreateInfo(APicture: TPicture): String; virtual; function CreateView(AOwner: TWinControl; AOffset: Integer; out AInfo: String): TControl; override; end; TIconExtractor = class(TExtractor) protected class function CheckSignature(AHexEditor: THxHexEditor; AOffset: Integer; AEmbeddedClass: TClass; const ASignature: String): Boolean; override; function CreateInfo(AIcon: TIcon): String; function CreateView(AOwner: TWinControl; AOffset: Integer; out AInfo: String): TControl; override; end; { ------ } { TObjectViewerFrame } TObjectViewerFrame = class(TBasicViewerFrame) mmoInfo: TMemo; ScrollBox: TScrollBox; Splitter1: TSplitter; private FExtractor: TExtractor; FExtractorControl: TControl; FLockUpdate: Integer; function GetAtObject: Boolean; public destructor Destroy; override; function FindObject(AIndex: Integer; AHexEditor: THxHexEditor; AOffset: Integer): Boolean; procedure UpdateData(AHexEditor: THxHexEditor); override; property AtObject: Boolean read GetAtObject; property Extractor: TExtractor read FExtractor; end; function RegisterExtractor(AClass: TExtractorClass; AEmbeddedClass: TClass; AExt: String; const ASignatures: array of string): integer; overload; function CanExtract(AHexEditor: THxHexEditor; AOffset: Integer): TExtractor; function CreateExtractor(AExt: string): TExtractor; overload; function CreateExtractor(AIndex: Integer): TExtractor; overload; function FindOffsetForExtractor(AIndex: Integer; AHexEditor: THxHexEditor; AOffset: Integer): Integer; function NumExtractors: integer; function RegisteredExtension(AIndex: Integer): String; function RegisteredExtractorSignature(AIndex: Integer): Boolean; implementation {$R *.lfm} uses hxStrings, hxUtils; const PIXEL_FORMATS: array[TPixelFormat] of string = ( 'Device', '1 bit', '4 bit', '8 bit', '15 bit', '16 bit', '24 bit', '32 bit', 'Custom' ); { Extractor list } type TExtractorItem = class FExtractorClass: TExtractorClass; FEmbeddedClass: TClass; FSignatures: TStringArray; FExtensions: String; function CreateExtractor: TExtractor; function FirstExt: String; function MatchesExt(AExt: String): Boolean; end; function TExtractorItem.CreateExtractor: TExtractor; begin Result := FExtractorClass.Create(FEmbeddedClass, FExtensions, FSignatures); end; function TExtractorItem.FirstExt: String; var sa: TStringArray; begin sa := FExtensions.Split('|'); if Length(sa) > 0 then Result := sa[0] else Result := ''; end; function TExtractorItem.MatchesExt(AExt: String): Boolean; var sa: TStringArray; ext: String; begin sa := FExtensions.Split('|'); for ext in sa do if ext = AExt then begin Result := true; exit; end; Result := false; end; { ---- } type TExtractorList = class(TFPList) private function GetItem(AIndex: integer): TExtractorItem; public destructor Destroy; override; property Items[AIndex: integer]: TExtractorItem read GetItem; default; end; var RegisteredExtractors: TExtractorList = nil; destructor TExtractorList.Destroy; var i: integer; begin for i := Count-1 downto 0 do Items[i].Free; inherited Destroy; end; function TExtractorList.GetItem(AIndex: integer): TExtractorItem; begin Result := TExtractorItem(inherited Items[AIndex]); end; { ---------- } function RegisterExtractor(AClass: TExtractorClass; AEmbeddedClass: TClass; AExt: String; const ASignatures: array of String): integer; var item: TExtractorItem; i: Integer; begin item := TExtractorItem.Create; item.FExtractorClass := AClass; item.FEmbeddedClass := AEmbeddedClass; item.FExtensions := AExt; SetLength(item.FSignatures, Length(ASignatures)); for i := 0 to High(ASignatures) do item.FSignatures[i] := ASignatures[i]; Result := RegisteredExtractors.Add(item); end; function CanExtract(AHexEditor: THxHexEditor; AOffset: Integer): TExtractor; var i, j: integer; item: TExtractorItem; begin for i := 0 to RegisteredExtractors.Count-1 do begin item := RegisteredExtractors[i]; for j := 0 to High(item.FSignatures) do if item.FExtractorClass.CheckSignature(AHexEditor, AOffset, item.FEmbeddedClass, item.FSignatures[j]) then begin Result := item.CreateExtractor; exit; end; end; Result := nil; end; function CreateExtractor(AExt: string): TExtractor; var i: integer; item: TExtractorItem; begin if (AExt <> '') then begin while AExt[1] = '.' do Delete(AExt, 1, 1); if AExt = '' then for i := 0 to RegisteredExtractors.Count-1 do begin item := RegisteredExtractors[i]; if item.MatchesExt(AExt) then begin Result := item.CreateExtractor; exit; end; end; end; Result := nil; end; function CreateExtractor(AIndex: Integer): TExtractor; begin if (AIndex >= 0) and (AIndex < RegisteredExtractors.Count) then Result := RegisteredExtractors[AIndex].CreateExtractor else Result := nil; end; function FindOffsetForExtractor(AIndex: Integer; AHexEditor: THxHexEditor; AOffset: Integer): Integer; var item: TExtractorItem; begin item := RegisteredExtractors[AIndex]; Result := item.FExtractorClass.FindOffset(AHexEditor, AOffset, item.FEmbeddedClass, item.FSignatures); end; function NumExtractors: Integer; begin Result := RegisteredExtractors.Count; end; function RegisteredExtension(AIndex: Integer): String; var item: TExtractorItem; begin item := RegisteredExtractors[AIndex]; Result := item.FirstExt; end; function RegisteredExtractorSignature(AIndex: Integer): Boolean; var item: TExtractorItem; begin item := RegisteredExtractors[AIndex]; if Assigned(item) then Result := Length(item.FSignatures) > 0 else Result := false; end; { TExtractor basic class } constructor TExtractor.Create(AEmbeddedClass: TClass; AFileExt: String; const ASignatures: TStringArray); begin inherited Create; FEmbeddedClass := AEmbeddedClass; FSignatures := ASignatures; FFileExt := AFileExt; end; { Checks whether an embedded object exists at the given offset in the HexEditor } function TExtractor.CanExtract(AHexEditor: THxHexEditor; AOffset: integer; out ASize: Integer): Boolean; var C: TControl; P: Integer; lInfo: String; sig: String; found: Boolean; begin Result := false; if Assigned(AHexEditor) and Assigned(AHexEditor.DataStorage) and (AOffset >= 0) then begin found := false; for sig in FSignatures do if CheckSignature(AHexEditor, AOffset, FEmbeddedClass, sig) then begin found := true; break; end; if not found then exit; AHexEditor.Seek(AOffset, soFromBeginning); AHexEditor.DataStorage.Position := AOffset; try P := AHexEditor.GetCursorPos; C := CreateView(nil, AOffset, lInfo); // Moves the stream pos to the end of the object if Assigned(C) then begin ASize := FHexEditor.DataStorage.Position - AOffset; Result := true; end else ASize := -1; finally C.Free; FHexEditor.DataStorage.Position := P; FHexEditor.Seek(P, soFromBeginning); end; end; end; { Possibly an embedded object exists at position "AOffset" of the HexEditor stream. CreateView tries to extract this object. When this is successful a component matching the embedded object is created. If not, the function returns nil. "AOwner" is the Owner (and parent) of the component to be created. MUST BE OVERRIDDEN FOR EVERY EXTRACTOR TYPE. } function TExtractor.CreateView(AOwner: TWinControl; AOffset: Integer; out AInfo: String): TControl; begin Result := nil; AInfo := ''; end; { Main method to be called from outside. Checks wheter an extractable embedded object exists at the "AOffset" of then "AHexEditor". If yes, the viewing component is created which fits to the type of the embedded object; the component is inserted as a child of "AParent". If not, the component is searched in "AParent" and destroyed. The function returns nil in this case. } function TExtractor.CheckAndShow(AHexEditor: THxHexEditor; AOffset: integer; AParent: TWinControl): TControl; var sig: String; found: Boolean; begin Result := nil; FHexEditor := AHexEditor; FOffset := AOffset; if Assigned(FHexEditor) then begin found := false; for sig in FSignatures do if CheckSignature(FHexEditor, FOffset, FEmbeddedClass, sig) then begin found := true; break; end; if not found then exit; try HideView(AParent); Result := CreateView(AParent, FOffset, FInfo); if Assigned(Result) then begin FSize := FHexEditor.DataStorage.Position - FOffset; //FHexEditor.Seek(FOffset, soFromBeginning); // Do not restore old stream pos because this will erase the selection needed by SelectObject Result.Parent := AParent; Result.Tag := FTag; FLastResult := true; exit; end; except FreeAndNil(Result); end; end; FHexEditor := nil; FOffset := -1; FSize := 0; FLastResult := false; if not FLastResult then begin HideView(AParent); if not Assigned(Result) then FLastResult := false; end else Result := FindView(AParent); end; { Checks whether the signature (a specific byte sequence) of the embedded object handled by the Extractor is found at the current offset of the hex editor. Example: The signature of bmp files is "BM" When the function result is true the calling method "CheckAndShow" tries to display the found object (which still may fail). The signature is provided as a parameter when the Extractor is created. MUST BE OVERRIDDEN IF A DIFFERENT CHECKING METHOD IS REQUIRED. } class function TExtractor.CheckSignature(AHexEditor: THxHexEditor; AOffset: Integer; AEmbeddedClass: TClass; const ASignature: String): Boolean; var s: string; n: integer; P: Integer; begin Result := false; n := Length(ASignature); if (n > 0) and Assigned(AHexEditor) and (AOffset >= 0) and (AOffset <= AHexEditor.DataSize - n) then begin SetLength(s, n); AHexEditor.ReadBuffer(s[1], AOffset, n); Result := (ASignature = s); end; end; function TExtractor.ExtractorFilter: String; var sa: TStringArray; i: Integer; begin sa := Lowercase(FFileExt).Split('|'); Result := Format(SExtractorFilterMask, [sa[0], sa[0], sa[0]]); for i := 1 to High(sa) do Result := Result + ';' + Format(SExtractorFilterMask, [sa[i], sa[i], sa[i]]); end; { Searches the signature of the embedded object known to the Extractor in the specified HexEditor between offset positions AStart and AEnd. Returns the offset of the first byte of the embedded object if the search was successful. Otherwise the function returns -1. The user can abort the search (via event "OnCheckUserAbort"), and the function returns -2 in this case. } function TExtractor.Find(AHexEditor: THxHexEditor; AStart, AEnd: Integer): Integer; var p: integer; crs: TCursor; aborted: boolean; s: string; sig: String; begin Result := -1; if AHexEditor = nil then exit; crs := Screen.Cursor; Screen.Cursor := crHourglass; try if (AEnd >= AHexEditor.DataSize) or (AEnd = -1) then AEnd := AHexEditor.DataSize-1; if AStart < 0 then AStart := 0; EnsureOrder(AStart, AEnd); for sig in FSignatures do begin p := AStart; while (p <= AEnd - Length(sig)) and (p <> -1) do begin s := sig; if s <> '' then begin s := AHexEditor.PrepareFindReplaceData(s, false, false); p := AHexEditor.Find(PChar(s), Length(s), p, AEnd, false); if p = -1 then Continue; end; if CheckSignature(AHexEditor, p, FEmbeddedClass, sig) then begin Result := p; exit; end; Application.ProcessMessages; aborted := false; if Assigned(FOnCheckUserAbort) then FOnCheckUserAbort(Self, aborted); if aborted then begin Result := -2; exit; end; inc(p); end; end; finally Screen.Cursor := crs; end; end; class function TExtractor.FindOffset(AHexEditor: THxHexEditor; AOffset: Integer; AEmbeddedClass: TClass; const ASignatures: TStringArray): Integer; var s: String; i: Integer; begin for i := 0 to High(ASignatures) do begin // Prepare and execute search for the embedded object's signature s := AHexEditor.PrepareFindReplaceData(ASignatures[i], false, false); Result := AHexEditor.Find(PChar(s), Length(s), AOffset, AHexEditor.DataSize-1, false); // Found if Result <> -1 then begin if CheckSignature(AHexEditor, Result, AEmbeddedClass, s) then exit; end; end; // No embedded object found Result := -1; end; { Searches for the viewing component of the Extractor in the specified parent. The component has a specific tag ("FTag"). } function TExtractor.FindView(AParent: TWinControl): TControl; var i: integer; begin if Assigned(AParent) then begin for i := 0 to AParent.ControlCount-1 do if AParent.Controls[i].Tag = FTag then begin Result := AParent.Controls[i]; exit; end; end; Result := nil; end; function TExtractor.GetFirstFileExt: String; var sa: TStringArray; begin sa := FFileExt.Split('|'); if Length(sa) > 0 then Result := sa[0] else Result := ''; end; { Checks whether the viewing component of the Extractor already exists inside the specified parent and removes it. } procedure TExtractor.HideView(AParent: TWinControl); var i: integer; C: TControl; begin if Assigned(AParent) then for i := 0 to AParent.ControlCount-1 do begin C := AParent.Controls[i]; if C.Tag = FTag then begin AParent.RemoveControl(C); C.Free; FInfo := ''; FSize := -1; exit; end; end; end; procedure TExtractor.Reset; begin FHexEditor := nil; FOffset := -1; FInfo := ''; end; procedure TExtractor.SaveToStream(AStream: TStream); var P: Integer; begin if Assigned(FHexEditor) then begin P := FHexEditor.DataStorage.Position; try FHexEditor.DataStorage.Position := FOffset; AStream.CopyFrom(FHexEditor.DataStorage, FSize); finally FHexEditor.DataStorage.Position := P; end; end; end; { TGraphicExtractor } class function TGraphicExtractor.CheckSignature(AHexEditor: THxHexEditor; AOffset: Integer; AEmbeddedClass: TClass; const ASignature: String): Boolean; begin Result := inherited CheckSignature(AHexEditor, AOffset, AEmbeddedClass, ASignature); { Do not call GraphicClass.IsStreamFormatSupported because it would usually do nothing more than our CheckSignature. } end; function TGraphicExtractor.CreateView(AOwner: TWinControl; AOffset: Integer; out AInfo: String): TControl; var pic: TPicture; begin pic := TPicture.Create; try FHexEditor.DataStorage.Position := AOffset; pic.LoadFromStream(FHexEditor.DataStorage); Result := TImage.Create(AOwner); with (Result as TImage) do begin Picture.Assign(pic); Align := alClient; Center := true; Proportional := true; AInfo := CreateInfo(pic); end; finally // do not reset the stream position here. Position is needed for size determination. pic.Free; end; end; function TGraphicExtractor.CreateInfo(APicture: TPicture): String; begin Result := Copy(FEmbeddedClass.ClassName, 2, MaxInt) + ' / ' + Format('%d x %d', [APicture.Width, APicture.Height]); if APicture.Graphic is TRasterImage then Result := Result + ' / ' + PIXEL_FORMATS[TRasterImage(APicture.Graphic).PixelFormat]; end; { TIconExtractor } class function TIconExtractor.CheckSignature(AHexEditor: THxHexEditor; AOffset: Integer; AEmbeddedClass: TClass; const ASignature: String): Boolean; type TIconDirectory = packed record Width: Byte; // Image width, 0 means: 256 Height: Byte; // Image height, 0 means: 256 PaletteSize: Byte; // 0 when no palette is used Reserved: byte; // 0 ColorPlanes: Word; // 0 or 1 BitsPerPixel: Word; ImageDataSize: DWord; // Image data size in bytes OffsetToImage: DWord; end; var P: Integer; n, m: Word; i: Integer; directory: TIconDirectory; totalSize: Integer; begin Result := inherited CheckSignature(AHexEditor, AOffset, AEmbeddedClass, ASignature); if Result then begin // Read the icon images directory and do a plausibility check P := AOffset + Length(ASignature); // Read number of images; AHexEditor.ReadBuffer(n, P, 2); if n = 0 then exit(false); n := LEToN(n); totalSize := 0; inc(P, 2); for i := 1 to n do begin AHexEditor.ReadBuffer(directory, P, SizeOf(directory)); if directory.Reserved <> 0 then exit(false); if not (LEToN(directory.BitsPerPixel) in [1, 4, 8, 16, 24, 32]) then exit(false); if not (LEToN(directory.ColorPlanes) in [0, 1]) then exit(false); totalSize := totalSize + LEToN(directory.ImageDataSize); if totalSize > AHexEditor.DataSize then exit(false); if LEToN(directory.OffsetToImage) > totalSize then exit(false); inc(P, SizeOf(directory)); end; end; end; function TIconExtractor.CreateInfo(AIcon: TIcon): String; var L: TStrings; i: Integer; begin L := TStringList.Create; try L.Add('Icon'); for i:=0 to AIcon.Count-1 do begin AIcon.Current := i; L.Add(Format('%d x %d, %s', [AIcon.Width, AIcon.Height, PIXEL_FORMATS[AIcon.PixelFormat]])); end; Result := L.Text; while Result[Length(Result)] in [#13, #10] do Delete(Result, Length(Result), 1); finally AIcon.Current := 0; L.Free; end; end; function TIconExtractor.CreateView(AOwner: TWinControl; AOffset: Integer; out AInfo: String): TControl; var ico: TIcon; i: Integer; begin ico := TIcon.Create; try FHexEditor.DataStorage.Position := AOffset; ico.LoadFromStream(FHexEditor.DataStorage); Result := TImage.Create(AOwner); with (Result as TImage) do begin Picture.Assign(ico); Align := alClient; Center := true; Proportional := true; AInfo := CreateInfo(ico); end; finally FHexEditor.DataStorage.Position := AOffset; ico.Free; end; end; { TObjectViewerFrame } destructor TObjectViewerFrame.Destroy; begin FreeAndNil(FExtractor); inherited; end; function TObjectViewerFrame.FindObject(AIndex: Integer; AHexEditor: THxHexEditor; AOffset: Integer): Boolean; var P: Integer; s: String; begin inherited; P := FindOffsetForExtractor(AIndex, AHexEditor, AOffset); if P >= 0 then begin AHexEditor.Seek(P, soFromBeginning); Result := true; end else begin Result := false; AHexEditor.SelStart := AHexEditor.GetCursorPos; AHexEditor.SelEnd := -1; if P = -1 then s := Format(SObjectNotFound, [RegisteredExtension(AIndex)]) else if P = -2 then s := Format(SExtractorSearchUserAbort, [RegisteredExtension(AIndex)]); MessageDlg(s, mtInformation, [mbOK], 0); end; end; function TObjectViewerFrame.GetAtObject: Boolean; begin Result := Assigned(FExtractorControl); end; procedure TObjectViewerFrame.UpdateData(AHexEditor: THxHexEditor); var P: Integer; begin if FLockUpdate > 0 then exit; P := AHexEditor.GetCursorPos; if (AHexEditor.SelStart > AHexEditor.SelEnd) and (P = AHexEditor.SelStart) then P := AHexEditor.SelEnd; FreeAndNil(FExtractor); FExtractor := CanExtract(AHexEditor, P); // creates a new extractor if FExtractor <> nil then begin FExtractorControl := FExtractor.CheckAndShow(AHexEditor, P, ScrollBox); mmoInfo.Lines.Text := FExtractor.Info; end else begin FreeAndNil(FExtractorControl); //lblInfo.Hide; mmoInfo.Lines.Text := '(no object)'; end; end; initialization RegisteredExtractors := TExtractorList.Create; RegisterExtractor(TGraphicExtractor, TBitmap, 'bmp', ['BM']); RegisterExtractor(TGraphicExtractor, TGifImage, 'gif', ['GIF']); RegisterExtractor(TIconExtractor, TIcon, 'ico', [#0#0#1#0]); RegisterExtractor(TGraphicExtractor, TJpegImage, 'jpg|jpeg|jfe', [#$FF#$D8#$FF#$E0#$00#$10'JFIF'#0, #$FF#$D8#$FF#$E1]); RegisterExtractor(TGraphicExtractor, TPortableAnyMapGraphic, 'pnm|pbm|pgm|ppm', ['P1','P2','P3','P4','P5','P6']); RegisterExtractor(TGraphicExtractor, TPortableNetworkGraphic, 'png', [#137'PNG'#13#10#26#10]); RegisterExtractor(TGraphicExtractor, TTiffImage, 'tif|tiff', ['II'#42#00, 'MM'#00#42]); RegisterExtractor(TGraphicExtractor, TPixMap, 'xpm', ['/* XPM */']); { RegisterRipper(TPcxRipper, rtGraphics, 'PCX', #10, TPcxGraphic); RegisterRipper(TWavRipper, rtMediaPlayer, 'WAV', 'RIFF'); RegisterRipper(TAviRipper, rtMediaPlayer, 'AVI', 'RIFF'); } finalization RegisteredExtractors.Free; end.
unit use1902; { ============================================================ CED 1902 amplifier control module (c) J. Dempster, University of Strathclyde, 1996-98 23/8/98 8/2/01 Updated to function as proper data module ============================================================} interface uses Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, WinProcs,WinTypes ; type TCED1902 = class(TDataModule) private { Private declarations } procedure TransmitLine( const Line : string ) ; function ReceiveLine : string ; public { Public declarations } ComPort : LongInt ; ComHandle : Integer ; InUse : Boolean ; Input : LongInt ; InputName : string[16] ; Gain : LongInt ; GainValue : Single ; HPFilter : LongInt ; HPFilterValue : Single ; LPFilter : LongInt ; LPFilterValue : Single ; NotchFilter : LongInt ; ACCoupled : LongInt ; DCOffset : LongInt ; DCOffsetVMax : single ; OverLapStructure : POverlapped ; function Check1902Error : string ; procedure UpdateAmplifier ; function DCOffsetRange : single ; procedure GetList( Command : string ; Var List : TStringList ) ; function Query( Request : string ) : string ; function OpenLink : Boolean ; procedure CloseLink ; end; var CED1902: TCED1902; implementation {$R *.DFM} uses shared ; { -------------------------------------- Write a line of ASCII text to Com port --------------------------------------} procedure TCED1902.TransmitLine( const Line : string { Text to be sent to Com port } ) ; var i,nC,nWritten : Integer ; xBuf : array[0..258] of char ; Overlapped : POverlapped ; begin { Copy command line to be sent to xMit buffer and and a CR character } nC := Length(Line) ; for i := 1 to nC do xBuf[i-1] := Line[i] ; xBuf[nC] := chr(13) ; Inc(nC) ; Overlapped := Nil ; WriteFile( ComHandle, xBuf, nC, nWritten, Overlapped ) ; if nWRitten <> nC then MessageDlg( ' Error writing to COM port ', mtWarning, [mbOK], 0 ) ; end ; { -------------------------------------- Retrieve error information from 1902 --------------------------------------} function TCED1902.Check1902Error : string ; { Error flag returned } var i,nC : Integer ; xBuf : array[0..258] of char ; Line : string ; begin Line := '?ER;' ; nC := Length(Line) ; for i := 1 to nC do xBuf[i-1] := Line[i] ; xBuf[nC] := chr(13) ; Inc(nC) ; if FileWrite( ComHandle, xBuf, nC ) = nC then begin Result := ReceiveLine ; end else begin Result := ' Error writing to COM port ' ; end ; end ; { ------------------------------------------------------- Read bytes from Com port until a line has been received -------------------------------------------------------} function TCED1902.ReceiveLine : string ; { Return line of bytes received } const TimeOut = 500 ; var Line : string ; rBuf : array[0..1] of char ; NumBytesRead : LongInt ; ComState : TComStat ; PComState : PComStat ; TimeOutTickCount : LongInt ; ComError : Integer ; begin { Set time that ReceiveLine will give up at if a full line has not been received } TimeOutTickCount := GetTickCount + TimeOut ; PComState := @ComState ; Line := '' ; repeat rBuf[0] := ' ' ; { Find out if there are any characters in receive buffer } ClearCommError( ComHandle, ComError, PComState ) ; NumBytesRead := 0 ; if ComState.cbInQue > 0 then begin ReadFile( ComHandle, rBuf, 1, NumBytesRead, OverlapStructure ) ; end ; if NumBytesRead > 0 then begin if (rBuf[0] <> chr(13)) and (rBuf[0]<>chr(10)) then Line := Line + rBuf[0] ; end ; until (rBuf[0] = chr(13)) or (GetTickCount >= TimeOutTickCount) ; Result := Line ; end ; { --------------------------------------------------- Transmit gain/filter settings to CED 1902 amplifier ---------------------------------------------------} procedure TCED1902.UpdateAmplifier ; var OK : Boolean ; begin { Open com link to CED 1902 } OK := OpenLink ; { If open successful, send commands } if OK then begin { Problem Here ?? First command to 1902 getting ignored } TransmitLine(format('IP%d;',[Input])); TransmitLine(format('IP%d;',[Input])); TransmitLine(format('GN%d;',[Gain])); TransmitLine(format('LP%d;',[LPFilter])); TransmitLine(format('HP%d;',[HPFilter])); TransmitLine(format('AC%d;',[ACCoupled])); TransmitLine(format('NF%d;',[NotchFilter])); { Set DC Offset } TransmitLine('OR1;' ); TransmitLine(format('OF%d;',[DCOffset])); TransmitLine('OR1;') ; TransmitLine(format('OF%d;',[DCOffset])); CloseLink ; end ; end ; function TCED1902.OpenLink : Boolean ; var DCB : TDCB ; { Device control block for COM port } CommTimeouts : TCommTimeouts ; begin if ComPort <= 1 then ComPort := 1 ; if ComPort >= 2 then ComPort := 2 ; { Open com port } ComHandle := CreateFile( PCHar(format('COM%d',[CED1902.ComPort])), GENERIC_READ or GENERIC_WRITE, 0, Nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_OVERLAPPED, 0) ; if ComHandle >= 0 then begin { Get current state of COM port and fill device control block } GetCommState( ComHandle, DCB ) ; { Change settings to those required for 1902 } DCB.BaudRate := CBR_9600 ; DCB.ByteSize := 7 ; DCB.Parity := EVENPARITY ; DCB.StopBits := ONESTOPBIT ; { Update COM port } SetCommState( ComHandle, DCB ) ; { Initialise Com port and set size of transmit/receive buffers } SetupComm( ComHandle, 4096, 4096 ) ; { Set Com port timeouts } GetCommTimeouts( ComHandle, CommTimeouts ) ; CommTimeouts.ReadIntervalTimeout := $FFFFFFFF ; CommTimeouts.ReadTotalTimeoutMultiplier := 0 ; CommTimeouts.ReadTotalTimeoutConstant := 0 ; CommTimeouts.WriteTotalTimeoutMultiplier := 0 ; CommTimeouts.WriteTotalTimeoutConstant := 5000 ; SetCommTimeouts( ComHandle, CommTimeouts ) ; Result := True ; end Else Result := False ; end ; procedure TCED1902.CloseLink ; begin CloseHandle( ComHandle ) ; end ; function TCED1902.DCOffsetRange : single ; begin if Input = 1 then Result := 0.0005 else if Input = 2 then Result := 0.5 else if Input = 3 then Result := 0.0005 else if Input = 4 then Result := 0.0005 else if Input = 5 then Result := 0.0001 else Result := 0.0001 ; end ; procedure TCED1902.GetList( Command : string ; { Command requesting list } Var List : TStringList { List of strings returned from 1902 } ) ; var NumItems,i : Integer ; InBuf : string ; begin { Request list of gains } TransmitLine( Command ) ; InBuf := ReceiveLine ; if InBuf = '' then begin TransmitLine( Command ) ; InBuf := ReceiveLine ; end ; { Read list back from 1902 } NumItems := ExtractInt( InBuf ) ; List.Clear ; for i := 0 to NumItems-1 do begin List.Add( ReceiveLine ) ; end ; end ; function TCED1902.Query( Request : string { Request 1902 command string } ) : string ; var InBuf : string ; begin InBuf := '' ; { Request list of gains } TransmitLine( Request ) ; InBuf := ReceiveLine ; if InBuf = '' then begin TransmitLine( Request ) ; InBuf := ReceiveLine ; end ; Result := InBuf ; end ; end.
unit Aurelius.Drivers.IBObjects; {$I Aurelius.inc} interface uses Classes, DB, Variants, Generics.Collections, IB_Components, IB_Access, IBODataset, Aurelius.Drivers.Base, Aurelius.Drivers.Interfaces; type TIBObjectsResultSetAdapter = class(TDriverResultSetAdapter<TIBOQuery>) end; TIBObjectsStatementAdapter = class(TInterfacedObject, IDBStatement) private FIBOQuery: TIBOQuery; public constructor Create(AIBOQuery: TIBOQuery); destructor Destroy; override; procedure SetSQLCommand(SQLCommand: string); procedure SetParams(Params: TEnumerable<TDBParam>); procedure Execute; function ExecuteQuery: IDBResultSet; end; TIBObjectsConnectionAdapter = class(TDriverConnectionAdapter<TIB_Connection>, IDBConnection) private FDefaultTransaction: TIBOTransaction; public constructor Create(AConnection: TIB_Connection; ASQLDialect: string; AOwnsConnection: boolean); override; destructor Destroy; override; procedure Connect; procedure Disconnect; function IsConnected: Boolean; function CreateStatement: IDBStatement; function BeginTransaction: IDBTransaction; function RetrieveSqlDialect: string; override; end; TIBObjectsTransactionAdapter = class(TInterfacedObject, IDBTransaction) private FIBTransaction: TIBOTransaction; FIBDatabase: TIB_Connection; public constructor Create(IBTransaction: TIBOTransaction; IBDatabase: TIB_Connection); destructor Destroy; override; procedure Commit; procedure Rollback; end; implementation uses SysUtils, Aurelius.Drivers.Exceptions, Aurelius.Global.Utils; { TIBObjectsStatementAdapter } constructor TIBObjectsStatementAdapter.Create(AIBOQuery: TIBOQuery); begin FIBOQuery := AIBOQuery; end; destructor TIBObjectsStatementAdapter.Destroy; begin FIBOQuery.Free; inherited; end; procedure TIBObjectsStatementAdapter.Execute; begin if FIBOQuery.IB_Transaction.InTransaction then FIBOQuery.ExecSQL else begin FIBOQuery.IB_Transaction.StartTransaction; try FIBOQuery.ExecSQL; FIBOQuery.IB_Transaction.Commit; except FIBOQuery.IB_Transaction.Rollback; raise; end; end; end; function TIBObjectsStatementAdapter.ExecuteQuery: IDBResultSet; var ResultSet: TIBOQuery; I: Integer; begin ResultSet := TIBOQuery.Create(nil); try ResultSet.IB_Connection := FIBOQuery.IB_Connection; ResultSet.IB_Session := FIBOQuery.IB_Session; ResultSet.SQL.Text := FIBOQuery.SQL.Text; for I := 0 to FIBOQuery.Params.Count - 1 do begin ResultSet.Params[I].DataType := FIBOQuery.Params[I].DataType; ResultSet.Params[I].Value := FIBOQuery.Params[I].Value; end; ResultSet.Open; except ResultSet.Free; raise; end; Result := TIBObjectsResultSetAdapter.Create(ResultSet); end; procedure TIBObjectsStatementAdapter.SetParams(Params: TEnumerable<TDBParam>); var P: TDBParam; Parameter: TParam; Bytes: TBytes; begin for P in Params do begin Parameter := FIBOQuery.ParamByName(P.ParamName); if P.ParamType = ftBlob then begin Bytes := TUtils.VariantToBytes(P.ParamValue); Parameter.DataType := P.ParamType; if VarIsNull(P.ParamValue) or (Length(Bytes) = 0) then Parameter.Clear else Parameter.AsBlob := Bytes; end else begin Parameter.DataType := P.ParamType; Parameter.Value := P.ParamValue; end; // Workaroudn for some unsupported data types if Parameter.DataType = ftWideMemo then Parameter.AsMemo := Parameter.Value; end; end; procedure TIBObjectsStatementAdapter.SetSQLCommand(SQLCommand: string); begin FIBOQuery.SQL.Text := SQLCommand; end; { TIBObjectsConnectionAdapter } destructor TIBObjectsConnectionAdapter.Destroy; begin FDefaultTransaction.Free; inherited; end; procedure TIBObjectsConnectionAdapter.Disconnect; begin if Connection <> nil then Connection.Connected := False; end; function TIBObjectsConnectionAdapter.RetrieveSqlDialect: string; begin if Connection <> nil then Result := 'Interbase' else Result := ''; end; function TIBObjectsConnectionAdapter.IsConnected: Boolean; begin if Connection <> nil then Result := Connection.Connected else Result := false; end; constructor TIBObjectsConnectionAdapter.Create(AConnection: TIB_Connection; ASQLDialect: string; AOwnsConnection: boolean); begin inherited; FDefaultTransaction := TIBOTransaction.Create(nil); FDefaultTransaction.IB_Connection := AConnection; FDefaultTransaction.IB_Session := AConnection.IB_Session; // FDefaultTransaction.AutoStopAction := saCommit; end; function TIBObjectsConnectionAdapter.CreateStatement: IDBStatement; var Statement: TIBOQuery; begin if Connection <> nil then begin Statement := TIBOQuery.Create(nil); try Statement.IB_Connection := Connection; Statement.IB_Transaction := FDefaultTransaction; Statement.IB_Session := Connection.IB_Session; except Statement.Free; raise; end; Result := TIBObjectsStatementAdapter.Create(Statement); end else Result := nil; end; procedure TIBObjectsConnectionAdapter.Connect; begin if Connection <> nil then Connection.Connected := True; end; function TIBObjectsConnectionAdapter.BeginTransaction: IDBTransaction; begin if Connection = nil then Exit(nil); Connection.Connected := true; if not FDefaultTransaction.InTransaction then begin FDefaultTransaction.StartTransaction; Result := TIBObjectsTransactionAdapter.Create(FDefaultTransaction, Connection); end else Result := TIBObjectsTransactionAdapter.Create(nil, Connection); end; { TIBObjectsTransactionAdapter } procedure TIBObjectsTransactionAdapter.Commit; begin if (FIBTransaction = nil) then Exit; FIBTransaction.Commit; end; constructor TIBObjectsTransactionAdapter.Create( IBTransaction: TIBOTransaction; IBDatabase: TIB_Connection); begin FIBTransaction := IBTransaction; FIBDatabase := IBDatabase; end; destructor TIBObjectsTransactionAdapter.Destroy; begin inherited; end; procedure TIBObjectsTransactionAdapter.Rollback; begin if (FIBTransaction = nil) then Exit; FIBTransaction.Rollback; end; end.
// Copyright 2018 The Casbin Authors. All Rights Reserved. // // 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 Tests.Policy.RBACWithDomainsPolicy; interface uses DUnitX.TestFramework, Casbin.Policy.Types; type [TestFixture] TTestPolicyRBACWithDomainsPolicy = class(TObject) private fPolicyManager: IPolicyManager; public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] [TestCase ('Initial.1','admin,domain1,data1,read#true', '#')] [TestCase ('Initial.2','admin,domain2,data2,read#true', '#')] procedure testInitialConditions(const aFilter: string; const aResult: boolean); [Test] procedure testFilteredPolicies; end; implementation uses Casbin.Adapter.Filesystem.Policy, Casbin.Policy, Casbin.Core.Base.Types, System.SysUtils; procedure TTestPolicyRBACWithDomainsPolicy.Setup; begin fPolicyManager:=TPolicyManager.Create ('..\..\..\Examples\Default\rbac_with_domains_policy.csv'); end; procedure TTestPolicyRBACWithDomainsPolicy.TearDown; begin end; procedure TTestPolicyRBACWithDomainsPolicy.testFilteredPolicies; begin fPolicyManager.load(['', 'domain1']); Assert.IsTrue(fPolicyManager.policyExists(['admin','domain1','data1','read']),'1'); Assert.IsFalse(fPolicyManager.policyExists(['admin','domain2','data2','read']),'2'); end; procedure TTestPolicyRBACWithDomainsPolicy.testInitialConditions(const aFilter: string; const aResult: boolean); var filters: TFilterArray; begin filters:=TFilterArray(aFilter.Split([','])); Assert.AreEqual(aResult, fPolicyManager.policyExists(filters)); end; initialization TDUnitX.RegisterTestFixture(TTestPolicyRBACWithDomainsPolicy); end.
unit SQLiteBatchMain; interface procedure ShowUsage; procedure PerformSQLBatch; implementation uses SysUtils, Windows, Classes, SQLite, SQLiteData; var qa,qf:int64; procedure Log(const x:string); var qb:int64; c:cardinal; begin if qf=0 then qb:=GetTickCount else QueryPerformanceCounter(qb); if qf=0 then c:=cardinal(qb)-cardinal(qa) else c:=(qb-qa)*1000 div qf; WriteLn(Format('%8dms %s',[c,x])); end; procedure ShowUsage; begin WriteLn('Usage: SQLiteBatch <database> [-<switches] <script>'); WriteLn('Switches:'); WriteLn(' -T encapsulate in a transaction'); WriteLn(' -X only perform when database file exists'); WriteLn(' -N only perform when database file doesn''t exist'); WriteLn(' -I ignore errors, skip to next ";"'); end; procedure PerformSQLBatch; var db:TSQLiteConnection; px,i,j,k,l,r:integer; fn,s:UTF8String; f:TFileStream; c:cardinal; st:TSQLiteStatement; fExisted,fTrans,fSkip:boolean; fCrit:integer; begin if not QueryPerformanceFrequency(qf) then qf:=0; if qf=0 then qa:=GetTickCount else QueryPerformanceCounter(qa); //defaults fCrit:=0; fTrans:=false; fSkip:=false; fn:=ParamStr(1); fExisted:=FileExists(fn); Log('Connecting to "'+fn+'"...'); db:=TSQLiteConnection.Create(fn); try px:=2; while px<=ParamCount do begin fn:=ParamStr(px); inc(px); if (fn<>'') and (fn[1] in ['-','/']) then begin l:=Length(fn); i:=2; while i<=l do begin case fn[i] of 'T','t':fTrans:=true; 'N','n':fCrit:=1;//only when not fExisted 'X','x':fCrit:=2;//only when fExisted 'I','i':fSkip:=true; else Log('Unknown switch "'+fn[i]+'"'); end; inc(i); end; end else begin case fCrit of 0:;//normal run 1: //N: only if not existed if fExisted then begin Log('Skipping "'+fn+'", database file exists'); fn:=''; end; 2://X: only if existed if not fExisted then begin Log('Skipping "'+fn+'", database file doesn''t exists'); fn:=''; end; //else raise? end; if fn<>'' then begin Log('Performing "'+fn+'"...'); f:=TFileStream.Create(fn,fmOpenRead or fmShareDenyWrite); try //TODO: support UTF-8, UTF-16 c:=f.Size; SetLength(s,c); f.Read(s[1],c); finally f.Free; end; //s:=UTF8Encode(s); //TODO: detect+ignore closing whitespace on trailing ';' if fTrans then db.Execute('BEGIN TRANSACTION'); try j:=0; k:=0; while s<>'' do begin l:=Length(s); try i:=1; st:=TSQLiteStatement.Create(db,s,i); try while (i<l) and (s[i+1]<=' ') do inc(i); { t:=''; for i:=0 to st.FieldCount-1 do t:=t+' '+st.FieldName[i]; i:=0; } //TODO: count EOL's for line indicator? if st.Read then r:=1 else r:=0; //while st.Read do inc(l);? finally st.Free; end; Log(Format('%8d #%8d/%d :%d',[j,k,c,r])); except on e:Exception do if fSkip then begin Log(Format('%8d #%8d/%d !!!',[j,k,c])); WriteLn(ErrOutput,'###'+e.ClassName); WriteLn(ErrOutput,e.Message); //ExitCode:=? //sqlite3_prepare_v2 doesn't update Tail on error //advance ourselves to next ";": while (i<=l) and (s[i]<>';') do if s[i]='''' then begin inc(i); while (i<=l) and (s[i]<>'''') do inc(i); end else inc(i); if (i<=l) then inc(i); while (i<l) and (s[i+1]<=' ') do inc(i); end else raise; end; s:=Copy(s,i+1,l-i); inc(j); inc(k,i); end; if fTrans then db.Execute('COMMIT TRANSACTION'); except if fTrans then db.Execute('ROLLBACK TRANSACTION'); raise; end; end; end; end; finally db.Free; end; end; end.
unit u_mainform; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls, tiQuery, tiQueryXMLLight, Client_AutoMap_Svr, Client_BOM, xml_db , RTTICtrls, Grids, tiBaseMediator, tiFormMediator, tiMediators, tiListMediators; type { TForm1 } TForm1 = class(TForm) btnCreateClient: TButton; btnReadClients: TButton; btnDelete: TButton; lbPhone: TListBox; lbClient: TListBox; sgClients: TStringGrid; sgPhoneNumbers: TStringGrid; procedure btnCreateClientClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnReadClientsClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure lbClientClick(Sender: TObject); procedure sgClientsSelection(Sender: TObject; aCol, aRow: Integer); private { private declarations } MyClientList: TClients; procedure UpdateClients; FMediator: TFormMediator; FPhoneMediator: TFormMediator; procedure SetupMediators; public { public declarations } end; var Form1: TForm1; implementation uses tiObject; { TForm1 } procedure TForm1.FormCreate(Sender: TObject); var XmlDB: TXMLDB; begin XmlDB := TXMLDB.Create; try XmlDB.CreateDatabase('dbxml.xml'); finally XmlDB.Free; end; RegisterMappings; RegisterFallBackMediators; RegisterFallBackListmediators; MyClientList := TClients.Create; MyClientList.Read; Writeln(MyClientList.AsDebugString); { if MyClientList.Count > 0 then ShowMessage('Ci sono diversi clienti');} UpdateClients; SetupMediators; end; procedure TForm1.FormDestroy(Sender: TObject); begin if FPhoneMediator.Active then FPhoneMediator.Active:= False; FMediator.Active:= False; if MyClientList.Dirty then MyClientList.Save; MyClientList.Free; end; procedure TForm1.lbClientClick(Sender: TObject); var i: integer; begin lbPhone.Clear; for i := 0 to MyClientList.Items[lbClient.ItemIndex].PhoneNumbers.Count - 1 do begin lbPhone.Items.Add(MyClientList.Items[lbClient.ItemIndex].PhoneNumbers.Items[i].NumberText); end; end; procedure TForm1.sgClientsSelection(Sender: TObject; aCol, aRow: Integer); var c: TClient; begin c := TClient(TStringGridMediator(FMediator.FindByComponent(sgClients).Mediator).SelectedObject); if Assigned(c) then begin FPhoneMediator.Subject := c.PhoneNumbers; if not FPhoneMediator.Active then FPhoneMediator.Active := True; end; end; procedure TForm1.UpdateClients; var i: integer; begin if MyClientList.Count > 0 then begin lbClient.Clear; for i := 0 to pred(MyClientList.Count) do begin lbClient.Items.Add(MyClientList.Items[i].ClientName); end; end; end; procedure TForm1.SetupMediators; begin if not Assigned(FMediator) then begin FMediator := TFormMediator.Create(self); FMediator.AddComposite('ClientName(150);ClientID(100);OID(36)', sgClients); // FMediator.AddComposite('NumberType(30);NumberText(30)', sgPhoneNumbers); end; FMediator.Subject := MyClientList; FMediator.Active := True; if not Assigned(FPhoneMediator) then begin FPhoneMediator := TFormMediator.Create(self); FPhoneMediator.AddComposite('NumberType(30);NumberText(30)', sgPhoneNumbers); end; // FPhoneMediator.Subject := MyClientList.Items[0].PhoneNumbers; // FPhoneMediator.Active := True; end; procedure TForm1.btnCreateClientClick(Sender: TObject); var MyClient: TClient; myPhoneNumber: TPhoneNumber; begin MyClient := TClient.CreateNew('',''); MyClient.ClientID:='XXXX-YYYY'; MyClient.ClientName:='Antonio'; myPhoneNumber := TPhoneNumber.CreateNew('',''); myPhoneNumber.NumberType:='Telefono-fisso'; myPhoneNumber.NumberText:='0773-723180'; MyClient.PhoneNumbers.Add(myPhoneNumber); myPhoneNumber := TPhoneNumber.CreateNew('',''); myPhoneNumber.NumberType:='Telefono-fisso'; myPhoneNumber.NumberText:='339-8843931'; MyClient.PhoneNumbers.Add(myPhoneNumber); MyClientList.Add(MyClient); MyClient := TClient.CreateNew('',''); MyClient.ClientID:='ZZZZ-WWWW'; MyClient.ClientName:='Simone'; myPhoneNumber := TPhoneNumber.CreateNew('',''); myPhoneNumber.NumberType:='Telefono-fisso'; myPhoneNumber.NumberText:='0773-725052'; MyClient.PhoneNumbers.Add(myPhoneNumber); MyClientList.Add(MyClient); MyClientList.Save; end; procedure TForm1.btnDeleteClick(Sender: TObject); var c: TClient; M: TMediatorView; begin M:=FMediator.FindByComponent(sgClients).Mediator; c := TClient(TStringGridMediator(M).SelectedObject); if Assigned(c) then begin MyClientList.Extract(c); C.Deleted:=True; C.Dirty:=True; C.Save; C.Free; M.ObjectToGui; end; end; procedure TForm1.btnReadClientsClick(Sender: TObject); var i: integer; begin lbClient.Clear; FMediator.Active:=False; FPhoneMediator.Active:=false; MyClientList.Clear; MyClientList.Read; UpdateClients; if MyClientList.Count > 0 then ShowMessage('Ci sono diversi clienti nella lista'); // FMediator.Active:=False; FMediator.Active:=True; FPhoneMediator.Active:= True; WriteLn(MyClientList.AsDebugString); end; initialization {$I u_mainform.lrs} end.
unit uSoftEdit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Types, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uForm, ICSLanguages, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, PngBitBtn, XMLIntf, System.ImageList, Vcl.ImgList, PngImageList, Vcl.Menus, Vcl.ComCtrls, SynEdit; type TfrmSoftEdit = class(TfrmForm) btnOk: TButton; btnCancel: TButton; btnSoftBrowse: TPngBitBtn; lePath: TLabeledEdit; leParams: TLabeledEdit; leName: TLabeledEdit; ImageIcon: TImage; OpenDialog1: TOpenDialog; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; lvProtocols: TListView; SynEditDefaultParams: TSynEdit; procedure FormShow(Sender: TObject); procedure btnSoftBrowseClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure lePathChange(Sender: TObject); private FSoftXMLNode: IXMLNode; FProtocolsXMLNode: IXMLNode; procedure FillControls; procedure SetImageIcon; public procedure ApplyXML; property SoftXMLNode: IXMLNode read FSoftXMLNode write FSoftXMLNode; // property ProtocolsXMLNode: IXMLNode read FProtocolsXMLNode write FProtocolsXMLNode; end; var frmSoftEdit: TfrmSoftEdit; implementation {$R *.dfm} uses ShlObj, uCommonTools, uClasses, uRegLite, uRegistry, uXMLTools; { TfrmSoftEdit } procedure TfrmSoftEdit.ApplyXML; var I: Integer; iNode: IXMLNode; begin xmlSetItemString(FSoftXMLNode.ChildNodes[ND_NAME], ND_PARAM_VALUE, icsB64Encode(leName.Text)); xmlSetItemString(FSoftXMLNode.ChildNodes[ND_PATH], ND_PARAM_VALUE, icsB64Encode(lePath.Text)); xmlSetItemString(FSoftXMLNode.ChildNodes[ND_PARAMS], ND_PARAM_VALUE, icsB64Encode(leParams.Text)); FSoftXMLNode.ChildNodes[ND_PROTOCOLS].ChildNodes.Clear; for I := 0 to lvProtocols.Items.Count - 1 do if lvProtocols.Items[I].Checked then begin iNode := FSoftXMLNode.ChildNodes[ND_PROTOCOLS].AddChild(ND_PROTOCOL); xmlSetItemString(iNode, ND_PARAM_VALUE, lvProtocols.Items[I].SubItems[0]); end; xmlSetItemString(FSoftXMLNode.ChildNodes[ND_DEFAULT_PARAMFILE1], ND_PARAM_VALUE, icsB64Encode(SynEditDefaultParams.Lines.Text)); end; procedure TfrmSoftEdit.btnSoftBrowseClick(Sender: TObject); begin inherited; if FileExists(lePath.Text) then OpenDialog1.InitialDir := ExtractFilePath(lePath.Text) else OpenDialog1.InitialDir := icsGetSpecialFolderLocation(Handle, CSIDL_PROGRAM_FILES); if OpenDialog1.Execute(Self.Handle) then lePath.Text := OpenDialog1.FileName; end; procedure TfrmSoftEdit.SetImageIcon; var FName: String; begin FName := lePath.Text; if not FileExists(FName) then FName := icsGetLongPathName(FName); if FileExists(FName) then ImageIcon.Picture.Icon.Handle := icsGetIconHandleFromFileName(FName, False); end; procedure TfrmSoftEdit.FillControls; var I, J, SubIdx: Integer; iNode: IXMLNode; LI: TListItem; begin leName.Text := icsB64Decode(xmlGetItemString(FSoftXMLNode.ChildNodes[ND_NAME], ND_PARAM_VALUE)); lePath.Text := icsB64Decode(xmlGetItemString(FSoftXMLNode.ChildNodes[ND_PATH], ND_PARAM_VALUE)); SetImageIcon; leParams.Text := icsB64Decode(xmlGetItemString(FSoftXMLNode.ChildNodes[ND_PARAMS], ND_PARAM_VALUE)); lvProtocols.Items.BeginUpdate; try lvProtocols.Items.Clear; for I := 0 to FProtocolsXMLNode.ChildNodes.Count - 1 do begin iNode := FProtocolsXMLNode.ChildNodes[I]; LI := lvProtocols.Items.Add; LI.Caption := icsB64Decode(xmlGetItemString(iNode.ChildNodes[ND_NAME], ND_PARAM_VALUE)); SubIdx := LI.SubItems.Add(xmlGetItemString(iNode, ND_PARAM_ID)); for J := 0 to FSoftXMLNode.ChildNodes[ND_PROTOCOLS].ChildNodes.Count - 1 do if xmlGetItemString(FSoftXMLNode.ChildNodes[ND_PROTOCOLS].ChildNodes[J], ND_PARAM_VALUE) = LI.SubItems[SubIdx] then begin LI.Checked := True; Break; end; end; finally lvProtocols.Items.EndUpdate; end; SynEditDefaultParams.Lines.Text := icsB64Decode(xmlGetItemString(FSoftXMLNode.ChildNodes[ND_DEFAULT_PARAMFILE1], ND_PARAM_VALUE)); end; procedure TfrmSoftEdit.FormCreate(Sender: TObject); begin inherited; FProtocolsXMLNode := FXML.DocumentElement.ChildNodes[ND_PROTOCOLS]; end; procedure TfrmSoftEdit.FormShow(Sender: TObject); begin inherited; FillControls; end; procedure TfrmSoftEdit.lePathChange(Sender: TObject); begin inherited; SetImageIcon; end; end.
unit VisibleDSA.AlgoVisualizer; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, Forms, VisibleDSA.AlgoVisHelper, BGRACanvas2D, VisibleDSA.Circle, VisibleDSA.MonteCarloPiData; type TAlgoVisualizer = class(TObject) private _circle: TCircle; _form: TForm; _count: integer; _data: TMonteCarloPiData; public constructor Create(form: TForm; n: integer); destructor Destroy; override; procedure Paint(canvas: TBGRACanvas2D); procedure Run; end; implementation uses VisibleDSA.AlgoForm; { TAlgoVisualizer } constructor TAlgoVisualizer.Create(form: TForm; n: integer); var x, y, r: integer; begin inherited Create; _form := form; _count := n; if _form.ClientWidth <> _form.ClientHeight then raise Exception.Create('This demo must be run in a square windows.'); x := form.ClientWidth div 2; y := form.ClientHeight div 2; r := form.ClientWidth div 2; _circle := TCircle.Create(x, y, r); _data := TMonteCarloPiData.Create(_circle); end; destructor TAlgoVisualizer.Destroy; begin FreeAndNil(_data); FreeAndNil(_circle); inherited Destroy; end; procedure TAlgoVisualizer.Paint(canvas: TBGRACanvas2D); var p: TPoint; i: integer; begin TAlgoVisHelper.SetStroke(3, CL_BLUE); TAlgoVisHelper.DrawCircle(canvas, _circle.X, _circle.Y, _circle.R); for i := 0 to _data.GetPointNumber - 1 do begin p := _data.GetPoint(i); if _circle.Contain(p) then begin TAlgoVisHelper.SetFill(CL_GREEN); end else begin TAlgoVisHelper.SetFill(CL_RED); end; TAlgoVisHelper.FillCircle(canvas, p.X, p.Y, 1); end; end; procedure TAlgoVisualizer.Run; var x, y, i: integer; begin Randomize; for i := 0 to _count - 1 do begin x := Random(_form.ClientWidth); y := Random(_form.ClientHeight); _data.AddPoint(TPoint.Create(x, y)); Writeln(FloatToStr(_data.EstimatePI)); end; TAlgoVisHelper.Pause(10); AlgoForm.BGRAVirtualScreen.RedrawBitmap; end; end.
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : http://www.webservicex.net/CurrencyConvertor.asmx?WSDL // >Import : http://www.webservicex.net/CurrencyConvertor.asmx?WSDL>0 // Encoding : utf-8 // Version : 1.0 // (20/01/2015 10:38:49 - - $Rev: 25127 $) // ************************************************************************ // unit CurrencyConvertor; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns; const IS_REF = $0080; type // ************************************************************************ // // The following types, referred to in the WSDL document are not being represented // in this file. They are either aliases[@] of other types represented or were referred // to but never[!] declared in the document. The types from the latter category // typically map to predefined/known XML or Embarcadero types; however, they could also // indicate incorrect WSDL documents that failed to declare or import a schema type. // ************************************************************************ // // !:double - "http://www.w3.org/2001/XMLSchema"[Gbl] // !:string - "http://www.w3.org/2001/XMLSchema"[] {$SCOPEDENUMS ON} { "http://www.webserviceX.NET/"[GblSmpl] } Currency = (AFA, ALL, DZD, ARS, AWG, AUD, BSD, BHD, BDT, BBD, BZD, BMD, BTN, BOB, BWP, BRL, GBP, BND, BIF, XOF, XAF, KHR, CAD, CVE, KYD, CLP, CNY, COP, KMF, CRC, HRK, CUP, CYP, CZK, DKK, DJF, DOP, XCD, EGP, SVC, EEK, ETB, EUR, FKP, GMD, GHC, GIP, XAU, GTQ, GNF, GYD, HTG, HNL, HKD, HUF, ISK, INR, IDR, IQD, ILS, JMD, JPY, JOD, KZT, KES, KRW, KWD, LAK, LVL, LBP, LSL, LRD, LYD, LTL, MOP, MKD, MGF, MWK, MYR, MVR, MTL, MRO, MUR, MXN, MDL, MNT, MAD, MZM, MMK, NAD, NPR, ANG, NZD, NIO, NGN, KPW, NOK, OMR, XPF, PKR, XPD, PAB, PGK, PYG, PEN, PHP, XPT, PLN, QAR, ROL, RUB, WST, STD, SAR, SCR, SLL, XAG, SGD, SKK, SIT, SBD, SOS, ZAR, LKR, SHP, SDD, SRG, SZL, SEK, CHF, SYP, TWD, TZS, THB, TOP, TTD, TND, TRL, USD, AED, UGX, UAH, UYU, VUV, VEB, VND, YER, YUM, ZMK, ZWD, TRY_); {$SCOPEDENUMS OFF} double_ = type Double; { "http://www.webserviceX.NET/"[GblElm] } // ************************************************************************ // // Namespace : http://www.webserviceX.NET/ // soapAction: http://www.webserviceX.NET/ConversionRate // transport : http://schemas.xmlsoap.org/soap/http // style : document // binding : CurrencyConvertorSoap12 // service : CurrencyConvertor // port : CurrencyConvertorSoap12 // URL : http://www.webservicex.net/CurrencyConvertor.asmx // ************************************************************************ // CurrencyConvertorSoap = interface(IInvokable) ['{7A5B2A2E-A240-0304-FA58-F86D9AFAA52F}'] function ConversionRate(const FromCurrency: Currency; const ToCurrency: Currency): Double; stdcall; end; // ************************************************************************ // // Namespace : http://www.webserviceX.NET/ // binding : CurrencyConvertorHttpGet // service : CurrencyConvertor // port : CurrencyConvertorHttpGet // ************************************************************************ // CurrencyConvertorHttpGet = interface(IInvokable) ['{44834808-BF25-E8E7-B6F8-2713C082359C}'] function ConversionRate(const FromCurrency: string; const ToCurrency: string): double_; stdcall; end; // ************************************************************************ // // Namespace : http://www.webserviceX.NET/ // binding : CurrencyConvertorHttpPost // service : CurrencyConvertor // port : CurrencyConvertorHttpPost // ************************************************************************ // CurrencyConvertorHttpPost = interface(IInvokable) ['{A7CCBD67-8708-2EFA-72E9-D461EF46582A}'] function ConversionRate(const FromCurrency: string; const ToCurrency: string): double_; stdcall; end; function GetCurrencyConvertorSoap(UseWSDL: Boolean = System.False; Addr: string = ''; HTTPRIO: THTTPRIO = nil): CurrencyConvertorSoap; function GetCurrencyConvertorHttpGet(UseWSDL: Boolean = System.False; Addr: string = ''; HTTPRIO: THTTPRIO = nil): CurrencyConvertorHttpGet; function GetCurrencyConvertorHttpPost(UseWSDL: Boolean = System.False; Addr: string = ''; HTTPRIO: THTTPRIO = nil): CurrencyConvertorHttpPost; implementation uses SysUtils; function GetCurrencyConvertorSoap(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): CurrencyConvertorSoap; const defWSDL = 'http://www.webservicex.net/CurrencyConvertor.asmx?WSDL'; defURL = 'http://www.webservicex.net/CurrencyConvertor.asmx'; defSvc = 'CurrencyConvertor'; defPrt = 'CurrencyConvertorSoap12'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as CurrencyConvertorSoap); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; function GetCurrencyConvertorHttpGet(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): CurrencyConvertorHttpGet; const defWSDL = 'http://www.webservicex.net/CurrencyConvertor.asmx?WSDL'; defURL = ''; defSvc = 'CurrencyConvertor'; defPrt = 'CurrencyConvertorHttpGet'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as CurrencyConvertorHttpGet); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; function GetCurrencyConvertorHttpPost(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): CurrencyConvertorHttpPost; const defWSDL = 'http://www.webservicex.net/CurrencyConvertor.asmx?WSDL'; defURL = ''; defSvc = 'CurrencyConvertor'; defPrt = 'CurrencyConvertorHttpPost'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as CurrencyConvertorHttpPost); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; initialization InvRegistry.RegisterInterface(TypeInfo(CurrencyConvertorSoap), 'http://www.webserviceX.NET/', 'utf-8'); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(CurrencyConvertorSoap), 'http://www.webserviceX.NET/ConversionRate'); InvRegistry.RegisterInvokeOptions(TypeInfo(CurrencyConvertorSoap), ioDocument); InvRegistry.RegisterInvokeOptions(TypeInfo(CurrencyConvertorSoap), ioSOAP12); InvRegistry.RegisterInterface(TypeInfo(CurrencyConvertorHttpGet), 'http://www.webserviceX.NET/', 'utf-8'); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(CurrencyConvertorHttpGet), ''); InvRegistry.RegisterInterface(TypeInfo(CurrencyConvertorHttpPost), 'http://www.webserviceX.NET/', 'utf-8'); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(CurrencyConvertorHttpPost), ''); RemClassRegistry.RegisterXSInfo(TypeInfo(Currency), 'http://www.webserviceX.NET/', 'Currency'); RemClassRegistry.RegisterExternalPropName(TypeInfo(Currency), 'TRY_', 'TRY'); RemClassRegistry.RegisterXSInfo(TypeInfo(double_), 'http://www.webserviceX.NET/', 'double_', 'double'); end.
unit UChannel; interface type TChannel = class strict private FName: string; FDescription: string; public constructor Create(const AName: string); property Name: string read FName write FName; property Description: string read FDescription write FDescription; end; TChannelBroadCast = class(TChannel) const BROADCAST_NAME = 'BROADCAST'; end; implementation constructor TChannel.Create(const AName: string); begin FName := AName; end; end.
unit ImplSwtControls; { ---------------------------------------------------------- Copyright (c) 2008-2015, Electric Power Research Institute, Inc. All rights reserved. ---------------------------------------------------------- } {$WARN SYMBOL_PLATFORM OFF} interface uses ComObj, ActiveX, OpenDSSengine_TLB, StdVcl; type TSwtControls = class(TAutoObject, ISwtControls) protected function Get_Action: ActionCodes; safecall; function Get_AllNames: OleVariant; safecall; function Get_Delay: Double; safecall; function Get_First: Integer; safecall; function Get_IsLocked: WordBool; safecall; function Get_Name: WideString; safecall; function Get_Next: Integer; safecall; function Get_SwitchedObj: WideString; safecall; function Get_SwitchedTerm: Integer; safecall; procedure Set_Action(Value: ActionCodes); safecall; procedure Set_Delay(Value: Double); safecall; procedure Set_IsLocked(Value: WordBool); safecall; procedure Set_Name(const Value: WideString); safecall; procedure Set_SwitchedObj(const Value: WideString); safecall; procedure Set_SwitchedTerm(Value: Integer); safecall; function Get_Count: Integer; safecall; end; implementation uses ComServ, DSSGlobals, Executive, ControlElem, SwtControl, Variants, SysUtils, PointerList; function ActiveSwtControl: TSwtControlObj; begin Result := nil; if ActiveCircuit <> Nil then Result := ActiveCircuit.SwtControls.Active; end; procedure Set_Parameter(const parm: string; const val: string); var cmd: string; begin if not Assigned (ActiveCircuit) then exit; SolutionAbort := FALSE; // Reset for commands entered from outside cmd := Format ('swtcontrol.%s.%s=%s', [ActiveSwtControl.Name, parm, val]); DSSExecutive.Command := cmd; end; function TSwtControls.Get_Action: ActionCodes; var elem: TSwtControlObj; begin Result := dssActionNone; elem := ActiveSwtControl; if elem <> nil then begin Case elem.CurrentAction of CTRL_CLOSE: Result := dssActionClose; CTRL_OPEN: Result := dssActionOpen; End; end; end; function TSwtControls.Get_AllNames: OleVariant; Var elem: TSwtControlObj; lst: TPointerList; k: Integer; Begin Result := VarArrayCreate([0, 0], varOleStr); Result[0] := 'NONE'; IF ActiveCircuit <> Nil THEN WITH ActiveCircuit DO If SwtControls.ListSize > 0 Then Begin lst := SwtControls; Result := VarArrayCreate([0, lst.ListSize-1], varOleStr); k:=0; elem := lst.First; WHILE elem<>Nil DO Begin Result[k] := elem.Name; Inc(k); elem := lst.Next; End; End; end; function TSwtControls.Get_Delay: Double; var elem: TSwtControlObj; begin Result := 0.0; elem := ActiveSwtControl; if elem <> nil then Result := elem.TimeDelay; end; function TSwtControls.Get_First: Integer; Var elem: TSwtControlObj; lst: TPointerList; Begin Result := 0; If ActiveCircuit <> Nil Then begin lst := ActiveCircuit.SwtControls; elem := lst.First; If elem <> Nil Then Begin Repeat If elem.Enabled Then Begin ActiveCircuit.ActiveCktElement := elem; Result := 1; End Else elem := lst.Next; Until (Result = 1) or (elem = nil); End; End; end; function TSwtControls.Get_IsLocked: WordBool; var elem: TSwtControlObj; begin Result := FALSE; elem := ActiveSwtControl; if elem <> nil then Result := elem.IsIsolated; end; function TSwtControls.Get_Name: WideString; var elem: TSwtControlObj; begin Result := ''; elem := ActiveSwtControl; if elem <> nil then Result := elem.Name; end; function TSwtControls.Get_Next: Integer; Var elem: TSwtControlObj; lst: TPointerList; Begin Result := 0; If ActiveCircuit <> Nil Then Begin lst := ActiveCircuit.SwtControls; elem := lst.Next; if elem <> nil then begin Repeat If elem.Enabled Then Begin ActiveCircuit.ActiveCktElement := elem; Result := lst.ActiveIndex; End Else elem := lst.Next; Until (Result > 0) or (elem = nil); End End; end; function TSwtControls.Get_SwitchedObj: WideString; var elem: TSwtControlObj; begin Result := ''; elem := ActiveSwtControl; if elem <> nil then Result := elem.ElementName; end; function TSwtControls.Get_SwitchedTerm: Integer; var elem: TSwtControlObj; begin Result := 0; elem := ActiveSwtControl; if elem <> nil then Result := elem.ElementTerminal; end; procedure TSwtControls.Set_Action(Value: ActionCodes); var elem: TSwtControlObj; begin elem := ActiveSwtControl; if elem <> nil then begin Case Value of dssActionOpen: Set_Parameter('Action', 'o'); dssActionClose: Set_Parameter('Action', 'c'); dssActionReset: begin // Reset means the shelf state Set_Parameter('Lock', 'n'); Set_Parameter('Action', 'c'); end; dssActionLock: Set_Parameter('Lock', 'y'); dssActionUnlock: Set_Parameter('Lock', 'n'); else // TapUp, TapDown, None have no effect End; end; end; procedure TSwtControls.Set_Delay(Value: Double); begin Set_Parameter ('Delay', FloatToStr (Value)); end; procedure TSwtControls.Set_IsLocked(Value: WordBool); begin If Value = TRUE then Set_Parameter ('Lock', 'y') else Set_Parameter ('Lock', 'n'); end; procedure TSwtControls.Set_Name(const Value: WideString); var ActiveSave : Integer; S: String; Found :Boolean; elem: TSwtControlObj; lst: TPointerList; Begin IF ActiveCircuit <> NIL THEN Begin lst := ActiveCircuit.SwtControls; S := Value; // Convert to Pascal String Found := FALSE; ActiveSave := lst.ActiveIndex; elem := lst.First; While elem <> NIL Do Begin IF (CompareText(elem.Name, S) = 0) THEN Begin ActiveCircuit.ActiveCktElement := elem; Found := TRUE; Break; End; elem := lst.Next; End; IF NOT Found THEN Begin DoSimpleMsg('SwtControl "'+S+'" Not Found in Active Circuit.', 5003); elem := lst.Get(ActiveSave); // Restore active Load ActiveCircuit.ActiveCktElement := elem; End; End; end; procedure TSwtControls.Set_SwitchedObj(const Value: WideString); begin Set_Parameter ('SwitchedObj', Value); end; procedure TSwtControls.Set_SwitchedTerm(Value: Integer); begin Set_Parameter ('SwitchedTerm', IntToStr (Value)); end; function TSwtControls.Get_Count: Integer; begin If Assigned(ActiveCircuit) Then Result := ActiveCircuit.SwtControls.ListSize; end; initialization TAutoObjectFactory.Create(ComServer, TSwtControls, Class_SwtControls, ciInternal, tmApartment); end.
unit FileMapping; {$MODE Delphi} { Wrapper class for filemapping version 0.1: Only supports opening of exisiting files and no appending version 0.2: copy on write, you can now write to it without actually messing up the file } interface uses {$ifdef darwin} macport, {$endif} {$ifdef windows} windows, {$endif} LCLIntf,classes,SysUtils; type EFileMapError=class(Exception); TFileMapping=class private FileHandle: THandle; FileMapping: THandle; FFileContent: pointer; FFileSize: Qword; FFilename: string; public property fileContent: pointer read FFileContent; property filesize: qword read FFileSize; property filename: string read FFilename; constructor create(filename: string); destructor destroy; override; end; implementation //function GetFileSize(hFile:HANDLE; lpFileSizeHigh:LPDWORD):DWORD; external 'kernel32' name 'GetFileSize'; resourcestring rsDoesNotExist = '%s does not exist'; rsMappingFailed = 'Mapping failed'; rsFailedCreatingAProperView = 'Failed creating a proper view'; destructor TFileMapping.destroy; begin //clean up the mapping if FFileContent<>nil then UnmapViewOfFile(FFileContent); if FileMapping<>0 then CloseHandle(FileMapping); if FileHandle<>0 then CloseHandle(FileHandle); inherited destroy; end; constructor TFileMapping.create(filename: string); begin inherited create; try //open file FileHandle := CreateFile(PChar(filename), GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (FileHandle = 0) or (FileHandle=INVALID_HANDLE_VALUE) then FileHandle := CreateFile(PChar(filename), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (FileHandle = 0) or (FileHandle=INVALID_HANDLE_VALUE) then raise EFileMapError.create(Format(rsDoesNotExist, [filename])); FFileSize:=0; FFileSize:=GetFileSize(FileHandle,pointer(ptruint(@fileSize)+4)); if FFileSize=0 then raise EFileMapError.create('Can not map an empty file'); //still here, so create filemapping FileMapping := CreateFileMapping(FileHandle, nil, PAGE_WRITECOPY , 0, 0, nil); if (FileMapping = 0) or (FileMapping=INVALID_HANDLE_VALUE) then raise EFileMapError.create(rsMappingFailed); //map it completely FFileContent:= MapViewOfFile(FileMapping, FILE_MAP_COPY , 0, 0, 0); if FFileContent=nil then raise EFileMapError.Create(rsFailedCreatingAProperView); ffilename:=filename; except on e: exception do begin if (FileMapping<>0) and (filemapping<>INVALID_HANDLE_VALUE) then CloseHandle(FileMapping); if (FileHandle<>0) and (FileHandle<>INVALID_HANDLE_VALUE) then CloseHandle(FileHandle); raise EFileMapError.create(e.message); end; end; end; end.
unit ucCOMANDO; // mComando { gerar comando DML (insert, update, delete) } interface uses Classes, SysUtils, StrUtils; type TmComando = class public class function getExistsCmd(pEntidade, pMetadata, pValues : String; pParams : String = '') : String; class function getFuncaoCmd(pEntidade, pMetadata, pValues, pParams: String): String; class function getInsertCmd(pEntidade, pMetadata, pValues : String; pParams : String = '') : String; class function getUpdateCmd(pEntidade, pMetadata, pValues : String; pParams : String = '') : String; class function getDeleteCmd(pEntidade, pMetadata, pValues : String; pParams : String = '') : String; end; implementation uses // ucPARAMINI, ucVALUE, ucLOGCONF, ucMETADATA, ucFUNCAO, ucITEM; const cEXISTS = 'select count(*) as TOTAL from <ENTIDADE> /*WHERE*/ '; cFUNCAO = 'select <FUNCAO> from <ENTIDADE> /*WHERE*/ '; cINSERT = 'insert into <ENTIDADE> (<FIELDS>) values (<VALUES>) '; cUPDATE = 'update <ENTIDADE> set <CAMPOS> /*WHERE*/ '; cDELETE = 'delete from <ENTIDADE> /*WHERE*/ '; var gTpDatabase, gEntidade, gMetadata, gLstTip, gValues : String; gInUpdateDb, gInWhereVal : Boolean; procedure setParams(pEntidade, pMetadata, pValues, pParams: String); begin gTpDatabase := IfNullS(item('TIPO_DATABASE', pParams), LerIni('TP_DATABASE')); gEntidade := pEntidade; gMetadata := pMetadata; gValues := pValues; gLstTip := TcMETADATA.getMetadataXml(pMetadata, 'tip'); gInUpdateDb := itemB('IN_UPDATEDB', pParams); gInWhereVal := itemB('IN_WHEREVAL', pParams); // TmDataSet.SelectFun() end; function getFiltro(pCpo, pVal : String) : String; begin Result := ''; putitem(Result, 'TIPO_DATABASE', gTpDatabase); putitem(Result, 'CD_CAMPO', pCpo); putitem(Result, 'TP_DADO', item(pCpo, gLstTip)); putitem(Result, 'VL_CAMPO', pVal); //Result := TmValue.GetFiltro(Result); end; function getValue(pCpo, pVal : String) : String; begin Result := ''; putitem(Result, 'TIPO_DATABASE', gTpDatabase); putitem(Result, 'CD_CAMPO', pCpo); putitem(Result, 'TP_DADO', item(pCpo, gLstTip)); putitem(Result, 'VL_CAMPO', pVal); //Result := TmValue.GetValue(Result); end; // insert function getFields() : String; var vLstCod, vCod : String; begin Result := ''; vLstCod := listCd(gValues); if (vLstCod = '') then Exit; repeat vCod := getitem(vLstCod); delitem(vLstCod); Result := Result + IfThen(Result<>'',', ') + vCod; until (vLstCod = ''); end; // insert function getValues() : String; var vLstCod, vCod, vVal : String; begin Result := ''; vLstCod := listCd(gValues); if (vLstCod = '') then Exit; repeat vCod := getitem(vLstCod); delitem(vLstCod); vVal := item(vCod, gValues); vVal := getValue(vCod, vVal); Result := Result + IfThen(Result<>'',', ') + vVal; until (vLstCod = ''); end; // exists / update / delete function getWhere() : String; var vLstKey, vLstCod, vCod, vVal : String; begin Result := ''; vLstCod := listCd(gValues); if (vLstCod = '') then Exit; vLstKey := IfThen(gInWhereVal, vLstCod, TcMETADATA.getMetadataXml(gMetadata, 'key')); repeat vCod := getitem(vLstCod); delitem(vLstCod); vVal := item(vCod, gValues); if (Pos(vCod, vLstKey) > 0) then begin vVal := getFiltro(vCod, vVal); Result := Result + IfThen(Result<>'','and ', 'where /*WHERE*/ ') + vVal + ' '; end; until (vLstCod = ''); end; // update function getCampos() : String; var vLstKey, vLstCod, vCod, vVal : String; begin Result := ''; vLstCod := listCd(gValues); if (vLstCod = '') then Exit; vLstKey := TcMETADATA.getMetadataXml(gMetadata, 'key'); repeat vCod := getitem(vLstCod); delitem(vLstCod); if (Pos(vCod, vLstKey) = 0) then begin vVal := item(vCod, gValues); if (gInUpdateDb = False) then begin vVal := getValue(vCod, vVal); end; Result := Result + IfThen(Result<>'',', ') + vCod + '=' + vVal + ' '; end; until (vLstCod = ''); end; // funcao function getFuncao(pParams : String) : String; var vLstFun, vFun, vVal : String; begin vLstFun := listCd(pParams); if (vLstFun = '') then Exit; repeat vFun := getitem(vLstFun); delitem(vLstFun); vVal := item(vFun, pParams); Result := Result + IfThen(Result<>'',', ') + vVal + ' as ' + vFun + ' '; until (vLstFun = ''); end; { TmComando } class function TmComando.getExistsCmd(pEntidade, pMetadata, pValues, pParams: String): String; begin setParams(pEntidade, pMetadata, pValues, pParams); Result := cEXISTS; Result := ReplaceStr(Result, '<ENTIDADE>', pEntidade); Result := ReplaceStr(Result, '/*WHERE*/', getWhere()); //TmLogConf.mensagem(tpGravarLogSql, 'pSql: ' + Result); end; class function TmComando.getFuncaoCmd(pEntidade, pMetadata, pValues, pParams: String): String; begin setParams(pEntidade, pMetadata, pValues, pParams); gInWhereVal := True; Result := cFUNCAO; Result := ReplaceStr(Result, '<ENTIDADE>', pEntidade); Result := ReplaceStr(Result, '<FUNCAO>', getFuncao(pParams)); Result := ReplaceStr(Result, '/*WHERE*/', getWhere()); //TmLogConf.mensagem(tpGravarLogSql, 'pSql: ' + Result); end; class function TmComando.getInsertCmd(pEntidade, pMetadata, pValues, pParams: String): String; begin setParams(pEntidade, pMetadata, pValues, pParams); Result := cINSERT; Result := ReplaceStr(Result, '<ENTIDADE>', pEntidade); Result := ReplaceStr(Result, '<FIELDS>', getFields()); Result := ReplaceStr(Result, '<VALUES>', getValues()); //TmLogConf.mensagem(tpGravarLogSql, 'pSql: ' + Result); end; class function TmComando.getUpdateCmd(pEntidade, pMetadata, pValues, pParams: String): String; begin setParams(pEntidade, pMetadata, pValues, pParams); Result := cUPDATE; Result := ReplaceStr(Result, '<ENTIDADE>', pEntidade); Result := ReplaceStr(Result, '<CAMPOS>', GetCampos()); Result := ReplaceStr(Result, '/*WHERE*/', getWhere()); //TmLogConf.mensagem(tpGravarLogSql, 'pSql: ' + Result); end; class function TmComando.getDeleteCmd(pEntidade, pMetadata, pValues, pParams: String): String; begin setParams(pEntidade, pMetadata, pValues, pParams); Result := cDELETE; Result := ReplaceStr(Result, '<ENTIDADE>', pEntidade); Result := ReplaceStr(Result, '/*WHERE*/', getWhere()); //TmLogConf.mensagem(tpGravarLogSql, 'pSql: ' + Result); end; end.
unit Principal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ActnList, CalculoOperacoes, System.Actions; type TFormPrincipal = class(TForm) EditValorEsquerda: TEdit; EditValorDireita: TEdit; EditResultado: TEdit; ButtonAdicao: TButton; ActionListCalculadora: TActionList; ActionAdicao: TAction; Label1: TLabel; LabelOperacao: TLabel; ButtonSubtracao: TButton; ActionSubtracao: TAction; ActionMultiplicacao: TAction; ButtonMultiplicacao: TButton; ButtonDivisao: TButton; ActionDivisao: TAction; procedure ActionDivisaoExecute(Sender: TObject); procedure ActionMultiplicacaoExecute(Sender: TObject); procedure ActionSubtracaoExecute(Sender: TObject); procedure ActionAdicaoExecute(Sender: TObject); private FCalculo: TDmCalculoOperacoes; function ObterValor(Edit: TEdit): Extended; public constructor Create(AOwner: TComponent); override; end; var FormPrincipal: TFormPrincipal; implementation {$R *.dfm} constructor TFormPrincipal.Create(AOwner: TComponent); begin inherited; FCalculo := TDmCalculoOperacoes.Create(AOwner); end; procedure TFormPrincipal.ActionDivisaoExecute(Sender: TObject); var VE, VD: Extended; begin LabelOperacao.Caption := '/'; VE := ObterValor(EditValorEsquerda); VD := ObterValor(EditValorDireita); EditResultado.Text := Format('%8.5f', [FCalculo.Dividir(VE, VD)]) end; procedure TFormPrincipal.ActionMultiplicacaoExecute(Sender: TObject); var VD, VE: Extended; begin LabelOperacao.Caption := '*'; VE := ObterValor(EditValorEsquerda); VD := ObterValor(EditValorDireita); EditResultado.Text := Format('%8.5f', [FCalculo.Multiplicar(VE, VD)]) end; procedure TFormPrincipal.ActionSubtracaoExecute(Sender: TObject); var VD, VE: Extended; begin LabelOperacao.Caption := '-'; VE := ObterValor(EditValorEsquerda); VD := ObterValor(EditValorDireita); EditResultado.Text := Format('%8.5f', [FCalculo.Subtrair(VE, VD)]) end; procedure TFormPrincipal.ActionAdicaoExecute(Sender: TObject); var VD, VE: Extended; begin LabelOperacao.Caption := '+'; VE := ObterValor(EditValorEsquerda); VD := ObterValor(EditValorDireita); EditResultado.Text := Format('%8.5f', [FCalculo.Somar(VE, VD)]) end; function TFormPrincipal.ObterValor(Edit: TEdit): Extended; begin Edit.Text := StringReplace(Edit.Text, '.', ',', [rfReplaceAll]); Result := StrToFloat(Edit.Text); end; end.
unit QuestionClass; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms, Math, Character; type TQuestion = Class private QTopic : String[30]; QSubTopic : String[30]; QQuestion : String; QCorrectAnswer : String; function ExpandBinomial (Binomial : String) : String; function GenerateAlgebraicFraction : String; function AddAlgebraicFractions (Equation1, Equation2 : String) : String; function GenerateVector : String; function GetMagnitudeOfVector (Vector : String) : String; function VectorScalarProduct (VectorA, VectorB : String) : String; function VectorAngleBetween (VectorA, VectorB : String) : String; function VectorThirdConnector (VectorA, VectorB : String) : String; function DifferentiateAToTheX (Equation : String) : String; function DifferentiateEToTheX (Equation : String) : String; function IntegrationEToTheX (Equation : String) : String; function IntegrationReciprocal (Equation : String) : String; function GenerateEquation(Constant, Linear, Quadratic, Cubic, Fraction, Trig, AdvancedTrig, Log, E, AToTheX : Boolean) : String; procedure GenerateParametricToCartesianQuestion; procedure GenerateIterationQuestion; public constructor Create(TheTopic: string; TheSubTopic: string); function GetTopic : String; function GetSubTopic : String; procedure SetTopic (NewTopic : String); procedure SetSubTopic (NewSubTopic : String); procedure SetQuestion (NewQuestion : String); procedure SetCorrectAnswer (NewCorrectAnswer : String); property Topic : String read GetTopic write SetTopic; property SubTopic : String read GetSubTopic write SetSubTopic; property Question : String read QQuestion write SetQuestion; property CorrectAnswer : String read QCorrectAnswer write SetCorrectAnswer; End; function ValueOfFunction (FunctionString : String; XValue : Real) : Real; procedure ShowMathsText (Text : String; X, Y, GapWidth : Integer; Canvas : TCanvas); procedure ClearCanvas (Form : TForm); implementation function ValueOfFunction(FunctionString : String; XValue : Real) : Real; var WorkingValue : Real; Count, ConstantCount, Coeff, Power : Integer; Constant : String; begin // Initialise WorkingValue := 0; // Go through all of the function to find unknown parameters for Count := 1 to Length(FunctionString) do begin // x is found - find power, coefficient and calculate with value of x if LowerCase(FunctionString[Count]) = 'x' then begin try Coeff := StrToInt(FunctionString[Count - 1]); if FunctionString[Count - 2] = '-' then Coeff := -Coeff; except Coeff := 1; end; Power := 0; try if FunctionString[Count + 1] = '^' then begin if FunctionString[Count + 2] = '{' then Power := StrToInt(FunctionString[Count + 3]) else Power := StrToInt(FunctionString[Count + 2]); end; except Power := 1; end; if Power = 3 then WorkingValue := WorkingValue + (Coeff * XValue * XValue * XValue) else if Power = 2 then WorkingValue := WorkingValue + (Coeff * XValue * XValue) else if Power = 1 then WorkingValue := WorkingValue + (Coeff * XValue); end // + is found, the next term will be positive else if FunctionString[Count] = '+' then begin ConstantCount := Count + 1; Constant := ''; // Get x coefficient and power and calculate term value repeat if LowerCase(FunctionString[ConstantCount]) = 'x' then Constant := '' else Constant := Constant + FunctionString[ConstantCount]; ConstantCount := ConstantCount + 1; until (Not(LowerCase(FunctionString[ConstantCount]) = 'x') and Not CharInSet(FunctionString[ConstantCount], ['0'..'9'])) or (ConstantCount > Length(FunctionString)); if Constant <> '' then WorkingValue := WorkingValue + StrToInt(Constant); end // - is found, the next term will be negative else if FunctionString[Count] = '-' then begin ConstantCount := Count + 1; Constant := ''; // Get x coefficient and power and calculate term value (with negative) repeat if LowerCase(FunctionString[ConstantCount]) = 'x' then Constant := '' else Constant := Constant + FunctionString[ConstantCount]; ConstantCount := ConstantCount + 1; until (Not(LowerCase(FunctionString[ConstantCount]) = 'x') and Not CharInSet(FunctionString[ConstantCount], ['0'..'9'])) or (ConstantCount > Length(FunctionString)); if Constant <> '' then WorkingValue := WorkingValue - StrToInt(Constant); end; end; Result := WorkingValue; end; function TQuestion.ExpandBinomial (Binomial : String) : String; var Constant, Power : Integer; Expansion : String; begin Constant := StrToInt(Binomial[4]); Power := StrToInt(Binomial[9]); Expansion := '1+'; Expansion := Expansion + IntToStr(Constant * Power) + 'x+'; Expansion := Expansion + IntToStr(Power * (Power - 1) * Sqr(Constant) DIV 2) + 'x^{2}+'; Expansion := Expansion + IntToStr(Power * (Power - 1) * (Power - 2) * (Constant * Constant * Constant) DIV 6) + 'x^{3}'; Result := Expansion; end; function TQuestion.GenerateAlgebraicFraction : String; var Fraction : String; begin Fraction := '\frac{'; Fraction := Fraction + IntToStr(Random(8) + 2); Fraction := Fraction + '}{'; Fraction := Fraction + 'x+' + IntToStr(Random(8) + 2); Fraction := Fraction + '}'; Result := Fraction; end; function TQuestion.AddAlgebraicFractions(Equation1, Equation2 : String) : String; var A, B, C, D : Integer; Sum : String; begin // Split coeffs and constants --- \frac{ax+b}{cx+d} --- \frac{ex+f}{gx+h} A := StrToInt(Equation1[7]); B := StrToInt(Equation1[12]); C := StrToInt(Equation2[7]); D := StrToInt(Equation2[12]); // Rewrite answer Sum := '\frac{' + IntToStr(A + C) + 'x+' + IntToStr(A*D + B*C) + '}{(x+' + IntToStr(B) + ')(x+' + IntToStr(D) + ')}'; Result := Sum; end; function TQuestion.GenerateVector : String; var ICoeff, JCoeff : Integer; begin repeat ICoeff := Random(19) - 9; until (ICoeff < -1) or (ICoeff > 1); repeat JCoeff := Random(19) - 9; until (JCoeff < -1) or (JCoeff > 1); if JCoeff > 0 then Result := IntToStr(ICoeff) + 'i+' + IntToStr(JCoeff) + 'j' else Result := IntToStr(ICoeff) + 'i' + IntToStr(JCoeff) + 'j'; end; function TQuestion.GetMagnitudeOfVector (Vector : String) : String; var ICoeff, JCoeff, SquaredMagnitude : Integer; begin // Split vector into coefficients of i and j if Vector[1] = '-' then begin ICoeff := StrToInt('-' + Vector[2]); JCoeff := StrToInt(Vector[5]); end else begin ICoeff := StrToInt(Vector[1]); JCoeff := StrToInt(Vector[4]); end; // Calculate magnitude SquaredMagnitude := Sqr(ICoeff) + Sqr(JCoeff); if SquaredMagnitude = 4 then Result := '2' else if SquaredMagnitude = 9 then Result := '3' else if SquaredMagnitude = 16 then Result := '4' else if SquaredMagnitude = 25 then Result := '5' else if SquaredMagnitude = 36 then Result := '6' else if SquaredMagnitude = 49 then Result := '7' else if SquaredMagnitude = 64 then Result := '8' else if SquaredMagnitude = 81 then Result := '9' else if SquaredMagnitude = 100 then Result := '10' else if SquaredMagnitude = 121 then Result := '11' else if SquaredMagnitude = 144 then Result := '12' else if SquaredMagnitude = 169 then Result := '13' else if SquaredMagnitude = 196 then Result := '14' else if SquaredMagnitude = 225 then Result := '15' else if SquaredMagnitude = 256 then Result := '16' else if SquaredMagnitude = 289 then Result := '17' else Result := '\sqrt{' + IntToStr(SquaredMagnitude) + '}'; end; function TQuestion.VectorScalarProduct(VectorA, VectorB : String) : String; var AICoeff, AJCoeff, BICoeff, BJCoeff : Integer; begin // Get coefficients of vector A if VectorA[1] = '-' then begin AICoeff := StrToInt('-' + VectorA[2]); if VectorA[4] = '-' then AJCoeff := StrToInt('-' + VectorA[5]) else AJCoeff := StrToInt(VectorA[5]); end else begin AICoeff := StrToInt(VectorA[1]); if VectorA[3] = '-' then AJCoeff := StrToInt('-' + VectorA[4]) else AJCoeff := StrToInt(VectorA[4]); end; // Get coefficients of vector B if VectorB[1] = '-' then begin BICoeff := StrToInt('-' + VectorB[2]); if VectorB[4] = '-' then BJCoeff := StrToInt('-' + VectorB[5]) else BJCoeff := StrToInt(VectorB[5]); end else begin BICoeff := StrToInt(VectorB[1]); if VectorB[3] = '-' then BJCoeff := StrToInt('-' + VectorB[4]) else BJCoeff := StrToInt(VectorB[4]); end; Result := IntToStr((AICoeff * BICoeff) + (AJCoeff * BJCoeff)); end; function TQuestion.VectorAngleBetween(VectorA, VectorB : String) : String; var VectorAMagnitude, VectorBMagnitude : Real; ChangingString : String; begin // If magnitude of vector is integer, write that if Length(GetMagnitudeOfVector(VectorA)) < 3 then VectorAMagnitude := StrToFloat(GetMagnitudeOfVector(VectorA)) // Else it is in surd form, write with square root else begin ChangingString := StringReplace(GetMagnitudeOfVector(VectorA), '\sqrt{', '', [rfReplaceAll]); ChangingString := StringReplace(ChangingString, '}', '', [rfReplaceAll]); VectorAMagnitude := sqrt(StrToInt(ChangingString)); end; // If magnitude of vector is integer, write that if Length(GetMagnitudeOfVector(VectorB)) < 3 then VectorBMagnitude := StrToFloat(GetMagnitudeOfVector(VectorB)) // Else it is in surd form, write with square root else begin ChangingString := StringReplace(GetMagnitudeOfVector(VectorB), '\sqrt{', '', [rfReplaceAll]); ChangingString := StringReplace(ChangingString, '}', '', [rfReplaceAll]); VectorBMagnitude := sqrt(StrToInt(ChangingString)); end; Result := IntToStr( Round(Arccos(StrToInt(VectorScalarProduct(VectorA, VectorB)) / (VectorAMagnitude * VectorBMagnitude)) * 180 / pi)); end; function TQuestion.VectorThirdConnector(VectorA, VectorB : String) : String; var AICoeff, AJCoeff, BICoeff, BJCoeff, CICoeff, CJCoeff : Integer; ThirdVector : String; begin // Split vector A into coefficient and constant if VectorA[1] = '-' then begin AICoeff := StrToInt('-' + VectorA[2]); if VectorA[4] = '-' then AJCoeff := StrToInt('-' + VectorA[5]) else AJCoeff := StrToInt(VectorA[5]); end else begin AICoeff := StrToInt(VectorA[1]); if VectorA[3] = '-' then AJCoeff := StrToInt('-' + VectorA[4]) else AJCoeff := StrToInt(VectorA[4]); end; // Split vector B into coefficient and constant if VectorB[1] = '-' then begin BICoeff := StrToInt('-' + VectorB[2]); if VectorB[4] = '-' then BJCoeff := StrToInt('-' + VectorB[5]) else BJCoeff := StrToInt(VectorB[5]); end else begin BICoeff := StrToInt(VectorB[1]); if VectorB[3] = '-' then BJCoeff := StrToInt('-' + VectorB[4]) else BJCoeff := StrToInt(VectorB[4]); end; // Replace 1 with i or j so not shown in the actual question (correct format) CICoeff := -1 * (AICoeff + BICoeff); CJCoeff := -1 * (AJCoeff + BJCoeff); ThirdVector := ''; if CICoeff = -1 then ThirdVector := '-i' else if CICoeff = 1 then ThirdVector := 'i' else if CICoeff <> 0 then ThirdVector := IntToStr(CICoeff) + 'i'; if CJCoeff = -1 then ThirdVector := ThirdVector + '-j' else if CJCoeff = 1 then ThirdVector := ThirdVector + '+j' else if CJCoeff < 0 then ThirdVector := ThirdVector + IntToStr(CJCoeff) + 'j' else if CJCoeff > 0 then ThirdVector := ThirdVector + '+' + IntToStr(CJCoeff) + 'j'; Result := ThirdVector; end; function TQuestion.DifferentiateAToTheX (Equation : String) : String; var Coeff, Term, Power, DiffEquation : String; begin // Split into coefficient, term and power Coeff := ''; Term := ''; Power := ''; if Equation[2] = '(' then begin Coeff := Equation[1]; Term := Equation[3]; if Equation[6] = 'x' then Power := '1' else Power := Equation[6]; end else begin Coeff := '1'; Term := Equation[1]; if Equation[4] = 'x' then Power := '1' else Power := Equation[4]; end; // Rewrite differential DiffEquation := ''; if Coeff <> '1' then DiffEquation := Coeff; DiffEquation := DiffEquation + '(' + Term + '^{'; if Power <> '1' then DiffEquation := DiffEquation + Power; DiffEquation := DiffEquation + 'x})ln(' + Term + ')'; // Return differential Result := DiffEquation; end; function TQuestion.DifferentiateEToTheX(Equation: String) : String; var Coeff, Power, DiffEquation : String; begin Coeff := ''; Power := ''; DiffEquation := ''; // Split into coeff and power if Equation[1] <> 'e' then begin Coeff := Equation[1]; if Equation[5] <> 'x' then begin // Negative number if Equation[5] = '-' then Power := Equation[5] + Equation[6] // Positive number else Power := Equation[5]; end else Power := '1'; end else begin Coeff := '1'; if Equation[4] <> 'x' then begin // Negative number if Equation[4] = '-' then Power := Equation[4] + Equation[5] // Positive number else Power := Equation[4]; end else Power := '1'; end; // Calculate differential if (Power <> '1') and (Coeff <> '1') then DiffEquation := IntToStr(StrToInt(Coeff) * StrToInt(Power)); DiffEquation := DiffEquation + 'e^{'; if (Power <> '1') then DiffEquation := DiffEquation + Power; DiffEquation := DiffEquation + 'x}'; // Return Differential Result := DiffEquation; end; function TQuestion.IntegrationEToTheX (Equation : String) : String; var Coeff, Power, IntEquation : String; begin Coeff := ''; Power := ''; IntEquation := ''; // Split into coeff and power if Equation[1] <> 'e' then begin Coeff := Equation[1]; if Equation[5] <> 'x' then begin // Negative number if Equation[5] = '-' then Power := Equation[5] + Equation[6] // Positive number else Power := Equation[5]; end else Power := '1'; end else begin Coeff := '1'; if Equation[4] <> 'x' then begin // Negative number if Equation[4] = '-' then Power := Equation[4] + Equation[5] // Positive number else Power := Equation[4]; end else Power := '1'; end; // Calculate new integrated coeff if StrToInt(Coeff) DIV StrToInt(Power) < 0 then IntEquation := '-'; if StrToInt(Coeff) MOD StrToInt(Power) = 0 then begin if Abs(StrToInt(Coeff)) > Abs(StrToInt(Power)) then IntEquation := IntEquation + IntToStr(Abs(StrToInt(Coeff) DIV StrToInt(Power))) + 'e^{' + Power + 'x}' else if Abs(StrToInt(Coeff)) = Abs(StrToInt(Power)) then IntEquation := IntEquation + 'e^{' + Power + 'x}' else begin IntEquation := IntEquation + '\frac{e^{' + Power + 'x}}{' + IntToStr(Abs(StrToInt(Power))) + '}'; end; end else IntEquation := IntEquation + '\frac{' + IntToStr(Abs(StrToInt(Coeff))) + 'e^{' + Power + 'x}}{' + IntToStr(Abs(StrToInt(Power))) + '}'; Result := IntEquation; end; function TQuestion.IntegrationReciprocal (Equation : String) : String; var Coeff, Constant, IntEquation : String; begin Coeff := Equation[10]; Constant := Equation[13]; IntEquation := '\frac{ln(' + Coeff + 'x+' + Constant + '}{' + Coeff + '}'; Result := IntEquation; end; // Generate an equation function TQuestion.GenerateEquation(Constant, Linear, Quadratic, Cubic, Fraction, Trig, AdvancedTrig, Log, E, AToTheX : Boolean) : String; var Equation : String; RandomInt : Integer; begin // Initialise equation Equation := ''; // Simple trig - sin, cos, tan if Trig then begin RandomInt := Random(3); if RandomInt = 0 then Equation := Equation + '\sin(x)'; if RandomInt = 1 then Equation := Equation + '\cos(x)'; if RandomInt = 2 then Equation := Equation + '\tan(x)'; end; // Advanced trig - sec, cot, cosec if AdvancedTrig then begin // Add a plus to the start if not first thing if Length(Equation) <> 0 then Equation := Equation + '+'; RandomInt := Random(3); if RandomInt = 0 then Equation := Equation + '\cot(x)'; if RandomInt = 1 then Equation := Equation + '\sec(x)'; if RandomInt = 2 then Equation := Equation + '\cosec(x)'; end; // Ln if Log then begin // Add a plus to the start if not first thing if Length(Equation) <> 0 then Equation := Equation + '+'; Equation := Equation + 'ln(x)'; end; // e if E then begin // Add a plus to the start if not first thing if Length(Equation) <> 0 then Equation := Equation + '+'; // Coefficient and e RandomInt := Random(9) + 1; if RandomInt <> 1 then Equation := Equation + IntToStr(RandomInt) + 'e^{'; // Power repeat RandomInt := Random(11) - 5; until (RandomInt <> 0) and (RandomInt <> 1) and (RandomInt <> -1); Equation := Equation + IntToStr(RandomInt); Equation := Equation + 'x}'; end; // a^x if AToTheX then begin // Add a plus to the start if not first thing if Length(Equation) <> 0 then Equation := Equation + '+'; // Coefficient RandomInt := Random(9) + 1; if RandomInt <> 1 then Equation := Equation + IntToStr(RandomInt) + '('; // A to the X RandomInt := Random(7) + 2; Equation := Equation + IntToStr(RandomInt); Equation := Equation + '^{x}'; if Equation[Length(Equation) - 5] = '(' then Equation := Equation + ')'; end; // Fraction if Fraction then begin // Add a plus to the start if not first thing if Length(Equation) <> 0 then Equation := Equation + '+'; Equation := Equation + '\frac{' + GenerateEquation(true, true, false, false, false, false, false, false, false, false) + '}{' + GenerateEquation(true, true, false, false, false, false, false, false, false, false) + '}'; end; // Cubic - x^3 if Cubic then begin // Add a plus to the start if not first thing if Length(Equation) <> 0 then Equation := Equation + '+'; Equation := Equation + 'x^{3}'; end; // Quadratic - x^2 if Quadratic then begin // Add a plus or minus to the start if not first thing if Length(Equation) <> 0 then begin RandomInt := Random(2); if RandomInt = 0 then Equation := Equation + '+' else Equation := Equation + '-'; // Random coefficient RandomInt := Random(5) + 2; if RandomInt = 1 then Equation := Equation + 'x^{2}' else Equation := Equation + IntToStr(RandomInt) + 'x^{2}'; end // No coefficient if first term else Equation := Equation + 'x^{2}'; end; // Linear - x if Linear then begin // Add a plus or minus to the start if not first thing if Length(Equation) <> 0 then begin RandomInt := Random(2); if RandomInt = 0 then Equation := Equation + '+' else Equation := Equation + '-'; // Random Coefficient RandomInt := Random(8) + 2; if RandomInt = 1 then Equation := Equation + 'x' else Equation := Equation + IntToStr(RandomInt) + 'x'; end // No coefficient if first term else Equation := Equation + 'x'; end; // Constant - number if Constant then begin // Add a plus to the start if not first thing if Length(Equation) <> 0 then begin RandomInt := Random(2); if RandomInt = 0 then Equation := Equation + '+' else Equation := Equation + '-'; end; Equation := Equation + IntToStr(Random(8) + 2); end; GenerateEquation := Equation; end; procedure TQuestion.GenerateParametricToCartesianQuestion; var QuestionType : Integer; XParametric, YParametric, CartesianEquation : String; begin // Choose question type QuestionType := Random(2); if QuestionType = 0 then begin // Create equations for question XParametric := IntToStr(Random(5) + 2) + 't+' + IntToStr(Random(8) + 2); YParametric := 't^{2}'; CartesianEquation := 'y=(\frac{x-' + XParametric[4] + '}{' + XParametric[1] + '})^{2}'; end else if QuestionType = 1 then begin // Create equations for question XParametric := IntToStr(Random(5) + 2) + 't+' + IntToStr(Random(8) + 2); YParametric := '\frac{1}{t}'; CartesianEquation := 'y=\frac{' + XParametric[1] + '}{x-' + XParametric[4] + '}'; end; // Write question and answer QQuestion := 'Write x=' + XParametric + ' and y=' + YParametric + ' in cartesian form'; QCorrectAnswer := CartesianEquation; end; procedure TQuestion.GenerateIterationQuestion; var XValue, StartingXValue : Real; Equation, IterativeEquation : String; Count, NumOfIterations : Integer; begin // Keep generating question until numbers are not too large (over 1000 or under -1000) repeat Equation := GenerateEquation(true, true, true, false, false, false, false, false, false, false); StartingXValue := (Random(20) + 1) / 10; XValue := StartingXValue; NumOfIterations := Random(5) + 3; for Count := 1 to NumOfIterations do XValue := ValueOfFunction(Equation, XValue); until (XValue >= -999) and (XValue <= 999); // Format question and output IterativeEquation := StringReplace(Equation, 'x', 'x_n', [rfReplaceAll]); QQuestion := 'x_{n+1}=' + IterativeEquation + ' and x_0=' + FloatToStr(StartingXValue) + '. Find x_' + IntToStr(NumOfIterations) + ' to 2dp'; QCorrectAnswer := FormatFloat('##0.00', XValue); end; constructor TQuestion.Create(TheTopic: string; TheSubTopic: string); var Equation1, Equation2, Equation3 : String; RandomNum : Integer; begin // Set topic and sub topic QTopic := AnsiString(TheTopic); QSubTopic := AnsiString(TheSubTopic); QQuestion := ''; QCorrectAnswer := ''; // Generate question and calculate answer // Algebra and Series if TheTopic = 'Algebra and Series' then begin if TheSubTopic = 'Algebraic Fractions' then begin Equation1 := GenerateAlgebraicFraction; Equation2 := GenerateAlgebraicFraction; Equation3 := AddAlgebraicFractions(Equation1, Equation2); QQuestion := 'Write ' + Equation1 + ' + ' + Equation2 + ' as a single fraction'; QCorrectAnswer := Equation3; end else if TheSubTopic = 'Partial Fractions' then begin Equation1 := GenerateAlgebraicFraction; Equation2 := GenerateAlgebraicFraction; Equation3 := AddAlgebraicFractions(Equation1, Equation2); QQuestion := 'Write ' + Equation3 + ' as two fractions'; QCorrectAnswer := Equation1 + '+' + Equation2; end else if TheSubTopic = 'Binomial Expansion' then begin Equation1 := '(1+' + IntToStr(Random(8) + 2) + 'x)^{' + IntToStr(Random(6) + 4) + '}'; Equation2 := ExpandBinomial(Equation1); QQuestion := 'Expand ' + Equation1 + ' to the cubic power'; QCorrectAnswer := Equation2; end; end; // Coordinate Geometry if TheTopic = 'Coordinate Geometry' then begin GenerateParametricToCartesianQuestion; end; // Differentiation if TheTopic = 'Differentiation' then begin // AToTheX if TheSubTopic = 'AToTheX' then begin Equation1 := GenerateEquation(false, false, false, false, false, false, false, false, false, true); Equation2 := DifferentiateAToTheX(Equation1); QQuestion := 'Differentiate ' + Equation1; QCorrectAnswer := Equation2; end // E To The X else if TheSubTopic = 'EToTheX' then begin Equation1 := GenerateEquation(false, false, false, false, false, false, false, false, true, false); Equation2 := DifferentiateEToTheX(Equation1); QQuestion := 'Differentiate ' + Equation1; QCorrectAnswer := Equation2; end; end; // Functions if TheTopic = 'Functions' then begin if TheSubTopic = 'Function Combinations' then begin Equation1 := GenerateEquation(true, true, true, true, false, false, false, false, false, false); Equation2 := GenerateEquation(true, true, false, false, false, false, false, false, false, false); RandomNum := Random(5) + 2; QQuestion := 'f(x)=' + Equation1 + ' and g(x)=' + Equation2 + '. Find gf(x) when x=' + IntToStr(RandomNum) + '.'; QCorrectAnswer := FloatToStr(ValueOfFunction(Equation2, ValueOfFunction(Equation1, RandomNum))); end else if TheSubTopic = 'Domain and Range' then begin Equation1 := '\frac{' + GenerateEquation(true, true, false, false, false, false, false, false, false, false) + '}{' + GenerateEquation(true, true, false, false, false, false, false, false, false, false) + '}'; QQuestion := 'f(x)=' + Equation1 + '. What value can x not be?'; if Equation1[13] = '+' then QCorrectAnswer := '-' + Equation1[14] else QCorrectAnswer := Equation1[14]; end; end; // Integration if TheTopic = 'Integration' then begin if TheSubTopic = 'Exponential' then begin Equation1 := GenerateEquation(false, false, false, false, false, false, false, false, true, false); Equation2 := IntegrationEToTheX(Equation1); QQuestion := 'Find \int' + Equation1; QCorrectAnswer := Equation2; end else if TheSubTopic = 'Reciprocal' then begin Equation1 := '\frac{1}{' + IntToStr(Random(8) + 2) + 'x+' + IntToStr(Random(8) + 2) + '}'; Equation2 := IntegrationReciprocal(Equation1); QQuestion := 'Find \int' + Equation1; QCorrectAnswer := Equation2; end; end; // Numerical Methods if TheTopic = 'Numerical Methods' then begin if TheSubTopic = 'Iteration' then GenerateIterationQuestion; end; // Trigonometry if TheTopic = 'Trigonometry' then begin if TheSubTopic = 'Sec, Cosec, Cot' then begin Equation1 := FloatToStr((Random(300) + 1) / 100); Equation2 := GenerateEquation(false, false, false, false, false, false, true, false, false, false); Equation2 := StringReplace(Equation2, 'x', Equation1, [rfReplaceAll]); QQuestion := 'Find the value of ' + Equation2 + ' to 2 decimal places'; if Equation2[2] = 's' then QCorrectAnswer := FormatFloat('#0.00', Sec(StrToFloat(Equation1))) else if Equation2[4] = 't' then QCorrectAnswer := FormatFloat('#0.00', Cot(StrToFloat(Equation1))) else if Equation2[4] = 's' then QCorrectAnswer := FormatFloat('#0.00', Csc(StrToFloat(Equation1))); end; end; // Vectors if TheTopic = 'Vectors' then begin // Magnitude if TheSubTopic = 'Magnitude' then begin Equation1 := GenerateVector; Equation2 := GetMagnitudeOfVector(Equation1); QQuestion := 'Find the magnitude of ' + Equation1 + '. Write your answer in exact form.'; QCorrectAnswer := Equation2; end // Scalar Product else if TheSubTopic = 'ScalarProduct' then begin Equation1 := GenerateVector; Equation2 := GenerateVector; QQuestion := 'Find the angle between ' + Equation1 + ' and ' + Equation2 + ' to the nearest degree.'; QCorrectAnswer := VectorAngleBetween(Equation1, Equation2); end // Lines else if TheSubTopic = 'Lines' then begin Equation1 := GenerateVector; Equation2 := GenerateVector; QQuestion := 'What vector connects the position vectors ' + Equation1 + ' and ' + Equation2 + '.'; QCorrectAnswer := VectorThirdConnector(Equation1, Equation2); end; end; end; function TQuestion.GetTopic : String; begin GetTopic := String(QTopic); end; function TQuestion.GetSubTopic : String; begin GetSubTopic := String(QSubTopic); end; procedure TQuestion.SetTopic (NewTopic : String); begin QTopic := AnsiString(NewTopic); end; procedure TQuestion.SetSubTopic (NewSubTopic : String); begin QSubTopic := AnsiString(NewSubTopic); end; procedure TQuestion.SetQuestion (NewQuestion : String); begin QQuestion := NewQuestion; end; procedure TQuestion.SetCorrectAnswer (NewCorrectAnswer : String); begin QCorrectAnswer := NewCorrectAnswer end; // Clears the canvas - text/images drawn on screen procedure ClearCanvas (Form : TForm); begin with Form do Canvas.FillRect(Rect(0, 0, ClientWidth, ClientHeight)); end; // Convert text into mathematical expression shown on screen procedure ShowMathsText (Text : String; X, Y, GapWidth : Integer; Canvas : TCanvas); var CurrentX, CurrentY, Count, XMovementHolder, XMovementHolder2 : Integer; RecursiveString : String; begin // Initialise variables Count := 1; CurrentX := X; CurrentY := Y; Canvas.Font.Size := 10; // Write out each character individually while Count <= Text.Length do begin // ^ is indices marker, raise previous to a power if Text[Count] = '^' then begin // Increase to power CurrentY := CurrentY - (5 * GapWidth); Count := Count + 1; // { if indices is more than one character, must be closed if Text[Count] = '{' then begin Count := Count + 1; RecursiveString := ''; repeat RecursiveString := RecursiveString + Text[Count]; Count := Count + 1; until (Text[Count] = '}') or (Count > Text.Length); ShowMathsText(RecursiveString, CurrentX, CurrentY, GapWidth, Canvas); CurrentX := CurrentX + (GapWidth * RecursiveString.Length * 8); end // Otherwise just one character else begin Canvas.TextOut(CurrentX, CurrentY, Text[Count]); CurrentX := CurrentX + (8 * GapWidth); end; // Remove Y back to normal line CurrentY := CurrentY + (5 * GapWidth); end // _ lowers the text else if Text[Count] = '_' then begin // Lower CurrentY := CurrentY + (5 * GapWidth); Count := Count + 1; // { if more than one character, must be closed if Text[Count] = '{' then begin Count := Count + 1; RecursiveString := ''; repeat RecursiveString := RecursiveString + Text[Count]; Count := Count + 1; until (Text[Count] = '}') or (Count > Text.Length); ShowMathsText(RecursiveString, CurrentX, CurrentY, GapWidth, Canvas); CurrentX := CurrentX + (GapWidth * RecursiveString.Length * 8); end // Otherwise just one character else begin Canvas.TextOut(CurrentX, CurrentY, Text[Count]); CurrentX := CurrentX + (8 * GapWidth); end; // Remove Y back to normal line CurrentY := CurrentY - (5 * GapWidth); end // \ Functions else if Text[Count] = '\' then begin Count := Count + 1; // Plus or Minus Sign if (Text[Count] = 'p') and (Text[Count + 1] = 'm') then begin Canvas.TextOut(CurrentX, CurrentY, '±'); CurrentX := CurrentX + (9 * GapWidth); Count := Count + 1; end // Minus or Plus Sign else if (Text[Count] = 'm') and (Text[Count + 1] = 'p') then begin Canvas.TextOut(CurrentX, CurrentY, '∓'); CurrentX := CurrentX + (9 * GapWidth); Count := Count + 1; end // Less Than or Equal To Sign else if (Text[Count] = 'l') and (Text[Count + 1] = 'e') and (Text[Count + 2] = 'q') then begin Canvas.TextOut(CurrentX, CurrentY, '≤'); CurrentX := CurrentX + (9 * GapWidth); Count := Count + 2; end // Greater Than or Equal To Sign else if (Text[Count] = 'g') and (Text[Count + 1] = 'e') and (Text[Count + 2] = 'q') then begin Canvas.TextOut(CurrentX, CurrentY, '≥'); CurrentX := CurrentX + (9 * GapWidth); Count := Count + 2; end // Infinity Sign else if (Text[Count] = 'i') and (Text[Count + 1] = 'n') and (Text[Count + 2] = 'f') then begin Canvas.TextOut(CurrentX, CurrentY, '∞'); CurrentX := CurrentX + (12 * GapWidth); Count := Count + 2; end // Theta Sign else if (Text[Count] = 't') and (Text[Count + 1] = 'h') and (Text[Count + 2] = 'e') and (Text[Count + 3] = 't') and (Text[Count + 4] = 'a') then begin Canvas.TextOut(CurrentX, CurrentY, 'Θ'); CurrentX := CurrentX + (12 * GapWidth); Count := Count + 4; end // Trig - Sin else if (Text[Count] = 's') and (Text[Count + 1] = 'i') and (Text[Count + 2] = 'n') then begin Canvas.TextOut(CurrentX, CurrentY, 'Sin'); CurrentX := CurrentX + (21 * GapWidth); Count := Count + 2; end // Trig - Cos else if (Text[Count] = 'c') and (Text[Count + 1] = 'o') and (Text[Count + 2] = 's') and (Text[Count + 3] <> 'e') then begin Canvas.TextOut(CurrentX, CurrentY, 'Cos'); CurrentX := CurrentX + (24 * GapWidth); Count := Count + 2; end // Trig - Tan else if (Text[Count] = 't') and (Text[Count + 1] = 'a') and (Text[Count + 2] = 'n') then begin Canvas.TextOut(CurrentX, CurrentY, 'Tan'); CurrentX := CurrentX + (24 * GapWidth); Count := Count + 2; end // Trig - Arcsin else if (Text[Count] = 'a') and (Text[Count + 1] = 'r') and (Text[Count + 2] = 'c') and (Text[Count + 3] = 's') and (Text[Count + 4] = 'i') and (Text[Count + 5] = 'n') then begin Canvas.TextOut(CurrentX, CurrentY, 'Arcsin'); CurrentX := CurrentX + (38 * GapWidth); Count := Count + 5; end // Trig - Arccos else if (Text[Count] = 'a') and (Text[Count + 1] = 'r') and (Text[Count + 2] = 'c') and (Text[Count + 3] = 'c') and (Text[Count + 4] = 'o') and (Text[Count + 5] = 's') then begin Canvas.TextOut(CurrentX, CurrentY, 'Arccos'); CurrentX := CurrentX + (40 * GapWidth); Count := Count + 5; end // Trig - Arctan else if (Text[Count] = 'a') and (Text[Count + 1] = 'r') and (Text[Count + 2] = 'c') and (Text[Count + 3] = 't') and (Text[Count + 4] = 'a') and (Text[Count + 5] = 'n') then begin Canvas.TextOut(CurrentX, CurrentY, 'Arctan'); CurrentX := CurrentX + (38 * GapWidth); Count := Count + 5; end // Trig - Cot else if (Text[Count] = 'c') and (Text[Count + 1] = 'o') and (Text[Count + 2] = 't') then begin Canvas.TextOut(CurrentX, CurrentY, 'Cot'); CurrentX := CurrentX + (21 * GapWidth); Count := Count + 2; end // Trig - Sec else if (Text[Count] = 's') and (Text[Count + 1] = 'e') and (Text[Count + 2] = 'c') then begin Canvas.TextOut(CurrentX, CurrentY, 'Sec'); CurrentX := CurrentX + (24 * GapWidth); Count := Count + 2; end // Trig - Cosec else if (Text[Count] = 'c') and (Text[Count + 1] = 'o') and (Text[Count + 2] = 's') and (Text[Count + 3] = 'e') and (Text[Count + 4] = 'c') then begin Canvas.TextOut(CurrentX, CurrentY, 'Cosec'); CurrentX := CurrentX + (38 * GapWidth); Count := Count + 4; end // Fractions ><><><><><><><><><><><><><><><><><><><><><><><><><><><>< else if (Text[Count] = 'f') and (Text[Count + 1] = 'r') and (Text[Count + 2] = 'a') and (Text[Count + 3] = 'c') and (Text[Count + 4] = '{') then begin // Write both top and bottom of the fraction XMovementHolder := CurrentX; Count := Count + 5; RecursiveString := ''; repeat RecursiveString := RecursiveString + Text[Count]; Count := Count + 1; until (Text[Count] = '}') or (Count > Length(Text)); ShowMathsText(RecursiveString, CurrentX, CurrentY - (8 * GapWidth), GapWidth, Canvas); XMovementHolder2 := Length(RecursiveString) * 8 * GapWidth; Count := Count + 2; RecursiveString := ''; repeat RecursiveString := RecursiveString + Text[Count]; Count := Count + 1; until (Text[Count] = '}') or (Count > Length(Text)); ShowMathsText(RecursiveString, CurrentX, CurrentY + (8 * GapWidth), GapWidth, Canvas); if Length(RecursiveString) * 8 * GapWidth > XMovementHolder2 then CurrentX := CurrentX + (Length(RecursiveString) * 8 * GapWidth) else CurrentX := CurrentX + XMovementHolder2; // Draw fraction line Canvas.MoveTo(XMovementHolder, CurrentY + (8 * GapWidth)); Canvas.LineTo(CurrentX, CurrentY + (8 * GapWidth)); CurrentX := CurrentX + (3 * GapWidth); end // Binomials - binom{}{} else if (Text[Count] = 'b') and (Text[Count + 1] = 'i') and (Text[Count + 2] = 'n') and (Text[Count + 3] = 'o') and (Text[Count + 4] = 'm') and (Text[Count + 5] = '{') then begin // Open bracket Canvas.Font.Size := 18; Canvas.TextOut(CurrentX, CurrentY - 8, '('); CurrentX := CurrentX + (10 * GapWidth); Canvas.Font.Size := 10; // Write both top and bottom of binomial, then work out where to place close bracket Count := Count + 6; RecursiveString := ''; repeat RecursiveString := RecursiveString + Text[Count]; Count := Count + 1; until (Text[Count] = '}') or (Count > Length(Text)); ShowMathsText(RecursiveString, CurrentX, CurrentY - (8 * GapWidth), GapWidth, Canvas); XMovementHolder := Length(RecursiveString) * 8 * GapWidth; Count := Count + 2; RecursiveString := ''; repeat RecursiveString := RecursiveString + Text[Count]; Count := Count + 1; until (Text[Count] = '}') or (Count > Length(Text)); ShowMathsText(RecursiveString, CurrentX, CurrentY + (8 * GapWidth), GapWidth, Canvas); if Length(RecursiveString) * 8 * GapWidth > XMovementHolder then CurrentX := CurrentX + (Length(RecursiveString) * 8 * GapWidth) else CurrentX := CurrentX + XMovementHolder; // Close bracket Canvas.Font.Size := 18; Canvas.TextOut(CurrentX, CurrentY - 8, ')'); CurrentX := CurrentX + (10 * GapWidth); Canvas.Font.Size := 10; end // Square Roots - sqrt{} else if (Text[Count] = 's') and (Text[Count + 1] = 'q') and (Text[Count + 2] = 'r') and (Text[Count + 3] = 't') and (Text[Count + 4] = '{') then begin Count := Count + 5; Canvas.Font.Size := 15; Canvas.TextOut(CurrentX, CurrentY - 6, '√'); Canvas.Font.Size := 10; CurrentX := CurrentX + (14 * GapWidth); XMovementHolder := CurrentX; RecursiveString := ''; repeat RecursiveString := RecursiveString + Text[Count]; Count := Count + 1; until (Text[Count] = '}') or (Count > Length(Text)); ShowMathsText(RecursiveString, CurrentX, CurrentY, GapWidth, Canvas); CurrentX := CurrentX + (Length(RecursiveString) * 8 * GapWidth); Canvas.MoveTo(XMovementHolder, CurrentY - (5 * GapWidth)); Canvas.LineTo(CurrentX, CurrentY - (5 * GapWidth)); end // Sum (Sigma) - sum{}{} else if (Text[Count] = 's') and (Text[Count + 1] = 'u') and (Text[Count + 2] = 'm') and (Text[Count + 3] = '{') then begin // Write out top and bottom of sigma, then work out where to put sigma Count := Count + 4; RecursiveString := ''; repeat RecursiveString := RecursiveString + Text[Count]; Count := Count + 1; until (Text[Count] = '}') or (Count > Length(Text)); ShowMathsText(RecursiveString, CurrentX, CurrentY - (8 * GapWidth), GapWidth, Canvas); XMovementHolder := Length(RecursiveString) * 8 * GapWidth; Count := Count + 2; RecursiveString := ''; repeat RecursiveString := RecursiveString + Text[Count]; Count := Count + 1; until (Text[Count] = '}') or (Count > Length(Text)); ShowMathsText(RecursiveString, CurrentX, CurrentY + (8 * GapWidth), GapWidth, Canvas); if Length(RecursiveString) * 8 * GapWidth > XMovementHolder then CurrentX := CurrentX + (Length(RecursiveString) * 8 * GapWidth) else CurrentX := CurrentX + XMovementHolder; // Sigma Canvas.Font.Size := 20; Canvas.TextOut(CurrentX, CurrentY - (8 * GapWidth), 'Σ'); Canvas.Font.Size := 10; CurrentX := CurrentX + (16 * GapWidth); end // Definite Integral - int{}{} else if (Text[Count] = 'i') and (Text[Count + 1] = 'n') and (Text[Count + 2] = 't') and (Text[Count + 3] = '{') then begin // Top and bottom of integral Count := Count + 4; RecursiveString := ''; repeat RecursiveString := RecursiveString + Text[Count]; Count := Count + 1; until (Text[Count] = '}') or (Count > Length(Text)); ShowMathsText(RecursiveString, CurrentX, CurrentY - (8 * GapWidth), GapWidth, Canvas); XMovementHolder := Length(RecursiveString) * 8 * GapWidth; Count := Count + 2; RecursiveString := ''; repeat RecursiveString := RecursiveString + Text[Count]; Count := Count + 1; until (Text[Count] = '}') or (Count > Length(Text)); ShowMathsText(RecursiveString, CurrentX, CurrentY + (8 * GapWidth), GapWidth, Canvas); if Length(RecursiveString) * 8 * GapWidth > XMovementHolder then CurrentX := CurrentX + (Length(RecursiveString) * 8 * GapWidth) else CurrentX := CurrentX + XMovementHolder; // Integral sign Canvas.Font.Size := 15; Canvas.TextOut(CurrentX, CurrentY - (5 * GapWidth), '∫'); Canvas.Font.Size := 10; CurrentX := CurrentX + (12 * GapWidth); end // Integral Sign - int else if (Text[Count] = 'i') and (Text[Count + 1] = 'n') and (Text[Count + 2] = 't') then begin Canvas.Font.Size := 15; Canvas.TextOut(CurrentX, CurrentY - (5 * GapWidth), '∫'); Canvas.Font.Size := 10; CurrentX := CurrentX + (12 * GapWidth); Count := Count + 2; end; end // Otherwise just a normal number/letter else begin Canvas.TextOut(CurrentX, CurrentY, Text[Count]); // Amount that X moves along depends on size on character on display if (Text[Count] = 'i') or (Text[Count] = 'l') or (Text[Count] = 't') or (Text[Count] = '.') or (Text[Count] = ',') then CurrentX := CurrentX + (4 * GapWidth) else if (Text[Count] = 'f') or (Text[Count] = 'j') or (Text[Count] = 'r') then CurrentX := CurrentX + (6 * GapWidth) else if (Text[Count] = 'I') or (Text[Count] = 'J') then CurrentX := CurrentX + (7 * GapWidth) else if (Text[Count] = 'u') or (Text[Count] = 'D') or (Text[Count] = 'G') or (Text[Count] = 'H') or (Text[Count] = 'U') or (Text[Count] = 'Y') then CurrentX := CurrentX + (9 * GapWidth) else if (Text[Count] = 'A') or (Text[Count] = 'N') or (Text[Count] = 'Q') or (Text[Count] = 'S') or (Text[Count] = 'V') or (Text[Count] = 'X') then CurrentX := CurrentX + (10 * GapWidth) else if (Text[Count] = 'm') or (Text[Count] = 'w') then CurrentX := CurrentX + (13 * GapWidth) else if (Text[Count] = 'M') or (Text[Count] = 'W') then CurrentX := CurrentX + (14 * GapWidth) else CurrentX := CurrentX + (8 * GapWidth); end; // Move onto next character Count := Count + 1; end; end; end.
unit uPrint; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uBase, StdCtrls, Buttons, ExtCtrls, CheckLst; type TfrmPrint = class(TfrmBase) cbPrint: TCheckListBox; cbSelAll: TCheckBox; procedure cbSelAllClick(Sender: TObject); procedure cbPrintClickCheck(Sender: TObject); private { Private declarations } protected //数据操作过程... procedure InitData; override; procedure SaveData; override; public { Public declarations } end; var frmPrint: TfrmPrint; function ShowPrint(): Boolean; implementation uses uGlobal; {$R *.dfm} function ShowPrint(): Boolean; begin with TfrmPrint.Create(Application.MainForm) do begin HelpHtml := 'print.html'; imgHelp.Visible := False; try InitData(); Result := ShowModal() = mrOk; if Result then Log.Write(App.UserID + '对类别显示做过改动'); finally Free; end; end; end; procedure TfrmPrint.InitData; begin with cbPrint, App.PrintSet do begin Checked[0] := PrintBase; Checked[1] := PrintDept; Checked[2] := PrintContact; Checked[3] := PrintSelf; Checked[4] := PrintFami; Checked[5] := PrintExper; Checked[6] := PrintAP; Checked[7] := PrintTrain; Checked[8] := PrintMove; Checked[9] := PrintOther; end; cbPrint.OnClickCheck(cbPrint); end; procedure TfrmPrint.SaveData; begin with cbPrint, App.PrintSet do begin PrintBase := Checked[0]; PrintDept := Checked[1]; PrintContact := Checked[2]; PrintSelf := Checked[3]; PrintFami := Checked[4]; PrintExper := Checked[5]; PrintAP := Checked[6]; PrintTrain := Checked[7]; PrintMove := Checked[8]; PrintOther := Checked[9]; end; Log.Write(App.UserID + '进行打印字段设置操作'); end; procedure TfrmPrint.cbSelAllClick(Sender: TObject); var i: Integer; begin for i := 0 to cbPrint.Count - 1 do cbPrint.Checked[i] := cbSelAll.Checked; end; procedure TfrmPrint.cbPrintClickCheck(Sender: TObject); var i: Integer; AllChecked: Boolean; begin AllChecked := True; for i := 0 to cbPrint.Count - 1 do if not cbPrint.Checked[i] then begin AllChecked := False; Break; end; //反判断 if AllChecked and not cbSelAll.Checked then begin cbSelAll.OnClick := nil; cbSelAll.Checked := True; cbSelAll.OnClick := cbSelAllClick; end; if cbSelAll.Checked and not AllChecked then begin cbSelAll.OnClick := nil; cbSelAll.Checked := False; cbSelAll.OnClick := cbSelAllClick; end; end; end.
{ This file is part of the SimpleBOT package. (c) Luri Darmawan <luri@fastplaz.com> For the full copyright and license information, please view the LICENSE file that was distributed with this source code. } { // USAGE: kamus := TKamusIbacorIntegration.Create; kamus.Token := 'ibacortoken'; Result := kamus.Find('gadis'); kamus.Free; } unit kamusibacor_integration; {$mode objfpc}{$H+} interface uses {$IFNDEF Windows} cthreads, {$ENDIF} common, http_lib, fpjson, Classes, SysUtils; type { TKamusIbacorIntegration } TKamusIbacorIntegration = class(TInterfacedObject) private FToken: string; public constructor Create; virtual; destructor Destroy; virtual; property Token: string read FToken write FToken; function Find(Text: string): string; end; implementation const _KAMUS_IBACOR_URL = 'http://ibacor.com/api/kamus-bahasa?k=%s&kata=%s'; var Response: IHTTPResponse; { TKamusIbacorIntegration } constructor TKamusIbacorIntegration.Create; begin FToken := ''; end; destructor TKamusIbacorIntegration.Destroy; begin end; function TKamusIbacorIntegration.Find(Text: string): string; var s: string; httpClient: THTTPLib; jsonData: TJSONData; begin Result := ''; Text := trim(Text); if Text = '' then Exit; if FToken = '' then Exit; s := Format(_KAMUS_IBACOR_URL, [FToken, Text]); httpClient := THTTPLib.Create; httpClient.URL := s; Response := httpClient.Get; httpClient.Free; if Response.ResultCode <> 200 then Exit; try jsonData := GetJSON(Response.ResultText); if jsonData.GetPath('status').AsString = 'success' then begin Result := Response.ResultText; end; jsonData.Free; except end; end; end.
// swmm5_iface.pas // // Example code for interfacing SWMM 5 with Delphi Pascal programs. // // Remember to add this unit to the Uses clause of the calling program. Unit SWMM5_IFACE Interface Uses SysUtils, Classes, Consts, WinTypes, WinProcs; Var SWMM_Nperiods: Integer; // number of reporting periods SWMM_FlowUnits: Integer; // flow units code SWMM_Nsubcatch: Integer; // number of subcatchments SWMM_Nnodes: Integer; // number of drainage system nodes SWMM_Nlinks: Integer; // number of drainage system links SWMM_Npolluts: Integer; // number of pollutants tracked SWMM_StartDate: Double; // start date of simulation SWMM_ReportStep: Integer; // reporting time step (seconds) Function RunSwmmExe(cmdLine : String): Integer; Function RunSwmmDll(inpFile: String; rptFile: String; outFile: String): Integer; Function OpenSwmmOutFile(outFile: String): Integer; Function GetSwmmResult(iType, iIndex, vIndex, period: Integer; var value: Single): Integer; Procedure CloseSwmmOutFile; Implementation Uses swmm5; Const SUBCATCH = 0; NODE = 1; LINK = 2; SYS = 3; RECORDSIZE = 4; // number of bytes per file record Var SubcatchVars: Integer; // number of subcatch reporting variable NodeVars: Integer; // number of node reporting variables LinkVars: Integer; // number of link reporting variables SysVars: Integer; // number of system reporting variables Fout: File; // file handle StartPos: LongInt; // file position where results start BytesPerPeriod: LongInt; // bytes used for results in each period //----------------------------------------------------------------------------- Function RunSwmmExe(cmdLine : String): Integer; //----------------------------------------------------------------------------- Var exitCode: Integer; pi: TProcessInformation; si: TStartupInfo; Begin // --- Initialize data structures FillMemory(@si, sizeof(si), 0); FillMemory(@pi, sizeof(pi), 0); si.cb := sizeof(si); si.wShowWindow := SW_SHOWNORMAL; // --- launch swmm5.exe exitCode := CreateProcess(Nil, PChar(cmdLine), Nil, Nil, False, NORMAL_PRIORITY_CLASS, Nil, Nil, si, pi ); // --- wait for program to end exitCode := WaitForSingleObject(pi.hProcess, INFINITE); // --- retrieve the error code produced by the program GetExitCodeProcess(pi.hProcess, exitCode); // --- release handles CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); Result := exitCode; End; //----------------------------------------------------------------------------- Function RunSwmmDll(inpFile: String; rptFile: String; outFile: String): Integer; //----------------------------------------------------------------------------- Var err : Integer; elapsedTime : Double; Begin // --- open a SWMM project err := swmm_open(inpFile, rptFile, outFile); If (err = 0) Then Begin // --- initialize all processing systems err := swmm_start(1); If (err = 0) Then Begin // --- step through the simulation Do ProcessMessages; err := swmm_step(elapsedTime); ///////////////////////////////////////////// // --- call progress reporting function here, // using elapsedTime as an argument ///////////////////////////////////////////// While (elapsedTime > 0.0) And (err = 0); End; // --- close all processing systems swmm_end(); End; // --- close the project swmm_close(); Result := err; End; //----------------------------------------------------------------------------- Function OpenSwmmOutFile(outFile: String): Integer; //----------------------------------------------------------------------------- Var magic1, magic2, errCode, version, position: Integer; offset, offset0: LongInt; err: Integer; Begin // --- open the output file AssignFile(Fout, outFile); {$I-} Reset(Fout, 1); {$I+} if IOResult <> 0 Then Begin Result := 2; Exit; End; // --- check that file contains at least 14 records If FileSize(Fout) < 14*RECORDSIZE Then Begin Result := 1; CloseFile(Fout); Exit; End; // --- read parameters from end of file Seek(Fout, FileSize(Fout) -5*RECORDSIZE); BlockRead(Fout, position, RECORDSIZE); offset0 := position; BlockRead(Fout, position, RECORDSIZE); StartPos := position; BlockRead(Fout, SWMM_Nperiods, RECORDSIZE); BlockRead(Fout, errCode, RECORDSIZE); BlockRead(Fout, magic2, RECORDSIZE); // --- read magic number from beginning of file Seek(Fout, 0); BlockRead(Fout, magic1, RECORDSIZE); // --- perform error checks If magic1 <> magic2 Then err = 1 Else If errCode <> 0 Then err = 1 Else If SWMM_Nperiods = 0 Then err = 1 Else err = 0; // --- quit if errors found if (err > 0 ) { Result := err; CloseFile(Fout); Exit; } // --- otherwise read additional parameters from start of file BlockRead(Fout, version, RECORDSIZE); BlockRead(Fout, SWMM_FlowUnits, RECORDSIZE); BlockRead(Fout, SWMM_Nsubcatch, RECORDSIZE); BlockRead(Fout, SWMM_Nnodes, RECORDSIZE); BlockRead(Fout, SWMM_Nlinks, RECORDSIZE); BlockRead(Fout, SWMM_Npolluts, RECORDSIZE); // Skip over saved subcatch/node/link input values offset := (SWMM_Nsubcatch+2) * RECORDSIZE // Subcatchment area + (3*SWMM_Nnodes+4) * RECORDSIZE // Node type, invert & max depth + (5*SWMM_Nlinks+6) * RECORDSIZE; // Link type, z1, z2, max depth & length offset := offset0 + offset; Seek(Fout, offset); // Read number & codes of computed variables BlockRead(Fout, SubcatchVars, RECORDSIZE); // # Subcatch variables Seek(Fout, FilePos(Fout)+(SubcatchVars*RECORDSIZE)); BlockRead(Fout, NodeVars, RECORDSIZE); // # Node variables Seek(Fout, FilePos(Fout)+(NodeVars*RECORDSIZE)); BlockRead(Fout, LinkVars, RECORDSIZE); // # Link variables Seek(Fout, FilePos(Fout)+(LinkVars*RECORDSIZE)); BlockRread(Fout, SysVars, RECORDSIZE); // # System variables // --- read data just before start of output results offset := StartPos - 3*RECORDSIZE; Seek(Fout, offset); BlockRead(Fout, SWMM_StartDate, 2*RECORDSIZE); BlockRead(Fout, SWMM_ReportStep, RECORDSIZE); // --- compute number of bytes of results values used per time period BytesPerPeriod := 2*RECORDSIZE + // date value (a double) (SWMM_Nsubcatch*SubcatchVars + SWMM_Nnodes*NodeVars + SWMM_Nlinks*LinkVars + SysVars)*RECORDSIZE; // --- return with file left open Result := err; End; //----------------------------------------------------------------------------- Function GetSwmmResult(iType, iIndex, vIndex, period: Integer; var value: Single): Integer; //----------------------------------------------------------------------------- Var offset: LongInt; Begin // --- compute offset into output file Result := 0; value := 0.0; offset := StartPos + (period-1)*BytesPerPeriod + 2*RECORDSIZE; if ( iType = SUBCATCH ) Then offset := offset + RECORDSIZE*(iIndex*SubcatchVars + vIndex) else if (iType = NODE) Then offset := offset + RECORDSIZE*(SWMM_Nsubcatch*SubcatchVars + iIndex*NodeVars + vIndex) else if (iType = LINK) Then offset := offset + RECORDSIZE*(SWMM_Nsubcatch*SubcatchVars + SWMM_Nnodes*NodeVars + iIndex*LinkVars + vIndex) else if (iType == SYS) Then offset := offset + RECORDSIZE*(SWMM_Nsubcatch*SubcatchVars + SWMM_Nnodes*NodeVars + SWMM_Nlinks*LinkVars + vIndex) else Exit; // --- re-position the file and read the result Seek(Fout, offset); BlockRead(Fout, value, RECORDSIZE); Result := 1; End; //----------------------------------------------------------------------------- Procedure CloseOutFile; //----------------------------------------------------------------------------- Begin CloseFile(Fout); End;
// ---------------------------------------------------------------------------- // Unit : PxMathParser.pas - a part of PxLib // Author : Fedor Koshevnikov, Igor Pavluk, Serge Korolev and // Matthias Hryniszak // Date : 2004-03-27 // Version : 1.0 // Description : Simply pass a string formula to GetFormulaValue() and you will // receive result // Changes log : 2004-03-27 - initial version // 2004-03-27 - added support for functions that return a value out // of a string // - added support for functions that convert values // (using ConvUtils and StdConvs units). A default // function for coverting units is added by default to // user-defined conversion functions. // - stripped dependencies with other Rx units // 2005-03-24 - incorporated into the PxLib // ToDo : Testing. // ---------------------------------------------------------------------------- unit PxMathParser; {$I PxDefines.inc} interface uses SysUtils, Classes, {$IFDEF USE_UNIT_CONVERSIONS} ConvUtils, {$ENDIF} PxBase, PxResources; type TPxMathParserFunc = ( pfArcTan, pfCos, pfSin, pfTan, pfAbs, pfExp, pfLn, pfLog, pfSqrt, pfSqr, pfInt, pfFrac, pfTrunc, pfRound, pfArcSin, pfArcCos, pfSign, pfNot ); EPxMathParserError = class(EPxException); TPxMathParserUserFunction = function(Value: Extended): Extended; TPxMathParserGetValueFunction = function(Value: String): Extended; {$IFDEF USE_UNIT_CONVERSIONS} TPxMathParserConvertValueFunction = function(Value: Extended; BaseType, ResultType: TConvType): Extended; {$ENDIF} TPxMathParser = class(TObject) private FCurPos: Cardinal; FParseText: string; function GetChar: Char; procedure NextChar; procedure SkipBlanks; function GetNumber(var AValue: Extended): Boolean; function GetConst(var AValue: Extended): Boolean; function GetFunction(var AValue: TPxMathParserFunc): Boolean; function GetUserFunction(var Index: Integer): Boolean; function GetGetValueFunction(var Index: Integer): Boolean; {$IFDEF USE_UNIT_CONVERSIONS} function GetConvertValueFunction(var Index: Integer): Boolean; {$ENDIF} function Term: Extended; function SubTerm: Extended; function Calculate: Extended; function GetString: String; {$IFDEF USE_UNIT_CONVERSIONS} function GetConvType(Expect: Char): TConvType; {$ENDIF} public function Exec(const AFormula: string): Extended; class procedure RegisterUserFunction(const Name: string; Proc: TPxMathParserUserFunction); class procedure UnregisterUserFunction(const Name: string); class procedure RegisterGetValueFunction(const Name: string; Proc: TPxMathParserGetValueFunction); class procedure UnregisterGetValueFunction(const Name: string); {$IFDEF USE_UNIT_CONVERSIONS} class procedure RegisterConvertValueFunction(const Name: string; Proc: TPxMathParserConvertValueFunction); class procedure UnregisterConvertValueFunction(const Name: string); {$ENDIF} end; function GetFormulaValue(const Formula: string): Extended; implementation uses Math; const SpecialChars = [#0..' ', '+', '-', '/', '*', ')', '^', ';']; FuncNames: array[TPxMathParserFunc] of PChar = ( 'ARCTAN', 'COS', 'SIN', 'TAN', 'ABS', 'EXP', 'LN', 'LOG', 'SQRT', 'SQR', 'INT', 'FRAC', 'TRUNC', 'ROUND', 'ARCSIN', 'ARCCOS', 'SIGN', 'NOT' ); { Parser errors } procedure InvalidCondition(Position: Integer; Str: String); begin if Position <> -1 then raise EPxMathParserError.CreateFmt('Error near position %d: %s', [Position, Str]) else raise EPxMathParserError.CreateFmt('Error: %s', [Str]); end; { IntPower and Power functions are copied from Borland's MATH.PAS unit } { User defined functions } type TFarUserFunction = TPxMathParserUserFunction; TFarGetValueFunction = TPxMathParserGetValueFunction; {$IFDEF USE_UNIT_CONVERSIONS} TFarConvertValueFunction = TPxMathParserConvertValueFunction; {$ENDIF} var UserFuncList: TStrings; GetValueFuncList: TStrings; {$IFDEF USE_UNIT_CONVERSIONS} ConvertValueFuncList: TStrings; {$ENDIF} function GetUserFuncList: TStrings; begin if not Assigned(UserFuncList) then begin UserFuncList := TStringList.Create; with TStringList(UserFuncList) do begin Sorted := True; Duplicates := dupIgnore; end; end; Result := UserFuncList; end; procedure FreeUserFunc; begin UserFuncList.Free; UserFuncList := nil; end; function GetGetValueFuncList: TStrings; begin if not Assigned(GetValueFuncList) then begin GetValueFuncList := TStringList.Create; with TStringList(GetValueFuncList) do begin Sorted := True; Duplicates := dupIgnore; end; end; Result := GetValueFuncList; end; procedure FreeGetValueFunc; begin GetValueFuncList.Free; GetValueFuncList := nil; end; {$IFDEF USE_UNIT_CONVERSIONS} function GetConvertValueFuncList: TStrings; begin if not Assigned(ConvertValueFuncList) then begin ConvertValueFuncList := TStringList.Create; with TStringList(ConvertValueFuncList) do begin Sorted := True; Duplicates := dupIgnore; end; end; Result := ConvertValueFuncList; end; procedure FreeConvertValueFunc; begin ConvertValueFuncList.Free; ConvertValueFuncList := nil; end; {$ENDIF} { TPxMathParser } function TPxMathParser.GetChar: Char; begin Result := FParseText[FCurPos]; end; procedure TPxMathParser.NextChar; begin Inc(FCurPos); end; procedure TPxMathParser.SkipBlanks; begin while FParseText[FCurPos] in [' '] do Inc(FCurPos); end; function TPxMathParser.GetNumber(var AValue: Extended): Boolean; var C: Char; SavePos: Cardinal; Code: Integer; IsHex: Boolean; TmpStr: string; begin Result := False; C := GetChar; SavePos := FCurPos; TmpStr := ''; IsHex := False; if C = '$' then begin TmpStr := C; NextChar; C := GetChar; while C in ['0'..'9', 'A'..'F', 'a'..'f'] do begin TmpStr := TmpStr + C; NextChar; C := GetChar; end; IsHex := True; Result := (Length(TmpStr) > 1) and (Length(TmpStr) <= 9); end else if C in ['+', '-', '0'..'9', '.', DecimalSeparator] then begin if (C in ['.', DecimalSeparator]) then TmpStr := '0' + '.' else TmpStr := C; NextChar; C := GetChar; if (Length(TmpStr) = 1) and (TmpStr[1] in ['+', '-']) and (C in ['.', DecimalSeparator]) then TmpStr := TmpStr + '0'; while C in ['0'..'9', '.', 'E', 'e', DecimalSeparator] do begin if C = DecimalSeparator then TmpStr := TmpStr + '.' else TmpStr := TmpStr + C; if (C = 'E') then begin if (Length(TmpStr) > 1) and (TmpStr[Length(TmpStr) - 1] = '.') then Insert('0', TmpStr, Length(TmpStr)); NextChar; C := GetChar; if (C in ['+', '-']) then begin TmpStr := TmpStr + C; NextChar; end; end else NextChar; C := GetChar; end; if (TmpStr[Length(TmpStr)] = '.') and (Pos('E', TmpStr) = 0) then TmpStr := TmpStr + '0'; Val(TmpStr, AValue, Code); Result := (Code = 0); end; Result := Result and (FParseText[FCurPos] in SpecialChars); if Result then begin if IsHex then AValue := StrToInt(TmpStr) { else AValue := StrToFloat(TmpStr) }; end else begin AValue := 0; FCurPos := SavePos; end; end; function TPxMathParser.GetConst(var AValue: Extended): Boolean; begin Result := False; case FParseText[FCurPos] of 'E': if FParseText[FCurPos + 1] in SpecialChars then begin AValue := Exp(1); Inc(FCurPos); Result := True; end; 'P': if (FParseText[FCurPos + 1] = 'I') and (FParseText[FCurPos + 2] in SpecialChars) then begin AValue := Pi; Inc(FCurPos, 2); Result := True; end; end end; function TPxMathParser.GetUserFunction(var Index: Integer): Boolean; var TmpStr: string; I: Integer; begin Result := False; if (FParseText[FCurPos] in ['A'..'Z', 'a'..'z', '_']) and Assigned(UserFuncList) then begin with UserFuncList do for I := 0 to Count - 1 do begin TmpStr := Copy(FParseText, FCurPos, Length(Strings[I])); if (CompareText(TmpStr, Strings[I]) = 0) and (Objects[I] <> nil) then begin if FParseText[FCurPos + Cardinal(Length(TmpStr))] = '(' then begin Result := True; Inc(FCurPos, Length(TmpStr)); Index := I; Exit; end; end; end; end; Index := -1; end; function TPxMathParser.GetGetValueFunction(var Index: Integer): Boolean; var TmpStr: string; I: Integer; begin Result := False; if (FParseText[FCurPos] in ['A'..'Z', 'a'..'z', '_']) and Assigned(GetValueFuncList) then begin with GetValueFuncList do for I := 0 to Count - 1 do begin TmpStr := Copy(FParseText, FCurPos, Length(Strings[I])); if (CompareText(TmpStr, Strings[I]) = 0) and (Objects[I] <> nil) then begin if FParseText[FCurPos + Cardinal(Length(TmpStr))] = '(' then begin Result := True; Inc(FCurPos, Length(TmpStr)); Index := I; Exit; end; end; end; end; Index := -1; end; {$IFDEF USE_UNIT_CONVERSIONS} function TPxMathParser.GetConvertValueFunction(var Index: Integer): Boolean; var TmpStr: string; I: Integer; begin Result := False; if (FParseText[FCurPos] in ['A'..'Z', 'a'..'z', '_']) and Assigned(ConvertValueFuncList) then begin with ConvertValueFuncList do for I := 0 to Count - 1 do begin TmpStr := Copy(FParseText, FCurPos, Length(Strings[I])); if (CompareText(TmpStr, Strings[I]) = 0) and (Objects[I] <> nil) then begin if FParseText[FCurPos + Cardinal(Length(TmpStr))] = '(' then begin Result := True; Inc(FCurPos, Length(TmpStr)); Index := I; Exit; end; end; end; end; Index := -1; end; {$ENDIF} function TPxMathParser.GetFunction(var AValue: TPxMathParserFunc): Boolean; var I: TPxMathParserFunc; TmpStr: string; begin Result := False; AValue := Low(TPxMathParserFunc); if FParseText[FCurPos] in ['A'..'Z', 'a'..'z', '_'] then begin for I := Low(TPxMathParserFunc) to High(TPxMathParserFunc) do begin TmpStr := Copy(FParseText, FCurPos, StrLen(FuncNames[I])); if CompareText(TmpStr, StrPas(FuncNames[I])) = 0 then begin AValue := I; if FParseText[FCurPos + Cardinal(Length(TmpStr))] = '(' then begin Result := True; Inc(FCurPos, Length(TmpStr)); Break; end; end; end; end; end; function TPxMathParser.Term: Extended; var Value: Extended; NoFunc: TPxMathParserFunc; UserFunc: Integer; Func: Pointer; {$IFDEF USE_UNIT_CONVERSIONS} CT1, CT2: TConvType; {$ENDIF} begin if FParseText[FCurPos] = '(' then begin Inc(FCurPos); Value := Calculate; if FParseText[FCurPos] <> ')' then InvalidCondition(FCurPos, SParseNotCramp); Inc(FCurPos); end else begin if not GetNumber(Value) then if not GetConst(Value) then if GetUserFunction(UserFunc) then begin Inc(FCurPos); Func := UserFuncList.Objects[UserFunc]; Value := TFarUserFunction(Func)(Calculate); if FParseText[FCurPos] <> ')' then InvalidCondition(FCurPos, SParseNotCramp); Inc(FCurPos); end else if GetGetValueFunction(UserFunc) then begin Inc(FCurPos); Func := GetValueFuncList.Objects[UserFunc]; Value := TFarGetValueFunction(Func)(GetString); if FParseText[FCurPos] <> ')' then InvalidCondition(FCurPos, SParseNotCramp); Inc(FCurPos); end {$IFDEF USE_UNIT_CONVERSIONS} else if GetConvertValueFunction(UserFunc) then begin Inc(FCurPos); Func := ConvertValueFuncList.Objects[UserFunc]; Value := Calculate; CT1 := GetConvType(';'); CT2 := GetConvType(')'); Value := TFarConvertValueFunction(Func)(Value, CT1, CT2); if FParseText[FCurPos] <> ')' then InvalidCondition(FCurPos, SParseNotCramp); Inc(FCurPos); end {$ENDIF} else if GetFunction(NoFunc) then begin Inc(FCurPos); Value := Calculate; try case NoFunc of pfArcTan: Value := ArcTan(Value); pfCos: Value := Cos(Value); pfSin: Value := Sin(Value); pfTan: if Cos(Value) = 0 then InvalidCondition(FCurPos, SParseDivideByZero) else Value := Sin(Value) / Cos(Value); pfAbs: Value := Abs(Value); pfExp: Value := Exp(Value); pfLn: if Value <= 0 then InvalidCondition(FCurPos, SParseLogError) else Value := Ln(Value); pfLog: if Value <= 0 then InvalidCondition(FCurPos, SParseLogError) else Value := Ln(Value) / Ln(10); pfSqrt: if Value < 0 then InvalidCondition(FCurPos, SParseSqrError) else Value := Sqrt(Value); pfSqr: Value := Sqr(Value); pfInt: Value := Round(Value); pfFrac: Value := Frac(Value); pfTrunc: Value := Trunc(Value); pfRound: Value := Round(Value); pfArcSin: if Value = 1 then Value := Pi / 2 else Value := ArcTan(Value / Sqrt(1 - Sqr(Value))); pfArcCos: if Value = 1 then Value := 0 else Value := Pi / 2 - ArcTan(Value / Sqrt(1 - Sqr(Value))); pfSign: if Value > 0 then Value := 1 else if Value < 0 then Value := -1; pfNot: Value := not Trunc(Value); end; except on E: EParserError do raise else InvalidCondition(-1, SParseInvalidFloatOperation); end; if FParseText[FCurPos] <> ')' then InvalidCondition(FCurPos, SParseNotCramp); Inc(FCurPos); end else InvalidCondition(FCurPos, SParseSyntaxError); end; Result := Value; end; function TPxMathParser.SubTerm: Extended; var Value: Extended; begin Value := Term; while FParseText[FCurPos] in ['*', '^', '/'] do begin Inc(FCurPos); if FParseText[FCurPos - 1] = '*' then Value := Value * Term else if FParseText[FCurPos - 1] = '^' then Value := Power(Value, Term) else if FParseText[FCurPos - 1] = '/' then try Value := Value / Term; except InvalidCondition(FCurPos, SParseDivideByZero); end; end; Result := Value; end; function TPxMathParser.Calculate: Extended; var Value: Extended; begin Value := SubTerm; while FParseText[FCurPos] in ['+', '-'] do begin Inc(FCurPos); if FParseText[FCurPos - 1] = '+' then Value := Value + SubTerm else Value := Value - SubTerm; end; if not (FParseText[FCurPos] in [#0, ')', '>', '<', '=', ',', ';']) then InvalidCondition(FCurPos, SParseSyntaxError); Result := Value; end; function TPxMathParser.GetString: String; begin Result := ''; SkipBlanks; if not (FParseText[FCurPos] in ['''']) then InvalidCondition(FCurPos, SParseSyntaxError); Inc(FCurPos); SkipBlanks; while not (FParseText[FCurPos] in [#0, '''']) do begin Result := Result + FParseText[FCurPos]; Inc(FCurPos); end; if not (FParseText[FCurPos] in ['''']) then InvalidCondition(FCurPos, SParseSyntaxError); Inc(FCurPos); SkipBlanks; if not (FParseText[FCurPos] in [')']) then InvalidCondition(FCurPos, SParseSyntaxError); end; {$IFDEF USE_UNIT_CONVERSIONS} function TPxMathParser.GetConvType(Expect: Char): TConvType; var S: String; begin S := ''; SkipBlanks; if not (FParseText[FCurPos] in [';']) then InvalidCondition(FCurPos, SParseSyntaxError); Inc(FCurPos); SkipBlanks; while FParseText[FCurPos] in ['A'..'Z', 'a'..'z', '0'..'9'] do begin S := S + FParseText[FCurPos]; Inc(FCurPos); end; SkipBlanks; if not (FParseText[FCurPos] in [Expect, #0]) then InvalidCondition(FCurPos, SParseSyntaxError); if S = '' then Result := 65535 else StrToConvUnit('1 ' + S, Result); end; {$ENDIF} function TPxMathParser.Exec(const AFormula: string): Extended; var I, J: Integer; begin J := 0; Result := 0; FParseText := ''; for I := 1 to Length(AFormula) do begin case AFormula[I] of '(': Inc(J); ')': Dec(J); end; if AFormula[I] > ' ' then FParseText := FParseText + UpCase(AFormula[I]); end; if J = 0 then begin FCurPos := 1; FParseText := FParseText + #0; if (FParseText[1] in ['-', '+']) then FParseText := '0' + FParseText; Result := Calculate; end else InvalidCondition(FCurPos, SParseNotCramp); end; class procedure TPxMathParser.RegisterUserFunction(const Name: string; Proc: TPxMathParserUserFunction); var I: Integer; begin if (Length(Name) > 0) and (Name[1] in ['A'..'Z', 'a'..'z', '_']) then begin if not Assigned(Proc) then UnregisterUserFunction(Name) else begin with GetUserFuncList do begin I := IndexOf(Name); if I < 0 then I := Add(Name); Objects[I] := @Proc; end; end; end else InvalidCondition(-1, SParseSyntaxError); end; class procedure TPxMathParser.UnregisterUserFunction(const Name: string); var I: Integer; begin if Assigned(UserFuncList) then with UserFuncList do begin I := IndexOf(Name); if I >= 0 then Delete(I); if Count = 0 then FreeUserFunc; end; end; class procedure TPxMathParser.RegisterGetValueFunction(const Name: string; Proc: TPxMathParserGetValueFunction); var I: Integer; begin if (Length(Name) > 0) and (Name[1] in ['A'..'Z', 'a'..'z', '_']) then begin if not Assigned(Proc) then UnregisterGetValueFunction(Name) else begin with GetGetValueFuncList do begin I := IndexOf(Name); if I < 0 then I := Add(Name); Objects[I] := @Proc; end; end; end else InvalidCondition(-1, SParseSyntaxError); end; class procedure TPxMathParser.UnregisterGetValueFunction(const Name: string); var I: Integer; begin if Assigned(GetValueFuncList) then with GetValueFuncList do begin I := IndexOf(Name); if I >= 0 then Delete(I); if Count = 0 then FreeGetValueFunc; end; end; {$IFDEF USE_UNIT_CONVERSIONS} class procedure TPxMathParser.RegisterConvertValueFunction(const Name: string; Proc: TPxMathParserConvertValueFunction); var I: Integer; begin if (Length(Name) > 0) and (Name[1] in ['A'..'Z', 'a'..'z', '_']) then begin if not Assigned(Proc) then UnregisterConvertValueFunction(Name) else begin with GetConvertValueFuncList do begin I := IndexOf(Name); if I < 0 then I := Add(Name); Objects[I] := @Proc; end; end; end else InvalidCondition(-1, SParseSyntaxError); end; class procedure TPxMathParser.UnregisterConvertValueFunction(const Name: string); var I: Integer; begin if Assigned(ConvertValueFuncList) then with ConvertValueFuncList do begin I := IndexOf(Name); if I >= 0 then Delete(I); if Count = 0 then FreeGetValueFunc; end; end; {$ENDIF} { *** } function GetFormulaValue(const Formula: string): Extended; begin with TPxMathParser.Create do try Result := Exec(Formula); finally Free; end; end; {$IFDEF USE_UNIT_CONVERSIONS} function ConvertValueUnit(Value: Extended; Base, Dest: TConvType): Extended; begin Result := 0; if (Base = 65535) and (Dest = 65535) then InvalidCondition(-1, SAtLeastOneUnitMustBeSpecified) else if Base = 65535 then Result := ConvertTo(Value, Dest) else if Dest = 65535 then Result := ConvertFrom(Base, Value) else Result := ConvertTo(ConvertFrom(Base, Value), Dest); end; {$ENDIF} initialization UserFuncList := nil; GetValueFuncList := nil; {$IFDEF USE_UNIT_CONVERSIONS} ConvertValueFuncList := nil; // TMathParser.RegisterConvertValueFunction('Convert', @ConvertValueUnit); {$ENDIF} finalization FreeUserFunc; FreeGetValueFunc; {$IFDEF USE_UNIT_CONVERSIONS} FreeConvertValueFunc; {$ENDIF} end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit ormbr.dml.generator.oracle; interface uses SysUtils, Rtti, ormbr.dml.generator, ormbr.mapping.classes, ormbr.mapping.explorer, ormbr.factory.interfaces, ormbr.types.database, ormbr.driver.register, ormbr.dml.commands, ormbr.criteria; type /// <summary> /// Classe de conexão concreta com dbExpress /// </summary> TDMLGeneratorOracle = class(TDMLGeneratorAbstract) public constructor Create; override; destructor Destroy; override; function GeneratorSelectAll(AClass: TClass; APageSize: Integer; AID: Variant): string; override; function GeneratorSelectWhere(AClass: TClass; AWhere: string; AOrderBy: string; APageSize: Integer): string; override; function GeneratorSequenceCurrentValue(AObject: TObject; ACommandInsert: TDMLCommandInsert): Int64; override; function GeneratorSequenceNextValue(AObject: TObject; ACommandInsert: TDMLCommandInsert): Int64; override; function GeneratorPageNext(ACommandSelect: string; APageSize: Integer; APageNext: Integer): string; override; end; implementation const cSelectRow = 'SELECT * FROM ( ' + sLineBreak + ' SELECT T.*, ROWNUM ROWINI FROM (%s) T'; { TDMLGeneratorOracle } constructor TDMLGeneratorOracle.Create; begin inherited; FDateFormat := 'yyyy-MM-dd'; FTimeFormat := 'HH:MM:SS'; end; destructor TDMLGeneratorOracle.Destroy; begin inherited; end; function TDMLGeneratorOracle.GeneratorPageNext(ACommandSelect: string; APageSize: Integer; APageNext: Integer): string; begin if APageSize > -1 then Result := Format(ACommandSelect, [IntToStr(APageNext + APageSize), IntToStr(APageNext)]); end; function TDMLGeneratorOracle.GeneratorSelectAll(AClass: TClass; APageSize: Integer; AID: Variant): string; var oCriteria: ICriteria; begin oCriteria := GetCriteriaSelect(AClass, AID); if APageSize > -1 then begin Result := Format(cSelectRow, [oCriteria.AsString]); Result := Result + sLineBreak + ' WHERE ROWNUM <= %s) ' + sLineBreak + 'WHERE ROWINI > %s'; end else Result := oCriteria.AsString; end; function TDMLGeneratorOracle.GeneratorSelectWhere(AClass: TClass; AWhere: string; AOrderBy: string; APageSize: Integer): string; var oCriteria: ICriteria; begin oCriteria := GetCriteriaSelect(AClass, -1); oCriteria.Where(AWhere); oCriteria.OrderBy(AOrderBy); if APageSize > -1 then begin Result := Format(cSelectRow, [oCriteria.AsString]); Result := Result + sLineBreak + ' WHERE ROWNUM <= %s) ' + sLineBreak + 'WHERE ROWINI >= %s'; end else Result := oCriteria.AsString; end; function TDMLGeneratorOracle.GeneratorSequenceCurrentValue(AObject: TObject; ACommandInsert: TDMLCommandInsert): Int64; begin Result := ExecuteSequence(Format('SELECT %s.CURRVAL FROM DUAL', [ACommandInsert.Sequence.Name])); end; function TDMLGeneratorOracle.GeneratorSequenceNextValue(AObject: TObject; ACommandInsert: TDMLCommandInsert): Int64; begin Result := ExecuteSequence(Format('SELECT %s.NEXTVAL FROM DUAL', [ACommandInsert.Sequence.Name])); end; initialization TDriverRegister.RegisterDriver(dnOracle, TDMLGeneratorOracle.Create); end.
unit LicenseZoneSelectFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, LicenseZone, Facade, StdCtrls, ActnList, Buttons; type TfrmLicenseZoneSelect = class(TFrame) lblCount: TLabel; grpLZSelect: TGroupBox; actlstLZSeach: TActionList; actSeach: TAction; cmbxLicenseZones: TComboBox; edtLZSeach: TEdit; act2: TAction; act1: TAction; btnPrev: TSpeedButton; btnNext: TSpeedButton; btnSearch: TSpeedButton; procedure act1PrevExecute(Sender : TObject); procedure act2NextExecute(Sender : TObject); procedure act1PrevUpdate(Sender : TObject); procedure act2NextUpdate(Sender : TObject); procedure actSeachExecute(Sender : TObject); procedure edtLZSeachEnter(Sender: TObject); procedure cmbxLicenseZonesChange(Sender: TObject); procedure actSeachUpdate(Sender: TObject); private { Private declarations } CurrentIndex: Integer; NewFrame: boolean; function GetActiveLicenseZone: TLicenseZone; procedure SetActiveLicenseZone(const Value: TLicenseZone); public { Public declarations } property ActiveLicenseZone: TLicenseZone read GetActiveLicenseZone write SetActiveLicenseZone; procedure PrepareLicenseZones; end; implementation {$R *.dfm} { TfrmLicenseZoneSelect } procedure TfrmLicenseZoneSelect.PrepareLicenseZones; begin CurrentIndex := 0; TMainFacade.GetInstance.AllLicenseZones.MakeList(cmbxLicenseZones.Items); lblCount.Caption := IntToStr(TMainFacade.GetInstance.AllLicenseZones.Count); NewFrame := true; edtLZSeach.Font.Color := clSilver; edtLZSeach.Text := 'Введите название лицензионного участка'; //btnLZSeach.Default := true; end; procedure TfrmLicenseZoneSelect.act1PrevExecute(Sender : TObject); begin cmbxLicenseZones.ItemIndex := cmbxLicenseZones.ItemIndex - 1; cmbxLicenseZonesChange(cmbxLicenseZones); end; procedure TfrmLicenseZoneSelect.act2NextExecute(Sender : Tobject); begin cmbxLicenseZones.ItemIndex := cmbxLicenseZones.ItemIndex + 1; cmbxLicenseZonesChange(cmbxLicenseZones); end; procedure TfrmLicenseZoneSelect.act1PrevUpdate(Sender : TObject); begin act1.Enabled := cmbxLicenseZones.ItemIndex > 0; end; procedure TfrmLicenseZoneSelect.act2NextUpdate(Sender : TObject); begin act2.Enabled := cmbxLicenseZones.ItemIndex < cmbxLicenseZones.Items.Count - 1; end; procedure TfrmLicenseZoneSelect.actSeachExecute(Sender : TObject); var i: integer; b: boolean; begin b := false; for i := CurrentIndex to cmbxLicenseZones.Items.Count - 1 do begin if Pos(AnsiUpperCase(edtLZSeach.Text), AnsiUpperCase(cmbxLicenseZones.Items[i])) > 0 then begin cmbxLicenseZones.ItemIndex := i; cmbxLicenseZonesChange(cmbxLicenseZones); CurrentIndex := i + 1; b := true; break; end; end; if not b then CurrentIndex := 0; end; procedure TfrmLicenseZoneSelect.edtLZSeachEnter(Sender: TObject); begin if NewFrame then begin edtLZSeach.Text := ''; edtLZSeach.Font.Color := clBlack; NewFrame := false; end; end; procedure TfrmLicenseZoneSelect.cmbxLicenseZonesChange(Sender: TObject); begin TMainFacade.GetInstance.ActiveLicenseZone := ActiveLicenseZone; end; function TfrmLicenseZoneSelect.GetActiveLicenseZone: TLicenseZone; begin Result := cmbxLicenseZones.Items.Objects[cmbxLicenseZones.ItemIndex] as TLicenseZone; end; procedure TfrmLicenseZoneSelect.SetActiveLicenseZone(const Value: TLicenseZone); begin cmbxLicenseZones.ItemIndex := cmbxLicenseZones.Items.IndexOfObject(Value); end; procedure TfrmLicenseZoneSelect.actSeachUpdate(Sender: TObject); begin actSeach.Enabled := (edtLZSeach.Font.Color = clBlack) and (edtLZSeach.Text <> ''); end; end.
unit uSocketFunction; //针对 delphi 语言特点的 socket 函数封装 interface uses Windows, WinSock, SysUtils; function SetNoBlock(so: TSocket):Boolean; //监听端口//简化接口,包括初始化环境和创建 socket function ListenPort(var Listensc:TSocket; port:Integer):Boolean; //接收一个连接 function AcceptSocket(Listensc:TSocket; var Acceptsc:TSocket):Boolean; //测试函数 function _send(s: TSocket; buf:AnsiString; len, flags: Integer): Integer; //测试函数 function _recv(s: TSocket; var buf:AnsiString; len, flags: Integer): Integer; implementation var g_InitSocket:Boolean = False; //初始化 socket 环境 procedure InitSock; var wsData: TWSAData; begin if WSAStartUp($202, wsData) <> 0 then begin WSACleanup(); end; end; //创建 socket function CreateSocket: TSocket; var errno:Integer; err: string; begin Result := socket(AF_INET, SOCK_STREAM, IPPROTO_IP);//一个客户端 tcp socket if SOCKET_ERROR = Result then begin errno := WSAGetLastError; err := SysErrorMessage(errno); //Result := False;//不一定,有可能是非阻塞 socket 未能立即完成//10035(WSAEWOULDBLOCK) 时 //Exit; //未调用 TThreadSafeSocket.InitSocket; end; end; //监听端口//简化接口,包括初始化环境和创建 socket function ListenPort(var Listensc:TSocket; port:Integer):Boolean; var sto:sockaddr_in; begin Result := False; if g_InitSocket = False then InitSock(); //创建一个套接字,将此套接字和一个端口绑定并监听此端口。 Listensc := CreateSocket();//Socket(AF_INET,SOCK_STREAM,0,Nil,0,WSA_FLAG_OVERLAPPED); if Listensc=SOCKET_ERROR then begin closesocket(Listensc); //WSACleanup(); Exit; end; sto.sin_family:=AF_INET; sto.sin_port := htons(port);//htons(5500); sto.sin_addr.s_addr:=htonl(INADDR_ANY); if WinSock.bind(Listensc, sto, sizeof(sto))=SOCKET_ERROR then //这个函数的声明和某些 winsocket2 的是不同的 begin closesocket(Listensc); Exit; end; //listen(Listensc,20); SOMAXCONN //listen(Listensc, SOMAXCONN); //listen(Listensc, $7fffffff);//WinSock2.SOMAXCONN); listen(Listensc, 1);//WinSock2.SOMAXCONN);// 2015/4/3 15:03:26 太大的话其实也是有问题的,会导致程序停止响应时客户端仍然可以连接上,并且大量的占用 Result := True; end; //接收一个连接 function AcceptSocket(Listensc:TSocket; var Acceptsc:TSocket):Boolean; begin Result := False; Acceptsc := Accept(Listensc, nil, nil); //判断Acceptsc套接字创建是否成功,如果不成功则退出。 if (Acceptsc= SOCKET_ERROR) then Exit; Result := True; end; function SetNoBlock(so: TSocket):Boolean; var errno:Integer; err: string; arg:Integer; begin Result := True; //-------------------------------------------------- //首先,设置通讯为非阻塞模式 arg := 1; ioctlsocket(so, FIONBIO, arg); //if SOCKET_ERROR = Connect(so, addr, Sizeof(TSockAddrIn)) then begin errno := WSAGetLastError; err := SysErrorMessage(errno); //Result := False;//不一定,有可能是非阻塞 socket 未能立即完成//10035(WSAEWOULDBLOCK) 时 //Exit; if errno <> WSAEWOULDBLOCK then //WSAEISCONN(10056) The socket is already connected begin //多次调试都是返回 WSAEWOULDBLOCK 的多,到这里来的可能性很小 Result := False; Exit; end; end; end; //send 函数的 delphi 特性封装,因为某些 delphi send 函数声明为 var 如果使用 string 实际上是会出错的,必须要取 string 有实际地址 //如果不明就里,直接把 string 的内容放到一个 ansichar 数据也行 //d7 WinSock.pas 的原声明为 function send(s: TSocket; var Buf; len, flags: Integer): Integer; stdcall; function _send(s: TSocket; buf:AnsiString; len, flags: Integer): Integer; begin //注意,用这句是不对的,虽然能编译//Result := send(s, buf, len, flags); //这是 delphi 的语言及 string 类型造成的特别语法,不用管它 Result := send(s, (@buf[1])^, len, flags); end; //方便字符应答式操作的函数 function _recv(s: TSocket; var buf:AnsiString; len, flags: Integer): Integer; //d7 WinSock.pas 的原声明为 function recv(s: TSocket; var Buf; len, flags: Integer): Integer; stdcall; begin SetLength(buf, len); FillChar((@buf[1])^, len, 0); //应该也是不能这样用的//Result :=recv(s, buf, len, flags); //这是 delphi 的语言及 string 类型造成的特别语法,不用管它 Result :=recv(s, (@buf[1])^, len, flags); end; end.
unit VisibleDSA.AlgoVisualizer; interface uses System.SysUtils, System.Types, System.Math, FMX.Graphics, FMX.Forms, VisibleDSA.AlgoVisHelper, VisibleDSA.MergeSortData; type TAlgoVisualizer = class(TObject) private _width: integer; _height: integer; _data: TMergeSortData; _form: TForm; procedure __setData(l, r, mergeIndex: integer); public constructor Create(form: TForm; sceneWidth, sceneHeight, n: integer); destructor Destroy; override; procedure Paint(canvas: TCanvas); procedure Run; end; implementation uses VisibleDSA.AlgoForm; type TArray_int = TArray<integer>; { TAlgoVisualizer } constructor TAlgoVisualizer.Create(form: TForm; sceneWidth, sceneHeight, n: integer); begin _form := form; _width := form.ClientWidth; _height := form.ClientHeight; _data := TMergeSortData.Create(n, _height); _form.Caption := 'Merge Sort Visualization'; end; destructor TAlgoVisualizer.Destroy; begin FreeAndNil(_data); inherited Destroy; end; procedure TAlgoVisualizer.Paint(canvas: TCanvas); var w: integer; i: integer; begin w := _width div _data.Length; for i := 0 to _data.Length - 1 do begin if (i >= _data.L) and (i <= _data.R) then TAlgoVisHelper.SetFill(CL_GREEN) else TAlgoVisHelper.SetFill(CL_GREY); if (i >= _data.L) and (i <= _data.MergeIndex) then TAlgoVisHelper.SetFill(CL_RED); TAlgoVisHelper.FillRectangle(canvas, i * w, _height - _data.GetValue(i), w - 1, _data.GetValue(i)); end; end; procedure TAlgoVisualizer.Run; function __arrayCopyOfRange__(arr: TArray_int; l, r: integer): TArray_int; var res: TArray_int; i: integer; begin SetLength(res, r - l + 1); for i := l to r do res[i - l] := arr[i]; Result := res; end; procedure __merge__(l, mid, r: integer); var aux: TArray_int; i, leftIndex, rightIndex: integer; begin aux := __arrayCopyOfRange__(_data.Numbers, l, r); // 初始化,leftIndex 指向左半部分的起始索引位置 l; // rightIndex 指向右半部分起始索引位置 mid+1 leftIndex := l; rightIndex := mid + 1; for i := l to r do begin if leftIndex > mid then // 如果左半部分元素已经全部处理完毕 begin _data.Numbers[i] := aux[rightIndex - l]; rightIndex := rightIndex + 1; end else if rightIndex > r then // 如果右半部分元素已经全部处理完毕 begin _data.Numbers[i] := aux[leftIndex - l]; leftIndex := leftIndex + 1; end else if aux[leftIndex - l] < aux[rightIndex - l] then // 左半部分所指元素 < 右半部分所指元素 begin _data.Numbers[i] := aux[leftIndex - l]; leftIndex := leftIndex + 1; end else // 左半部分所指元素 >= 右半部分所指元素 begin _data.Numbers[i] := aux[rightIndex - l]; rightIndex := rightIndex + 1; end; __setData(l, r, i); end; end; var sz, i: integer; begin __setData(-1, -1, -1); sz := 1; while sz < _data.Length do begin i := 0; while i < _data.Length - sz do begin // 对 arr[i...i+sz-1] 和 arr[i+sz...i+2*sz-1] 进行归并 __merge__(i, i + sz - 1, Min(i + sz + sz - 1, _data.Length - 1)); i := i + sz * 2; end; sz := sz * 2; end; __setData(0, _data.Length - 1, _data.Length - 1); end; procedure TAlgoVisualizer.__setData(l, r, mergeIndex: integer); begin _data.L := l; _data.R := r; _data.MergeIndex := mergeIndex; TAlgoVisHelper.Pause(10); AlgoForm.PaintBox.Repaint; end; end.
unit UxlRichEditClasses; interface uses Windows, UxlClasses, UxlRichEdit, UxlStack; type TxlRichEditDecorator = class (TxlInterfacedObject, IRichEditDecorator) private procedure SetColor (value: TColor); function GetColor (): TColor; protected FEditor: TxlRichEdit; FBrush: TxlBrush; FhdcCpb: HDC; //与RichEdit兼容的Dc FEnabled: boolean; procedure DoBeforePaint (); virtual; procedure DoPaint (); virtual; procedure DoOnNotify (code, lparam: dword); virtual; procedure AfterSwitchEnable (); virtual; procedure SetEnable (value: boolean); virtual; public constructor Create (AEditor: TxlRichEdit); virtual; destructor Destroy (); override; procedure BeforePaint (); procedure Paint (); procedure OnNotify (code, lparam: dword); procedure EditorRecreated (); virtual; property Color: TColor read GetColor write SetColor; property Enabled: boolean read FEnabled write SetEnable; end; TxlRichEditLineNumber = class (TxlRichEditDecorator) private FFont: TxlFont; FOldLeftMargin: integer; procedure SetFont (value: TxlFont); procedure f_CalcBarWidth (var i_barwidth, i_linecount, i_halfcharwidth: integer); protected // procedure AfterSwitchEnable (); override; procedure SetEnable (value: boolean); override; procedure DoBeforePaint (); override; public constructor Create (AEditor: TxlRichEdit); override; destructor Destroy (); override; procedure EditorRecreated (); override; property Font: TxlFont read FFont write SetFont; end; type TxlRichEditHLSuper = class (TxlRichEditDecorator) protected procedure f_HighlightText (hdcEdit: HDC; i_start, i_end, i_paintheight: integer); function f_CreateBmp (hdcEdit: HDC; var o_pos: TPos): HBitMap; procedure f_GetVisibleText (var s_text: widestring; var i_offset: cardinal); end; TxlRichEditHighlightSelLine = class (TxlRichEditHLSuper) private FRect: TRect; FErasedOnce: boolean; protected procedure DoBeforePaint (); override; procedure DoPaint (); override; procedure DoOnNotify (code, lparam: dword); override; public end; TxlRichEditHighlightText = class (TxlRichEditHLSuper) private FText: widestring; FMatchCase: boolean; FThickness: integer; procedure SetText (const value: widestring); procedure SetMatchCase (value: boolean); protected procedure DoPaint (); override; public property Text: widestring read FText write SetText; property MatchCase: boolean read FMatchCase write SetMatchCase; property Thickness: integer read FThickness write FThickness; // 0 为背景色高亮,否则为下划线高亮 end; TULScheme = record RightChar: widechar; // LeftChar 固定为 #28. RightChar建议值:#29, #30, #31, #127 Color: TColor; Thickness: integer; // 为 0 时为背景色高亮 end; TxlRichEditHighLightTextBlock = class (TxlRichEditHLSuper) private FSchemes: array of TULScheme; FStack: TxlIntStack; procedure SetScheme (index: integer; const value: TULScheme); function GetScheme (index: integer): TULScheme; // procedure SetColor (index: integer; value: TColor); // function GetColor (index: integer): TColor; function IndexValid (index: integer): boolean; protected procedure DoPaint (); override; public constructor Create (AEditor: TxlRichEdit); override; destructor Destroy (); override; function AddScheme (const value: TULScheme): integer; overload; // return index function AddScheme (rc: widechar; cl: TColor; tn: integer = 1): integer; overload; property Schemes[index: integer]: TULScheme read GetScheme write SetScheme; // property Colors[index: integer]: TColor read GetColor write SetColor; class function LeftChar (): widechar; end; type TxlRichEditFindHandler = class private FEditor: TxlRichEdit; FHLText: TxlRichEditHighlightText; Ffindtext: widestring; Fdirup: boolean; Fmatchcase: boolean; Fwholeword: boolean; Frollback: boolean; FWithinSelRange: boolean; FAllowReplace: boolean; FReplaceText: widestring; // FSelectFirstMatch: boolean; procedure SetFindText (const value: widestring); procedure SetMatchCase (value: boolean); function GetHLMatch (): boolean; procedure SetHLMatch (value: boolean); function GetHLColor (): TColor; procedure SetHLColor (value: TColor); function GetHLThickness (): integer; procedure SetHLThickness (value: integer); function DoFind (i_min, i_max: integer; b_dirup: boolean): integer; // returns pos of the first match public constructor Create (AEditor: TxlRichEdit); destructor Destroy (); override; function Find (b_reverse: boolean = false): boolean; // function Replace (): boolean; function ReplaceAll (): boolean; function CanFind (): boolean; function CanReplace (): boolean; property FindText: widestring read FFindText write SetFindText; property DirUp: boolean read FDirUp write FDirUp; property MatchCase: boolean read FMatchCase write SetMatchCase; property WholeWord: boolean read FWholeWord write FWholeWord; property RollBack: boolean read FRollBack write FRollBack; property WithinSelRange: boolean read FWithinSelRange write FWithinSelRange; property AllowReplace: boolean read FAllowReplace write FAllowReplace; property ReplaceText: widestring read FReplaceText write FReplaceText; property HighlightMatch: boolean read GetHLMatch write SetHLMatch; property HighlightColor: TColor read GetHLColor write SetHLColor; property HighlightThickness: integer read GetHLThickness write SetHLThickness; // property SelectFirstMatch: boolean read FSelectFirstMatch write FSelectFirstMatch; end; implementation uses UxlWinDef, UxlWindow, Messages, RichEdit, CommDlg, UxlFunctions, UxlMath, UxlStrUtils, UxlCommDlgs; constructor TxlRichEditFindHandler.Create (AEditor: TxlRichEdit); begin FEditor := AEditor; FHLText := TxlRichEditHighlightText.Create (AEditor); FHLText.Color := RGB (100, 100, 100); end; destructor TxlRichEditFindHandler.Destroy (); begin FHLText.free; inherited; end; procedure TxlRichEditFindHandler.SetFindText (const value: widestring); begin FFindText := value; FHLText.Text := value; end; procedure TxlRichEditFindHandler.SetMatchCase (value: boolean); begin FMatchCase := value; FHLText.MatchCase := value; end; function TxlRichEditFindHandler.GetHLMatch (): boolean; begin result := FHLText.Enabled; end; procedure TxlRichEditFindHandler.SetHLMatch (value: boolean); begin FHLText.Enabled := value; end; function TxlRichEditFindHandler.GetHLColor (): TColor; begin result := FHLText.Color; end; procedure TxlRichEditFindHandler.SetHLColor (value: TColor); begin FHLText.Color := value; end; function TxlRichEditFindHandler.GetHLThickness (): integer; begin result := FHLText.Thickness; end; procedure TxlRichEditFindHandler.SetHLThickness (value: integer); begin FHLText.Thickness := value; end; function TxlRichEditFindHandler.CanFind (): boolean; begin result := (FFindText <> ''); end; function TxlRichEditFindHandler.CanReplace (): boolean; begin result := AllowReplace and CanFind; end; function TxlRichEditFindHandler.DoFind (i_min, i_max: integer; b_dirup: boolean): integer; var wp: WPARAM; ft: TFindTextW; begin wp := 0; if not b_dirup then wp := wp or FR_DOWN; if wholeword then wp := wp or FR_WHOLEWORD; if matchcase then wp := wp or FR_MatchCase; if (i_max > i_min) and b_dirup then // 在选区内查询 begin ft.chrg.cpMin := i_max; ft.chrg.cpMax := i_min; end else begin ft.chrg.cpMin := i_min; ft.chrg.cpMax := i_max; end; ft.lpstrtext := pwidechar(FFindText); result := FEditor.Perform (EM_FINDTEXTW, wp, lparam(@ft)); end; function TxlRichEditFindHandler.Find (b_reverse: boolean = false): boolean; var i_pos, j, i_start, i_len: integer; b_dirup: boolean; begin result := false; if not CanFind then exit; b_dirup := dirup xor b_reverse; if (not WithinSelRange) and IsSameStr (FEditor.SelText, findtext, matchcase) then begin FEditor.GetSel (i_pos, j); if b_dirup then FEditor.SetSel (i_pos, 0) else FEditor.SetSel (i_pos + 1, 0); end; FEditor.GetSel (i_start, i_len); if WithinSelRange and (i_len > 0) then i_pos := DoFind (i_start, i_start + i_len, b_dirup) else i_pos := DoFind (i_start, -1, b_dirup); if (i_pos < 0) and (not WithinSelRange) and rollback then // 循环查找 begin if b_dirup then i_pos := DoFind (FEditor.TextLength, -1, b_dirup) else i_pos := DoFind (0, -1, b_dirup); end; result := i_pos >= 0; if result then begin FEditor.SetFocus; FEditor.SetSel (i_pos, length(findtext)); WithinSelRange := false; end; end; function TxlRichEditFindHandler.Replace (): boolean; var i, j: integer; begin result := CanReplace; if result then begin result := IsSameStr (FEditor.SelText, findtext, matchcase); if result then begin FEditor.GetSel (i, j); FEditor.SelText := replacetext; FEditor.SetSel (i + length(replacetext), 0); end; end; end; function TxlRichEditFindHandler.ReplaceAll (): boolean; var b_dirup: boolean; i_pos, i_start, j, i_len, i_len2, i_last: integer; begin result := false; if not CanReplace then exit; b_dirup := Dirup; if rollback and (not WithinSelRange) then begin b_dirup := false; FEditor.SetSel (0, 0); end; i_len := Length(FindText); i_len2 := Length(ReplaceText); FEditor.GetSel (i_start, j); if WithinSelRange then i_last := i_start + j else i_last := -1; while true do begin i_pos := DoFind (i_start, i_last, b_dirup); if i_pos < 0 then break; FEditor.SetSel (i_pos, i_len); FEditor.SelText := ReplaceText; result := true; i_start := i_pos + i_len2; if WithinSelRange then begin i_last := i_last + i_len2 - i_len; if i_start >= i_last then break; end; end; end; //------------------------ constructor TxlRichEditDecorator.Create (AEditor: TxlRichEdit); var hdcEdit: HDC; begin FEditor := AEditor; FBrush := TxlBrush.Create; hdcEdit := GetDC ( FEditor.handle ); //获取RichEdit的Dc FhdcCpb := CreateCompatibleDC( hdcEdit ); //创建与RichEdit兼容的Dc SetBkMode( FhdcCpb, TRANSPARENT ); SetTextColor( FhdcCpb, $000000 ); //设置显示行号的前景色 SetTextAlign (FhdcCpb, TA_RIGHT); ReleaseDC (FEditor.handle, hdcEdit); FEditor.AddDecorator (self); end; destructor TxlRichEditDecorator.Destroy (); begin FEditor.RemoveDecorator (self); FBrush.free; DeleteDC( FhdcCpb ); inherited; end; procedure TxlRichEditDecorator.BeforePaint (); begin if Enabled then DoBeforePaint; end; procedure TxlRichEditDecorator.Paint (); begin if Enabled then DoPaint; end; procedure TxlRichEditDecorator.EditorRecreated (); begin end; procedure TxlRichEditDecorator.OnNotify (code, lparam: dword); begin if Enabled then DoOnNotify (code, lparam); end; procedure TxlRichEditDecorator.DoBeforePaint (); begin end; procedure TxlRichEditDecorator.DoPaint (); begin end; procedure TxlRichEditDecorator.DoOnNotify (code, lparam: dword); begin end; procedure TxlRichEditDecorator.SetColor (value: TColor); begin FBrush.Color := value; FEditor.Redraw; end; function TxlRichEditDecorator.GetColor (): TColor; begin result := FBrush.Color; end; procedure TxlRichEditDecorator.SetEnable (value: boolean); begin if value <> FEnabled then begin FEnabled := value; AfterSwitchenable; FEditor.Redraw; end; end; procedure TxlRichEditDecorator.AfterSwitchEnable (); begin end; //---------------------- constructor TxlRichEditLineNumber.Create (AEditor: TxlRichEdit); begin inherited Create (AEditor); FFont := TxlFont.Create; FOldLeftMargin := FEditor.LeftMargin; end; destructor TxlRichEditLineNumber.Destroy (); begin FFont.free; inherited; end; procedure TxlRichEditLineNumber.SetEnable (value: boolean); begin inherited SetEnable (value); FOldLeftMargin := FEditor.LeftMargin; end; procedure TxlRichEditLineNumber.SetFont (value: TxlFont); begin FFont.Assign(value); end; procedure TxlRichEditLineNumber.f_CalcBarWidth (var i_barwidth, i_linecount, i_halfcharwidth: integer); var i, i_charcount: integer; begin i_LineCount := FEditor.LineCount; i_charcount := Length(IntToStr(i_LineCount)); GetCharWidth32 (FhdcCpb, 57, 57, i); i_barwidth := (i_charcount + 1) * i + 4; i_halfcharwidth := i div 2 + 2; end; procedure TxlRichEditLineNumber.EditorRecreated (); begin FEditor.Perform (EM_SETMARGINS, EC_LEFTMARGIN, MakeLParam(FOldLeftMargin, 0)); end; procedure TxlRichEditLineNumber.DoBeforePaint (); procedure f_DetectFirstChar (var i_y: integer; var i_linenumber: integer); var o_point: TPoint; i_index: cardinal; begin i_index := FEditor.GetCharIndex (0, 0); i_linenumber := FEditor.Perform (EM_LINEFROMCHAR, i_index, 0); FEditor.Perform (EM_POSFROMCHAR, dword(@o_point), i_index); i_y := o_point.y; end; var cr: TRect; //RichEdit的客户区大小 BarRect: TRect; // 行号区 hdcBmp: HBITMAP; //RichEdit兼容的位图dc chHeight: integer; //字符的高度,常量 ClientHeight: integer; //RichEdit的客户区高度 i_line: integer; i_FirstLine: integer; //文本框中的第一个可见行的行号。 i_LineCount: integer; //文本的总行数 hdcEdit: HDC; i_barwidth, i_halfcharwidth, i_y, i_right, i_leftmargin: integer; s: widestring; begin // 获取行高与第一行位置 f_DetectFirstChar (i_y, i_FirstLine); chHeight := FEditor.LineHeight; FFont.Height := chHeight; SelectObject (FhdcCpb, Ffont.Handle); f_CalcBarWidth (i_barwidth, i_linecount, i_halfcharwidth); i_leftmargin := i_barwidth + FEditor.LeftMargin; // i_currentleftmargin := LoWord (FEditor.Perform (EM_GETMARGINS, 0, 0)); // 执行速度的瓶颈,千万不可! if i_leftmargin <> FOldLeftMargin then begin // f_AdjustLeftMargin; // 执行速度的瓶颈,千万不可! FEditor.Perform (EM_SETMARGINS, EC_LEFTMARGIN, MakeLParam(i_leftmargin, 0)); FOldLeftMargin := i_leftmargin; FEditor.Redraw; // 必须,否则在行号区会残留一些如光标一类的幻影 end; GetClientRect( FEditor.handle, cr); BarRect := cr; BarRect.Right := BarRect.Left + i_barwidth; ClientHeight := cr.bottom - cr.top; //获取RichEdit的客户区高度 hdcEdit := GetDC ( FEditor.handle ); //获取RichEdit的Dc hdcBmp := CreateCompatibleBitmap ( hdcEdit, i_barwidth, ClientHeight ); //创建与RichEdit兼容的位图Dc,用来显示行号。 SelectObject( FhdcCpb, hdcBmp ); //将位图dc选入RichEdit环境中 FillRect ( FhdcCpb, BarRect, FBrush.handle ); //填充显示行号dc的背景颜色。 i_right := BarRect.Right - i_halfcharwidth; // 行号右侧适当留空 for i_line := i_FirstLine + 1 to i_LineCount do //在位图dc中循环输出行号 begin s := IntToStr(i_line); TextOutW (FhdcCpb, i_right, i_y, pwidechar(s), Length(s)); Inc (i_y, chHeight); if ( i_y > ClientHeight) then break; end; // 将已"画好"的位图真正"贴"到RichEdit中 BitBlt ( hdcEdit, 0, 0, i_barwidth, ClientHeight, FhdcCpb, 0, 0, SRCCOPY ); DeleteObject( hdcBmp ); cr.Right := i_barwidth; ValidateRect (FEditor.handle, @cr); ReleaseDC( FEditor.handle, hdcEdit ); end; //------------------------ procedure TxlRichEditHighlightSelLine.DoOnNotify (code, lparam: dword); begin if code = EN_SelChange then DoBeforePaint; end; procedure TxlRichEditHighlightSelLine.DoBeforePaint (); procedure f_Erase (); begin InvalidateRect (FEditor.handle, @FRect, true); // 擦除先前的高亮痕迹 end; var o_point: TPoint; i, j: integer; begin GetCaretPos (o_point); if o_point.y <> FRect.Top then // 防止频繁erase而闪烁 f_Erase else begin i := FEditor.Perform (EM_LINEINDEX, FEditor.LineNumber, 0); j := FEditor.GetCharIndex (o_point.x, o_point.y); if j - i <= 1 then // 无此在一行中输入第一字符时会出现两行高亮的问题 f_Erase; end; end; procedure TxlRichEditHighlightSelLine.DoPaint (); var o_TextRect: TRect; hdcBmp: HBITMAP; //RichEdit兼容的位图dc hdcEdit: HDC; o_pos: TPos; o_point: TPoint; begin o_textrect := FEditor.TextRect; GetCaretPos (o_point); if not InRange (o_point.y, o_textrect.top, o_textrect.bottom) then exit; hdcEdit := GetDC (FEditor.handle); hdcBmp := f_CreateBmp (hdcEdit, o_pos); SelectObject( FhdcCpb, hdcBmp ); //将位图dc选入RichEdit环境中 FillRect( FhdcCpb, PosToRect (o_pos), FBrush.handle ); o_pos.x := o_TextRect.left; o_pos.y := o_point.y; BitBlt ( hdcEdit, o_pos.x, o_pos.y, o_pos.width, o_pos.height, FhdcCpb, 0, 0, SRCAND ); DeleteObject( hdcBmp ); o_pos.height := o_pos.height * 3; // 不乘3则擦不干净 FRect := PosToRect (o_pos); ReleaseDC (FEditor.handle, hdcEdit); end; //---------------------- procedure TxlRichEditHLSuper.f_HighlightText (hdcEdit: HDC; i_start, i_end, i_paintheight: integer); function f_GetRightX (i_y: integer): integer; var i, j, i_width: integer; s: widestring; begin j := i_y + FEditor.LineHeight; i := FEditor.GetCharIndex (0, j); while j > i_y do begin dec (i); FEditor.GetCharXY (i, result, j); end; s := FEditor.GetTextBlock (i, 1); // GetTextExtentPoint32W (hdcEdit, pwidechar(s), 1, sz); GetCharWidth32W (hdcEdit, Ord(s[1]), Ord(s[1]), i_width); inc (result, i_width + 5); end; var i_x, i_y, i_width, i_firstx, i_firsty, i_lastx, i_lasty, i_lineheight: integer; o_textrect: TRect; tm: TTextMetric; begin o_textrect := FEditor.TextRect; i_lineheight := FEditor.LineHeight; if i_paintheight <= 0 then i_paintheight := i_lineheight; FEditor.GetCharXY (i_start, i_firstx, i_firsty); FEditor.GetCharXY (i_end, i_lastx, i_lasty); GetTextMetrics (hdcEdit, tm); i_y := i_firsty; while i_y <= i_lasty do begin if i_y = i_firsty then // 第一行 begin i_x := i_firstx; if i_firsty = i_lasty then i_Width := i_lastx - i_firstx else i_width := f_GetRightX (i_y) - i_firstx; // + tm.tmMaxCharWidth *6 div 5; // o_textrect.right end else if i_y = i_lasty then // 最后一行 begin i_x := o_textrect.Left; i_width := i_lastx - i_x; end else begin i_x := o_textrect.Left; i_width := f_GetRightX (i_y) - i_x; // + tm.tmMaxCharWidth *6 div 5; end; BitBlt ( hdcEdit, i_x, i_y + i_lineheight - i_paintheight, i_width, i_paintheight, FhdcCpb, 0, 0, SRCAND ); inc (i_y, i_lineheight); end; end; function TxlRichEditHLSuper.f_CreateBmp (hdcEdit: HDC; var o_pos: TPos): HBitMap; var o_textrect: TRect; begin o_textrect := FEditor.TextRect; o_pos.x := 0; o_pos.y := 0; o_pos.width := o_TextREct.Right - o_textrect.Left; o_pos.height := FEditor.LineHeight; result := CreateCompatibleBitmap( hdcEdit, o_pos.width, o_pos.height ); //创建与RichEdit兼容的位图Dc。 end; procedure TxlRichEditHLSuper.f_GetVisibleText (var s_text: widestring; var i_offset: cardinal); var i_end: cardinal; begin FEditor.GetVisibleTextRange (i_offset, i_end); s_text := FEditor.GetTextBlock (i_offset, i_end - i_offset + 1); end; //---------------------- procedure TxlRichEditHighlightText.SetText (const value: widestring); begin if value <> FText then begin FText := value; FEditor.Redraw; end; end; procedure TxlRichEditHighlightText.SetMatchCase (value: boolean); begin if value <> FMatchCase then begin FMatchCase := value; FEditor.Redraw; end; end; procedure TxlRichEditHighlightText.DoPaint (); var i_offset, i_len, i_pos: cardinal; o_pos: TPos; s_text, s_tar: widestring; hdcEdit: HDC; hdcBmp: HBITMAP; //RichEdit兼容的位图dc begin hdcEdit := GetDC (FEditor.handle); hdcBmp := f_CreateBmp (hdcEdit, o_pos); SelectObject( FhdcCpb, hdcBmp ); //将位图dc选入RichEdit环境中 FillRect( FhdcCpb, PosToRect(o_pos), FBrush.handle ); f_GetVisibleText (s_text, i_offset); s_tar := FText; i_len := length(s_tar); if not FMatchCase then begin s_tar := lowercase (s_tar); s_text := lowercase (s_text); end; i_pos := FirstPos (s_tar, s_text); while i_pos > 0 do begin f_HighlightText (hdcEdit, i_pos + i_offset - 1, i_pos + i_offset + i_len - 1, FThickness); i_pos := FirstPos (s_tar, s_text, i_pos + i_len); end; DeleteObject( hdcBmp ); ReleaseDC (FEditor.handle, hdcEdit); end; //--------------------------- constructor TxlRichEditHighlightTextBlock.Create (AEditor: TxlRichEdit); begin inherited Create (AEditor); FStack := TxlIntStack.Create; end; destructor TxlRichEditHighlightTextBlock.Destroy (); begin FStack.free; inherited; end; function TxlRichEditHighlightTextBlock.IndexValid (index: integer): boolean; begin result := InRange (index, 0, Length(FSchemes) - 1); end; procedure TxlRichEditHighlightTextBlock.SetScheme (index: integer; const value: TULScheme); begin if IndexValid (index) then FSchemes[index] := value else AddScheme (value); end; function TxlRichEditHighlightTextBlock.GetScheme (index: integer): TULScheme; begin if IndexValid (index) then result := FSchemes[index]; end; function TxlRichEditHighlightTextBlock.AddScheme (const value: TULScheme): integer; // return index var n: integer; begin n := Length (FSchemes); SetLength (FSchemes, n + 1); FSchemes[n] := value; end; function TxlRichEditHighlightTextBlock.AddScheme (rc: widechar; cl: TColor; tn: integer = 1): integer; var o_scheme: TULScheme; begin with o_scheme do begin RightChar := rc; Color := cl; Thickness := tn; end; result := AddScheme (o_scheme); end; procedure TxlRichEditHighlightTextBlock.DoPaint (); function f_IsRightChar (c: widechar; var sc: integer): boolean; var i: integer; begin result := false; for i := Low(FSchemes) to High(FSchemes) do if c = FSchemes[i].RightChar then begin result := true; sc := i; break; end; end; var i_offset: cardinal; i, sc, lp: integer; o_pos: TPos; s_text: widestring; hdcEdit: HDC; hdcBmp: HBITMAP; //RichEdit兼容的位图dc begin hdcEdit := GetDC (FEditor.handle); hdcBmp := f_CreateBmp (hdcEdit, o_pos); SelectObject( FhdcCpb, hdcBmp ); //将位图dc选入RichEdit环境中 f_GetVisibleText (s_text, i_offset); FStack.Clear; for i := 1 to Length(s_text) do if s_text[i] = LeftChar then FStack.Push (i) else if (f_IsRightChar (s_text[i], sc) and FStack.Pop (lp)) then begin FBrush.Color := FSchemes[sc].Color; FillRect( FhdcCpb, PosToRect(o_pos), FBrush.handle ); f_HighlightText (hdcEdit, lp + i_offset, i + i_offset - 1, FSchemes[sc].Thickness); end; DeleteObject( hdcBmp ); ReleaseDC (FEditor.handle, hdcEdit); end; class function TxlRichEditHighlightTextBlock.LeftChar (): widechar; begin result := #28; //#1, #127; end; end.
unit BaseGUI; interface uses Classes, Forms, Windows, Controls, StdCtrls, Contnrs, SysUtils, CheckLst, Grids, ComCtrls, Graphics, ActnList; type TAdapterButton = (abAutoSave, abClear, abSave, abReload, abAdd, abDelete, abFind, abSort, abSelectAll, abAddGroup, abEdit, abCancel); TAdapterButtons = set of TAdapterButton; TCheckEvent = procedure (Sender: TObject) of object; TParameterType = (ptChangesDisabled, ptDate, ptString, ptFloat, ptInteger, ptSelect, ptBoolean, ptNonEmptyList, ptTreeMultiSelect); THintedControl = class private FEmptyAllowed: boolean; FName: string; FPreCheckEvent: TCheckEvent; FControl: TControl; FAdditional: TObject; FValueType: TParameterType; public // событие которое было повешено на элемент до этого property PreCheckEvent: TCheckEvent read FPreCheckEvent write FPreCheckEvent; // основной компонент property Control: TControl read FControl write FControl; // дополнение, например, строка или столбец таблицы property Additional: TObject read FAdditional write FAdditional; property ValueType: TParameterType read FValueType write FValueType; // не считать пустое значение ошибкой property EmptyAllowed: boolean read FEmptyAllowed write FEmptyAllowed; property Name: string read FName write FName; end; THintManager = class(TList) private FStatus: TControl; FErrorRow: integer; FCheckEvent: TCheckEvent; function GetItem(const Index: integer): THintedControl; procedure sgrDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure CheckArray(const AParamIndex: integer); function GetByName(const AName: string): integer; function GetItemsByName(const AName: string): THintedControl; function TreeViewMultiSelectionApplied(ATrw: TTreeView): integer; function GetValue(AHintedControl: THintedControl): string; public function Add(AControl: TControl; AAdditional: TObject; const AValueType: TParameterType; const AName: string; const AEmptyAllowed: boolean): THintedControl; property Status: TControl read FStatus write FStatus; property Items[const Index: integer]: THintedControl read GetItem; property ItemsByName[const AName: string]: THintedControl read GetItemsByName; // проверяет всюду ли введены валидные значения function Check: boolean; property CheckEvent: TCheckEvent read FCheckEvent write FCheckEvent; procedure Clear; override; constructor Create(AStatus: TControl); destructor Destroy; override; end; IGUIAdapter = interface function GetChangeMade: boolean; procedure SetChangeMade(const Value: boolean); function GetAutoSave: boolean; procedure SetAutoSave(const Value: boolean); function GetAdapterButtons: TAdapterButtons; procedure SetAdapterButtons(const Value: TAdapterButtons); procedure BeforeReload; procedure AfterReload; procedure AfterAdd; procedure AfterDelete; procedure Clear; procedure SelectAll; function Save: integer; procedure Reload; function Add: integer; function Delete: integer; function StartFind: integer; property Buttons: TAdapterButtons read GetAdapterButtons write SetAdapterButtons; property ChangeMade: boolean read GetChangeMade write SetChangeMade; property AutoSave: boolean read GetAutoSave write SetAutoSave; end; TGUIAdapter = class(TComponent) private FChangeMade: boolean; FAutoSave: boolean; FAdapterButtons: TAdapterButtons; FOnAfterReload, FOnAfterAdd, FOnAfterDelete: TNotifyEvent; FOnBeforeReload: TNotifyEvent; procedure DoOnExitEvent(Sender: TObject); function GetFrame: TFrame; procedure BtnFindFormClose(Sender: TObject); function GetApplyCancelSaveMode: boolean; protected frmFind: TForm; function GetChangeMade: boolean; procedure SetChangeMade(const Value: boolean); function GetAutoSave: boolean; procedure SetAutoSave(const Value: boolean); function GetAdapterButtons: TAdapterButtons; procedure SetAdapterButtons(const Value: TAdapterButtons); procedure BeforeReload; virtual; procedure AfterReload; virtual; procedure AfterAdd; virtual; procedure AfterDelete; virtual; function GetCanAddGroup: boolean; virtual; function GetCanAdd: boolean; virtual; function GetCanDelete: boolean; virtual; function GetCanEdit: boolean; virtual; function GetCanSave: boolean; virtual; function GetCanReload: boolean; virtual; function GetCanClear: boolean; virtual; function GetCanFind: boolean; virtual; function GetCanCancel: boolean; virtual; public property CanClear: boolean read GetCanClear; procedure Clear; virtual; procedure SelectAll; virtual; property CanSave: boolean read GetCanSave; function Save: integer; virtual; property CanReload: boolean read GetCanReload; procedure Reload; virtual; property CanAdd: boolean read GetCanAdd; function Add (): integer; virtual; property CanEdit: boolean read GetCanEdit; function Edit: integer; virtual; function Cancel: boolean; virtual; property CanCancel: boolean read GetCanCancel; property CanAddGroup: boolean read GetCanAddGroup; procedure AddGroup; virtual; property CanDelete: boolean read GetCanDelete; function Delete: integer; virtual; property CanFind: boolean read GetCanFind; function StartFind: integer; virtual; property ChangeMade: boolean read GetChangeMade write SetChangeMade; property AutoSave: boolean read GetAutoSave write SetAutoSave; property Buttons: TAdapterButtons read GetAdapterButtons write SetAdapterButtons; property ApplyCancelSaveMode: boolean read GetApplyCancelSaveMode; property Frame: TFrame read GetFrame; property OnBeforeReload: TNotifyEvent read FOnBeforeReload write FOnBeforeReload; property OnAfterReload: TNotifyEvent read FOnAfterReload write FOnAfterReload; property OnAfterAdd: TNotifyEvent read FOnAfterAdd write FOnAfterAdd; property OnAfterDelete: TNotiFyEvent read FOnAfterDelete write FOnAfterDelete; constructor Create(AOwner: TComponent); override; end; TSortOrder = class private FName: string; FCompare: TListSortCompare; FReverseCompare: TListSortCompare; public property Name: string read FName write FName; property Compare: TListSortCompare read FCompare write FCompare; property ReverseCompare: TListSortCompare read FReverseCompare write FReverseCompare; constructor Create; end; TSortOrders = class(TObjectList) private function GetItems(Index: integer): TSortOrder; public function AddOrder(AName: string; ACompare, AReverseCompare: TListSortCompare): TSortOrder; property Items[Index: integer]: TSortOrder read GetItems; constructor Create; end; TCollectionGUIAdapter = class(TGUIAdapter) private FList: TListBox; FSortOrders: TSortOrders; FStraightOrder: boolean; FOrderBy: integer; FCheckList: TCheckListBox; protected function GetCanSort: boolean; virtual; public property OrderBy: integer read FOrderBy write FOrderBy; property StraightOrder: boolean read FStraightOrder write FStraightOrder; function Add: integer; override; procedure AddGroup; override; procedure SelectAll; override; property CanSort: boolean read getCanSort; property SortOrders: TSortOrders read FSortOrders; property List: TListBox read FList write FList; property CheckList: TCheckListBox read FCheckList write FCheckList; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; TSubStringFunction = function (SubStr, S: string): boolean; var comps: array[0 .. 3] of TSubStringFunction; procedure Invert(AListBox: TListBox); implementation uses BaseConsts, ExtCtrls; { TGUIAdapter } function Starting(SubStr, S: string): boolean; begin Result := pos(AnsiUpperCase(SubStr), AnsiUpperCase(S)) = 1; end; function Containing(SubStr, S: string): boolean; begin Result := pos(AnsiUpperCase(SubStr), AnsiUpperCase(S)) > 0; end; function NotContaining(SubStr, S: string): boolean; begin Result := Not Containing(SubStr, S); end; function Equal(SubStr, S: string): boolean; begin Result := AnsiUpperCase(SubStr) = AnsiUpperCase(S); end; procedure Invert(AListBox: TListBox); var i: integer; begin for i := 0 to AListBox.Items.Count - 1 do AListBox.Selected[i] := not AListBox.Selected[i]; end; function TGUIAdapter.Add: integer; begin Result := 0; AfterAdd; end; procedure TGUIAdapter.AddGroup; begin AfterAdd; end; procedure TGUIAdapter.AfterAdd; begin if Assigned(FOnAfterAdd) then FOnAfterAdd(Self); end; procedure TGUIAdapter.AfterDelete; begin if Assigned(FOnAfterDelete) then FOnAfterDelete(Self); end; procedure TGUIAdapter.AfterReload; begin if Assigned(FOnAfterReload) then FOnAfterReload(Self); end; procedure TGUIAdapter.BeforeReload; begin DoOnExitEvent(nil); if Assigned(FOnBeforeReload) then FOnBeforeReload(Self); end; procedure TGUIAdapter.BtnFindFormClose(Sender: TObject); begin if Assigned(frmFind) then frmFind.Close; end; function TGUIAdapter.Cancel: boolean; begin Result := false; end; procedure TGUIAdapter.Clear; begin ChangeMade := false; end; constructor TGUIAdapter.Create(AOwner: TComponent); begin inherited; if (AOwner is TFrame) then (AOwner as TFrame).OnExit := DoOnExitEvent; FAutoSave := true; //FAutoSave := false; FAdapterButtons := [abClear, abSave, abReload, abFind] end; function TGUIAdapter.Delete: integer; begin Result := 0; AfterDelete; end; procedure TGUIAdapter.DoOnExitEvent(Sender: TObject); begin if ChangeMade then begin if AutoSave or (MessageBox(Frame.Handle, PChar(sAutoSaveMessage), PChar('Есть вопрос'), MB_YESNO + MB_ICONQUESTION + MB_DEFBUTTON1 + MB_APPLMODAL) = ID_YES) then Save else ChangeMade := false; end; end; function TGUIAdapter.Edit: integer; begin Result := 0; AfterAdd; end; function TGUIAdapter.GetAdapterButtons: TAdapterButtons; begin Result := FAdapterButtons; end; function TGUIAdapter.GetApplyCancelSaveMode: boolean; begin Result := abCancel in Buttons; end; function TGUIAdapter.GetAutoSave: boolean; begin Result := FAutoSave; end; function TGUIAdapter.GetCanAdd: boolean; begin Result := true; end; function TGUIAdapter.GetCanAddGroup: boolean; begin Result := true; end; function TGUIAdapter.GetCanCancel: boolean; begin Result := true; end; function TGUIAdapter.GetCanClear: boolean; begin Result := true; end; function TGUIAdapter.GetCanDelete: boolean; begin Result := true; end; function TGUIAdapter.GetCanEdit: boolean; begin Result := true; end; function TGUIAdapter.GetCanFind: boolean; begin Result := true; end; function TGUIAdapter.GetCanReload: boolean; begin Result := true; end; function TGUIAdapter.GetCanSave: boolean; begin Result := true; end; function TGUIAdapter.GetChangeMade: boolean; begin Result := FChangeMade; end; function TGUIAdapter.GetFrame: TFrame; begin Result := nil; if Owner is TFrame then Result := Owner as TFrame end; procedure TGUIAdapter.Reload; begin ChangeMade := false; AfterReload; end; function TGUIAdapter.Save: integer; begin ChangeMade := false; Result := 0; end; procedure TGUIAdapter.SelectAll; begin ChangeMade := false; end; procedure TGUIAdapter.SetAdapterButtons(const Value: TAdapterButtons); begin FAdapterButtons := Value; end; procedure TGUIAdapter.SetAutoSave(const Value: boolean); begin FAutoSave := Value; end; procedure TGUIAdapter.SetChangeMade(const Value: boolean); begin FChangeMade := Value; end; function TGUIAdapter.StartFind: integer; var pnl: TPanel; btn: TButton; begin Result := 0; if not Assigned(frmFind) then begin // создаём форму с панелькой и кнопкой закрыть frmFind := TForm.Create(Application.MainForm); frmFind.Parent := nil; frmFind.FormStyle := fsStayOnTop; frmFind.BorderIcons := [biSystemMenu]; frmFind.Position := poMainFormCenter; frmFind.Tag := 0; frmFind.Height := 400; frmFind.Width := 400; pnl := TPanel.Create(frmFind); pnl.Parent := frmFind; pnl.Align := alBottom; pnl.Height := 50; pnl.BevelOuter := bvLowered; btn := TButton.Create(pnl); btn.Parent := pnl; btn.Anchors := [akRight, akBottom]; btn.OnClick := BtnFindFormClose; btn.Top := 14; btn.Left := 100; btn.Caption := 'Закрыть'; // btn.ModalResult := mrCancel; Result := 0; end; end; { TSortOrder } constructor TSortOrder.Create; begin end; { TSortOrders } function TSortOrders.AddOrder(AName: string; ACompare, AReverseCompare: TListSortCompare): TSortOrder; begin Result := TSortOrder.Create; Result.Name := AName; Result.Compare := ACompare; Result.ReverseCompare := AReverseCompare; Add(Result); end; constructor TSortOrders.Create; begin inherited Create(true); end; function TSortOrders.GetItems(Index: integer): TSortOrder; begin Result := inherited Items[Index] as TSortOrder; end; { TCollectionGUIAdapter } function TCollectionGUIAdapter.Add: integer; begin if Assigned (List) then begin List.ItemIndex := List.Count - 1; List.Selected[List.ItemIndex] := true; end; Result := inherited Add; end; procedure TCollectionGUIAdapter.AddGroup; begin inherited; end; constructor TCollectionGUIAdapter.Create(AOwner: TComponent); begin inherited; FSortOrders := TSortOrders.Create; end; destructor TCollectionGUIAdapter.Destroy; begin FSortOrders.Free; inherited; end; function TCollectionGUIAdapter.getCanSort: boolean; begin Result := SortOrders.Count > 0; end; procedure TCollectionGUIAdapter.SelectAll; var i: integer; begin inherited; if Assigned (CheckList) then for i := 0 to CheckList.Count - 1 do CheckList.Checked[i] := true; ChangeMade := true; end; { THintManager } function THintManager.Add(AControl: TControl; AAdditional: TObject; const AValueType: TParameterType; const AName: string; const AEmptyAllowed: boolean): THintedControl; var hC: THintedControl; begin hC := ItemsByName[AName]; if Assigned(hC) then begin Result := hC; exit; end; hC := THintedControl.Create; with hC do begin Control := AControl; Additional := AAdditional; ValueType := AValueType; Name := AName; EmptyAllowed := AEmptyAllowed; if Assigned(CheckEvent) then begin //FPreCheckEvent := nil; if Control is TEdit then begin // сохраняем старое действие, которое там было // то есть пробуем if Assigned((Control as TEdit).OnChange) and not Assigned(FPreCheckEvent) then FPreCheckEvent := (Control as TEdit).OnChange; (Control as TEdit).OnChange := CheckEvent end else if Control is TCombobox then begin if (Assigned((Control as TComboBox).OnChange)) and not Assigned(FPreCheckEvent) then FPreCheckEvent := (Control as TComboBox).OnChange; (Control as TCombobox).OnChange := CheckEvent end {else if (Control is TDateEdit) then begin if Assigned((Control as TDateEdit).OnChange) and not Assigned(FPreCheckEvent) then FPreCheckEvent := (Control as TDateEdit).OnChange; (Control as TDateEdit).OnChange := CheckEvent end} else if (Control is TLabeledEdit) then begin if Assigned((Control as TLabeledEdit).OnChange) and not Assigned(FPreCheckEvent) then FPreCheckEvent := (Control as TLabeledEdit).OnChange; (Control as TLabeledEdit).OnChange := CheckEvent end; end; end; inherited Add(hC); Result := hC; end; function THintManager.Check: boolean; var i, j: integer; Val: String; edt: TEdit; begin Result := true; for i := 0 to Count - 1 do with Items[i] do begin Val := ''; edt := nil; FErrorRow := -1; if (Status is TLabel) then (Status as TLabel).Caption := '' else if (Status is TStatusBar) then begin (Status as TStatusBar).SimpleText := ''; for j := 0 to (Status as TStatusBar).Panels.Count - 2 do (Status as TStatusBar).Panels[j].Text := ''; end; if Assigned(FPreCheckEvent) then if (@FPreCheckEvent <> @FCheckEvent) then FPreCheckEvent(nil); try Val := trim(GetValue(Items[i])); if not (Control is TStringGrid) then begin if EmptyAllowed and (trim(Val) = '') then continue; case ValueType of ptTreeMultiSelect: if Val = '0' then raise Exception.Create('Список не заполнен'); ptNonEmptyList: if Val = '0' then raise Exception.Create('Список не заполнен'); ptSelect: if Val = '' then raise Exception.Create('Ничего не выбрано'); ptDate: StrToDateTime(Val); ptFloat: begin val := StringReplace(Val, ',', DecimalSeparator, []); val := StringReplace(Val, '.', DecimalSeparator, []); StrToFloat(Val); end; ptInteger: StrToInt(Val); ptBoolean: if not (StrToInt(Val) in [0, 1]) then raise Exception.Create('Неверное преобразование'); ptString: if Val = '' then raise Exception.Create('Неверное преобразование'); end end else CheckArray(i); except if (Status is TLabel) then (Status as TLabel).Caption := Format('Проверьте значение %s', [Name]) else if (Status is TStatusBar) then (Status as TStatusBar).Panels[0].Text := Format('Проверьте значение %s', [Name]); if Assigned(edt) then begin edt.Font.Color := clRed; edt.Font.Style := [fsBold]; end; if (Control is TStringGrid) then (Control as TStringGrid).OnDrawCell := sgrDrawCell; Result := false; break; end end; end; procedure THintManager.CheckArray(const AParamIndex: integer); var i: integer; strs: TStrings; begin FErrorRow := -1; strs := Items[AParamIndex].Additional as TStrings; for i := 1 to strs.Count - 1 do begin FErrorRow := i; if Items[AParamIndex].EmptyAllowed and (trim(Strs[i]) = '') then continue; case Items[AParamIndex].ValueType of ptDate: StrToDateTime(strs[i]); ptFloat: begin Strs[i] := StringReplace(Strs[i], ',', DecimalSeparator, []); Strs[i] := StringReplace(Strs[i], ',', DecimalSeparator, []); StrToFloat(Strs[i]); end; ptInteger: StrToInt(Strs[i]); ptBoolean: if not (StrToInt(Strs[i]) in [0, 1]) then raise Exception.Create('Неверное преобразование'); ptString: if Strs[i] = '' then raise Exception.Create('Неверное преобразование'); end; end; end; procedure THintManager.Clear; var i: integer; begin try for i := Count - 1 downto 0 do with Items[i] do begin if Control is TEdit then // возвращаем всё на место // если обработчик уничтожен (очищен) (Control as TEdit).OnChange := FPreCheckEvent else if Control is TCombobox then (Control as TCombobox).OnChange := FPreCheckEvent; Items[i].Free; end; finally inherited Clear; end; inherited Clear; end; constructor THintManager.Create(AStatus: TControl); begin inherited Create; Status := AStatus; end; destructor THintManager.Destroy; begin inherited Destroy; end; function THintManager.GetByName(const AName: string): integer; var i: integer; begin Result := -1; for i := 0 to Count - 1 do if AnsiUpperCase(Items[i].Name) = AnsiUpperCase(AName) then begin Result := i; break; end; end; function THintManager.GetItem(const Index: integer): THintedControl; begin Result := THintedControl(inherited Items[Index]); end; function THintManager.GetItemsByName(const AName: string): THintedControl; var i: integer; begin i := GetByName(AName); if i > -1 then Result := Items[i] else Result := nil; end; function THintManager.GetValue(AHintedControl: THintedControl): string; var val: string; begin with AHintedControl do if Control is TCustomEdit then begin val := (Control as TCustomEdit).Text; if Control is TEdit then begin (Control as TEdit).Font.Color := clBlack; (Control as TEdit).Font.Style := []; end else if Control is TLabeledEdit then begin (Control as TLabeledEdit).Font.Color := clBlack; (Control as TLabeledEdit).Font.Style := []; end; end else if Control is TComboBox then Val := (Control as TComboBox).Text else if Control is TMemo then Val := (Control as TMemo).Text else if Control is TStringGrid then (Control as TStringGrid).OnDrawCell := nil else if Control is TRadioGroup then begin with (Control as TRadioGroup) do if ItemIndex > -1 then Val := trim(Items[ItemIndex]); end else if Control is TListBox then with Control as TListBox do begin case ValueType of ptNonEmptyList: Val := IntToStr(Items.Count); ptSelect: if ItemIndex > -1 then Val := trim(Items[ItemIndex]); end; end else if Control is TTreeView then with Control as TTreeView do begin case ValueType of ptNonEmptyList: Val := IntToStr(Items.Count); ptSelect: if Assigned(Selected) then Val := Selected.Text; ptTreeMultiSelect: Val := IntToStr(TreeViewMultiSelectionApplied(Control as TTreeView)); end; end; Result := Val; end; procedure THintManager.sgrDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin if (FErrorRow > -1) then begin if (ARow = FErrorRow) then with (Sender as TStringGrid) do begin Canvas.Font.Color := clRed; Canvas.Font.Style := [fsBold]; Canvas.TextOut(Rect.Left + 2, Rect.Top + 2, Cells[ACol, ARow]); end; end; end; function THintManager.TreeViewMultiSelectionApplied(ATrw: TTreeView): integer; var i: integer; begin Result := 0; for i := 0 to ATrw.Items.Count - 1 do Result := Result + ord(ATrw.Items[i].SelectedIndex = 1); end; initialization comps[0] := Starting; comps[1] := Containing; comps[2] := Equal; comps[3] := NotContaining; end.
(** * $Id: dco.framework.Command.pas 846 2014-05-25 18:04:45Z QXu $ * * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either * express or implied. See the License for the specific language governing rights and limitations under the License. *) unit dco.framework.Command; interface uses System.Types, superobject { An universal object serialization framework with Json support }; type /// <summary>This abstract class represents the basis of a RPC command. Any RPC command should be inherited from /// TCommand.</summary> TCommand = class public type TType = (REQUEST, NOTIFICATION); TClassReference = class of TCommand; public class function Type_: TType; virtual; abstract; class function HandleInMainThread_: Boolean; virtual; abstract; class function Method_: string; virtual; abstract; function Params_: ISuperObject; virtual; abstract; end; implementation end.
unit TBGConnection.Model.DataSet.Interfaces; interface uses Data.DB; type ICacheDataSetSubject = interface; iDataSet = interface ['{E90FC360-74B8-4D5C-9418-F517DFF564A4}'] function DataSet : TDataSet; overload; function DataSet (Value : TDataSet) : iDataSet; overload; function GUUID : String; function SQL : String; overload; function SQL (Value : String) : iDataSet; overload; end; iDriverProxy = interface ['{7EA13C01-D9FA-464F-AD0D-364365168D39}'] function CacheDataSet(Key : String; var Value : iDataSet) : boolean; function AddCacheDataSet(Key : String; Value : iDataSet) : iDriverProxy; function RemoveCache(Key : String) : iDriverProxy; function ClearCache : iDriverProxy; function ReloadCache(Value : String) : iDriverProxy; function ObserverList : ICacheDataSetSubject; end; ICacheDataSetObserver = interface ['{13C186CF-11B0-44E3-B202-E755F7FD5500}'] function Update(Value : String) : ICacheDataSetObserver; end; ICacheDataSetSubject = interface ['{2065188E-47F8-431A-9AE7-20E0915E89B3}'] function AddObserver(Value : ICacheDataSetObserver) : ICacheDataSetSubject; function RemoveObserver(Value : ICacheDataSetObserver) : ICacheDataSetSubject; function Notify(Value : String) : ICacheDataSetSubject; end; iDataSetFactory = interface ['{E884A6C6-6C80-4953-A52C-2AD0A4D157DB}'] function DataSet(Observer : ICacheDataSetSubject) : iDataSet; end; implementation end.
unit UCommonClasses; interface uses Windows, UxlIniFile, UxlList, UxlClasses, UxlWinControl, UxlWindow, UxlWinClasses; type TIniFileEx = class (TxlIniFile) public procedure ReadItemList (const s_section: widestring; o_list: TxlStrList); procedure SaveItemList (const s_section: widestring; o_list: TxlStrList); end; TBrowseHistory = class private FIDList: TxlIntList; FPos: integer; public constructor Create (); destructor Destroy (); override; function GetPrior (): integer; function GetNext (): integer; procedure Add (id: integer); procedure Delete (id: integer); function HasPrior (): boolean; function HasNext (): boolean; end; type IClipObserver = interface procedure ClipNotify (const s_text: widestring); end; TClipWatcher = class (TxlInterfacedObject, IMessageObserver) private FWin: TxlWindow; FHNext: HWND; FPassNext: boolean; FLastTime: integer; FTimer: TxlTimer; FObservers: TxlInterfaceList; procedure DrawClipboard (wParam, lParam: DWORD); procedure ChangeCBChain (wParam, lParam: DWORD); procedure SetStart (b_start: boolean); procedure ReLinkChain (Sender: TObject); procedure NotifyObservers (const s: widestring); public constructor Create (AWindow: TxlWindow); destructor Destroy (); override; procedure AddObserver (value: IClipObserver); procedure RemoveObserver (value: IClipObserver); procedure PassNext (); function ProcessMessage (ASender: TxlWinControl; AMessage, wParam, lParam: DWORD; var b_processed: boolean): DWORD; end; implementation uses Messages, UxlFunctions; procedure TIniFileEx.ReadItemList (const s_section: widestring; o_list: TxlStrList); var i, n: integer; begin Cache.ReadSection (s_section); n := Cache.GetInteger ('ItemCount', 0); o_list.Clear; for i := 0 to n - 1 do o_list.Add (Cache.GetString ('Item' + IntToStr(i), '')); end; procedure TIniFileEx.SaveItemList (const s_section: widestring; o_list: TxlStrList); var i: integer; begin Section := s_section; WriteInteger('ItemCount', o_list.Count); for i := o_list.Low to o_list.High do WriteString('Item' + IntToStr(i), o_list[i]); end; //-------------------------- constructor TBrowseHistory.Create (); begin FIDList := TxlIntList.Create; FPOs := -1; end; destructor TBrowseHistory.Destroy (); begin FIDList.Free; inherited; end; function TBrowseHistory.GetPrior (): integer; begin if FPos > FIDList.Low then dec (FPos); result := FIDList[FPos]; end; function TBrowseHistory.GetNext (): integer; begin if FPos < FIDList.High then inc (FPos); result := FIDList[FPos]; end; procedure TBrowseHistory.Add (id: integer); var i, n: integer; begin if (not FIDList.PosValid(FPos)) or (id <> FIDList[FPos]) then begin n := FIDList.High; for i := n downto FPOs + 1 do FIDList.Delete (i); FIDList.Add (id); FPos := FIDList.High; end; end; procedure TBrowseHistory.Delete (id: integer); var i: integer; begin i := FIDList.Find (id); FIDList.Delete (i); end; function TBrowseHistory.HasPrior (): boolean; begin result := FPos > FIDList.Low; end; function TBrowseHistory.HasNext (): boolean; begin result := FPos < FIDList.High; end; //------------------------ constructor TClipWatcher.Create (AWindow: TxlWindow); begin FWin := AWindow; FObservers := TxlInterfaceList.Create; FTimer := TimerCenter.NewTimer; FTimer.Interval := 1200000; FTimer.OnTimer := RelinkChain; FWin.AddMessageObserver (self); end; destructor TClipWatcher.Destroy (); begin SetStart (false); TimerCenter.ReleaseTimer (FTimer); FWin.RemoveMessageObserver (self); FObservers.free; inherited; end; procedure TClipWatcher.AddObserver (value: IClipObserver); begin if FObservers.Count = 0 then SetStart (true); FObservers.Add (value); end; procedure TClipWatcher.RemoveObserver (value: IClipObserver); begin FObservers.Remove (value); if FObservers.Count = 0 then SetStart (false); end; procedure TClipWatcher.NotifyObservers (const s: widestring); var i: integer; begin i := FObservers.Low; while i <= FObservers.High do begin if FObservers[i] <> nil then IClipObserver(FObservers[i]).ClipNotify (s); inc (i); end; end; procedure TClipWatcher.PassNext (); begin FPassNext := true; end; procedure TClipWatcher.SetStart (b_start: boolean); begin if b_start then FHNext := SetClipboardViewer (FWin.handle) else ChangeClipboardChain (FWin.handle, FHNext); FTimer.Enabled := b_start; FPassNext := false; FLastTime := 0; end; procedure TClipWatcher.ReLinkChain (Sender: TObject); begin ChangeClipboardChain (FWin.handle, FHNext); FHNext := SetClipboardViewer (FWin.handle); end; //------------------------ function TClipWatcher.ProcessMessage (ASender: TxlWinControl; AMessage, wParam, lParam: DWORD; var b_processed: boolean): DWORD; begin b_processed := false; case AMessage of WM_DRAWCLIPBOARD: DrawClipboard (wParam, lParam); WM_CHANGECBCHAIN: ChangeCBChain (wParam, lParam); end; end; procedure TClipWatcher.DrawClipboard (wParam, lParam: DWORD); var i_time: integer; s: widestring; begin i_time := GetTickCount; if i_time - Flasttime <= 100 then // 防止由于某些未知因素引起的死循环 exit else Flasttime := i_time; s := Clipboard.Text; if (s <> '') and (not FPassNext) then NotifyObservers (s); FPassNext := false; if IsWindow(FHNext) and (FHNext <> FWin.handle) then PostMessageW (FHNext, WM_DRAWCLIPBOARD, wParam, lParam); end; procedure TClipWatcher.ChangeCBChain (wParam, lParam: DWORD); begin if wParam = FHNext then FHNext := lParam else if IsWindow(FHNext) and (FHNext <> FWin.handle) then PostMessageW (FHNext, WM_CHANGECBCHAIN, wParam, lParam); end; end.
unit UregraCRUDConsultor; interface uses URegraCRUD , UEntidade , UConsultor , URepositorioDB , URepositorioConsultor ; type TRegraCRUDConsultor = class(TRegraCRUD) private function ValidateEmail(const emailAddress: string): Boolean; protected procedure ValidaAtualizacao(const coENTIDADE: TENTIDADE); override; procedure ValidaInsercao(const coENTIDADE: TENTIDADE); override; public constructor Create; override; function RetornaConsultor(const ciIdConsultor: Integer): TCONSULTOR; function RetornaConsultores: TArray<TCONSULTOR>; procedure ValidaEmail(const csEmail: String); procedure ValidaNome(const csNome: String); procedure ValidaNomeDuplicidade(const csNome: String; const ciIdCONSULTOR: Integer); end; implementation { TRegraCRUDConsultor } uses Generics.Collections , SysUtils , UUtilitarios , UMensagens , UConstantes , RegularExpressions ; constructor TRegraCRUDConsultor.Create; begin inherited; FRepositorioDB := TRepositorioDB<TENTIDADE>(TRepositorioConsultor.Create); end; function TRegraCRUDConsultor.RetornaConsultor( const ciIdConsultor: Integer): TCONSULTOR; var loCONSULTOR: TCONSULTOR; begin Result:= nil; for loCONSULTOR in TRepositorioCONSULTOR(FRepositorioDB).RetornaTodos do begin if loCONSULTOR.ID = ciIdConsultor then begin Result:= loCONSULTOR; end; end; end; function TRegraCRUDConsultor.RetornaConsultores: TArray<TCONSULTOR>; begin Result:= TRepositorioConsultor(FRepositorioDB).RetornaTodos.ToArray; end; procedure TRegraCRUDConsultor.ValidaAtualizacao(const coENTIDADE: TENTIDADE); begin inherited; ValidaNome(TCONSULTOR(coENTIDADE).NOME); ValidaNomeDuplicidade(TCONSULTOR(coENTIDADE).NOME, TCONSULTOR(coENTIDADE).ID); ValidaEmail(TCONSULTOR(coENTIDADE).EMAIL); end; procedure TRegraCRUDConsultor.ValidaEmail(const csEmail: String); begin if not ValidateEmail(csEmail) then begin raise EValidacaoNegocio.Create(STR_CONSULTOR_EMAIL_INVALIDO); end; end; procedure TRegraCRUDConsultor.ValidaInsercao(const coENTIDADE: TENTIDADE); begin inherited; ValidaNome(TCONSULTOR(coENTIDADE).NOME); ValidaNomeDuplicidade(TCONSULTOR(coENTIDADE).NOME, TCONSULTOR(coENTIDADE).ID); ValidaEmail(TCONSULTOR(coENTIDADE).EMAIL); end; procedure TRegraCRUDConsultor.ValidaNome(const csNome: String); begin if Trim(csNome) = EmptyStr then begin raise EValidacaoNegocio.Create(STR_CONSULTOR_NOME_NAO_INFORMADO); end; end; procedure TRegraCRUDConsultor.ValidaNomeDuplicidade(const csNome: String; const ciIdCONSULTOR: Integer); var loCONSULTOR: TCONSULTOR; begin for loCONSULTOR in TRepositorioCONSULTOR(FRepositorioDB).RetornaTodos do begin if (Trim(loCONSULTOR.NOME) = Trim(csNome)) and (loCONSULTOR.ID <> ciIdCONSULTOR) then begin raise EValidacaoNegocio.Create(STR_CONSULTOR_NOME_JA_EXISTE); end; end; end; function TRegraCRUDConsultor.ValidateEmail(const emailAddress: string): Boolean; var RegEx: TRegEx; begin RegEx := TRegex.Create('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]*[a-zA-Z0-9]+$'); Result := RegEx.Match(emailAddress).Success; end; end.
// generic wrapper for logging control, to produce more readable logs procedure log(msg: string); begin // if log string is not empty => separate it with full new line and proper tab indentation if Assigned(logMessage) then begin logMessage := logMessage + #13#10#9 + msg; // not empty => only prepend with tab end else begin logMessage := #9 + msg; end; end; procedure warn(msg: string); begin log('WARNING: ' + msg); end;
(* NIM/Nama : 16515019/Stevanno Hero Leadervand*) (* Nama file : lingkaran.pas *) (* Topik : Prosedural Pascal *) (* Tanggal : 6 April 2016 *) (* Deskripsi : Memasukkan data 2 lingkaran dan mengecek hubungan 2 lingkaran tersebut *) Program ProsesLingkaran; { Input: 2 buah Lingkaran } { Output: luas, keliling, dan hubungan lingkaran A dan B } { KAMUS } const PI : real = 3.1415; type { Definisi Type Koordinat } Koordinat = record x, y: real; end; { Definisi Type Lingkaran } Lingkaran = record c : Koordinat; { titik pusat lingkaran } r : real; { jari-jari, > 0 } end; var A, B : Lingkaran; { variabel untuk lingkaran A dan B } { FUNGSI DAN PROSEDUR } function isRValid (r: real): boolean; {isRValid true apabila r > 0} {ALGORITMA} begin isRValid := r > 0; end; procedure InputLingkaran (var A : Lingkaran); { I.S.: A sembarang } { F.S.: A terdefinisi sesuai dengan masukan pengguna. Pemasukan jari-jari diulangi sampai didapatkan jari-jari yang benar yaitu r > 0. Pemeriksaan apakah jari- jari valid menggunakan fungsi IsRValid. Jika jari-jari tidak valid, dikeluarkan pesan kesalahan “Jari-jari harus > 0”. } {ALGORITMA} begin readln(A.c.x, A.c.y); repeat readln(A.r); if (not(isRValid(A.r))) then writeln('Jari-jari harus > 0'); until (isRValid(A.r)); end; function KelilingLingkaran (A: Lingkaran) : real; { Menghasilkan keliling lingkaran A = 2 * PI * A.r } begin KelilingLingkaran := 2 * PI * A.r; end; function LuasLingkaran (A: Lingkaran) : real; { Menghasilkan luas lingkaran A = PI * A.r * A.r } begin LuasLingkaran := PI * A.r * A.r; end; function Jarak (P1, P2: Koordinat) : real; { Menghasilkan jarak antara P1 dan P2 } begin Jarak := sqrt((P2.x-P1.x)*(P2.x-P1.x)+(P2.y-P1.y)*(P2.y-P1.y)); end; function HubunganLingkaran (A, B: Lingkaran) : integer; { Menghasilkan integer yang menyatakan hubungan lingkaran A dan B, yaitu: 1 = A dan B sama; 2 = A dan B berimpit; 3 = A dan B beririsan; 4 = A dan B bersentuhan; 5 = A dan B saling lepas } {ALGORITMA} begin if (A.c.x = B.c.x) and (A.c.y = B.c.y) and (A.r = B.r) then HubunganLingkaran := 1 else if (A.c.x = B.c.x) and (A.c.y = B.c.y) and (A.r <> B.r) then HubunganLingkaran := 2 else if Jarak(A.c, B.c) < (A.r + B.r) then HubunganLingkaran := 3 else if Jarak(A.c, B.c) = (A.r + B.r) then HubunganLingkaran := 4 else if Jarak(A.c, B.c) > (A.r + B.r) then HubunganLingkaran := 5; end; { ALGORITMA PROGRAM UTAMA } begin writeln('Masukkan lingkaran A:'); InputLingkaran(A); writeln('Masukkan lingkaran B:'); InputLingkaran(B); writeln('Keliling lingkaran A = ', KelilingLingkaran(A):0:2); writeln('Luas lingkaran A = ', LuasLingkaran(A):0:2); writeln('Keliling lingkaran B = ', KelilingLingkaran(B):0:2); writeln('Luas lingkaran B = ', LuasLingkaran(B):0:2); write('A dan B adalah '); if (HubunganLingkaran(A,B)) = 1 then writeln('sama') else if (HubunganLingkaran(A,B)) = 2 then writeln('berimpit') else if (HubunganLingkaran(A,B)) = 3 then writeln('beririsan') else if (HubunganLingkaran(A,B)) = 4 then writeln('bersentuhan') else if (HubunganLingkaran(A,B)) = 5 then writeln('saling lepas'); end.
unit UMenuManager; interface uses Windows, UxlWindow, UxlMenu, UxlClasses, UxlExtClasses, UxlList, UxlWinClasses, UGlobalObj, UxlMiscCtrls, UxlWinControl, UPageFactory, UTypeDef; type TMenuSuper = class (TxlMenu, ILangObserver, IMessageObserver) private FMenuTip: TxlTrackingTip; protected procedure OnCreate (); override; procedure OnDestroy (); override; procedure f_UpdateViewMenu (); procedure f_InitNewPagesMenu (h_popup: HMenu); procedure f_InitPopupMenu (h_popup: HMenu; c_items: array of integer); procedure f_InitViewMenu (h: HMenu); procedure f_InitTextToolsMenu (h: HMenu); procedure f_InitSubsequentFindMenu (h: HMenu); procedure f_DetermineDeleteOrClosePage (); procedure f_DetermineDeleteOrRemoveItem (); function f_DetermineAddOrRemoveFavorite (): integer; public procedure LanguageChanged(); virtual; procedure UpdateListMenu (h_pmenu: HMENU; pid: integer); function ProcessMessage (ASender: TxlWinControl; AMessage, wparam, lparam: DWORD; var b_processed: boolean): DWORD; end; type TMainMenu = class (TMenuSuper) private Fpopup, Fhinsertcliptext, Fhinserttemplate, Fhfavorite, Fhview, FhTExtTools, FhSubsequentFind, FhWorkSpace, FhEdit: HMenu; FhrecentRoot, FhRecentCreate, FhRecentModify, FhRecentVisit: HMenu; procedure Initialize (b_asmainmenu: boolean); public procedure LanguageChanged(); override; procedure InitMenuPopup (h_menu: HMenu); override; end; type TTrayMenu = class (TMenuSuper, IEventObserver) private Fhtraypopup, Fhopenfastlink, Fhinsertcliptext, Fhinserttemplate: HMENU; FWinStatus: word; procedure f_SetRestoreItem (); protected procedure OnCreate (); override; procedure OnDestroy (); override; public procedure LanguageChanged(); override; procedure InitMenuPopup (h_menu: HMenu); override; procedure EventNotify (event, wparam, lparam: integer); end; type TPopupMenu = class (TMenuSuper, IEventObserver) private FhPopup: HMenu; protected procedure OnCreate (); override; procedure OnDestroy (); override; public procedure EventNotify (event, wparam, lparam: integer); // procedure InitMenuPopup (h_menu: HMenu); override; end; type TAccelTable = class (TxlAccelTable) protected procedure OnInitialize (); override; end; type TMenuManager = class (TxlInterfacedObject, IOptionObserver, IMemorizer, ICommandExecutor, IEventObserver, ISizeObserver) private FWndParent: TxlWindow; FMainMenu: TMainMenu; FSysMenu: TMainMenu; FAccelTable: TxlAccelTable; FPopupMenu: TPopupMenu; FToolBar: TxlToolBar; FTrayMenu: TTrayMenu; FTrayIcon: TxlTrayIcon; procedure f_OnTrayIconClick (sender: TObject); procedure f_OnToolBarContextMenu (sender: TObject); public constructor Create (WndParent: TxlWindow); destructor Destroy (); override; procedure OptionChanged (); procedure SaveMemory (); procedure RestoreMemory (); procedure ExecuteCommand (opr: word); function CheckCommand (opr: word): boolean; procedure EventNotify (event, wparam, lparam: integer); procedure AdjustAppearance (); property TrayMenu: TTrayMenu read FTrayMenu; end; implementation uses Messages, Resource, UDialogs, UDefineToolbarBox, UxlFunctions, UxlStrUtils, UxlMath, UOptionManager, ULangManager, UPageSuper, UxlListView, UPageProperty, UPageStore, UxlCommDlgs; const c_tooltipwidth = 400; procedure TMenuSuper.OnCreate (); var o_style: TToolTipStyle; begin with o_style do begin TipWidth := c_tooltipwidth; InitialTime := 500; AutoPopTime := 0; end; FMenuTip := TxlTrackingTip.Create (FWndParent); FMenuTip.Style := o_style; LangMan.AddObserver (self); CommandMan.AddSender (self); FWndParent.AddMessageObserver (self); inherited; end; procedure TMenuSuper.OnDestroy (); begin FWndParent.RemoveMessageObserver (self); LangMan.RemoveObserver (self); CommandMan.RemoveSender (self); FMenuTip.Free; inherited; end; function TMenuSuper.ProcessMessage (ASender: TxlWinControl; AMessage, wparam, lparam: DWORD; var b_processed: boolean): DWORD; var id, i_index: integer; rt: TRect; s_tip: widestring; pt: TPoint; begin b_processed := false; if AMessage = WM_MENUSELECT then begin id := LoWord(wparam); if ListCenter.GetSubItem (id, i_index, s_tip, 200) then begin // calculate suitable place GetMenuItemRect (0, lparam, i_index, rt); if FWndParent.StayOnTop and (FWndParent.Status <> wsMinimize) then // 此种情况下不能将 Tooltip StayOnTop,否则菜单条会转到后台。因此 ToolTip 只能显示在菜单右侧以防被遮没 begin pt.x := rt.Right + 5; pt.y := rt.Top; FMenuTip.ShowTip (pt, s_tip); end else begin GetCursorPos (pt); if PointInRect (pt, rt) then FMenuTip.ShowTip (s_tip) // 不规定位置,待Tip浮现时实时取位置 else begin // 针对不用鼠标,而用键盘触发 wm_menuselect 的场合,将 Tip 显示在菜单条下侧 pt.x := (rt.Left + rt.Right) div 2; pt.y := rt.Bottom; FMenuTip.ShowTip (pt, s_tip); end; end; b_processed := true; end else FMenuTip.HideTip; end; end; procedure TMenuSuper.LanguageChanged (); var i: integer; o_list: TxlIntList; begin o_list := TxlIntList.Create; GetItemList (Fhandle, o_list); for i := o_List.Low to o_List.High do ItemText[o_list[i]] := LangMan.GetItem(o_list[i]); o_list.free; end; procedure TMenuSuper.UpdateListMenu (h_pmenu: HMENU; pid: integer); var i, m, n, id: integer; o_list: TxlStrList; begin o_list := TxlStrList.Create; ListCenter.FillList (pid, o_list); m := o_list.count; n := GetItemCount (h_pmenu); for i := 0 to m - 1 do begin id := pid + i + 1; if i < n then ItemText[id] := o_list[i] else AddItem(h_pmenu, id, o_list[i]); end; for i := m to n - 1 do Deleteitem (pid + i + 1); o_list.free; end; procedure TMenuSuper.f_UpdateViewMenu (); var v: TListPageView; b: boolean; begin b := PageCenter.ActivePage.ListProperty <> nil; if b then v := PageCenter.ActivePage.ListProperty.View; ItemChecked[rb_icon] := b and (v = lpvIcon); ItemChecked[rb_smallicon] := b and (v = lpvSmallIcon); ItemChecked[rb_list] := b and (v = lpvList); ItemChecked[rb_report] := b and (v = lpvReport); ItemChecked[rb_blog] := b and (v = lpvBlog); end; procedure TMenuSuper.f_InitNewPagesMenu (h_popup: HMenu); begin ClearPopup (h_popup); with OptionMan.Options do begin if EnableCalcPage then AddItem (h_popup, m_newcalc, CommandMan.ItemText[m_newcalc]); if EnableMemoPage then AddItem (h_popup, m_newmemo, CommandMan.ItemText[m_newmemo]); if EnableDictPage then AddItem (h_popup, m_newdict, CommandMan.ItemText[m_newdict]); if EnableLinkPage then AddItem (h_popup, m_newlink, CommandMan.ItemText[m_newlink]); if EnableContactPage then AddItem (h_popup, m_newcontact, CommandMan.ItemText[m_newcontact]); end; end; procedure TMenuSuper.f_InitPopupMenu (h_popup: HMenu; c_items: array of integer); var i: integer; begin ClearPopup (h_popup); for i := Low(c_items) to High(c_items) do if c_items[i] = 0 then AddSeparator (h_popup) else AddItem (h_popup, c_items[i], CommandMan.ItemText[c_items[i]]); end; procedure TMenuSuper.f_InitViewMenu (h: HMenu); begin f_InitPopupMenu (h, [rb_icon, rb_smallicon, rb_list, rb_report, rb_blog]); end; procedure TMenuSuper.f_InitTextToolsMenu (h: HMenu); begin f_InitPopupMenu (h, [m_highlight1, m_highlight2, m_highlight3, m_highlight4, m_removehighlight, 0, m_ol, m_ul1, m_ul2, m_removelist, 0, m_noemptyline, m_oneemptyline]); end; procedure TMenuSuper.f_InitSubsequentFindMenu (h: HMenu); begin f_InitPopupMenu (h, [m_findnext, m_findprevious, m_replace, m_replace_p, m_replaceall]); end; procedure TMenuSuper.f_DetermineDeleteOrClosePage (); begin if PageCenter.ActivePage = nil then exit; if PageCenter.ActivePage.SingleInstance then ItemText[m_deletepage] := LangMan.GetItem (m_closepage) else ItemText[m_deletepage] := LangMan.GetItem (m_deletepage); end; procedure TMenuSuper.f_DetermineDeleteOrRemoveItem (); var p: TPageSuper; begin p := PageCenter.ActivePage; if p = nil then exit; if p.PageControl = pcEdit then ItemTExt[m_delete] := LangMan.GetItem (m_delete) else if p.IsVirtualContainer then ItemText[m_delete] := LangMan.GetItem (m_removeitem) else ItemText[m_delete] := LangMan.GetItem (m_deleteitem); end; function TMenuSuper.f_DetermineAddOrRemoveFavorite (): integer; var id: integer; begin if PageCenter.ActivePage = nil then exit; PageStore.GetFirstPageId(ptFavorite, id); if PageStore[id].Childs.FindChild(PageCenter.ActivePage.id) >= 0 then result := m_removefavorite else result := m_addfavorite; end; //------------------- procedure TMainMenu.Initialize (b_asmainmenu: boolean); var hm, h, hParent: HMenu; begin if b_asMainMenu then hparent := self.Handle else begin FPopup := AddPopup (self.handle, m_popup); hParent := FPopup; end; hm := AddPopup (hParent, mc_workspace); FhWorkSpace := hm; AddItem (hm, m_newnote); if OptionMan.HaveExtPage then begin h := AddPopup (hm, m_newpage); f_InitNewPagesMenu (h); end; AddItem (hm, m_newgroup); AddSeparator (hm); AddItem (hm, m_rename); AddItem (hm, m_switchlock); AddItem (hm, m_save); AddItem (hm, m_deletepage); AddSeparator (hm); AddItem (hm, m_property); Fhview := AddPopup (hm, m_view); f_InitViewMenu (Fhview); AddSeparator (hm); AddItem (hm, m_import); AddItem (hm, m_export); AddItem (hm, m_sendmail); AddSeparator (hm); AddItem (hm, m_exit); hm := AddPopup (hParent, mc_edit); FhEdit := hm; AddItem (hm, m_clear); AddItem (hm, m_undo); AddItem (hm, m_redo); AddItem (hm, m_selectall); AddSeparator (hm); AddItem (hm, m_cut); AddItem (hm, m_copy); AddItem (hm, m_paste); AddItem (hm, m_delete); AddSeparator (hm); AddItem (hm, m_newitem); AddItem (hm, m_insertitem); AddItem (hm, m_edititem); AddSeparator (hm); AddItem (hm, m_wordwrap); FhTextTools := AddPopup (hm, m_texttools); f_InitTextToolsMenu (FhTextTools); AddSeparator (hm); AddItem (hm, m_find); FhSubsequentFind := AddPopup (hm, m_subsequentfind); f_InitSubsequentFindMenu (FhSubsequentFind); AddItem (hm, m_highlightmatch); AddSeparator (hm); AddItem (hm, m_insertlink); with OptionMan.Options do begin if EnableTemplate then Fhinserttemplate := AddPopup (hm, m_inserttemplate); if EnableClipboard then Fhinsertcliptext := AddPopup (hm, m_insertcliptext); end; hm := AddPopup (hParent, mc_navigation); AddItem (hm, m_prior); AddItem (hm, m_next); AddItem (hm, m_levelup); AddSeparator (hm); h := AddPopup (hm, m_recentroot); FhRecentCreate := AddPopup (h, m_recentcreate); FhRecentModify := AddPopup (h, m_recentModify); FhRecentVisit := AddPopup (h, m_recentVisit); AddSeparator (h); AddItem (h, m_managerecent); Fhrecentroot := h; Fhfavorite := AddPopup (hm, m_favorite); AddSeparator (hm); AddItem (hm, m_search); // AddItem (hm, m_tag); AddItem (hm, m_recyclebin); hm := AddPopup (hParent, mc_tools); AddItem (hm, m_showtree); AddItem (hm, m_stayontop); AddItem (hm, m_transparent); AddItem (hm, m_specialmode); with OptionMan.Options do begin if EnableTemplate or EnableLinkPage then AddSeparator (hm); if EnableTemplate then AddItem (hm, m_template); if EnableLinkPage then AddItem (hm, m_fastlink); if EnableClipboard then begin AddSeparator (hm); AddItem (hm, m_watchclipboard); AddItem (hm, m_clearclipboard); AddItem (hm, m_clipboard); end; end; AddSeparator (hm); AddItem (hm, m_statistics); AddSeparator (hm); AddItem (hm, m_definetoolbar); AddItem (hm, m_options); hm := AddPopup (hParent, mc_help); AddItem (hm, m_helptopic); AddSeparator (hm); AddItem (hm, m_homepage); AddItem (hm, m_forum); AddSeparator (hm); AddItem (hm, m_donate); AddItem (hm, m_about); LanguageChanged; end; procedure TMainMenu.LanguageChanged (); begin inherited; if FPopup = 0 then // as main menu FWndParent.Redraw; end; procedure TMainMenu.InitMenuPopup (h_menu: HMenu); var m: integer; begin if (h_menu = FPopup) then begin InitMenuPopup (Fhinsertcliptext); InitMenuPopup (Fhinserttemplate); end else if (h_menu = Fhinsertcliptext) then UpdateListMenu (h_menu, m_insertcliptext) else if h_menu = Fhinserttemplate then UpdateListMenu (h_menu, m_inserttemplate) // else if h_menu = FhrecentRoot then // begin // UpdateListMenu (FhrecentCreate, m_recentcreate); // UpdateListMenu (FhrecentModify, m_recentmodify); // UpdateListMenu (FhrecentVisit, m_recentvisit); else if h_menu = FhrecentCreate then UpdateListMenu (h_menu, m_recentcreate) else if h_menu = FhrecentModify then UpdateListMenu (h_menu, m_recentmodify) else if h_menu = FhrecentVisit then UpdateListMenu (h_menu, m_recentvisit) else if h_menu = Fhfavorite then begin ClearPopup (h_menu); UpdateListMenu (h_menu, m_favorite); AddSeparator (h_menu); m := f_DetermineAddOrRemoveFavorite; AddItem (h_menu, m, #9 + LangMan.GetItem (m)); AddItem (h_menu, m_managefavorite, #9 + LangMan.GetItem (m_managefavorite)); end else if h_menu = Fhview then f_UpdateViewMenu else if h_menu = FhWorkSpace then f_DetermineDeleteOrClosePage else if h_menu = FhEdit then f_DetermineDeleteOrRemoveItem; end; //---------------------- procedure TTrayMenu.OnCreate (); var hm: HMenu; begin hm := AddPopup (Fhandle, m_tray); with OptionMan.Options do begin if EnableLinkPage then begin Fhopenfastlink := AddPopup (hm, m_openfastlink); AddSeparator (hm); end; if EnableTemplate then Fhinserttemplate := AddPopup (hm, m_inserttemplate); if EnableClipboard then begin Fhinsertcliptext := AddPopup (hm, m_insertcliptext); AddItem (hm, m_watchclipboard); AddItem (hm, m_clearclipboard); end; if EnableTemplate or EnableClipboard then AddSeparator (hm); end; AddItem (hm, m_newnoteforeground); AddItem (hm, m_autorecord); AddItem (hm, m_options); AddSeparator (hm); AddItem (hm, m_restore); AddItem (hm, m_exit); Fhtraypopup := hm; EventMan.AddObserver (self); inherited; end; procedure TTrayMenu.OnDestroy (); begin EventMan.RemoveObserver (self); inherited; end; procedure TTrayMenu.InitMenuPopup (h_menu: HMenu); begin if h_menu = Fhtraypopup then begin InitMenuPopup (Fhinsertcliptext); InitMenuPopup (Fhinserttemplate); InitMenuPopup (Fhopenfastlink); ItemEnabled[m_inserttemplate] := true; ItemEnabled[m_insertcliptext] := true; end else if h_menu = Fhinsertcliptext then UpdateListMenu (h_menu, m_insertcliptext) else if h_menu = Fhinserttemplate then UpdateListMenu (h_menu, m_inserttemplate) else if h_menu = Fhopenfastlink then UpdateListMenu (h_menu, m_openfastlink); end; procedure TTrayMenu.f_SetRestoreItem (); begin if FWinStatus = p_Minimized then ItemText[m_restore] := LangMan.GetItem (m_restore) else ItemText[m_restore] := LangMan.GetItem (m_minimize); end; procedure TTrayMenu.LanguageChanged (); begin inherited; f_SetRestoreItem (); end; procedure TTrayMenu.EventNotify (event, wparam, lparam: integer); begin if event = e_WinStatusChanged then begin case wparam of p_minimized, p_maximized, p_restored: begin FWinStatus := wparam; f_SetRestoreItem (); end; end; end; end; //-------------------------------- procedure TPopupMenu.OnCreate (); begin inherited; FhPopup := AddPopup(FHandle, m_popup); EventMan.AddObserver(self); end; procedure TPopupMenu.OnDestroy (); begin EventMan.RemoveObserver (self); inherited; end; const TreeMenus: array [0..8] of integer = (m_newnote, m_newgroup, 0, m_rename, m_switchlock, m_property, 0, m_export, m_deletepage); EditorMenus: array[0..7] of integer = (m_cut, m_copy, m_paste, m_delete, 0, m_find, 0, m_insertlink); EditorNoSelMenus: array[0..11] of integer = (m_undo, m_redo, m_selectall, 0, m_wordwrap, m_removehighlight, 0, m_find, m_highlightmatch, 0, m_paste, m_insertlink); ListMenus: array[0..3] of integer = (m_newitem, m_insertitem, m_edititem, m_delete); ListNoSelMenus: array[0..2] of integer = (m_newitem, 0, m_property); ToolbarMenus: array[0..0] of integer = (m_definetoolbar); // FavoriteListMenus: array[0..1] of integer = (m_edititem, m_removeitem); SearchMenus: array[0..4] of integer = (m_search, 0, m_property, 0, m_deletepage); RecycleBinMenus: array[0..4] of integer = (m_clear, 0, m_property, 0, m_deletepage); SysPageMenus: array[0..2] of integer = (m_property, 0, m_deletepage); RecentPagesMenus: array[0..0] of integer = (m_property); procedure TPopupMenu.EventNotify (event, wparam, lparam: integer); procedure f_PopulatePopupMenu (const i_menuitems: array of integer); var i, m: integer; begin ClearPopup (FhPopup); for i := Low(i_menuitems) to High(i_menuitems) do begin m := i_menuitems[i]; if m = 0 then AddSeparator (FhPopup) else begin AddItem(FhPopup, m, LangMan.GetItem(m)); //.GetItem(m)); ItemEnabled[m] := CommandMan.ItemEnabled[m]; end; end; end; procedure f_InsertPopup (i_pos: integer; m_menu: integer); var h: HMenu; begin h := InsertPopup (FhPopup, i_pos, m_menu, CommandMan.ItemText[m_menu]); case m_menu of m_view: begin f_InitViewMenu (h); f_UpdateViewMenu; end; m_texttools: f_InitTextToolsMenu (h); m_subsequentfind: f_InitSubsequentFindMenu (h); m_inserttemplate, m_insertcliptext: UpdateListMenu (h, m_menu); end; end; var h: HMenu; m: integer; begin if event <> e_ContextMenuDemand then exit; // FHasViewMenu := wparam in [PageContext, SearchContext, RecycleBinContext, SysPageContext, RecentPagesContext, ListNoSelContext]; case wparam of PageContext: begin f_PopulatePopupMenu (TreeMenus); if PageCenter.ActivePage.PageControl <> pcEdit then f_InsertPopup (6, m_view); if OptionMan.HaveExtPage then begin h := InsertPopup (FhPopup, 1, m_newpage, CommandMan.ItemText[m_newpage]); f_InitNewPagesMenu (h); end; m := f_DetermineAddOrRemoveFavorite; InsertItem (FhPopup, 9, m, LangMan.GetItem(m)); end; SearchContext: begin f_PopulatePopupMenu (SearchMenus); f_InsertPopup (3, m_view); end; RecycleBinContext: begin f_PopulatePopupMenu (RecycleBinMenus); f_InsertPopup (3, m_view); end; SysPageContext: begin f_PopulatePopupMenu (SysPageMenus); f_InsertPopup (1, m_view); end; RecentPagesContext: begin f_PopulatePopupMenu (RecentPagesMenus); f_InsertPopup (1, m_view); end; EditorContext: begin f_PopulatePopupMenu (EditorMenus); f_InsertPopup (5, m_texttools); if OptionMan.Options.EnableClipboard then f_InsertPopup (9, m_insertcliptext); if OptionMan.Options.EnableTemplate then f_InsertPopup (9, m_inserttemplate); end; EditorNoSelContext: begin f_PopulatePopupMenu (EditorNoSelMenus); f_InsertPopup (8, m_subsequentfind); ItemChecked[m_wordwrap] := CommandMan.ItemChecked[m_wordwrap]; if OptionMan.Options.EnableClipboard then f_InsertPopup (13, m_insertcliptext); if OptionMan.Options.EnableTemplate then f_InsertPopup (13, m_inserttemplate); end; ListContext: f_PopulatePopupMenu (ListMenus); ListnoselContext: begin f_PopulatePopupMenu (ListNoSelMenus); f_InsertPopup (3, m_view); end; // FavoriteListContext: // f_PopulatePopupMenu (FavoriteListMenus); ToolbarContext: f_PopulatePopupMenu (ToolbarMenus); else exit; end; f_DetermineDeleteOrClosePage; f_DetermineDeleteOrRemoveItem; EventMan.EventNotify (WM_ENTERMENULOOP); Popup (m_popup); EventMan.EventNotify (WM_EXITMENULOOP); end; //-------------------------- procedure TAccelTable.OnInitialize (); var s_file: widestring; begin AddKey (m_newnote, 'Ctrl+N'); AddKey (m_newgroup, 'Ctrl+G'); AddKey (m_rename, 'F2'); AddKey (m_switchlock, 'F6'); AddKey (m_save, 'Ctrl+S'); AddKey (m_deletepage, 'Shift+Del'); AddKey (m_moveup, 'Alt+Up'); AddKey (m_movedown, 'Alt+Down'); AddKey (m_undo, 'Ctrl+Z', false); AddKey (m_redo, 'Ctrl+Y', false); AddKey (m_selectall, 'Ctrl+A', false); AddKey (m_cut, 'Ctrl+X', false); AddKey (m_copy, 'Ctrl+C', false); AddKey (m_paste, 'Ctrl+V', false); AddKey (m_clear, 'Ctrl+L'); AddKey (m_find, 'Ctrl+F'); AddKey (m_findnext, 'F3'); AddKey (m_findprevious, 'Shift+F3'); AddKey (m_replace, 'F4'); AddKey (m_replace_p, 'Shift+F4'); AddKey (m_replaceall, 'Ctrl+F4'); AddKey (m_newitem, 'Ctrl+I'); AddKey (m_insertlink, 'Ctrl+K'); AddKey (m_delete, 'Del', false); AddKey (m_prior, 'Alt+Left'); AddKey (m_next, 'Alt+Right'); AddKey (m_levelup, 'Ctrl+U'); AddKey (m_search, 'Ctrl+Shift+F'); AddKey (m_showtree, 'Ctrl+T'); AddKey (m_stayontop, 'Ctrl+P'); AddKey (m_transparent, 'Ctrl+R'); AddKey (m_specialmode, 'Ctrl+H'); AddKey (m_helptopic, 'F1'); AddKey (hk_switchfocus, 'Ctrl+Tab'); AddKey (hk_selastitle, 'F10'); AddKey (hk_treeleft, 'Ctrl+Alt+Left'); AddKey (hk_treeright, 'Ctrl+Alt+Right'); LoadFromFile (ProgDir + 'accel.txt'); CreateAccelTable; end; //----------------------------- const defbuttons: array [0..20] of integer = (m_newnote, m_newpage, m_newgroup, 0, m_switchlock, m_property, m_view, 0, m_undo, m_texttools, m_find, m_newitem, 0, m_prior, m_next, m_levelup, m_favorite, 0, m_showtree, m_stayontop, m_specialmode); allbuttons: array [0..59] of integer = (m_newnote, m_newpage, m_newcalc, m_newmemo, m_newdict, m_newlink, m_newcontact, m_newgroup, m_rename, m_switchlock, m_save, m_deletepage, m_property, m_view, m_import, m_export, m_sendmail, m_exit, m_clear, m_undo, m_redo, m_selectall, m_cut, m_copy, m_paste, m_delete, m_newitem, m_insertitem, m_edititem, m_wordwrap, m_texttools, m_find, m_subsequentfind, m_insertlink, m_inserttemplate, m_insertcliptext, m_prior, m_next, m_levelup, m_recentcreate, m_recentmodify, m_recentvisit, m_favorite, m_search, m_recyclebin, m_showtree, m_stayontop, m_transparent, m_specialmode, m_template, m_fastlink, m_watchclipboard, m_clearclipboard, m_clipboard, m_statistics, m_definetoolbar, m_options, m_helptopic, m_homepage, m_forum); constructor TMenuManager.Create (WndParent: TxlWindow); begin FWndParent := WndParent; FAccelTable := TAccelTable.Create (); FMainMenu := TMainMenu.create (WndParent); FAccelTable.AssociateMenu (FMainMenu); FMainMenu.Initialize(true); FSysMenu := TMainMenu.Create(FWndParent); FSysMenu.Initialize(false); FSysMenu.AccelTable := FAccelTable; FToolBar := TxlToolBar.create (WndParent); with FToolBar do begin AssociateMenu (FMainMenu); OnContextMenu := f_OnToolBarContextMenu; end; FPopupMenu := TPopupMenu.create (WndParent); FTrayMenu := TTrayMenu.create (WndParent); FTrayIcon := TxlTrayIcon.Create (WndParent, MainIcon, 'minipad2'); with FTrayIcon do begin Menu := FTrayMenu; OnClick := f_OnTrayIconClick; end; with WndParent do begin SetAccelTable(FAccelTable); SetToolbar (FToolbar); end; OptionMan.AddObserver (self); MemoryMan.AddObserver (self); CommandMan.AddExecutor(self); EventMan.AddObserver (self); SizeMan.AddObserver (self); CommandMan.AddSender (FSysMenu); end; destructor TMenuManager.Destroy (); begin SizeMan.RemoveObserver (self); EventMan.RemoveObserver (self); OptionMan.RemoveObserver (self); MemoryMan.RemoveObserver(self); CommandMan.RemoveExecutor(self); with FWndParent do begin SetAccelTable(nil); SetToolbar (nil); SetMainMenu(nil); SetTrayIcon (nil); end; FToolBar.free; FPopupMenu.free; FSysMenu.Free; FMainMenu.free; FTrayIcon.Free; FTrayMenu.free; FAccelTable.Free; inherited; end; procedure TMenuManager.AdjustAppearance (); var b: boolean; begin if (OptionMan.options.showmenubar) and SizeMan.ShowMenu then FWndParent.SetMainMenu(FMainMenu) else FWndParent.SetMainMenu(nil); b := OptionMan.options.showtoolbar and SizeMan.ShowToolbar; FToolBar.visible := b; end; procedure TMenuManager.EventNotify (event, wparam, lparam: integer); begin case event of e_ContextMenuDemand: if (wparam = ProgramContext) then FSysMenu.Popup; end; end; procedure TMenuManager.OptionChanged (); begin AdjustAppearance; if OptionMan.Options.ShowTrayIcon then FWndParent.SetTrayIcon (FTrayIcon) else FWndParent.SetTrayIcon (nil); end; procedure TMenuManager.SaveMemory (); begin end; procedure TMenuManager.RestoreMemory (); var i: integer; o_list: TxlIntList; begin o_list := TxlIntList.Create (); o_list.Separator := ','; o_list.Text := MemoryMan.TBList; if o_list.count = 0 then for i := low(defbuttons) to high(defbuttons) do o_list.add (defbuttons[i]); for i := o_list.High downto o_list.Low do if not FMainMenu.ItemExists(o_list[i]) then o_list.Delete(i); for i := o_list.High - 1 downto o_list.Low do if o_list[i] = o_list[i + 1] then o_list.Delete(i + 1); FToolBar.SetButtons (o_list); o_list.free; end; procedure TMenuManager.ExecuteCommand (opr: word); procedure f_DefineToolBar (); var o_currentlist, o_alllist, o_defaultlist: TxlIntList; i: integer; begin o_currentlist := TxlIntList.Create (); o_currentlist.Separator := ','; FToolBar.GetButtons (o_currentlist); o_alllist := TxlIntList.create; for i := Low(allbuttons) to high(allbuttons) do if FMainMenu.ItemExists(allbuttons[i]) then o_alllist.add (allbuttons[i]); o_defaultlist := TxlIntList.Create; for i := Low(defbuttons) to high(defbuttons) do o_defaultlist.Add(defbuttons[i]); with TDefineToolBarbox.create (FWndParent) do begin Initialize (o_currentlist, o_alllist, o_defaultlist); // 对象指针传入 if Execute () then begin MemoryMan.TBList := o_currentlist.text; RestoreMemory; FWndParent.Update; end; Free; end; o_currentlist.Free; o_alllist.free; end; begin case opr of m_definetoolbar: f_DefineToolBar; // m_showtree, m_stayontop, m_transparent, m_specialmode, m_wordwrap: // CommandMan.SwitchCheck(opr); end; end; function TMenuManager.CheckCommand (opr: word): boolean; begin result := true; end; procedure TMenuManager.f_OnTrayIconClick (sender: TObject); begin EventMan.EventNotify (e_TrayIconClicked); end; procedure TMenuManager.f_OnToolBarContextMenu (sender: TObject); begin EventMan.EventNotify(e_ContextMenuDemand, ToolbarContext); end; end.
unit mainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,untComLib, ComCtrls,untComTypeLibrary, ShellApi, ActiveX, Registry; type TForm1 = class(TForm) Button1: TButton; Edit1: TEdit; TreeView1: TTreeView; Button2: TButton; OpenDialog1: TOpenDialog; LabelCOMInfo: TLabel; Memo1: TMemo; Label1: TLabel; edtClsId: TEdit; lbl1: TLabel; edtProgID: TEdit; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Memo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); procedure edtClsIdDblClick(Sender: TObject); procedure edtClsIdKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } procedure ShowInterface(); procedure AddToTreeView(list:TComInfoList); procedure ComLibToTreeView(com1: TTypeLibrary); procedure ComLibToMemo(com1: TTypeLibrary); procedure FindClsId(clsid: string); procedure EnumSubKeys(RootKey: HKEY; const Key: string); public { Public declarations } FilePath: string; // declare our DROPFILES message handler procedure AcceptFiles( var msg : TMessage ); message WM_DROPFILES; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.AcceptFiles( var msg : TMessage ); const cnMaxFileNameLen = 255; var i, nCount : integer; acFileName : array [0..cnMaxFileNameLen] of char; FileExt : string; begin // find out how many files we're accepting nCount := DragQueryFile( msg.WParam, $FFFFFFFF, acFileName, cnMaxFileNameLen ); // query Windows one at a time for the file name for i := 0 to nCount-1 do begin DragQueryFile( msg.WParam, i, acFileName, cnMaxFileNameLen ); // do your thing with the acFileName //MessageBox( Handle, acFileName, '', MB_OK ); FileExt := ExtractFileExt(acFileName); Edit1.Text := acFileName; ShowInterface(); end; // let Windows know that you're done DragFinish( msg.WParam ); end; procedure TForm1.AddToTreeView(list: TComInfoList); var i,j:Integer; MyTreeNode1: TTreeNode; begin for i:=0 to List.Count -1 do begin MyTreeNode1:=TreeView1.Items.Add(nil, List.Items[i].CoClassName +'\'+ List.Items[i].Guid +'['+IntToHex(List.Items[i].TypeFlags,4 )+']' ); for j:=0 to List.Items[i].Functions.Count -1 do begin TreeView1.Items.AddChild(MyTreeNode1,Format('%-30.30s [%4d][ %s ] %8.8x',[List.Items[i].Functions.Items[j].Name, List.Items[i].Functions.Items[j].oVft ,List.Items[i].Functions.Items[j].FuncKind,List.Items[i].Functions.Items[j].Offset] )); end; end; end; procedure TForm1.ComLibToTreeView(com1: TTypeLibrary); var i,j:Integer; MyTreeNode1: TTreeNode; begin TreeView1.Items.Clear; for i:=0 to com1.CoClassCount-1 do begin with com1.CoClasses[i] do begin MyTreeNode1:=TreeView1.Items.Add(nil,'[ CoClass ] '+Name +'\'+GuidToString(Guid )); for j:=0 to Interfacecount-1 do begin TreeView1.Items.AddChild(MyTreeNode1,Format('%s\%s',[Interfaces[j].Name, GuidToString(Interfaces[j].Guid ) ])); end; for j:=0 to functionCount-1 do begin TreeView1.Items.AddChild(MyTreeNode1,Format('%-30.30s [%s] %8.8x', [Functions[j].Name,Functions[j].InvokeKind ,Functions[j].Offset ])); end; end; end; for i:=0 to com1.InterfaceCount -1 do begin with com1.Interfaces[i] do begin MyTreeNode1:=TreeView1.Items.Add(nil,'[ Interface ] '+Name ); for j:=0 to FunctionCount-1 do begin TreeView1.Items.AddChild(MyTreeNode1,Format('[%d]%s',[Functions[j].id, Functions[j].Name])); end; end; end; end; procedure TForm1.edtClsIdDblClick(Sender: TObject); begin edtClsId.SelectAll; end; procedure TForm1.edtClsIdKeyPress(Sender: TObject; var Key: Char); var text_len: Integer; begin if key=#13 then begin text_len := Length(edtClsId.Text); if text_len = 38 then begin FindClsId(edtClsId.Text); end else if text_len = 36 then begin FindClsId('{' + edtClsId.Text + '}'); end else begin MessageBox(0, '您输入的CLSID长度错误,请检查!', '错误', MB_OK); end; //Prevent beep Key := #0; end; end; procedure TForm1.ComLibToMemo(com1: TTypeLibrary); var i, j, k:Integer; str: string; clsid: string; progid:PChar; ret:Integer; begin Memo1.Clear; Memo1.Lines.Add(Com1.Name +'\'+GuidTostring(com1.Guid) + com1.Description); for i:=0 to com1.CoClassCount-1 do begin with com1.CoClasses[i] do begin clsid := GuidToString(Guid); edtClsId.Text := clsid; ret := ActiveX.ProgIDFromCLSID(Guid, progid); if ret = S_OK then begin edtProgID.Text := progid; end else if ret = REGDB_E_CLASSNOTREG then begin Memo1.Lines.Add('ProgID = [Not registered]'); end; Memo1.Lines.Add(''); str := Format('[CoClass %d/%d]', [i + 1, com1.CoClassCount]) + Name + '\'+ clsid; Memo1.Lines.Add(str); str := Format(' Interface count: %d', [Interfacecount]); Memo1.Lines.Add(str); for j:=0 to Interfacecount-1 do begin str := Format(' %s\%s', [Interfaces[j].Name, GuidToString(Interfaces[j].Guid ) ]); Memo1.Lines.Add(str); end; str := Format(' Function count: %d', [functionCount]); Memo1.Lines.Add(str); for j:=0 to functionCount-1 do begin str := Format(' %-30.30s [%s] %8.8x', [Functions[j].Name, Functions[j].InvokeKind , Functions[j].Offset ]); Memo1.Lines.Add(str); end; end; end; //显示所有接口的函数 for i:=0 to com1.InterfaceCount -1 do begin with com1.Interfaces[i] do begin str := Format('[Interface %s(%d/%d)] %d Functions', [com1.Interfaces[i].Name, i + 1, com1.InterfaceCount, FunctionCount]); Memo1.Lines.Add(str); for j:=0 to FunctionCount-1 do begin str := Format(' [%-3d]%s %s', [Functions[j].ID, Functions[j].Value.DataTypeName, Functions[j].Name]); //Memo1.Lines.Add(str); str := str + '('; for k := 0 to Functions[j].ParamCount - 1 do begin str := str + Format('%s %s', [Functions[j].Params[k].DataTypeName, Functions[j].Params[k].Name]); if k < Functions[j].ParamCount - 1 then begin str := str + ', '; end; end; str := str + ')'; Memo1.Lines.Add(str); end; end; end; //显示所有接口的属性 for i:=0 to com1.InterfaceCount -1 do begin str := Format('[Interface %s(%d/%d)] %d Properties', [com1.Interfaces[i].Name, i + 1, com1.InterfaceCount, com1.Interfaces[i].PropertyCount]); Memo1.Lines.Add(str); for j:=0 to com1.Interfaces[i].PropertyCount - 1 do begin str := Format(' [%-3d]%s %s', [com1.Interfaces[i].Properties[j].ID, com1.Interfaces[i].Properties[j].Value.DataTypeName, com1.Interfaces[i].Properties[j].Name ]); Memo1.Lines.Add(str); end; end; Memo1.Perform(WM_VSCROLL,SB_TOP,nil); end; procedure TForm1.ShowInterface(); var com1:TTypeLibrary; begin if Edit1.Text = '' then begin exit; end; try com1:=TTypeLibrary.Create(Edit1.Text); //ComLibToTreeView(com1); ComLibToMemo(com1); com1.Destroy; except on E : Exception do begin ShowMessage(E.Message); Memo1.Clear; LabelCOMInfo.Caption := ''; end; end; end; procedure TForm1.Button1Click(Sender: TObject); begin ShowInterface(); end; procedure TForm1.Button2Click(Sender: TObject); begin if OpenDialog1.Execute then Edit1.Text := OpenDialog1.FileName ; end; procedure TForm1.FormCreate(Sender: TObject); begin // tell Windows that you're // accepting drag and drop files // DragAcceptFiles( Handle, True ); end; procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key=VK_ESCAPE then Close; end; procedure TForm1.FormShow(Sender: TObject); begin if Length(FilePath) > 0 then begin Edit1.Text := FilePath; ShowInterface; end; end; procedure TForm1.Memo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin //Ctrl+A进行全选 if (Key=Ord('A')) and (ssCtrl in Shift) then begin Memo1.SelectAll; Key:=0; end; end; procedure TForm1.EnumSubKeys(RootKey: HKEY; const Key: string); var Registry: TRegistry; SubKeyNames: TStringList; Name: string; begin Registry := TRegistry.Create; Try Registry.RootKey := RootKey; Registry.OpenKeyReadOnly(Key); SubKeyNames := TStringList.Create; Try Registry.GetKeyNames(SubKeyNames); for Name in SubKeyNames do MessageBox(0, 'Found!','dfef', MB_OK); Finally SubKeyNames.Free; End; Finally Registry.Free; End; end; procedure TForm1.FindClsId(clsid: string); var reg: TRegistry; Key: String; begin Key := 'CLSID\' + clsid; reg := TRegistry.Create; reg.RootKey := HKEY_CLASSES_ROOT; Try if (reg.KeyExists(Key)) then Begin if (reg.OpenKeyReadOnly(Key + '\InprocServer32')) then begin Edit1.Text :=reg.ReadString(''); ShowInterface(); end else begin MessageBox(0, 'Open InprocServer32 key error','ERROR', MB_OK); end; End; finally End; end; end.
unit PingAPIU; interface uses Windows, WinSock2, SysUtils; {$REGION 'GetAddrInfo'} type ULONG_PTR = NativeUInt; SIZE_T = ULONG_PTR; TIN6_ADDR = record s6_bytes: array[0..15] of u_char; { case Integer of 0: (s6_bytes: array[0..15] of u_char); 1: (s6_words: array[0..7] of u_short); } end; sockaddr_in6 = record sin6_family: Smallint; sin6_port: u_short; sin6_flowinfo: u_long; sin6_addr : TIN6_ADDR; sin6_scope_id: u_long; end; TSockAddrIn6 = sockaddr_in6; PSockAddrIn6 = ^sockaddr_in6; PAddrInfoW = ^ADDRINFOW; ADDRINFOW = record ai_flags : Integer; // AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST ai_family : Integer; // PF_xxx ai_socktype : Integer; // SOCK_xxx ai_protocol : Integer; // 0 or IPPROTO_xxx for IPv4 and IPv6 ai_addrlen : size_t; // Length of ai_addr ai_canonname : PWideChar; // Canonical name for nodename ai_addr : PSockAddrIn; // Binary address ai_next : PAddrInfoW; // Next structure in linked list end; TAddrInfoW = ADDRINFOW; LPADDRINFOW = PAddrInfoW; function GetAddrInfoW(const nodename: PWideChar; const servname : PWideChar; const hints: PAddrInfoW; var res: PaddrinfoW): Integer; stdcall; external 'ws2_32.dll'; procedure FreeAddrInfoW(ai: PAddrInfoW); stdcall; external 'ws2_32.dll'; {žENDREGION} {$REGION 'ICMP related functions and types'} type PIPOptionInformation = ^TIPOptionInformation; TIPOptionInformation = record Ttl: Byte; // time to live Tos: Byte; // type of service Flags: Byte; // ip header flags OptionsSize: Byte; // size in bytes of options data OptionsData: ^Byte; // pointer to options data end; ICMP_ECHO_REPLY = record Address: in_addr; // replying address Status: ULONG; // reply ip_status RoundTripTime: ULONG; // rtt in milliseconds DataSize: ULONG; // reply data size in bytes Reserved: ULONG; // reserved for system use Data: Pointer; // pointer to the reply data Options: PIPOptionInformation; // reply options end; PICMP_ECHO_REPLY = ^ICMP_ECHO_REPLY; function IcmpCreateFile: THandle; stdcall; external 'icmp.dll'; function IcmpCloseHandle(icmpHandle: THandle): Boolean; stdcall; external 'icmp.dll'; function IcmpSendEcho(icmpHandle: THandle; DestinationAddress: in_addr; RequestData: Pointer; RequestSize: Word; RequestOptions: PIPOptionInformation; ReplyBuffer: Pointer; ReplySize: DWORD; Timeout: DWORD): DWORD; stdcall; external 'icmp.dll'; {$ENDREGION} {$REGION 'ICMP6 related constants, functions and types'} const ICMP_ECHO = 8; ICMP_ECHOREPLY = 0; ICMP_UNREACH = 3; ICMP_TIME_EXCEEDED = 11; // rfc-2292 ICMP6_ECHO = 128; ICMP6_ECHOREPLY = 129; ICMP6_UNREACH = 1; ICMP6_TIME_EXCEEDED = 3; AI_CANONNAME = 2; AI_NUMERICHOST = 4; type TIP_OPTION_INFORMATION = record Ttl: Byte; Tos: Byte; Flags: Byte; OptionsSize: Byte; OptionsData: PAnsiChar; end; PIP_OPTION_INFORMATION = ^TIP_OPTION_INFORMATION; TICMPV6_ECHO_REPLY = record Address: TSockAddrIn6; Status: Integer; RoundTripTime: Integer; end; PICMPV6_ECHO_REPLY = ^TICMPV6_ECHO_REPLY; function Icmp6CreateFile: Integer; stdcall; external 'iphlpapi.dll'; function Icmp6SendEcho2(handle: Integer; Event: Pointer; ApcRoutine: Pointer; ApcContext: Pointer; SourceAddress: PSockAddrIn6; DestinationAddress: PSockAddrIn6; RequestData: Pointer; RequestSize: Integer; RequestOptions: PIP_OPTION_INFORMATION; ReplyBuffer: Pointer; ReplySize: Integer; Timeout: Integer): Integer; stdcall; external 'iphlpapi.dll'; {$ENDREGION} function GetHumanAddress(addr: PSockAddr; const addrlen: NativeUInt): String; implementation const NI_MAXHOST = 1025; // Max size of a fully-qualified domain name. NI_NUMERICHOST = $2 ; // Return numeric form of the host's address. function GetNameInfoW(pSockaddr: PSockAddr; SockaddrLength: Integer; host: PWideChar; hostlen: u_int; serv: PWideChar; servlen: u_int; flags: Integer): Integer; stdcall; external 'Ws2_32.dll'; function GetHumanAddress(addr: PSockAddr; const addrlen: NativeUInt): String; var ClientHost: array[0..NI_MAXHOST-1] of Char; begin GetNameInfoW(addr, addrlen, ClientHost, NI_MAXHOST, nil, 0, NI_NUMERICHOST); Result := ClientHost; end; end.
unit Plus.System.AnonymousEvent; interface uses System.Classes, System.SysUtils; type TNotifyEventWrapper = class(TComponent) private FProc: TProc<TObject>; public constructor Create(Owner: TComponent; Proc: TProc<TObject>); published procedure Event(Sender: TObject); end; function AnonymousMethodToTNotifyEvent(Owner: TComponent; Proc: TProc<TObject>) : TNotifyEvent; implementation constructor TNotifyEventWrapper.Create(Owner: TComponent; Proc: TProc<TObject>); begin inherited Create(Owner); FProc := Proc; end; procedure TNotifyEventWrapper.Event(Sender: TObject); begin FProc(Sender); end; function AnonymousMethodToTNotifyEvent(Owner: TComponent; Proc: TProc<TObject>) : TNotifyEvent; begin Result := TNotifyEventWrapper.Create(Owner, Proc).Event; end; end.
{Ä Fido Pascal Conference ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ PASCAL Ä Msg : 455 of 535 From : Gregory P. Smith 1:104/332.11 21 Apr 93 14:59 To : Joe Maffuccio 1:321/212.0 Subj : Generating AVT/0 & ANSI codes ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ On Apr 19 23:40, Joe Maffuccio of 1:321/212 wrote: JM> I just recieved your PAvatar 1.50 package in the mail. Um, haha, I have a JM> question. How do I use it? Hhaa. Ok, lets say in a door. Something JM> simple. Say this. I have a door, the function that sends strings out to JM> the user is called Procedure Print(var Message:string);. Let's say I JM> wanted to send that message in the color light blue to the user. How JM> would I go about doing that with PAvatar. I also want to add something JM> that will allow me to just call a procedure with a number or two, and JM> have PAvatar change color both locally and over the modem. Here's a unit I just pieced together from some old code I wrote a couple years ago. It'll generate AVT/0+ and ANSI codes: ========== } Unit TermCode; {$S-,D-,L-,R-,F-,O-} { Generate ANSI and AVT/0+ codes for color and cursor ctrl } { Public Domain -- by Gregory P. Smith } { untested } interface type Str12 = string[12]; { Maximum size for most ANSI strings } Str3 = string[3]; grTermType = (TTY, ANSI, AVT0); { TTY, ANSI or Avatar/0+ } var grTerm : grTermType; grColor : Byte; { Last color set } { Non Specific functions } Function grRepChar(c:char;n:byte): string; { Repeat Chars } Function grSetPos(x,y:byte): Str12; { Set Cursor Position } Function grCLS: Str12; { Clear Screen + reset Attr } Function grDelEOL: Str12; { Delete to EOL } Function grSetAttr(a:byte): Str12; { Change writing color } Function grSetColor(fg,bg:byte): Str12; { Change color fg & bg } { AVT/0+ Specific functions } Function AVTRepPat(pat:string;n:byte): string; { Repeat Pattern (AVT/0+) } Function AVTScrollUp(n,x1,y1,x2,y2:byte): Str12; Function AVTScrollDown(n,x1,y1,x2,y2:byte): Str12; Function AVTClearArea(a,l,c:byte): Str12; Function AVTInitArea(ch:char;a,l,c:byte): Str12; IMPLEMENTATION const hdr = #27'['; { ansi header } { Misc support functions } function bts(x:byte): str3; { byte to string } var z: str3; begin Str(x,z); bts := z; end; function Repl(n:byte; c:char): string; var z : string; begin fillchar(z[1],n,c); z[0] := chr(n); repl := z; end; { Cursor Control functions } function grRepChar(c:char;n:byte): string; begin if grTerm = AVT0 then grRepChar := ^Y+c+chr(n) else grRepChar := repl(n,c); end; { repcahr } function grSetPos(x,y:byte): Str12; begin case grTerm of ANSI : if (x = 1) and (y > 1) then grSetPos := hdr+bts(y)+'H' { x defualts to 1 } else grSetPos := hdr+bts(y)+';'+bts(x)+'H'; AVT0 : grSetPos := ^V+^H+chr(y)+chr(x); TTY : grSetPos := ''; end; { case } end; function grCLS: Str12; begin case grTerm of ANSI : grCLS := hdr+'2J'; TTY, AVT0 : grCLS := ^L; end; if grTerm = AVT0 then GrColor := 3; { reset the color } end; { cls } function grDelEOL: Str12; { clear rest of line } begin case grTerm of ANSI : grDelEOL := hdr+'K'; AVT0 : grDelEOL := ^V^G; TTY : grDelEOL := ''; end; end; { Color functions } function grSetAttr(a:byte): Str12; const ANS_Colors : Array[0..7] of char = ('0','4','2','6','1','5','3','7'); var tmp : Str12; begin tmp := ''; case grTerm of ANSI : begin tmp := hdr; if (a and $08)=8 then tmp := tmp+'1' else tmp := tmp+'0'; { bright } if (a and $80)=$80 then tmp := tmp+';5'; { blink } tmp := tmp+';3'+ANS_Colors[a and $07]; { foreground } tmp := tmp+';4'+ANS_Colors[(a shr 4) and $07]; { background } grSetAttr := tmp+'m'; { complete ANSI code } end; AVT0 : begin tmp := ^V+^A+chr(a AND $7f); if a > 127 then tmp := tmp+^V+^B; { Blink } grSetAttr := tmp; end; TTY : grSetAttr := ''; end; { case } GrColor := a; { Current Attribute } end; { setattr } function grSetColor(fg,bg:byte): Str12; begin grSetColor := grSetAttr((bg shl 4) OR (fg and $0f)); end; { SetColor } { AVATAR Specific functions: } function AVTRepPat(pat:string;n:byte): string; { Repeat Pattern (AVT/0+) } begin AVTRepPat := ^V+^Y+pat[0]+pat+chr(n); { Repeat pat n times } end; function AVTScrollUp(n,x1,y1,x2,y2:byte): Str12; begin AVTScrollUp := ^V+^J+chr(n)+chr(y1)+chr(x1)+chr(y2)+chr(x2); end; { AVTScrollUp } function AVTScrollDown(n,x1,y1,x2,y2:byte): Str12; begin AVTScrollDown := ^V+^K+chr(n)+chr(y1)+chr(x1)+chr(y2)+chr(x2); end; { AVTScrollDown } function AVTClearArea(a,l,c:byte): Str12; var b:byte; s:Str12; begin { Clear lines,columns from cursor pos with Attr } b := a and $7f; s := ^V+^L+chr(b)+chr(l)+chr(c); if a > 127 then Insert(^V+^B,s,1); { blink on } AVTClearArea := s; GrColor := a; end; { AVTClearArea } function AVTInitArea(ch:char;a,l,c:byte): Str12; var b:byte; s:Str12; begin b := a AND $7f; s := ^V+^M+chr(b)+ch+chr(l)+chr(c); if a > 127 then Insert(^V+^B,s,1); AvtInitArea := s; GrColor := a; end; { AVTInitArea } { Initalization code } BEGIN GrTerm := AVT0; { Default to Avatar } GrColor := 3; { Cyan is the AVT/0+ defualt } END. ============= set GrTerm to whatever terminal codes you want to create; then you can use the common routines to generate ANSI or Avatar codes. Here's a Print procedure that you were mentioning: Procedure Print(var msg:string); var idx : byte begin if length(msg) > 0 then for idx := 1 to length(msg) do begin Parse_AVT1(msg[idx]); SendOutComPortThingy(msg[idx]); end; { for } end; You could modify this so that it pays attention to the TextAttr variable of the Crt unit if you wish so that it compares TextAttr to GrColor and adds a SetAttr(TextAttr) command in before it sends msg. Hope that helps, .. Greg
{ Copy landscape data in defined rectangular area between worldspaces with optional height adjustment. Height adjustment is needed when the default water levels don't match in source and destination areas. For example in source area it is -2048, in destination 0, then adjustment should be 2048 to raise landscape. Adjustment must always be divisible by 8!!! When patch plugin option is checked a new plugin will be created to patch landscape in destination area. When not checked, landscape records will be changed directly. } unit CopyAreaLandData; const bCopyLayers = False; // True to copy landscape textures, though this requires textures availability in destination plugin var World1, World2, Plugin: IInterface; X1, Y1, W, H, X2, Y2, HeightAdjust: Integer; bPlugin: Boolean; //=========================================================================== // returns LAND record for CELL record function GetLandscapeForCell(cell: IInterface; aAddIfMissing: Boolean; aPlugin: IInterface): IInterface; var cellchild, r: IInterface; i: integer; begin cellchild := FindChildGroup(ChildGroup(cell), 9, cell); // get Temporary group of cell for i := 0 to Pred(ElementCount(cellchild)) do begin r := ElementByIndex(cellchild, i); if Signature(r) <> 'LAND' then Continue; // copy land as override if new plugin is provided if Assigned(aPlugin) then begin AddRequiredElementMasters(cell, Plugin, False); Result := wbCopyElementToFile(r, aPlugin, False, True); end else Result := r; Exit; end; if not aAddIfMissing then Exit; // add a new one if missing // copy cell as override if new plugin is provided if Assigned(aPlugin) then begin AddRequiredElementMasters(cell, Plugin, False); cell := wbCopyElementToFile(cell, aPlugin, False, True); end Result := Add(cell, 'LAND', True); end; //============================================================================ // get cell record by X,Y grid coordinates from worldspace function GetCellFromWorldspace(Worldspace: IInterface; GridX, GridY: integer): IInterface; var blockidx, subblockidx, cellidx: integer; wrldgrup, block, subblock, cell: IInterface; Grid, GridBlock, GridSubBlock: TwbGridCell; LabelBlock, LabelSubBlock: Cardinal; begin Grid := wbGridCell(GridX, GridY); GridSubBlock := wbSubBlockFromGridCell(Grid); LabelSubBlock := wbGridCellToGroupLabel(GridSubBlock); GridBlock := wbBlockFromSubBlock(GridSubBlock); LabelBlock := wbGridCellToGroupLabel(GridBlock); wrldgrup := ChildGroup(Worldspace); // iterate over Exterior Blocks for blockidx := 0 to Pred(ElementCount(wrldgrup)) do begin block := ElementByIndex(wrldgrup, blockidx); if GroupLabel(block) <> LabelBlock then Continue; // iterate over SubBlocks for subblockidx := 0 to Pred(ElementCount(block)) do begin subblock := ElementByIndex(block, subblockidx); if GroupLabel(subblock) <> LabelSubBlock then Continue; // iterate over Cells for cellidx := 0 to Pred(ElementCount(subblock)) do begin cell := ElementByIndex(subblock, cellidx); if (Signature(cell) <> 'CELL') or GetIsPersistent(cell) then Continue; if (GetElementNativeValues(cell, 'XCLC\X') = Grid.x) and (GetElementNativeValues(cell, 'XCLC\Y') = Grid.y) then begin Result := cell; Exit; end; end; Break; end; Break; end; end; //=========================================================================== procedure CopyElement(recsrc, recdst: IInterface; elName: string); var el: IInterface; begin el := ElementByPath(recsrc, elName); if not Assigned(el) then begin RemoveElement(recdst, elName); Exit; end; if not ElementExists(recdst, elName) then Add(recdst, elName, True); ElementAssign(ElementByPath(recdst, elName), LowInteger, el, False); end; //=========================================================================== procedure FillWorldspaces(lst: TStrings); var sl: TStringList; i, j: integer; f, wrlds, wrld: IInterface; s: string; begin sl := TStringList.Create; for i := 0 to Pred(FileCount) do begin f := FileByIndex(i); wrlds := GroupBySignature(f, 'WRLD'); for j := 0 to Pred(ElementCount(wrlds)) do begin wrld := ElementByIndex(wrlds, j); if ElementType(wrld) <> etMainRecord then Continue; s := EditorID(wrld); if sl.IndexOf(s) = -1 then sl.AddObject(s, wrld); end; end; sl.Sort; lst.AddStrings(sl); sl.Free; end; //=========================================================================== function OptionsForm: Boolean; var frm: TForm; lbl: TLabel; cmbWorldFrom, cmbWorldTo: TComboBox; edX1, edY1, edW, edH, edX2, edY2, edH2: TEdit; chkPlugin: TCheckBox; btnOk, btnCancel: TButton; begin frm := TForm.Create(nil); try frm.Caption := 'Copy landscape'; frm.Width := 400; frm.Height := 310; frm.Position := poMainFormCenter; frm.BorderStyle := bsDialog; cmbWorldFrom := TComboBox.Create(frm); cmbWorldFrom.Parent := frm; cmbWorldFrom.Left := 8; cmbWorldFrom.Top := 26; cmbWorldFrom.Width := frm.Width - 26; cmbWorldFrom.Style := csDropDownList; cmbWorldFrom.DropDownCount := 20; FillWorldspaces(cmbWorldFrom.Items); if cmbWorldFrom.Items.Count > 0 then cmbWorldFrom.ItemIndex := 0; lbl := TLabel.Create(frm); lbl.Parent := frm; lbl.Left := cmbWorldFrom.Left; lbl.Top := cmbWorldFrom.Top - 16; lbl.Caption := 'From worldspace'; edX1 := TEdit.Create(frm); edX1.Parent := frm; edX1.Left := 8; edX1.Top := cmbWorldFrom.Top + 50; edX1.Width := 32; edX1.Text := '0'; edY1 := TEdit.Create(frm); edY1.Parent := frm; edY1.Left := edX1.Left + 40; edY1.Top := edX1.Top; edY1.Width := edX1.Width; edY1.Text := '0'; edW := TEdit.Create(frm); edW.Parent := frm; edW.Left := edY1.Left + 40; edW.Top := edX1.Top; edW.Width := edX1.Width; edW.Text := '4'; edH := TEdit.Create(frm); edH.Parent := frm; edH.Left := edW.Left + 40; edH.Top := edX1.Top; edH.Width := edX1.Width; edH.Text := '4'; lbl := TLabel.Create(frm); lbl.Parent := frm; lbl.Left := edX1.Left; lbl.Top := edX1.Top - 16; lbl.Caption := 'Area: South West cell coordinates, cells Width and Height'; cmbWorldTo := TComboBox.Create(frm); cmbWorldTo.Parent := frm; cmbWorldTo.Left := 8; cmbWorldTo.Top := 130; cmbWorldTo.Width := frm.Width - 26; cmbWorldTo.Style := csDropDownList; cmbWorldTo.DropDownCount := 20; FillWorldspaces(cmbWorldTo.Items); if cmbWorldTo.Items.Count > 0 then cmbWorldTo.ItemIndex := Pred(cmbWorldTo.Items.Count); lbl := TLabel.Create(frm); lbl.Parent := frm; lbl.Left := cmbWorldTo.Left; lbl.Top := cmbWorldTo.Top - 16; lbl.Caption := 'To worldspace'; edX2 := TEdit.Create(frm); edX2.Parent := frm; edX2.Left := 8; edX2.Top := cmbWorldTo.Top + 50; edX2.Width := 32; edX2.Text := '10'; edY2 := TEdit.Create(frm); edY2.Parent := frm; edY2.Left := edX2.Left + 40; edY2.Top := edX2.Top; edY2.Width := edX2.Width; edY2.Text := '10'; edH2 := TEdit.Create(frm); edH2.Parent := frm; edH2.Left := edY2.Left + 40; edH2.Top := edY2.Top; edH2.Width := 64; lbl := TLabel.Create(frm); lbl.Parent := frm; lbl.Left := edX2.Left; lbl.Top := edX2.Top - 16; lbl.Caption := 'South West cell coordinates, optional Height adjustment in game units'; chkPlugin := TCheckBox.Create(frm); chkPlugin.Parent := frm; chkPlugin.Left := 8; chkPlugin.Top := edX2.Top + 40; chkPlugin.Width := frm.Width - 26; chkPlugin.Caption := 'Create patch plugin'; chkPlugin.Checked := True; btnOk := TButton.Create(frm); btnOk.Parent := frm; btnOk.Caption := 'OK'; btnOk.ModalResult := mrOk; btnOk.Left := frm.Width - 180; btnOk.Top := frm.Height - 64; btnCancel := TButton.Create(frm); btnCancel.Parent := frm; btnCancel.Caption := 'Cancel'; btnCancel.ModalResult := mrCancel; btnCancel.Left := btnOk.Left + btnOk.Width + 10; btnCancel.Top := btnOk.Top; if frm.ShowModal <> mrOk then Exit; if (cmbWorldFrom.ItemIndex = -1) or (cmbWorldTo.ItemIndex = -1) or (cmbWorldFrom.ItemIndex = cmbWorldTo.ItemIndex) then Exit; World1 := ObjectToElement(cmbWorldFrom.Items.Objects[cmbWorldFrom.ItemIndex]); World2 := ObjectToElement(cmbWorldTo.Items.Objects[cmbWorldTo.ItemIndex]); X1 := StrToInt(edX1.Text); Y1 := StrToInt(edY1.Text); W := StrToInt(edW.Text); H := StrToInt(edH.Text); X2 := StrToInt(edX2.Text); Y2 := StrToInt(edY2.Text); if edH2.Text <> '' then HeightAdjust := StrToInt(edH2.Text); bPlugin := chkPlugin.Checked; Result := True; finally frm.Free; end; end; //=========================================================================== function Initialize: integer; var cell1, land1, cell2, land2: IInterface; i, j: Integer; begin Result := 1; if wbSimpleRecords then begin MessageDlg('Simple records must be unchecked in xEdit options', mtInformation, [mbOk], 0); Exit; end; if not OptionsForm then Exit; //Exit; if bPlugin then begin Plugin := AddNewFile; if not Assigned(Plugin) then Exit; AddRequiredElementMasters(World2, Plugin, False); end; for i := 0 to Pred(W) do for j := 0 to Pred(H) do begin cell1 := GetCellFromWorldspace(World1, X1 + i, Y1 + j); land1 := GetLandscapeForCell(cell1, False, nil); if not Assigned(land1) then Continue; cell2 := GetCellFromWorldspace(World2, X2 + i, Y2 + j); if not Assigned(cell2) then begin AddMessage(Format('Skipped: Destination cell not found %s <%d,%d>', [EditorID(World2), X2 + i, Y2 + j])); Continue; end; land2 := GetLandscapeForCell(cell2, True, Plugin); CopyElement(land1, land2, 'DATA'); CopyElement(land1, land2, 'VNML'); CopyElement(land1, land2, 'VHGT'); CopyElement(land1, land2, 'VCLR'); if bCopyLayers then CopyElement(land1, land2, 'Layers'); SetElementNativeValues(land2, 'VHGT\Offset', GetElementNativeValues(land2, 'VHGT\Offset') + HeightAdjust / 8); AddMessage(Format('Copied: %s <%d,%d> to %s <%d,%d>', [ EditorID(World1), X1 + i, Y1 + j, EditorID(World2), X2 + i, Y2 + j ])); end; end; end.
unit uProgramInput; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, cxControls, cxContainer, cxEdit, dxSkinsCore, dxSkinCaramel, cxCheckBox, cxTextEdit, StdCtrls, ExtCtrls, cxButtons, uGlobal, cxMaskEdit, cxDropDownEdit, cxLabel, cxColorComboBox, dxSkinOffice2007Blue, dxSkinBlack, dxSkinBlue, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinFoggy, dxSkinGlassOceans, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinPumpkin, dxSkinSeven, dxSkinSharp, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinsDefaultPainters, dxSkinValentine, dxSkinXmas2008Blue, cxGroupBox, cxRadioGroup; type TfrmProgramInput = class(TForm) btnOK: TcxButton; btnClose: TcxButton; Panel1: TPanel; Label6: TLabel; chkUsed: TcxCheckBox; cxLabel1: TcxLabel; cboProgram: TcxComboBox; cxLabel2: TcxLabel; cboWard: TcxComboBox; txtProgramName: TcxTextEdit; Label1: TLabel; cxColor: TcxColorComboBox; rgLinkRecord: TcxRadioGroup; procedure FormShow(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cboProgramPropertiesChange(Sender: TObject); private { Private declarations } procedure SetControls; function isValidInput: Boolean; public { Public declarations } ProgramInfo: TProgramInfo; end; var frmProgramInput: TfrmProgramInput; implementation uses uConfig, uDB; {$R *.dfm} procedure TfrmProgramInput.btnOKClick(Sender: TObject); begin if not isValidInput then Exit; if oGlobal.YesNo('진행하시겠습니까?') = mrYes then begin if ProgramInfo.Mode = emAppend then begin ProgramInfo.ProgramTypeID := dbMain.GetProgramTypeID(cboProgram.Text); ProgramInfo.ProgramTypeName := cboProgram.Text; end; ProgramInfo.ProgramName := trim(txtProgramName.Text); ProgramInfo.Color := cxColor.ColorValue; ProgramInfo.WardID := dbMain.GetWardID(ProgramInfo.HospitalID, cboWard.Text); ProgramInfo.WardName := cboWard.Text; ProgramInfo.UseAll := cboWard.ItemIndex = 0; ProgramInfo.Used := chkUsed.Checked; ProgramInfo.LinkRecordID := rgLinkRecord.ItemIndex; ModalResult := mrOK; end; end; procedure TfrmProgramInput.cboProgramPropertiesChange(Sender: TObject); begin rgLinkRecord.Visible := False; if cboProgram.ItemIndex < 0 then Exit; if dbMain.isProgramTypeLinkRecord(cboProgram.Text) then rgLinkRecord.Visible := True; end; procedure TfrmProgramInput.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; end; procedure TfrmProgramInput.FormShow(Sender: TObject); begin if dbMain.GetWardList(ProgramInfo.HospitalID, cboWard.Properties.Items, True) then cboWard.ItemIndex := 0; if dbMain.GetProgramTypeList(cboProgram.Properties.Items, False) then cboProgram.ItemIndex := 0; SetControls; if ProgramInfo.Mode = emAppend then cboProgram.SetFocus else txtProgramName.SetFocus; end; function TfrmProgramInput.isValidInput: Boolean; begin result := false; if cboProgram.ItemIndex < 0 then begin oGlobal.Msg('구분을 선택하십시오!'); cboProgram.SetFocus; Exit; end; if cboWard.ItemIndex < 0 then begin oGlobal.Msg('사용병동을 선택하십시오!'); cboWard.SetFocus; Exit; end; if oGlobal.isNullStr(txtProgramName.Text) then begin oGlobal.Msg('프로그램이름을 입력하십시오!'); txtProgramName.SetFocus; Exit; end; if rgLinkRecord.Visible and (rgLinkRecord.ItemIndex < 0) then begin oGlobal.Msg('연동할 기록지를 선택하십시오!'); Exit; end; result := True; end; procedure TfrmProgramInput.SetControls; begin rgLinkRecord.Visible := False; cboProgram.ItemIndex := cboProgram.Properties.Items.IndexOf(ProgramInfo.ProgramTypeName); cboWard.ItemIndex := cboWard.Properties.Items.IndexOf(ProgramInfo.WardName); if cboWard.ItemIndex < 0 then cboWard.ItemIndex := 0; txtProgramName.Text := ProgramInfo.ProgramName; chkUsed.Checked := ProgramInfo.Used; rgLinkRecord.ItemIndex := ProgramInfo.LinkRecordID; // 0-사회사업지도, 1-사회재활훈련 cxColor.ColorValue := ProgramInfo.Color; cboProgram.Enabled := ProgramInfo.Mode = emAppend; end; end.
unit rallyx_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,gfx_engine,namco_snd,samples,rom_engine, pal_engine,konami_snd,sound_engine; //Driver genericas procedure Cargar_rallyxh; function iniciar_rallyxh:boolean; procedure reset_rallyxh; procedure cerrar_rallyxh; //especificas procedure jungler_principal; function jungler_getbyte(direccion:word):byte; procedure jungler_putbyte(direccion:word;valor:byte); function rallyx_getbyte(direccion:word):byte; procedure rallyx_putbyte(direccion:word;valor:byte); procedure rallyx_outbyte(valor:byte;puerto:word); procedure rallyx_playsound; implementation const //Jungler jungler_rom:array[0..4] of tipo_roms=( (n:'jungr1';l:$1000;p:0;crc:$5bd6ad15),(n:'jungr2';l:$1000;p:$1000;crc:$dc99f1e3), (n:'jungr3';l:$1000;p:$2000;crc:$3dcc03da),(n:'jungr4';l:$1000;p:$3000;crc:$f92e9940),()); jungler_pal:array[0..2] of tipo_roms=( (n:'18s030.8b';l:$20;p:0;crc:$55a7e6d1),(n:'tbp24s10.9d';l:$100;p:$20;crc:$d223f7b8),()); jungler_char:array[0..2] of tipo_roms=( (n:'5k';l:$800;p:0;crc:$924262bf),(n:'5m';l:$800;p:$800;crc:$131a08ac),()); jungler_sound:tipo_roms=(n:'1b';l:$1000;p:0;crc:$f86999c3); jungler_dots:tipo_roms=(n:'82s129.10g';l:$100;p:0;crc:$c59c51b7); //Rally X rallyx_rom:array[0..4] of tipo_roms=( (n:'1b';l:$1000;p:0;crc:$5882700d),(n:'rallyxn.1e';l:$1000;p:$1000;crc:$ed1eba2b), (n:'rallyxn.1h';l:$1000;p:$2000;crc:$4f98dd1c),(n:'rallyxn.1k';l:$1000;p:$3000;crc:$9aacccf0),()); rallyx_pal:array[0..2] of tipo_roms=( (n:'rx-1.11n';l:$20;p:0;crc:$c7865434),(n:'rx-7.8p';l:$100;p:$20;crc:$834d4fda),()); rallyx_char:tipo_roms=(n:'8e';l:$1000;p:0;crc:$277c1de5); rallyx_sound:tipo_roms=(n:'rx-5.3p';l:$100;p:0;crc:$4bad7017); rallyx_dots:tipo_roms=(n:'rx1-6.8m';l:$100;p:0;crc:$3c16f62c); rallyx_samples:tipo_nombre_samples=(nombre:'bang.wav'); //New Rally X nrallyx_rom:array[0..4] of tipo_roms=( (n:'nrx_prg1.1d';l:$1000;p:0;crc:$ba7de9fc),(n:'nrx_prg2.1e';l:$1000;p:$1000;crc:$eedfccae), (n:'nrx_prg3.1k';l:$1000;p:$2000;crc:$b4d5d34a),(n:'nrx_prg4.1l';l:$1000;p:$3000;crc:$7da5496d),()); nrallyx_pal:array[0..2] of tipo_roms=( (n:'nrx1-1.11n';l:$20;p:0;crc:$a0a49017),(n:'nrx1-7.8p';l:$100;p:$20;crc:$4e46f485),()); nrallyx_char:array[0..2] of tipo_roms=( (n:'nrx_chg1.8e';l:$800;p:0;crc:$1fff38a4),(n:'nrx_chg2.8d';l:$800;p:$800;crc:$85d9fffd),()); nrallyx_sound:tipo_roms=(n:'rx1-5.3p';l:$100;p:0;crc:$4bad7017); nrallyx_dots:tipo_roms=(n:'rx1-6.8m';l:$100;p:0;crc:$3c16f62c); var last,scroll_x,scroll_y:byte; hacer_int:boolean; //jungler procedure update_video_jungler;inline; var f,nchar,y,x,color:word; h,atrib:byte; begin //Backgorund (256x256) for f:=0 to $3ff do begin if gfx[0].buffer[f] then begin x:=f div 32; y:=31-(f mod 32); atrib:=memoria[$8c00+f]; color:=(atrib and $3f) shl 2; nchar:=memoria[$8400+f]; put_gfx_flip(x*8,y*8,nchar,color,1,0,(atrib and $80)=0,(atrib and $40)<>0); if (atrib and $20)=0 then put_gfx_block_trans(x*8,y*8,5,8,8) else put_gfx_trans_flip(x*8,y*8,nchar,color,5,0,(atrib and $80)=0,(atrib and $40)<>0); gfx[0].buffer[f]:=false; end; end; actualiza_trozo(0,0,256,256,1,0,32,256,256,4); //Sprites for f:=$f downto $a do begin atrib:=memoria[$8000+(f*2)]; nchar:=(atrib and $fc) shr 2; color:=(memoria[$8801+(f*2)] and $3f) shl 2; x:=memoria[$8800+(f*2)]-1; y:=memoria[$8001+(f*2)]+((memoria[$8801+(f*2)] and $80) shl 1); put_gfx_sprite_mask(nchar,color,(atrib and 2)<>0,(atrib and 1)<>0,1,0,$f); actualiza_gfx_sprite(x,y,4,1); end; actualiza_trozo(0,0,256,256,5,0,32,256,256,4); //Foreground (solo 256x64) f:=$20; while f<$3ff do begin for h:=0 to 7 do begin if gfx[2].buffer[f] then begin x:=f div 32; y:=7-(f mod 8); color:=(memoria[$8800+f] and $3f) shl 2; nchar:=memoria[$8000+f]; put_gfx(x*8,y*8,nchar,color,2,0); gfx[2].buffer[f]:=false; end; f:=f+1; end; f:=f+24; end; actualiza_trozo(0,32,256,32,2,0,0,256,32,4); actualiza_trozo(0,0,256,32,2,0,32,256,32,4); //Disparos for f:=$14 to $20 do begin x:=memoria[$8820+f]; if x>=16 then begin nchar:=(memoria[$a030+f] and $7) xor 7; y:=memoria[$8020+f]+((memoria[$a030+f] xor $ff) and $8) shl 5; if y>288 then y:=y and $FF; put_gfx_trans(0,0,nchar,16,3,2); actualiza_trozo(0,0,4,4,3,x,y,4,4,4); end; end; end; procedure eventos_jungler; begin if event.arcade then begin if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.start[1] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40); if arcade_input.down[0] then marcade.in2:=(marcade.in2 and $7f) else marcade.in2:=(marcade.in2 or $80); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40); if arcade_input.start[0] then marcade.in1:=(marcade.in1 and $7f) else marcade.in1:=(marcade.in1 or $80); end; end; procedure jungler_principal; var frame_m,frame_s:single; f:byte; begin init_controls(false,false,false,true); frame_m:=main_z80.tframes; frame_s:=snd_z80.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin konami_sound.frame:=f; //Main CPU main_z80.run(frame_m); frame_m:=frame_m+main_z80.tframes-main_z80.contador; //Sound CPU snd_z80.run(frame_s); frame_s:=frame_s+snd_z80.tframes-snd_z80.contador; if f=239 then begin if hacer_int then main_z80.pedir_nmi:=PULSE_LINE; update_video_jungler; end; end; actualiza_trozo(16+ADD_SPRITE,ADD_SPRITE,224,288,4,0,0,224,288,pant_temp); eventos_jungler; video_sync; end; end; function jungler_getbyte(direccion:word):byte; begin case direccion of $a000:jungler_getbyte:=marcade.in0; $a080:jungler_getbyte:=marcade.in1; $a100:jungler_getbyte:=marcade.in2; $a180:jungler_getbyte:=$b7; else jungler_getbyte:=memoria[direccion]; end; end; procedure jungler_putbyte(direccion:word;valor:byte); begin if direccion<$4000 then exit; memoria[direccion]:=valor; case direccion of $8000..$83ff:gfx[2].buffer[direccion and $3ff]:=true; $8400..$87ff:gfx[0].buffer[direccion and $3ff]:=true; $8800..$8bff:gfx[2].buffer[direccion and $3ff]:=true; $8c00..$8fff:gfx[0].buffer[direccion and $3ff]:=true; $a100:konami_sound.sound_latch:=valor; $a180:begin if ((last=0) and (valor<>0)) then snd_z80.pedir_irq:=HOLD_LINE; last:=valor; end; $a181:hacer_int:=valor<>0; end; end; //Rally X procedure update_video_rallyx;inline; var f,nchar,y,x,color:word; h,atrib:byte; begin //Backgorund (256x256) for f:=0 to $3ff do begin if gfx[0].buffer[f] then begin y:=f div 32; x:=f mod 32; atrib:=memoria[$8c00+f]; color:=(atrib and $3f) shl 2; nchar:=memoria[$8400+f]; put_gfx_flip(x*8,y*8,nchar,color,1,0,(atrib and $40)=0,(atrib and $80)<>0); if (atrib and $20)=0 then put_gfx_block_trans(x*8,y*8,5,8,8) else put_gfx_flip(x*8,y*8,nchar,color,5,0,(atrib and $40)=0,(atrib and $80)<>0); gfx[0].buffer[f]:=false; end; end; scroll_x_y(1,4,scroll_x-3,scroll_y); //Sprites for f:=$f downto $a do begin atrib:=memoria[$8000+(f*2)]; nchar:=(atrib and $fc) shr 2; color:=(memoria[$8801+(f*2)] and $3f) shl 2; y:=241-memoria[$8800+(f*2)]; x:=memoria[$8001+(f*2)]+((memoria[$8801+(f*2)] and $80) shl 1); put_gfx_sprite_mask(nchar,color,(atrib and 1)<>0,(atrib and 2)<>0,1,0,$f); actualiza_gfx_sprite(x,y,4,1); end; scroll_x_y(5,4,scroll_x-3,scroll_y); //Foreground (solo 256x64) f:=$20; while f<$3ff do begin for h:=0 to 7 do begin if gfx[2].buffer[f] then begin y:=f div 32; x:=f mod 8; atrib:=memoria[$8800+f]; color:=(atrib and $3f) shl 2; nchar:=memoria[$8000+f]; put_gfx_flip(x*8,y*8,nchar,color,2,0,(atrib and $40)=0,(atrib and $80)<>0); gfx[2].buffer[f]:=false; end; f:=f+1; end; f:=f+24; end; actualiza_trozo(32,0,32,256,2,224,0,32,256,4); actualiza_trozo(0,0,32,256,2,256,0,32,256,4); //Radar for f:=0 to $b do begin y:=237-memoria[$8834+f]; atrib:=memoria[$a004+f]; nchar:=((atrib and $e) shr 1) xor 7; x:=memoria[$8034+f]+((not(atrib) and $8) shl 5); if x<32 then x:=x+256; put_gfx_trans(0,0,nchar,16,3,2); actualiza_trozo(0,0,4,4,3,x,y+15,4,4,4); end; end; procedure eventos_rallyx; begin if event.arcade then begin if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80); if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40); if arcade_input.coin[1] then marcade.in1:=(marcade.in1 and $7f) else marcade.in1:=(marcade.in1 or $80); if arcade_input.start[1] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40); end; end; procedure rallyx_principal; var frame:single; f:byte; begin init_controls(false,false,false,true); frame:=main_z80.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin main_z80.run(frame); frame:=frame+main_z80.tframes-main_z80.contador; if f=239 then begin if hacer_int then main_z80.pedir_irq:=ASSERT_LINE; update_video_rallyx; end; end; actualiza_trozo(ADD_SPRITE,16+ADD_SPRITE,288,224,4,0,0,288,224,pant_temp); if sound_status.hay_sonido then namco_playsound; eventos_rallyx; video_sync; end; end; function rallyx_getbyte(direccion:word):byte; begin case direccion of $a000:rallyx_getbyte:=marcade.in0; $a080:rallyx_getbyte:=marcade.in1; $a100:rallyx_getbyte:=marcade.in2; else rallyx_getbyte:=memoria[direccion]; end; end; procedure rallyx_putbyte(direccion:word;valor:byte); begin if direccion<$4000 then exit; memoria[direccion]:=valor; case direccion of $8000..$83ff:gfx[2].buffer[direccion and $3ff]:=true; $8400..$87ff:gfx[0].buffer[direccion and $3ff]:=true; $8800..$8bff:gfx[2].buffer[direccion and $3ff]:=true; $8c00..$8fff:gfx[0].buffer[direccion and $3ff]:=true; $a100..$a11f:namco_sound.registros_namco[direccion and $1f]:=valor; $a130:scroll_x:=valor; $a140:scroll_y:=valor; $a180:begin if ((valor=0) and (last<>0)) then start_sample(0); last:=valor; end; $a181:begin hacer_int:=(valor<>0); if not(hacer_int) then main_z80.pedir_irq:=CLEAR_LINE; end; $a183:main_screen.flip_main_screen:=(valor and 1)<>0; end; end; procedure rallyx_outbyte(valor:byte;puerto:word); begin if (puerto and $ff)=0 then begin main_z80.im0:=valor; main_z80.pedir_irq:=CLEAR_LINE; end; end; procedure rallyx_playsound; begin samples_update; end; //Funciones genericas procedure Cargar_rallyxh; begin case main_vars.tipo_maquina of 29:llamadas_maquina.bucle_general:=jungler_principal; 50:llamadas_maquina.bucle_general:=rallyx_principal; 70:llamadas_maquina.bucle_general:=rallyx_principal; end; llamadas_maquina.iniciar:=iniciar_rallyxh; llamadas_maquina.cerrar:=cerrar_rallyxh; llamadas_maquina.reset:=reset_rallyxh; llamadas_maquina.fps_max:=60.606060606060; end; procedure cerrar_rallyxh; begin main_z80.free; if main_vars.tipo_maquina=29 then begin konamisnd_close; snd_z80.free; end else close_samples; close_audio; close_video; end; procedure reset_rallyxh; begin main_z80.reset; case main_vars.tipo_maquina of 29:begin marcade.in2:=$FF; snd_z80.reset; konamisnd_reset; end; 50,70:begin marcade.in2:=$cb; namco_sound_reset; reset_samples; end; end; reset_audio; last:=0; marcade.in0:=$FF; marcade.in1:=$FF; end; function iniciar_rallyxh:boolean; var colores:tpaleta; f,x,y:word; ctemp1:byte; memoria_temp:array[0..$3fff] of byte; const ps_rx:array[0..15] of dword=(8*8+0, 8*8+1, 8*8+2, 8*8+3, 16*8+0, 16*8+1, 16*8+2, 16*8+3, 24*8+0, 24*8+1, 24*8+2, 24*8+3, 0, 1, 2, 3); ps_x:array[0..15] of dword=(8*8, 8*8+1, 8*8+2, 8*8+3, 0, 1, 2, 3, 24*8+0, 24*8+1, 24*8+2, 24*8+3, 16*8+0, 16*8+1, 16*8+2, 16*8+3); ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 32*8, 33*8, 34*8, 35*8, 36*8, 37*8, 38*8, 39*8); pc_x:array[0..7] of dword=(8*8+0, 8*8+1, 8*8+2, 8*8+3, 0, 1, 2, 3); pc_y:array[0..7] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8); pd_x:array[0..3] of dword=(0*8, 1*8, 2*8, 3*8); pd_y:array[0..3] of dword=(0*32, 1*32, 2*32, 3*32); procedure cargar_chars(tipo:byte); begin init_gfx(0,8,8,256); if tipo=1 then begin gfx[0].trans[0]:=true; gfx_set_desc_data(2,0,16*8,4,0); end else begin gfx[0].trans[3]:=true; gfx_set_desc_data(2,0,16*8,0,4); end; convert_gfx(0,0,@memoria_temp[0],@pc_x[0],@pc_y[0],(tipo=1),false); end; procedure cargar_sprites(tipo:byte); begin init_gfx(1,16,16,64); gfx[1].trans[0]:=true; if tipo=1 then begin gfx_set_desc_data(2,0,64*8,4,0); convert_gfx(1,0,@memoria_temp[0],@ps_x[0],@ps_y[0],true,false); end else begin gfx_set_desc_data(2,0,64*8,0,4); convert_gfx(1,0,@memoria_temp[0],@ps_rx[0],@ps_y[0],false,false); end; end; procedure cargar_disparo; begin init_gfx(2,4,4,8); gfx[2].trans[3]:=true; gfx_set_desc_data(2,0,16*8,6,7); convert_gfx(2,0,@memoria_temp[0],@pd_x[0],@pd_y[0],false,false) end; begin iniciar_rallyxh:=false; iniciar_audio(false); //Pantallas: principal+char y sprites case main_vars.tipo_maquina of 29:begin x:=224; y:=288; screen_init(2,256,64); end; 50,70:begin x:=288; y:=224; screen_init(2,64,256); end; end; screen_init(1,256,288); screen_mod_scroll(1,256,256,255,256,256,255); screen_init(3,4,4,true); screen_init(4,512,512,false,true); screen_mod_sprites(4,512,512,$1ff,$1ff); screen_init(5,256,288,true); screen_mod_scroll(5,256,256,255,256,256,255); iniciar_video(x,y); //Main CPU main_z80:=cpu_z80.create(3072000,$100); case main_vars.tipo_maquina of 29:begin //jungler main_z80.change_ram_calls(jungler_getbyte,jungler_putbyte); //Audio CPU snd_z80:=cpu_z80.create(1789772,$100); snd_z80.change_ram_calls(konamisnd_getbyte,konamisnd_putbyte); //Sound Chip konamisnd_init(1,snd_z80.numero_cpu,1,snd_z80.clock,nil); //cargar roms if not(cargar_roms(@memoria[0],@jungler_rom[0],'jungler.zip',0)) then exit; //cargar sonido if not(cargar_roms(@mem_snd[0],@jungler_sound,'jungler.zip',1)) then exit; //convertir chars if not(cargar_roms(@memoria_temp[0],@jungler_char[0],'jungler.zip',0)) then exit; cargar_chars(1); //convertir sprites cargar_sprites(1); //Y ahora el'disparo' if not(cargar_roms(@memoria_temp[0],@jungler_dots,'jungler.zip',1)) then exit; cargar_disparo; //poner la paleta if not(cargar_roms(@memoria_temp[0],@jungler_pal[0],'jungler.zip',0)) then exit; end; 50:begin //rallyx main_z80.change_ram_calls(rallyx_getbyte,rallyx_putbyte); main_z80.change_io_calls(nil,rallyx_outbyte); //cargar roms if not(cargar_roms(@memoria[0],@rallyx_rom[0],'rallyx.zip',0)) then exit; //cargar sonido y samples if not(cargar_roms(@namco_sound.onda_namco[0],@rallyx_sound,'rallyx.zip',1)) then exit; namco_sound_init(3,false); if load_samples('rallyx.zip',@rallyx_samples,1) then begin main_z80.init_sound(rallyx_playsound); end; //convertir chars if not(cargar_roms(@memoria_temp[0],@rallyx_char,'rallyx.zip',1)) then exit; cargar_chars(0); //convertir sprites cargar_sprites(0); //Y ahora el'disparo' if not(cargar_roms(@memoria_temp[0],@rallyx_dots,'rallyx.zip',1)) then exit; cargar_disparo; //poner la paleta if not(cargar_roms(@memoria_temp[0],@rallyx_pal[0],'rallyx.zip',0)) then exit; end; 70:begin //new rally x main_z80.change_ram_calls(rallyx_getbyte,rallyx_putbyte); main_z80.change_io_calls(nil,rallyx_outbyte); //cargar roms y ordenarlas if not(cargar_roms(@memoria_temp[0],@nrallyx_rom[0],'nrallyx.zip',0)) then exit; copymemory(@memoria[$0],@memoria_temp[$0],$800); copymemory(@memoria[$1000],@memoria_temp[$800],$800); copymemory(@memoria[$800],@memoria_temp[$1000],$800); copymemory(@memoria[$1800],@memoria_temp[$1800],$800); copymemory(@memoria[$2000],@memoria_temp[$2000],$800); copymemory(@memoria[$3000],@memoria_temp[$2800],$800); copymemory(@memoria[$2800],@memoria_temp[$3000],$800); copymemory(@memoria[$3800],@memoria_temp[$3800],$800); //cargar sonido y samples if not(cargar_roms(@namco_sound.onda_namco[0],@nrallyx_sound,'nrallyx.zip',1)) then exit; namco_sound_init(3,false); if load_samples('rallyx.zip',@rallyx_samples,1) then begin main_z80.init_sound(rallyx_playsound); end; //convertir chars if not(cargar_roms(@memoria_temp[0],@nrallyx_char[0],'nrallyx.zip',0)) then exit; cargar_chars(0); //convertir sprites cargar_sprites(0); //Y ahora el'disparo' if not(cargar_roms(@memoria_temp[0],@nrallyx_dots,'nrallyx.zip',1)) then exit; cargar_disparo; //poner la paleta if not(cargar_roms(@memoria_temp[0],@nrallyx_pal[0],'nrallyx.zip',0)) then exit; end; end; for f:=0 to 31 do begin ctemp1:=memoria_temp[f]; colores[f].r:=$21*(ctemp1 and 1)+$47*((ctemp1 shr 1) and 1)+$97*((ctemp1 shr 2) and 1); colores[f].g:=$21*((ctemp1 shr 3) and 1)+$47*((ctemp1 shr 4) and 1)+$97*((ctemp1 shr 5) and 1); colores[f].b:=0+$50*((ctemp1 shr 6) and 1)+$ab*((ctemp1 shr 7) and 1); end; set_pal(colores,32); //color lookup for f:=0 to 255 do begin gfx[1].colores[f]:=memoria_temp[$20+f] and $f; gfx[0].colores[f]:=memoria_temp[$20+f] and $f; end; //final reset_rallyxh; iniciar_rallyxh:=true; end; end.
unit ormbr.criteria.resultset; interface uses Generics.Collections, // ormbr.criteria, dbebr.factory.interfaces, ormbr.bind; type ICriteriaSet = interface ['{0285A016-824C-41C7-9680-44127BB62AD0}'] function SetConnection(const AConnection: IDBConnection): ICriteriaSet; // function SQL(const ACriteria: ICriteria): ICriteriaSet; overload; function SQL(const ASQL: string): ICriteriaSet; overload; function AsResultSet: IDBResultSet; end; TCriteria = class(TInterfacedObject, ICriteriaSet) private FSQL: string; FConnection: IDBConnection; public class function New: ICriteriaSet; function SetConnection(const AConnection: IDBConnection): ICriteriaSet; // function SQL(const ACriteria: ICriteria): ICriteriaSet; overload; function SQL(const ASQL: string): ICriteriaSet; overload; function AsResultSet: IDBResultSet; end; ICriteriaObject<M: class, constructor> = interface ['{E1AA571D-E8BC-4A79-8B67-D7E77680F29C}'] function SetConnection(AConnection: IDBConnection): ICriteriaObject<M>; // function SQL(ACriteria: ICriteria): ICriteriaObject<M>; overload; function SQL(ASQL: string): ICriteriaObject<M>; overload; function AsList: TObjectList<M>; function AsValue: M; end; TCriteria<M: class, constructor> = class(TInterfacedObject, ICriteriaObject<M>) private FSQL: string; FConnection: IDBConnection; public class function New: ICriteriaObject<M>; function SetConnection(AConnection: IDBConnection): ICriteriaObject<M>; // function SQL(ACriteria: ICriteria): ICriteriaObject<M>; overload; function SQL(ASQL: string): ICriteriaObject<M>; overload; function AsList: TObjectList<M>; function AsValue: M; end; implementation { TCriteria<M> } function TCriteria.AsResultSet: IDBResultSet; begin Result := FConnection.ExecuteSQL(FSQL); end; class function TCriteria.New: ICriteriaSet; begin Result := Self.Create; end; function TCriteria.SetConnection(const AConnection: IDBConnection): ICriteriaSet; begin FConnection := AConnection; Result := Self; end; function TCriteria.SQL(const ASQL: string): ICriteriaSet; begin FSQL := ASQL; Result := Self; end; //function TCriteria.SQL(const ACriteria: ICriteria): ICriteriaSet; //begin // FSQL := ACriteria.AsString; // Result := Self; //end; function TCriteria<M>.AsList: TObjectList<M>; var LResultSet: IDBResultSet; LObject: M; begin LResultSet := FConnection.ExecuteSQL(FSQL); try if LResultSet.RecordCount = 0 then Exit(nil); Result := TObjectList<M>.Create; while LResultSet.NotEof do begin LObject := M.Create; TBind.Instance.SetFieldToProperty(LResultSet, LObject); Result.Add(LObject); end; finally LResultSet.Close; FConnection.Disconnect; end; end; function TCriteria<M>.AsValue: M; var LResultSet: IDBResultSet; begin LResultSet := FConnection.ExecuteSQL(FSQL); try if LResultSet.RecordCount = 0 then Exit(nil); Result := M.Create; TBind.Instance.SetFieldToProperty(LResultSet, Result); finally LResultSet.Close; FConnection.Disconnect; end; end; class function TCriteria<M>.New: ICriteriaObject<M>; begin Result := Self.Create; end; //function TCriteria<M>.SQL(ACriteria: ICriteria): ICriteriaObject<M>; //begin // FSQL := ACriteria.AsString; // Result := Self; //end; function TCriteria<M>.SetConnection(AConnection: IDBConnection): ICriteriaObject<M>; begin FConnection := AConnection; Result := Self; end; function TCriteria<M>.SQL(ASQL: string): ICriteriaObject<M>; begin FSQL := ASQL; Result := Self; end; end.
UNIT XMS; (**) INTERFACE (**) VAR XMSErrorCode : byte; { Error Code - Defined in XMS Spec } XMSAddr : Pointer; { Entry Point for HIMEM.SYS Driver } FUNCTION XMSDriverLoaded: Boolean; FUNCTION XMSTotalMemoryAvailable: Word; FUNCTION XMSLargestBlockAvailable: Word; FUNCTION XMSAllocateBlock(KBSize: Word): Word; FUNCTION XMSReleaseBlock(Handle: Word): Boolean; FUNCTION XMSMoveDataTo(SourceAddr: Pointer; NumBytes: LongInt; XMSHandle: Word; XMSOffset: LongInt): Boolean; FUNCTION XMSGetDataFrom(XMSHandle: Word; XMSOffset: LongInt; NumBytes: LongInt; LowMemAddr: Pointer): Boolean; Function lock(h : Word) : LongInt; (**) IMPLEMENTATION (**) TYPE XMSMoveStruct = record movelen : LongInt; { length of block to move in bytes } case integer of { Case 0 Variant for Low Memory to XMS } 0: (SHandle : Word; { source handle = 0 for conventional memory } SPtr : pointer; { source address } XMSHdl : Word; { XMS destination handle } XMSOffset : LongInt); { 32 bit XMS offset } { Case 1 Variant for XMS to Low Memory } 1: (XMSH : Word; { XMS source handle } XMSOfs : LongInt; { starting offset in XMS} DHandle : Word; { 0 when conventional memory destination } DPtr : pointer); { address in conventional memory } END; VAR moveparms : XMSMoveStruct; { structure for moving to and from XMS } {**************************************************************} { XMSDriverLoaded - Returns true IF Extended Memory Driver } { HIMEM.SYS Loaded } { - Sets Entry Point Address - XMSAddr } {**************************************************************} FUNCTION XMSDriverLoaded: Boolean; CONST himemseg: Word = 0; himemofs: Word = 0; BEGIN XMSErrorCode := 0; ASM mov ax,4300h { Check to see IF HIMEM.SYS installed } int 2fh cmp al,80h { Returns AL = 80H IF installed } jne @1 mov ax,4310h { Now get the entry point } int 2fh mov himemofs,bx mov himemseg,es @1: END; XMSDriverLoaded := (himemseg <> 0); XMSAddr := Ptr(himemseg,himemofs); END; {**************************************************************} { XMSTotalMemoryAvailable - Returns Total XMS Memory Available } {**************************************************************} FUNCTION XMSTotalMemoryAvailable: Word; BEGIN XMSErrorCode := 0; XMSTotalMemoryAvailable := 0; IF XMSAddr = nil THEN { Check IF HIMEM.SYS Loaded } IF NOT XMSDriverLoaded THEN exit; ASM mov ah,8 call XMSAddr or ax,ax jnz @1 mov XMSErrorCode,bl { Set Error Code } xor dx,dx @1: mov @Result,dx { DX = total free extended memory } END; END; {**************************************************************} { XMSLargestBlockAvailable - Returns Largest Contiguous } { XMS Block Available } {**************************************************************} FUNCTION XMSLargestBlockAvailable: Word; BEGIN XMSErrorCode := 0; XMSLargestBlockAvailable := 0; IF XMSAddr = nil THEN { Check IF HIMEM.SYS Loaded } IF NOT XMSDriverLoaded THEN exit; ASM mov ah,8 call XMSAddr or ax,ax jnz @1 mov XMSErrorCode,bl { On Error, Set Error Code } @1: mov @Result,ax { AX=largest free XMS block } END; END; {***************************************************************} { XMSAllocateBlock - Allocates Block of XMS Memory } { - Input - KBSize: No of Kilobytes requested } { - Returns Handle for memory IF successful } {***************************************************************} FUNCTION XMSAllocateBlock(KBSize: Word): Word; BEGIN XMSAllocateBlock := 0; XMSErrorCode := 0; IF XMSAddr = nil THEN { Check IF HIMEM.SYS Loaded } IF NOT XMSDriverLoaded THEN exit; ASM mov ah,9 mov dx,KBSize call XMSAddr or ax,ax jnz @1 mov XMSErrorCode,bl { On Error, Set Error Code } xor dx,dx @1: mov @Result,dx { DX = handle for extended memory } END; END; {**************************************************************} { XMSReleaseBlock - Releases Block of XMS Memory } { - Input: Handle identifying memory to be } { released } { - Returns true IF successful } {**************************************************************} FUNCTION XMSReleaseBlock(Handle: Word): Boolean; VAR OK : Word; BEGIN XMSErrorCode := 0; XMSReleaseBlock := false; IF XMSAddr = nil THEN { Check IF HIMEM.SYS Loaded } IF NOT XMSDriverLoaded THEN exit; ASM mov ah,0Ah mov dx,Handle call XMSAddr or ax,ax jnz @1 mov XMSErrorCode,bl { On Error, Set Error Code } @1: mov OK,ax END; XMSReleaseBlock := (OK <> 0); END; Function lock(h : Word) : LongInt; Assembler; Asm mov ah, $C mov dx, h call XMSAddr {lock xms block} cmp ax, 1 je @OK xor bx, bx xor dx, dx @OK: {set block to nil (0) if err} mov ax, bx end; {**************************************************************} { XMSMoveDataTo - Moves Block of Data from Conventional } { Memory to XMS Memory } { - Data Must have been previously allocated } { - Input - SourceAddr : address of data in } { conventional memory } { - NumBytes : number of bytes to move } { - XMSHandle : handle of XMS block } { - XMSOffset : 32 bit destination } { offset in XMS block } { - Returns true IF completed successfully } {**************************************************************} FUNCTION XMSMoveDataTo(SourceAddr: Pointer; NumBytes: LongInt; XMSHandle: Word; XMSOffset: LongInt): Boolean; VAR Status : Word; BEGIN XMSErrorCode := 0; XMSMoveDataTo := false; IF XMSAddr = nil THEN { Check IF HIMEM.SYS Loaded } IF NOT XMSDriverLoaded THEN exit; MoveParms.MoveLen := NumBytes; MoveParms.SHandle := 0; { Source Handle=0 For Conventional Memory} MoveParms.SPtr := SourceAddr; MoveParms.XMSHdl := XMSHandle; MoveParms.XMSOffset := XMSOffset; ASM mov ah,0Bh mov si,offset MoveParms call XMSAddr mov Status,ax { Completion Status } or ax,ax jnz @1 mov XMSErrorCode,bl { Save Error Code } @1: END; XMSMoveDataTo := (Status <> 0); END; {**************************************************************} { XMSGetDataFrom - Moves Block From XMS to Conventional Memory } { - Data Must have been previously allocated } { and moved to XMS } { - Input - XMSHandle : handle of source } { XMS block } { - XMSOffset : 32 bit source offset } { in XMS block } { - NumBytes : number of bytes to move } { - LowMemAddr : destination addr in } { conventional memory } { - Returns true IF completed successfully } {**************************************************************} FUNCTION XMSGetDataFrom(XMSHandle: Word; XMSOffset: LongInt; NumBytes: LongInt; LowMemAddr: Pointer): Boolean; VAR Status : Word; BEGIN XMSErrorCode := 0; XMSGetDataFrom := false; IF XMSAddr = nil THEN { Check IF HIMEM.SYS Loaded } IF NOT XMSDriverLoaded THEN exit; MoveParms.MoveLen := NumBytes; { Set-Up Structure to Pass } MoveParms.XMSh := XMSHandle; MoveParms.XMSOfs := XMSOffset; MoveParms.DHandle := 0; { Dest Handle=0 For Conventional Memory} MoveParms.DPtr := LowMemAddr; ASM mov ah,0Bh mov si,offset MoveParms call XMSAddr mov Status,ax { Completion Status } or ax,ax jnz @1 mov XMSErrorCode,bl { Set Error Code } @1: END; XMSGetDataFrom := (Status <> 0); END; BEGIN XMSAddr := nil; { Initialize XMSAddr } XMSErrorCode := 0; END.
unit frmMain1; interface uses Seedkey, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Edit, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FMX.Objects, FMX.Effects, FMX.Layouts; type TfrmMain = class(TForm) StyleBook: TStyleBook; lblHeader: TLabel; edtSeed: TEdit; lblSeed: TLabel; edtAlgo: TEdit; lblAlgo: TLabel; btnGenerate: TButton; edtKey: TEdit; lblKey: TLabel; chkBrute: TCheckBox; MemoResults: TMemo; btnHelp: TButton; ShadowEffect1: TShadowEffect; ShadowEffect2: TShadowEffect; ShadowEffect3: TShadowEffect; ShadowEffect4: TShadowEffect; ShadowEffect5: TShadowEffect; ShadowEffect6: TShadowEffect; GlowEffect1: TGlowEffect; ScaledLayout1: TScaledLayout; RectBottomBreak: TRectangle; RectTopBreak: TRectangle; RectContainer: TRectangle; procedure chkBruteChange(Sender: TObject); procedure btnGenerateClick(Sender: TObject); procedure btnHelpClick(Sender: TObject); private procedure BruteCalc; procedure SingleCalc; public { Public declarations } end; var frmMain: TfrmMain; implementation {$R *.fmx} procedure TfrmMain.BruteCalc; var cnt: integer; seed: integer; key: string; begin try seed := strtoint('$' + edtSeed.Text); except on e: exception do begin showmessage('Invalid SEED Hex Value'); edtSeed.Text := ''; exit; end; end; MemoResults.Lines.Clear; MemoResults.Lines.Add('Calculating all 256 combinations'); MemoResults.Lines.Add(''); for cnt := 0 to 255 do begin key := Seedkey.create_key(seed, cnt).ToHexString(4); if length(key) = 3 then key := '0' + key; if length(key) = 2 then key := '00' + key; if cnt <= 15 then MemoResults.Lines.Add('Algorithm 0' + cnt.ToHexString(1) + ' - Key = ' + key) else MemoResults.Lines.Add('Algorithm ' + cnt.ToHexString(1) + ' - Key = ' + key); end; end; procedure TfrmMain.SingleCalc; var cnt: integer; seed: integer; begin if length(Trim(edtAlgo.Text)) < 2 then begin showmessage('Invalid Algorithm HEX Value. Must be 2 characters long.'); exit; end; try seed := strtoint('$' + edtSeed.Text); except on e: exception do begin showmessage('Invalid SEED Hex Value'); edtSeed.Text := ''; exit; end; end; try cnt := strtoint('$' + edtAlgo.Text); except on e: exception do begin showmessage('Invalid Algorithm Hex Value'); edtAlgo.Text := ''; exit; end; end; MemoResults.Lines.Clear; MemoResults.Lines.Add('Calculating single algorithm'); MemoResults.Lines.Add(''); MemoResults.Lines.Add('Key = ' + Seedkey.create_key(seed, cnt).ToHexString); edtKey.Text := Seedkey.create_key(seed, cnt).ToHexString; end; procedure TfrmMain.btnGenerateClick(Sender: TObject); begin if length(Trim(edtSeed.Text)) < 4 then begin showmessage('Invalid Seed HEX Value. Must be 4 characters long.'); exit; end; case chkBrute.IsChecked of true: BruteCalc; false: SingleCalc; end; end; procedure TfrmMain.btnHelpClick(Sender: TObject); begin showmessage('Input your 4 digit SEED value. Then input your 2 digit ' + 'Algorithm number if you know it or use the brute force to calculate all 256 combinations. ' + 'Use the GENERATE button to do your calculations.'); end; procedure TfrmMain.chkBruteChange(Sender: TObject); begin edtAlgo.Text := ''; edtKey.Text := ''; case chkBrute.IsChecked of true: begin lblAlgo.Visible := false; lblKey.Visible := false; edtAlgo.Visible := false; edtKey.Visible := false; end; false: begin lblAlgo.Visible := true; lblKey.Visible := true; edtAlgo.Visible := true; edtKey.Visible := true; end; end; end; end.
unit UMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, JvComponentBase, JvTrayIcon, IniFiles, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, UBackupScript, Vcl.ComCtrls; type TfrmMain = class(TForm) TrayIcon: TJvTrayIcon; PopupMenu: TPopupMenu; menuConfiguracoes: TMenuItem; menuSeparador2: TMenuItem; menuSair: TMenuItem; pnlBotoes: TPanel; btnGravar: TSpeedButton; btnCancelar: TSpeedButton; btnAjuda: TSpeedButton; tmrBackupMongo: TTimer; tmrBackupPostGreSql: TTimer; pgcBackupMongoDB: TPageControl; tbsBackupBancoTestes: TTabSheet; tbsParametros: TTabSheet; GroupBox1: TGroupBox; edtPathBINMongoDB: TEdit; GroupBox2: TGroupBox; edtHostMongoDB: TEdit; GroupBox3: TGroupBox; edtPort: TEdit; GroupBox4: TGroupBox; edtPathDestination: TEdit; GroupBox5: TGroupBox; GroupBox6: TGroupBox; edtBancoDestino: TComboBox; btnCopiarBancoOrigemProducaoParaDestinoTestess: TBitBtn; GroupBox7: TGroupBox; edtUserName: TEdit; GroupBox8: TGroupBox; edtPassword: TEdit; edtBancoOrigem: TComboBox; btnAddBancoOrigem: TSpeedButton; btnAddBancoDestino: TSpeedButton; gpbAdicionarNovoBanco: TGroupBox; GroupBox10: TGroupBox; GroupBox11: TGroupBox; BitBtn1: TBitBtn; edtBancoDados: TEdit; edtNomeBancoDados: TEdit; Panel1: TPanel; btnAdicionarNovoBanco: TSpeedButton; btnCancelarAdicionarNovoBanco: TSpeedButton; tmrBackupMySql: TTimer; procedure menuSairClick(Sender: TObject); procedure menuConfiguracoesClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure tmrBackupMongoTimer(Sender: TObject); procedure btnGravarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure btnAjudaClick(Sender: TObject); procedure tmrBackupPostGreSqlTimer(Sender: TObject); procedure btnCopiarBancoOrigemProducaoParaDestinoTestessClick( Sender: TObject); procedure btnCancelarAdicionarNovoBancoClick(Sender: TObject); procedure btnAdicionarNovoBancoClick(Sender: TObject); procedure btnAddBancoOrigemClick(Sender: TObject); procedure btnAddBancoDestinoClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure tmrBackupMySqlTimer(Sender: TObject); private FIniName: String; FAppFolder: String; FBaseName: String; INI: TIniFile; Backup: TBackupScript; procedure CopiarBancoOrigemProducaoParaDestinoTestes(Origem, Destino: String); procedure AdicionarBancoALista(TipoLista: Integer; Banco: String); procedure CarregarListaBancos; { Private declarations } public { Public declarations } published property IniName: String read FIniName; property AppFolder: String read FAppFolder; property BaseName: String read FBaseName; end; var frmMain: TfrmMain; implementation {$R *.dfm} procedure TfrmMain.btnAddBancoDestinoClick(Sender: TObject); begin gpbAdicionarNovoBanco.Tag := 2; gpbAdicionarNovoBanco.Visible := True; edtBancoDados.SetFocus; end; procedure TfrmMain.btnAddBancoOrigemClick(Sender: TObject); begin gpbAdicionarNovoBanco.Tag := 1; gpbAdicionarNovoBanco.Visible := True; edtBancoDados.SetFocus; end; procedure TfrmMain.btnAdicionarNovoBancoClick(Sender: TObject); var sBanco: String; begin if (Trim(edtBancoDados.Text) <> '') and (Trim(edtNomeBancoDados.Text) <> '') then begin sBanco := Format('%s_%s', [edtBancoDados.Text, edtNomeBancoDados.Text]); case gpbAdicionarNovoBanco.Tag of 1: begin AdicionarBancoALista(1, sBanco); end; 2: begin AdicionarBancoALista(2, sBanco); end; end; gpbAdicionarNovoBanco.Tag := 0; gpbAdicionarNovoBanco.Visible := False; end else ShowMessage('Preencha todos os campos!'); end; procedure TfrmMain.AdicionarBancoALista(TipoLista: Integer; Banco: String); var FileName: String; begin try case TipoLista of 1: begin FileName := ChangeFileExt(Application.ExeName, '_BANCOS_PRODUCAO.TXT'); edtBancoOrigem.Items.Add(Banco); edtBancoOrigem.Items.SaveToFile(FileName); end; 2: begin FileName := ChangeFileExt(Application.ExeName, '_BANCOS_TESTE.TXT'); edtBancoDestino.Items.Add(Banco); edtBancoDestino.Items.SaveToFile(FileName); end; end; finally end; end; procedure TfrmMain.btnAjudaClick(Sender: TObject); begin ShowMessage('Ainda não implementado!'); end; procedure TfrmMain.btnCancelarAdicionarNovoBancoClick(Sender: TObject); begin gpbAdicionarNovoBanco.Visible := False; end; procedure TfrmMain.btnCancelarClick(Sender: TObject); begin Close; end; procedure TfrmMain.btnCopiarBancoOrigemProducaoParaDestinoTestessClick( Sender: TObject); begin CopiarBancoOrigemProducaoParaDestinoTestes(edtBancoOrigem.Text, edtBancoDestino.Text); end; procedure TfrmMain.CopiarBancoOrigemProducaoParaDestinoTestes(Origem, Destino: String); var iPos: Integer; begin iPos := Pos('_', Origem); if iPos > 0 then Origem := Copy(Origem, 1, iPos-1); iPos := Pos('_', Destino); if iPos > 0 then Destino := Copy(Destino, 1, iPos-1); if (Trim(Origem) <> '') and (Trim(Destino) <> '') then begin INI.WriteString('Config', 'BancoOrigem', edtBancoOrigem.Text); INI.WriteString('Config', 'BancoDestino', edtBancoDestino.Text); Backup.PathBINMongoDB := INI.ReadString('Config', 'PathBINMongoDB', 'C:\Program Files\MongoDB\Server\4.0\bin'); Backup.HostMongoDB := INI.ReadString('Config', 'HostMongoDB', '10.20.30.25'); Backup.Port := INI.ReadString('Config', 'Port', '27017'); Backup.Username := INI.ReadString('Config', 'Username', 'admin'); Backup.Password := INI.ReadString('Config', 'Password', 'NuYmR5Y34U'); Backup.PathDestination := INI.ReadString('Config', 'PathDestination', 'C:\MongoDB_Backup'); Backup.BaseName := ChangeFileExt(ExtractFileName(Application.ExeName), ''); Backup.CopiarBancoOrigemProducaoParaDestinoTestes(Origem, Destino); ShowMessage('Copia Realizada!'); end else ShowMessage('É necessário informar a origem e o destino!'); end; procedure TfrmMain.btnGravarClick(Sender: TObject); begin case pgcBackupMongoDB.ActivePageIndex of 0: begin btnCopiarBancoOrigemProducaoParaDestinoTestess.Click; end; 1: begin INI.WriteString('Config', 'PathBINMongoDB', edtPathBINMongoDB.Text); INI.WriteString('Config', 'HostMongoDB', edtHostMongoDB.Text); INI.WriteString('Config', 'Port', edtPort.Text); INI.WriteString('Config', 'Username', edtUserName.Text); INI.WriteString('Config', 'Password', edtPassword.Text); INI.WriteString('Config', 'PathDestination', edtPathDestination.Text); Visible := False; end; end; end; procedure TfrmMain.FormCreate(Sender: TObject); begin Backup := TBackupScript.Create; FAppFolder := ExtractFileDir(Application.ExeName); FIniName := ChangeFileExt(Application.ExeName, '.INI'); FBaseName := ChangeFileExt(Application.ExeName, ''); INI := TIniFile.Create(FIniName); edtPathBINMongoDB.Text := INI.ReadString('Config', 'PathBINMongoDB', 'C:\Program Files\MongoDB\Server\4.0\bin'); edtHostMongoDB.Text := INI.ReadString('Config', 'HostMongoDB', '10.20.30.25'); edtPort.Text := INI.ReadString('Config', 'Port', '27017'); edtUserName.Text := INI.ReadString('Config', 'Username', 'admin'); edtPassword.Text := INI.ReadString('Config', 'Password', 'NuYmR5Y34U'); edtPathDestination.Text := INI.ReadString('Config', 'PathDestination', 'C:\MongoDB_Backup'); edtBancoOrigem.Text := INI.ReadString('Config', 'BancoOrigem', ''); edtBancoDestino.Text := INI.ReadString('Config', 'BancoDestino', ''); tmrBackupMongo.Enabled := (ParamCount >= 1) and (LowerCase(ParamStr(1)) = '-backupmongo'); tmrBackupPostGreSql.Enabled := (ParamCount >= 1) and (LowerCase(ParamStr(1)) = '-backuppostgresql'); tmrBackupMySql.Enabled := (ParamCount >= 1) and (LowerCase(ParamStr(1)) = '-backupmysql'); if tmrBackupMongo.Enabled or tmrBackupPostGreSql.Enabled or tmrBackupMySql.Enabled then begin pgcBackupMongoDB.ActivePageIndex := 1; Application.ProcessMessages; end; end; procedure TfrmMain.FormShow(Sender: TObject); begin CarregarListaBancos; end; procedure TfrmMain.CarregarListaBancos; var FileNameProducao, FileNameTestes: String; begin FileNameProducao := ChangeFileExt(Application.ExeName, '_BANCOS_PRODUCAO.TXT'); FileNameTestes := ChangeFileExt(Application.ExeName, '_BANCOS_TESTE.TXT'); if FileExists(FileNameProducao) then edtBancoOrigem.Items.LoadFromFile(FileNameProducao); if FileExists(FileNameTestes) then edtBancoDestino.Items.LoadFromFile(FileNameTestes); end; procedure TfrmMain.menuConfiguracoesClick(Sender: TObject); begin Show; end; procedure TfrmMain.menuSairClick(Sender: TObject); begin Close; end; procedure TfrmMain.tmrBackupMongoTimer(Sender: TObject); begin tmrBackupMongo.Enabled := False; Caption := 'Backup MongoDB'; TrayIcon.Hint := Caption; if Visible then Hide; Backup.PathBINMongoDB := INI.ReadString('Config', 'PathBINMongoDB', 'C:\Program Files\MongoDB\Server\4.0\bin'); Backup.HostMongoDB := INI.ReadString('Config', 'HostMongoDB', '10.20.30.25'); Backup.Port := INI.ReadString('Config', 'Port', '27017'); Backup.Username := INI.ReadString('Config', 'Username', 'admin'); Backup.Password := INI.ReadString('Config', 'Password', 'NuYmR5Y34U'); Backup.PathDestination := INI.ReadString('Config', 'PathDestination', 'C:\MongoDB_Backup'); Backup.BaseName := ChangeFileExt(ExtractFileName(Application.ExeName), ''); Backup.RealizarBackupTodosDatabasesMongoDB; Application.Terminate; end; procedure TfrmMain.tmrBackupMySqlTimer(Sender: TObject); begin tmrBackupMySql.Enabled := False; Caption := 'Backup MySql'; TrayIcon.Hint := Caption; if Visible then Hide; Backup.PathBINMongoDB := INI.ReadString('Config', 'PathBINMongoDB', 'C:\Program Files\MySQL\MySQL Shell 1.0\bin'); Backup.HostMongoDB := INI.ReadString('Config', 'HostMongoDB', '10.20.30.18'); Backup.Port := INI.ReadString('Config', 'Port', '3306'); Backup.Username := INI.ReadString('Config', 'Username', 'root'); Backup.Password := INI.ReadString('Config', 'Password', '5fDXpd8U'); Backup.PathDestination := INI.ReadString('Config', 'PathDestination', 'F:\MySql_Web_Backup'); Backup.BaseName := ChangeFileExt(ExtractFileName(Application.ExeName), ''); Backup.RealizarBackupTodosDatabasesMySql; Application.Terminate; end; procedure TfrmMain.tmrBackupPostGreSqlTimer(Sender: TObject); begin tmrBackupPostGreSql.Enabled := False; Caption := 'Backup PostGreSql'; TrayIcon.Hint := Caption; if Visible then Hide; Backup.PathBINMongoDB := INI.ReadString('Config', 'PathBINMongoDB', 'C:\Program Files (x86)\pgAdmin 4\v4\runtime'); Backup.HostMongoDB := INI.ReadString('Config', 'HostMongoDB', '10.20.30.24'); Backup.Port := INI.ReadString('Config', 'Port', '5432'); Backup.Username := INI.ReadString('Config', 'Username', 'admin'); Backup.Password := INI.ReadString('Config', 'Password', 'NuYmR5Y34U'); Backup.PathDestination := INI.ReadString('Config', 'PathDestination', 'F:\PostGreSql_Web_Backup'); Backup.BaseName := ChangeFileExt(ExtractFileName(Application.ExeName), ''); Backup.RealizarBackupTodosDatabasesPostGreSql; Application.Terminate; end; end.
uses Math; type node = record i:integer; next:^node; end; pnode=^node; function insert(p:pnode; i:integer):pnode; var new_node:pnode; begin if p = nil then begin new(new_node); new_node^.i:=i; new_node^.next:=nil; exit(new_node); end; if i > p^.i then begin p^.next:=insert(p^.next, i); exit(p); end else begin new(new_node); new_node^.i:=i; new_node^.next:=p; exit(new_node); end; end; function prepend(var p:pnode; i:integer):pnode; var t:pnode; begin writeln('prepending ', i, '...'); if p = nil then begin new(t); t^.i:=i; t^.next:=nil; exit(t); end; new(t); t^.i:=i; t^.next:=p; exit(t); end; function append(var p:pnode; i:integer):pnode; var t:pnode; begin writeln('apending ', i, '...'); if p = nil then begin new(t); t^.i:=i; t^.next:=nil; exit(t); end; p^.next := append(p^.next, i); exit(p); end; procedure print_list(p:pnode); begin writeln('Printing...'); if p = nil then writeln('list is empty'); while p<>nil do begin writeln(p^.i); p:=p^.next; end; end; procedure pretty_print(p:pnode); begin if p=nil then begin writeln('nil'); exit; end; write(p^.i,'-->'); pretty_print(p^.next); end; procedure delete_first(var p:pnode); var t:pnode; begin if p = nil then exit else begin t:=p; p:=p^.next; dispose(t); end; end; procedure delete_last(var p:pnode); var t:pnode; begin if p = nil then exit; if p^.next = nil then begin t:=p; p:=p^.next; dispose(t); exit; end; if p^.next^.next = nil then begin t:=p^.next; p^.next:=nil; dispose(t); exit; end; while p^.next^.next <> nil do begin p:=p^.next; end; t:=p^.next; p^.next:=nil; dispose(t); end; procedure destroy_list(var p:pnode); var temp:pnode; begin if p = nil then exit; temp:=p; p:=p^.next; destroy_list(p); dispose(temp); end; function recursive_read(var p:pnode):pnode; var temp:pnode; i:integer; begin if not seekEof then begin readln(i); p:=append(p, i); recursive_read(p); exit(p); end else exit; end; procedure rotate_list(var p:pnode); var q,t:pnode; head,tail:pnode; begin if (p = nil) or (p^.next = nil) then exit; head:=p; q:=p; while q^.next^.next <> nil do begin q:=q^.next; end; tail:=q^.next; tail^.next:=head^.next; q^.next:=head; head^.next:=nil; p:=tail; end; function second_to_last(p:pnode):integer; var q:pnode; begin if (p = nil) or (p^.next = nil) then exit; q:=p; while q^.next^.next <> nil do begin q:=q^.next; end; exit(q^.i); end; procedure delete_nth(var p:pnode; n:integer); var q,prev:pnode; begin if p = nil then exit; prev:=nil; q:=p; n-=1; if n = 0 then begin if prev = nil then p:=nil else begin prev^.next:=q^.next; dispose(q); end; exit; end; writeln('head'); while (q^.next <> nil) or (n<>0) do begin n-=1; q:=q^.next; end; if n <> 0 then exit; prev^.next:=q^.next; dispose(q); end; function rec_delete_nth(p:pnode; n:integer):pnode; begin if p = nil then exit(nil); if n = 1 then exit(p^.next); p^.next := rec_delete_nth(p^.next, n-1); exit(p); end; function delete_other(p:pnode):pnode; function rec(p:pnode; n:integer):pnode; var t:pnode; begin if p = nil then exit(nil); if n mod 2 = 1 then begin t:=p; p:=rec(p^.next, n+1); dispose(t); exit(p); end else begin p^.next:= rec(p^.next, n+1); exit(p); end; end; begin exit(rec(p,1)); end; function reverse_list(var p:pnode):pnode; function rec(var q,p:pnode):pnode; var t:pnode; begin if p^.next = nil then begin p^.next:=q; exit(p); end; t:=p^.next; p^.next:=q; exit(rec(p, t)); end; var q,t,head,tail:pnode; begin if p = nil then exit; t:=nil; exit(rec(t, p)); end; procedure remove(var p:pnode); var q,last:pnode; begin q:=p; while q <> nil do begin if q^.i <> 0 then begin writeln('remember ',q^.i); last:=q; end; q:=q^.next; end; last^.next:=nil; end; procedure even_odd_split(var even,odd,p:pnode); begin if p = nil then exit; if p^.i mod 2 = 0 then even:=append(even, p^.i) else odd:=append(odd, p^.i); even_odd_split(even, odd, p^.next); end; function permutation(var a:array of integer):boolean; var visited:array of boolean; procedure visit(i:integer; var visited:array of boolean); begin visited[i]:=true; if not visited[a[i]] then begin visit(a[i], visited); end else exit; end; var i:integer; begin setLength(visited, length(a)); visit(0, visited); for i := 0 to high(visited) do begin if not visited[i] then exit(false); end; exit(true); end; function odd_delete(var p:pnode):pnode; begin if p = nil then exit(nil); if p^.i mod 2 = 0 then begin p^.next:=odd_delete(p^.next); exit(p); end else exit(odd_delete(p^.next)); end; function double_every_node(var p:pnode):pnode; var t,new_node:pnode; begin if p = nil then exit(nil); t:=p^.next; double_every_node(t); new(new_node); new_node^.i:=p^.i; new_node^.next:=t; p^.next:=new_node; exit(p); end; function delete_adjacent(var p:pnode):pnode; begin if p = nil then exit(nil); if p^.i = p^.next^.i then begin p^.next:=delete_adjacent(p^.next^.next); exit(p); end else begin p^.next:=delete_adjacent(p^.next); exit(p); end; end; procedure add(var p:pnode; d:integer); function converToInt(p:pnode):integer; var degree:integer=0; digit:integer=0; begin if p = nil then exit(0); while p <> nil do begin digit:= digit + p^.i*(10**degree); p:=p^.next; degree+=1; end; exit(digit); end; function converToPnode(i:integer):pnode; var new_node:pnode; digit:integer; begin if i = 0 then exit(nil); digit := i mod 10; new(new_node); new_node^.i:=digit; i:= i div 10; new_node^.next:=converToPnode(i); exit(new_node); end; var s:pnode; result:integer; begin result:=converToInt(p); writeln(result); p:=converToPnode(converToInt(p)+d); end; function largest(a:array of integer):integer; var lo,hi,mid:integer; begin lo:=-1; hi:=length(a); while hi - lo > 1 do begin mid := (hi+lo) div 2; if a[mid]<a[mid-1] then hi:=mid else lo:=mid; end; exit(a[mid-1]); end; function sort(p:pnode):pnode; function sink(q,p:pnode):pnode; var t:pnode; begin if p = nil then begin q^.next:=nil; exit(q); end; if q^.i > p^.i then begin p^.next:=sink(q,p^.next); exit(p); end else begin q^.next:=p; exit(q); end; end; begin if p = nil then exit(nil); if p^.next = nil then exit(p); exit(sink(p, sort(p^.next))); end; var p:pnode; even,odd:pnode; perm:array[0..4] of integer=(3,2,0,5,1); a:array[0..10] of integer=(2,4,7,10,13,15,17,14,13,5,1); begin p:=recursive_read(p); pretty_print(p); p:=reverse_list(p); pretty_print(p); end.
unit Itex; { ================================================================================ Interface unit for Imaging Technology ITEX library (c) J. Dempster, University of Strathclyde 31/7/01 Started 13/6/3 1/2/5 8/7/5 .... Higher performance frame transfer implemented using polling of frame grabber with 20 ms timed routine 9/12/13 .. Char/String converted to ANSIChar/ANSIString for Delphi XE3 compatibility Program drive now searched for ITEX folder (rather than C:) ================================================================================ } interface uses sysutils, Dialogs, classes, mmsystem ; Const VME_STD_MODE = 1 ; VME_EXT_MODE = 0 ; INQUIRE = -1 ; OFF = 0 ; ITEX_ON = 1 ; ITX_OFF = 0 ; ITX_ON = 1 ; ITX_SKIP = -1 ; ITX_SET = 0 ; ITX_GET = 1 ; ITX_BSWAP_OFF = 0 ; // disable byteswap ITX_BSWAP_ON = 1 ; // enable byteswap ITX_MBOARD = 0 ; // mother board ITX_DBOARD = 1 ; // daughter board ITX_TBOARD = 2 ; // translator board SEQ0 = 100 ; SEQ1 = 101 ; SEQ2 = 102 ; SEQ3 = 103 ; SEQ4 = 104 ; SEQ5 = 105 ; SEQ6 = 106 ; SEQ7 = 107 ; SEQ8 = 108 ; SEQ9 = 109 ; ITX_MAXSYSTEMS = 8 ; ICP_FREEZE = 0 ; ICP_SNAP = 2 ; ICP_GRAB = 3 ; ICP_FRAMEA0 = 0 ; ICP_FRAMEA1 = 1 ; ICP_FRAMEA = 2 ; ICP_FRAMEB0 = 3 ; ICP_FRAMEB1 = 4 ; ICP_FRAMEB = 5 ; ICP_FRAMERGB = 7 ; ITX_INQUIRE = -1 ; ITX_FREEZE_BITS = 0 ; ITX_SNAP_BITS = 2 ; ITX_GRAB_BITS = 3 ; ICP_PIX8 = 8 ; ICP_PIX16 = 16 ; ICP_PIX24 = 24; ICP_PIX32 = 32; // ITEX Error ants ITX_NO_ERROR = 0 ; // successfull operation */ ITX_GEN_ERROR = -1 ; // general/generic error */ ITX_FILE_ERROR = -2 ; // File I/O error */ ITX_FORMAT_ERROR = -3 ; // format error */ ITX_ALLOC_ERROR = -4 ; // memory allocation error */ ITX_ACCESS_ERROR = -5 ; // access error */ ITX_MATH_ERROR = -6 ; // math error */ ITX_TIMEOUT = -7 ; // time out error */ ITX_BADARG = -8 ; // bad argument error */ ITX_BADCNF = -9 ; // Bad configuration variable */ ITX_BAD_MODCNF = -10 ; // Bad MODCNF structure pointer */ ITX_BAD_ROICNF = -11 ; // Bad ROICNF structure pointer */ ITX_BAD_IFILE = -12 ; // Bad image file or filename */ ITX_BAD_SPEED = -13 ; // Bad Speed */ ITX_BAD_ID = -14 ; // Bad Module ID */ ITX_DEALLOC_ERROR = -15 ; // memory deallocation (free) error */ ITX_BAD_SYS = -16 ; // Bad system number (e.g. empty cnflist) */ ITX_BAD_INTRID = -17 ; // Invalid (disconnected) interrupt event id */ ITX_OS_ERROR = -18 ; // Host OS reported error */ ITX_RESOURCE_BUSY = -19 ; // Cannot obtain resource */ ITX_DIAG_ERROR = -20 ; // Itex Diagnostic System Error */ IPL_ERROR = -21 ; // Itex Image Processing Library Error*/ ITX_OBSOLETE = -22 ; // Function is obsolete */ ITX_WRONG_SERIALNO = -23 ; // application - wrong serial# */ ITX_WRONG_OEMNO = -24 ; // application - wrong OEM # */ ITX_PRODUCT_EXPIRED = -25 ; // application - product expired */ ITX_PRODUCT_MAXCNT = -26 ; // application - max execute count exceeded */ ITX_SWP_BAD_AUTHCODE = -27 ; // No valid authorization code found. */ ITX_SWP_AUTH_FAULT = -28 ; // General Software Protection Authorize fault */ ITX_INVALID_DRIVER_HANDLE = -29 ; // bad driver handle associated with ITex//s kernel mode driver (only for NT, OS/2, ...) */ ITX_OS_NO_SUPPORT = -30 ; // This operating system does not support this function */ ITX_STRETCH_TO_FIT = -1 ; // Used for decimation/zoom during display // error types */ WARNING = 1 ; // low incidence error */ SEVERE = 2 ; // high incidence error */ ABORT = 3 ; // abortive condition */ MAX_ERRLVL = 3 ; // maximum error level value */ // error message display methods */ ITX_NO_EMSG = 1 ; // don//t use error messages */ ITX_DISP_EMSG = 2 ; // display err messages as they occur */ ITX_QUE_EMSG = 3 ; // queue error messages */ ITX_FILE_EMSG = 4 ; // store errors msgs in a file */ MAX_EMSG_STATE = 4 ; // maximum error msg disp state value */ AMDIG_PSIZE8 = 0 ; AMDIG_PSIZE10 = 1 ; AMDIG_PSIZE12 = 2 ; AMDIG_PSIZE16 = 3 ; FrameEmptyFlag = 32000 ; type TCP_COLOR =( ICP_MONO, ICP_RED, ICP_GREEN, ICP_BLUE, ICP_RGB, ICP_MONO_WORD_LO, ICP_MONO_WORD_HI, ICP_YCRCB, ICP_RGB_PLANAR, ICP_YCRCBMONO, ICP_RGB_PACK24 ) ; TITEX = record ConfigFileName : ANSIstring ; PModHandle : Pointer ; AModHandle : Pointer ; GrabHandle : Pointer ; FrameWidth : Word ; FrameHeight : Word ; FrameID : SmallInt ; FrameNum : Integer ; NumFrames : Integer ; NumFramesTotal : SmallInt ; FrameBuf : Pointer ; NumBytesPerFrame : Integer ; NumBytesPerPixel : Integer ; CaptureInProgress : Boolean ; SystemInitialised : Boolean ; HostTransferPossible : Boolean ; TimerProcInUse : Boolean ; TimerID : Integer ; end ; PITEX = ^TITEX ; TITX_HW_PARAMS = ( ITX_HW_ART_REV, ITX_HW_ECO, ITX_HW_SERIAL_NUM, ITX_HW_DISP_KIND, ITX_BRD_KIND, //* value of type ITX_BRD_TYPE */ ITX_MAX_HW_PARAM ) ; TITX_BRD_TYPE = ( ITX_BRD_NULL, ITX_BRD_PA, ITX_BRD_IMS, ITX_BRD_IMA, ITX_BRD_IML, ITX_BRD_ICVL, ITX_BRD_ICP, ITX_BRD_IMP, ITX_BRD_CMP, ITX_BRD_IMV, ITX_BRD_ICA, ITX_NUM_BRD_TYPES ) ; Titx_init_sys = Function( SysNum : SmallInt ) : SmallInt ; stdcall ; Titx_remove_sys = Function( SysNum : SmallInt ) : SmallInt ; stdcall ; Titx_show_cnf = Function( PModule : Pointer ) : SmallInt ; stdcall ; Titx_init = Function( PModule : Pointer ) : SmallInt ; stdcall ; Titx_load_cnf = Function( itxpath : PANSIChar ) : SmallInt ; stdcall ; Titx_get_modcnf = Function( PModule : Pointer ; ModuleName : PANSIChar ; Location : SmallInt ) : Pointer ; stdcall ; Titx_get_brd_param = Function( PModule : Pointer ; ParamID : TITX_HW_PARAMS ; var Result : Cardinal ) : SmallInt ; stdcall ; Titx_get_acq_dim = Function( PModule : Pointer ; var FrameWidth : Word ; var FrameHeight : Word ) : SmallInt ; stdcall ; Titx_get_am = Function( AModule : Pointer ) : Pointer ; stdcall ; Titx_grab = Function( PModule : Pointer ; Frame : SmallInt ) : SmallInt ; stdcall ; Titx_grab_latest_seqnum = Function( GrabID : Pointer ; LockNum : Boolean ; var Frame : Pointer ; WaitNewer : Boolean ) : Integer ; stdcall ; Titx_imagefile_props = Function( FileName : PANSIChar ; Source : Array of Byte ; var dx : SmallInt ; var dy : SmallInt ; var ImageClass : SmallInt ; var Bits : SmallInt ; var Compress : SmallInt ) : SmallInt ; stdcall ; Titx_acqbits = Function( PModule : Pointer ; FrameID : SmallInt ; Mode : SmallInt ) : SmallInt ; stdcall ; Titx_snap = Function( PModule : Pointer ; Frame : SmallInt ) : SmallInt ; stdcall ; Titx_wait_acq = Function( PModule : Pointer ; Frame : SmallInt ) : SmallInt ; stdcall ; Titx_snap_async = Function( PModule : Pointer ; Frame : SmallInt ) : SmallInt ; stdcall ; Titx_read_area = Function( PModule : Pointer ; Frame : SmallInt ; x : SmallInt ; y : SmallInt ; dx : SmallInt ; dy : SmallInt ; Buf : PByteArray ) : SmallInt ; stdcall ; Titx_host_grab = Function( PModule : Pointer ; Dest : PByteArray ; NumFrames : Integer ) : Pointer ; stdcall ; Titx_host_grab_area = Function( PModule : Pointer ; x : SmallInt ; y : SmallInt ; dx : SmallInt ; dy : SmallInt ; Dest : PByteArray ; NumFrames : Integer ) : Pointer ; stdcall ; Titx_host_grab_lock = Function( GrabID : Pointer ; SeqNum : Integer ) : SmallInt ; stdcall ; Titx_host_grab_release = Function( GrabID : Pointer ; SeqNum : Integer ) : SmallInt ; stdcall ; Titx_host_grab_stop = Function( GrabID : Pointer ) : SmallInt ; stdcall ; Titx_host_snap = Function( PModule : Pointer ; Dest : PByteArray ) : SmallInt ; stdcall ; Titx_host_snap_area = Function( PModule : Pointer ; x : SmallInt ; y : SmallInt ; dx : SmallInt ; dy : SmallInt ; Dest : Array of Byte ) : SmallInt ; stdcall ; Titx_host_trig_read = Function( PModule : Pointer ; Dest : Array of Byte ) : SmallInt ; stdcall ; Titx_host_trig_snap = Function( PModule : Pointer ; Dest : Array of Byte ) : SmallInt ; stdcall ; Titx_host_wait_trig = Function( PModule : Pointer ; Dest : Array of Byte ; WaitTime : Integer ) : SmallInt ; stdcall ; Titx_host_start_acq = Function( PModule : Pointer ; x : SmallInt ; y : SmallInt ; dx : SmallInt ; dy : SmallInt ; Dest : Array of Byte ; RingNumFrames : Integer ; TotalNumFrames : Integer ) : Integer ; stdcall ; Titx_host_start_dualtap_acq = Function( PModule : Pointer ; x : SmallInt ; y : SmallInt ; dx : SmallInt ; dy : SmallInt ; Dest : Array of Byte ; RingNumFrames : Integer ; TotalNumFrames : Integer ) : Integer ; stdcall ; Titx_host_frame_seqnum = Function( GrabID : Pointer ; RingFrameNumber : Integer ) : Integer ; stdcall ; Titx_host_wait_acq = Function( GrabID : Pointer ; SeqenceNumber : Integer ; TimeOutMiliSec : Integer ; LockFrame : Integer ; Buff : Array of Integer ) : Integer ; stdcall ; Titx_read_performance = Function( PModule : Pointer ) : Single ; stdcall ; Titx_select_cam_port = Function( PModule : Pointer ; Port : SmallInt ) : SmallInt ; stdcall ; Titx_set_port_camera = Function( PModule : Pointer ; CameraName : PANSIChar ; Port : SmallInt ) : SmallInt ; stdcall ; Titx_strcpy = Function( OutStr : PANSIChar ; InStr : PANSIChar ) : PANSIChar ; stdcall ; Titx_get_modname = Function( PModule : Pointer ) : Integer ; stdcall ; Titx_create_host_frame = Function( PModule : Pointer ; FrameID : SmallInt ; NumFrames : Integer ) : SmallInt ; stdcall ; Titx_delete_all_hframes = Function( PModule : Pointer ) : SmallInt ; stdcall ; Titx_host_frame_lock = Function( PModule : Pointer ; FrameID : SmallInt ; FrameNum : Integer ) : Pointer ; stdcall ; Titx_host_frame_unlock = Procedure( PModule : Pointer ; FrameID : SmallInt ; FramNum : Integer ; FramePointer : Pointer ) ; stdcall ; Ticp_create_frame = Function( PModule : Pointer ; dx : SmallInt ; dy : SmallInt ; Depth : SmallInt ; Color : SmallInt ) : SmallInt ; stdcall ; Ticp_delete_frame = Function( PModule : Pointer ; FrameID : SmallInt ) : SmallInt ; stdcall ; Ticp_delete_all_frames = Function( PModule : Pointer ) : SmallInt ; stdcall ; Ticp_start_ping_pong = Function( PModule : Pointer ; Frame1 : SmallInt ; Frame2 : SmallInt ; RecordMode : SmallInt ) : SmallInt ; stdcall ; Ticp_stop_ping_pong = Function( PModule : Pointer ) : SmallInt ; stdcall ; Ticp_get_active_ubm_frame = Function( PModule : Pointer ; Context : Integer ; var CurrentFrame : SmallInt ) : SmallInt ; stdcall ; Ticp_acq_addr_status = Function( PModule : Pointer ) : SmallInt ; stdcall ; Ticp_acq_pending = Function( PModule : Pointer ) : SmallInt ; stdcall ; Ticp_clr_frame = Function( PModule : Pointer ; FrameID : SmallInt ; Value : Integer ) : SmallInt ; stdcall ; Ticp_clr_area = Function( PModule : Pointer ; FrameID : SmallInt ; x : SmallInt ; y : SmallInt ; dx : SmallInt ; dy : SmallInt ; Value : Integer ) : SmallInt ; stdcall ; Ticp_rpix = Function( PModule : Pointer ; FrameID : SmallInt ; x : SmallInt ; y : SmallInt ) : Integer ; stdcall ; Tamdig_hact = Function( PModule : Pointer ; Size : SmallInt ) : SmallInt ; stdcall ; Tamdig_vact = Function( PModule : Pointer ; Size : SmallInt ) : SmallInt ; stdcall ; Tamdig_psize = Function( PModule : Pointer ; Size : SmallInt ) : SmallInt ; stdcall ; function ITEX_StartCapture( var ITEX : TITEX ; FrameLeft : Integer ; FrameRight : Integer ; FrameTop : Integer ; FrameBottom : Integer ; FrameBuf : Pointer ; NumFrames : Integer ; var FrameWidth : Integer ; var FrameHeight : Integer ) : Boolean ; procedure ITEX_TimerProc( uID,uMsg : SmallInt ; ITEX : PITEX ; dw1,dw2 : LongInt ) ; stdcall ; function ITEX_StopCapture( var ITEX : TITEX ) : Boolean ; function ITEX_OpenFrameGrabber( var ITEX : TITEX ; CameraInfo : TStringList ; NumBytesPerPixel : Integer ; PCVision : Boolean ) : Boolean ; procedure ITEX_LoadLibrary ; function ITEX_GetDLLAddress( Handle : Integer ; const ProcName : string ) : Pointer ; procedure ITEX_CloseFrameGrabber( var ITEX : TITEX ) ; function ITEX_GetLatestFrameNumber( var ITEX : TITEX ) : Integer ; var ITX_init_sys : Titx_init_sys ; ITX_remove_sys : Titx_remove_sys ; ITX_show_cnf : Titx_show_cnf ; ITX_init : Titx_init ; ITX_load_cnf : Titx_load_cnf ; ITX_get_modcnf : Titx_get_modcnf ; ITX_get_brd_param : Titx_get_brd_param ; ITX_get_acq_dim : Titx_get_acq_dim ; ITX_get_am : Titx_get_am ; ITX_grab : Titx_grab ; ITX_read_area : TITX_read_area ; ITX_grab_latest_seqnum : Titx_grab_latest_seqnum ; ITX_imagefile_props : Titx_imagefile_props ; ITX_snap : Titx_snap ; ITX_snap_async : Titx_snap_async ; ITX_wait_acq : TITX_wait_acq ; ITX_acqbits : Titx_acqbits ; ITX_host_grab : Titx_host_grab ; ITX_host_grab_area : Titx_host_grab_area ; ITX_host_grab_lock : Titx_host_grab_lock ; ITX_host_grab_release : Titx_host_grab_release ; ITX_host_grab_stop : Titx_host_grab_stop ; ITX_host_snap : Titx_host_snap ; ITX_host_snap_area : Titx_host_snap_area ; ITX_host_trig_read : Titx_host_trig_read ; ITX_host_trig_snap : Titx_host_trig_snap ; ITX_host_wait_trig : Titx_host_wait_trig ; ITX_host_start_acq : Titx_host_start_acq ; ITX_host_start_dualtap_acq :Titx_host_start_dualtap_acq ; ITX_host_frame_seqnum : Titx_host_frame_seqnum ; ITX_host_wait_acq : Titx_host_wait_acq ; ITX_read_performance : Titx_read_performance ; ITX_select_cam_port : Titx_select_cam_port ; ITX_set_port_camera : Titx_set_port_camera ; ITX_strcpy : Titx_strcpy ; ITX_get_modname : Titx_get_modname ; ITX_create_host_frame : Titx_create_host_frame ; ITX_delete_all_hframes : Titx_delete_all_hframes ; ITX_host_frame_lock : Titx_host_frame_lock ; ITX_host_frame_unlock : Titx_host_frame_unlock ; ICP_create_frame : TICP_create_frame ; icp_delete_frame : Ticp_delete_frame ; icp_delete_all_frames : Ticp_delete_all_frames ; ICP_start_ping_pong : Ticp_start_ping_pong ; ICP_stop_ping_pong : Ticp_stop_ping_pong ; ICP_get_active_ubm_frame : Ticp_get_active_ubm_frame ; icp_acq_addr_status : Ticp_acq_addr_status ; icp_clr_frame : Ticp_clr_frame ; icp_clr_area : Ticp_clr_area ; icp_acq_pending : Ticp_acq_pending ; icp_rpix : Ticp_rpix ; amdig_hact : Tamdig_hact ; amdig_vact : Tamdig_vact ; amdig_psize : Tamdig_psize ; LibraryLoaded : Boolean ; implementation uses WinTypes ; procedure ITEX_LoadLibrary ; { --------------------------------- Load itex.DLL library into memory ---------------------------------} var LibFileName : string ; Drive : string ; LibraryHnd : THandle ; begin // Load ITEX interface DLL library LibFileName := '' ; Drive := ExtractFileDrive(ParamStr(0)) ; if FileExists(Drive + '\itex41\lib\itxco10.dll') then LibFileName := Drive + '\itex41\lib\itxco10.dll' else if FileExists(Drive + '\itex33\lib\itxco10.dll') then LibFileName := Drive + '\itex33\lib\itxco10.dll' ; // else begin // FileName := ExtractFilePath(ParamStr(0)) + '\itxco10.dll' ; // if FileExists(FileName) then LibFileName := FileName ; // end ; LibraryHnd := LoadLibrary(PChar(LibFileName)); { Get addresses of procedures in library } if LibraryHnd > 0 then begin @ITX_init_sys :=ITEX_GetDLLAddress(LibraryHnd,'itx_init_sys') ; @ITX_remove_sys :=ITEX_GetDLLAddress(LibraryHnd,'itx_remove_sys') ; @ITX_show_cnf :=ITEX_GetDLLAddress(LibraryHnd,'itx_show_cnf') ; @ITX_init :=ITEX_GetDLLAddress(LibraryHnd,'itx_init') ; @ITX_load_cnf :=ITEX_GetDLLAddress(LibraryHnd,'itx_load_cnf') ; @ITX_get_modcnf :=ITEX_GetDLLAddress(LibraryHnd,'itx_get_modcnf') ; @ITX_get_brd_param :=ITEX_GetDLLAddress(LibraryHnd,'itx_get_brd_param') ; @ITX_get_acq_dim :=ITEX_GetDLLAddress(LibraryHnd,'itx_get_acq_dim') ; @ITX_get_am :=ITEX_GetDLLAddress(LibraryHnd,'itx_get_am') ; @ITX_grab :=ITEX_GetDLLAddress(LibraryHnd,'itx_grab') ; @ITX_grab_latest_seqnum :=ITEX_GetDLLAddress(LibraryHnd,'itx_grab_latest_seqnum') ; @ITX_imagefile_props :=ITEX_GetDLLAddress(LibraryHnd,'itx_imagefile_props') ; @ITX_snap :=ITEX_GetDLLAddress(LibraryHnd,'itx_snap') ; @ITX_wait_acq :=ITEX_GetDLLAddress(LibraryHnd,'itx_wait_acq') ; @ITX_snap_async :=ITEX_GetDLLAddress(LibraryHnd,'itx_snap_async') ; @ITX_acqbits :=ITEX_GetDLLAddress(LibraryHnd,'itx_acqbits') ; @ITX_read_area :=ITEX_GetDLLAddress(LibraryHnd,'itx_read_area') ; @ITX_host_grab :=ITEX_GetDLLAddress(LibraryHnd,'itx_host_grab') ; @ITX_host_grab_area :=ITEX_GetDLLAddress(LibraryHnd,'itx_host_grab_area') ; @ITX_host_grab_lock :=ITEX_GetDLLAddress(LibraryHnd,'itx_host_grab_lock') ; @ITX_host_grab_release :=ITEX_GetDLLAddress(LibraryHnd,'itx_host_grab_release') ; @ITX_host_grab_stop :=ITEX_GetDLLAddress(LibraryHnd,'itx_host_grab_stop') ; @ITX_host_snap :=ITEX_GetDLLAddress(LibraryHnd,'itx_host_snap') ; @ITX_host_snap_area :=ITEX_GetDLLAddress(LibraryHnd,'itx_host_snap_area') ; @ITX_host_trig_read :=ITEX_GetDLLAddress(LibraryHnd,'itx_host_trig_read') ; @ITX_host_trig_snap :=ITEX_GetDLLAddress(LibraryHnd,'itx_host_trig_snap') ; @ITX_host_wait_trig :=ITEX_GetDLLAddress(LibraryHnd,'itx_host_wait_trig') ; @ITX_host_start_acq :=ITEX_GetDLLAddress(LibraryHnd,'itx_host_start_acq') ; @ITX_host_frame_seqnum :=ITEX_GetDLLAddress(LibraryHnd,'itx_host_frame_seqnum') ; @ITX_host_wait_acq :=ITEX_GetDLLAddress(LibraryHnd,'itx_host_wait_acq') ; @ITX_read_performance :=ITEX_GetDLLAddress(LibraryHnd,'itx_read_performance') ; @ITX_select_cam_port :=ITEX_GetDLLAddress(LibraryHnd,'itx_select_cam_port') ; @ITX_set_port_camera :=ITEX_GetDLLAddress(LibraryHnd,'itx_set_port_camera') ; @ITX_strcpy :=ITEX_GetDLLAddress(LibraryHnd,'itx_strcpy') ; @ITX_get_modname :=ITEX_GetDLLAddress(LibraryHnd,'itx_get_modname') ; @ITX_create_host_frame :=ITEX_GetDLLAddress(LibraryHnd,'itx_create_host_frame') ; @ITX_delete_all_hframes :=ITEX_GetDLLAddress(LibraryHnd,'itx_delete_all_hframes') ; @ITX_host_frame_lock :=ITEX_GetDLLAddress(LibraryHnd,'itx_host_frame_lock') ; @ITX_host_frame_unlock :=ITEX_GetDLLAddress(LibraryHnd,'itx_host_frame_unlock') ; @ICP_create_frame :=ITEX_GetDLLAddress(LibraryHnd,'icp_create_frame') ; @icp_delete_frame :=ITEX_GetDLLAddress(LibraryHnd,'icp_delete_frame') ; @icp_delete_all_frames :=ITEX_GetDLLAddress(LibraryHnd,'icp_delete_all_frames') ; @ICP_start_ping_pong :=ITEX_GetDLLAddress(LibraryHnd,'icp_start_ping_pong') ; @ICP_stop_ping_pong :=ITEX_GetDLLAddress(LibraryHnd,'icp_stop_ping_pong') ; @ICP_get_active_ubm_frame :=ITEX_GetDLLAddress(LibraryHnd,'icp_get_active_ubm_frame') ; @icp_acq_addr_status :=ITEX_GetDLLAddress(LibraryHnd,'icp_acq_addr_status') ; @icp_clr_frame :=ITEX_GetDLLAddress(LibraryHnd,'icp_clr_frame') ; @icp_clr_area :=ITEX_GetDLLAddress(LibraryHnd,'icp_clr_area') ; @icp_rpix :=ITEX_GetDLLAddress(LibraryHnd,'icp_rpix') ; @icp_acq_pending :=ITEX_GetDLLAddress(LibraryHnd,'icp_acq_pending') ; @amdig_hact := ITEX_GetDLLAddress(LibraryHnd,'amdig_hact') ; @amdig_vact := ITEX_GetDLLAddress(LibraryHnd,'amdig_vact') ; @amdig_psize := ITEX_GetDLLAddress(LibraryHnd,'amdig_psize') ; LibraryLoaded := True ; end else begin ShowMessage( 'ITXC10.DLL not found in ' + LibFileName + ' !' ) ; LibraryLoaded := False ; end ; end ; function ITEX_GetDLLAddress( Handle : Integer ; const ProcName : string ) : Pointer ; // --------------------------------------------- // Get address of procedure within ITEX library // --------------------------------------------- begin Result := GetProcAddress(Handle,PChar(ProcName)) ; if Result = Nil then ShowMessage('itxco10.DLL: ' + ProcName + ' not found') ; end ; function ITEX_OpenFrameGrabber( var ITEX : TITEX ; CameraInfo : TStringList ; // Camera information (OUT) NumBytesPerPixel : Integer ; // Bytes per pixel PCVision : Boolean // PCVISION board in use ) : Boolean ; // ----------------------------------- // Initialise frame grabber sub-system // ----------------------------------- var dwValue : Cardinal ; begin Result := False ; // Load ITEX interface library (if necessary) if not LibraryLoaded then ITEX_LoadLibrary ; if not LibraryLoaded then Exit ; // Load camera configuration from file if itx_load_cnf(PANSIChar(ITEX.ConfigFileName)) <> ITX_NO_ERROR then begin ShowMessage('Could not load config file ' + ITEX.ConfigFileName); Exit ; end ; // Initialise system if itx_init_sys(0) <> ITX_NO_ERROR then begin ShowMessage('System Initialisation failed!') ; ITEX.SystemInitialised := False ; Exit ; end else ITEX.SystemInitialised := True ; // Get pointer to frame grabber module if PCVision then ITEX.PModHandle := itx_get_modcnf( Nil, Nil, SEQ0 ) else ITEX.PModHandle := itx_get_modcnf( Nil, 'ICP', SEQ0 ) ; if ITEX.PModHandle = Nil then begin ShowMessage('Frame grabber module not found!'); Exit ; end ; // Get pointer to acquisition module ITEX.AModHandle := itx_get_am( ITEX.PModHandle ) ; if ITEX.AModHandle = Nil then begin ShowMessage('Acquisition module not found!'); Exit ; end ; // Get camera frame dimensions if itx_get_acq_dim( ITEX.PModHandle, ITEX.FrameWidth, ITEX.FrameHeight ) <> ITX_NO_ERROR then ShowMessage('Error reading camera frame dimensions '); // Create a camera frame ITEX.NumBytesPerPixel := NumBytesPerPixel ; if itx_get_brd_param( ITEX.PModHandle, ITX_BRD_KIND, dwValue ) = ITX_NO_ERROR then CameraInfo.Add(format('Frame grabber board type = %d',[dwValue])) ; if itx_get_brd_param( ITEX.PModHandle, ITX_HW_SERIAL_NUM, dwValue ) = ITX_NO_ERROR then CameraInfo.Add(format('Frame grabber Serial #%d',[dwValue])) ; // Enable DMA-based transfer if available if PCVision then ITEX.HostTransferPossible := True else ITEX.HostTransferPossible := False ; // Clear frame polling timer fields ITEX.TimerID := -1 ; ITEX.TimerProcInUse := False ; CameraInfo.Add( format('Frame size w=%d, h=%d',[ITEX.FrameWidth,ITEX.FrameHeight])) ; Result := True ; end ; procedure ITEX_CloseFrameGrabber( var ITEX : TITEX ) ; // ----------------------------------- // Shut down frame grabber sub-system // ----------------------------------- begin if ITEX.SystemInitialised then begin // Delete any existing frames icp_delete_all_frames(ITEX.PModHandle) ; itx_remove_sys(0) ; ITEX.SystemInitialised := False ; ITEX.PModHandle := Nil ; ITEX.AModHandle := Nil ; end ; // Stop timer (if still running) if ITEX.TimerID >= 0 then begin timeKillEvent( ITEX.TimerID ) ; ITEX.TimerID := -1 ; end ; end ; function ITEX_StartCapture( var ITEX : TITEX ; FrameLeft : Integer ; // Left edge of capture region FrameRight : Integer ; // Right edge of capture region FrameTop : Integer ; // Top edge of capture region FrameBottom : Integer ; // Bottom edge of capture region FrameBuf : Pointer ; // Pointer to frame storage buffer NumFrames : Integer ; // No. frames in storage buffer var FrameWidth : Integer ; // Frame width (OUT) var FrameHeight : Integer // Frame height (OUT) ) : Boolean ; // ------------------------------------------ // Start capture of images into frame buffer // ------------------------------------------ const TimerTickInterval = 20 ; // Timer tick resolution (ms) begin // Ensure frame limits are valid for use with frame grabber hardware if (FrameLeft mod 8) <> 0 then ShowMessage('ITEX_StartCapture : FrameLeft must be multiple of 8!') ; FrameWidth := FrameRight - FrameLeft + 1 ; FrameWidth := (FrameWidth div 4)*4 ; FrameHeight := FrameBottom - FrameTop + 1 ; ITEX.FrameWidth := FrameWidth ; ITEX.FrameHeight := FrameHeight ; // Delete any existing frames icp_delete_all_frames(ITEX.PModHandle) ; // Create a camera frame if (ITEX.NumBytesPerPixel < 2) then begin // 2 byte pixels ITEX.FrameID := ICP_Create_Frame( ITEX.PModHandle, ITEX.FrameWidth, ITEX.FrameHeight, 8, 0 ) ; end else begin // Single byte pixels ITEX.FrameID := ICP_Create_Frame( ITEX.PModHandle, ITEX.FrameWidth, ITEX.FrameHeight, 16, 0 ) ; end ; // Clear camera frame icp_clr_frame( ITEX.PModHandle, ITEX.FrameID, FrameEmptyFlag ) ; { if (FrameWidth mod 16) <> 0 then MessageDlg( 'ITEX_StartCapture : FrameWidth must be multiple of 16!', mtInformation,[mbOk], 0) ;} // Set frame width and height within acquisition module amdig_hact( ITEX.AModHandle, FrameWidth-1 ) ; amdig_vact( ITEX.AModHandle, FrameHeight-1 ) ; amdig_psize( ITEX.AModHandle, AMDIG_PSIZE12 ) ; Result := False ; if FrameBuf = Nil then begin ShowMessage('ITEX_StartCapture failed! (Frame buffer not allocated)') ; exit ; end ; if ITEX.PModHandle = Nil then begin ShowMessage('ITEX_StartCapture failed! (No PModule)') ; exit ; end ; if ITEX.HostTransferPossible then begin // If DMA transfer to host buffer possible - use it // ------------------------------------------------ if ITEX.GrabHandle = Nil then begin ITEX.GrabHandle := itx_host_grab_area( ITEX.PModHandle, SmallInt(FrameLeft), SmallInt(FrameTop), SmallInt(FrameRight - FrameLeft + 1), SmallInt(FrameBottom - FrameTop + 1), FrameBuf, NumFrames ) ; if ITEX.GrabHandle = Nil then ShowMessage('ITEX_StartCapture failed! (itx_host_grab failed)') else Result := True ; end ; end else begin // DMA transfer not available - // Monitor frame buffer at 20ms intervals // and read frame-by-frame from ITEX_TimerProc // -------------------------------------------------------------- ITEX.NumFrames := NumFrames ; ITEX.FrameNum := 0 ; ITEX.NumBytesPerFrame := FrameWidth*FrameHeight*ITEX.NumBytesPerPixel ; ITEX.FrameBuf := FrameBuf ; // Clear buffer in frame grabber memory icp_clr_frame( ITEX.PModHandle, ITEX.FrameID, FrameEmptyFlag ) ; // Disable timer if it is running if ITEX.TimerID >= 0 then begin timeKillEvent( ITEX.TimerID ) ; ITEX.TimerID := -1 ; end ; // Start frame acquisition monitor procedure ITEX.TimerProcInUse := False ; ITEX.TimerID := TimeSetEvent( TimerTickInterval, TimerTickInterval, @ITEX_TimerProc, Cardinal(@ITEX), TIME_PERIODIC ) ; // Start continuous frame capture into buffer on frame grabber card itx_acqbits( ITEX.PModHandle, ITEX.FrameID, ITX_GRAB_BITS ) ; Result := True ; end ; ITEX.CaptureInProgress := True ; end ; function ITEX_StopCapture( var ITEX : TITEX ) : Boolean ; // ------------------------------------------ // Stop capture of images into frame buffer // ------------------------------------------ begin if ITEX.HostTransferPossible then begin // Disable continuous frame capture & transfer if ITEX.GrabHandle <> Nil then begin itx_host_grab_stop( ITEX.GrabHandle ) ; ITEX.GrabHandle := Nil ; end ; end else begin // Stop continuous frame capture within card itx_acqbits( ITEX.PModHandle, ITEX.FrameID, ITX_FREEZE_BITS ) ; // Disable timer if it is running if ITEX.TimerID >= 0 then begin timeKillEvent( ITEX.TimerID ) ; ITEX.TimerID := -1 ; end ; end ; ITEX.CaptureInProgress := False ; Result := ITEX.CaptureInProgress ; end ; function ITEX_GetLatestFrameNumber( var ITEX : TITEX ) : Integer ; // ------------------------------------------ // Stop capture of images into frame buffer // ------------------------------------------ var FramePointer : Pointer ; begin if ITEX.GrabHandle <> Nil then Result := itx_grab_latest_seqnum( ITEX.GrabHandle, False, FramePointer, False ) else Result := -1 ; end ; procedure ITEX_TimerProc( uID,uMsg : SmallInt ; ITEX : PITEX ; dw1,dw2 : LongInt ) ; stdcall ; { ----------------------------------------------------------------- Frame monitor and read polling procedure, called at 20ms intervals ----------------------------------------------------------------- } var FramePointer : Pointer ; EndPixel : Integer ; begin // Quit if DMA transfer possible (should not have been called) if ITEX^.HostTransferPossible then Exit ; // Prevent multiple entry if ITEX^.TimerProcInUse then Exit ; // Set in use flag ITEX^.TimerProcInUse := True ; // Read last pixel in frame // (Non-zero indicates frame available) EndPixel := icp_rpix( ITEX^.PModHandle, ITEX^.FrameID, ITEX^.FrameWidth-1, ITEX^.FrameHeight-1 ) ; // If frame available transfer to host frame buffer if EndPixel <> FrameEmptyFlag then begin FramePointer := Pointer(ITEX^.FrameNum*ITEX^.NumBytesPerFrame + Integer(ITEX^.FrameBuf)) ; itx_read_area( ITEX^.PModHandle, ITEX^.FrameID, 0, 0, ITEX^.FrameWidth, ITEX^.FrameHeight, FramePointer ) ; Inc(ITEX^.FrameNum) ; if ITEX^.FrameNum >= ITEX^.NumFrames then ITEX^.FrameNum := 0 ; // Clear buffer in frame grabber memory icp_clr_frame( ITEX^.PModHandle, ITEX^.FrameID, FrameEmptyFlag ) ; end ; ITEX^.TimerProcInUse := False ; end ; Initialization LibraryLoaded := False ; end.
program test_comptonprofiles; {$APPTYPE CONSOLE} {$IFDEF FPC} {$linklib libxrl} {$ENDIF} {$mode objfpc} {$h+} uses xraylib, xrltest, Classes, SysUtils, fpcunit, testreport, testregistry; type TestComptonProfiles = class(TTestCase) private procedure _Test_bad_Z_0; procedure _Test_bad_Z_103; procedure _Test_bad_pz; procedure _Test_bad_Z_0_partial; procedure _Test_bad_Z_103_partial; procedure _Test_bad_pz_partial; procedure _Test_bad_shell_low_partial; procedure _Test_bad_shell_high_partial; published procedure Test_pz_0; procedure Test_pz_100; procedure Test_pz_50; procedure Test_bad_input; end; procedure TestComptonProfiles.Test_pz_0; var profile, profile1, profile2: double; begin profile := ComptonProfile(26, 0.0); AssertEquals(7.060, profile, 1E-6); profile := ComptonProfile_Partial(26, N1_SHELL, 0.0); AssertEquals(1.550, profile, 1E-6); profile1 := ComptonProfile_Partial(26, L2_SHELL, 0.0); profile2 := ComptonProfile_Partial(26, L3_SHELL, 0.0); AssertEquals(profile1, profile2, 1E-6); end; procedure TestComptonProfiles.Test_pz_100; var profile, profile1, profile2: double; begin profile := ComptonProfile(26, 100.0); AssertEquals(1.800E-5, profile, 1E-8); profile := ComptonProfile_Partial(26, N1_SHELL, 100.0); AssertEquals(5.100E-09, profile, 1E-12); profile1 := ComptonProfile_Partial(26, L2_SHELL, 100.0); profile2 := ComptonProfile_Partial(26, L3_SHELL, 100.0); AssertEquals(profile1, profile2, 1E-10); AssertEquals(profile1, 1.100E-8, 1E-10); end; procedure TestComptonProfiles.Test_pz_50; var profile, profile1, profile2: double; begin profile := ComptonProfile(26, 50.0); AssertEquals(0.0006843950273082384, profile, 1E-8); profile := ComptonProfile_Partial(26, N1_SHELL, 50.0); AssertEquals(2.4322755767709126e-07, profile, 1E-10); profile1 := ComptonProfile_Partial(26, L2_SHELL, 50.0); profile2 := ComptonProfile_Partial(26, L3_SHELL, 50.0); AssertEquals(profile1, profile2, 1E-10); AssertEquals(profile1, 2.026953933016568e-06, 1E-10); end; procedure TestComptonProfiles.Test_bad_input; begin AssertException(EArgumentException, @_Test_bad_Z_0); ComptonProfile(102, 0.0); AssertException(EArgumentException, @_Test_bad_Z_103); AssertException(EArgumentException, @_Test_bad_pz); AssertException(EArgumentException, @_Test_bad_Z_0_partial); ComptonProfile_Partial(102, K_SHELL, 0.0); AssertException(EArgumentException, @_Test_bad_Z_103_partial); AssertException(EArgumentException, @_Test_bad_pz_partial); AssertException(EArgumentException, @_Test_bad_shell_low_partial); AssertException(EArgumentException, @_Test_bad_shell_high_partial); end; procedure TestComptonProfiles._Test_bad_Z_0; begin ComptonProfile(0, 0.0); end; procedure TestComptonProfiles._Test_bad_Z_103; begin ComptonProfile(103, 0.0); end; procedure TestComptonProfiles._Test_bad_pz; begin ComptonProfile(26, -1.0); end; procedure TestComptonProfiles._Test_bad_Z_0_partial; begin ComptonProfile_Partial(0, K_SHELL, 0.0); end; procedure TestComptonProfiles._Test_bad_Z_103_partial; begin ComptonProfile_Partial(103, K_SHELL, 0.0); end; procedure TestComptonProfiles._Test_bad_pz_partial; begin ComptonProfile_Partial(26, K_SHELL, -1.0); end; procedure TestComptonProfiles._Test_bad_shell_low_partial; begin ComptonProfile_Partial(26, -1, 0.0); end; procedure TestComptonProfiles._Test_bad_shell_high_partial; begin ComptonProfile_Partial(26, N2_SHELL, 0.0); end; var App: TestRunner; begin RegisterTest(TestComptonProfiles); App := TestRunner.Create(nil); App.Initialize; App.Run; App.Free; end.
unit Report; interface uses Registrator, BaseObjects; type // Объемы ГРР и затраты за период по недропользователям и видам работ TGRRReportByOrganization = class (TRegisteredIDObject) public constructor Create (ACollection: TIDObjects); override; end; TGRRReportByOrganizations = class (TRegisteredIDObjects) private function GetItems(Index: Integer): TGRRReportByOrganization; public property Items[Index: Integer]: TGRRReportByOrganization read GetItems; Constructor Create; override; end; implementation uses ReportPoster, facade; { TGRRReportByOrganizations } constructor TGRRReportByOrganizations.Create; begin inherited; FObjectClass := TGRRReportByOrganization; Poster := TMainFacade.GetInstance.DataPosterByClassType[TGRRReportByOrganizationDataPoster]; end; function TGRRReportByOrganizations.GetItems( Index: Integer): TGRRReportByOrganization; begin Result := inherited Items[Index] as TGRRReportByOrganization; end; { TGRRReportByOrganization } constructor TGRRReportByOrganization.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Объемы ГРР и затраты за период по недропользователям и видам работ'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TGRRReportByOrganizationDataPoster]; end; end.
// ************************************************************************************************** // // Unit Vcl.Styles.InnoSetup // unit for the VCL Styles Plugin for Inno Setup // https://github.com/RRUZ/vcl-styles-plugins // // The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); // you may not use this file except in compliance with the License. You may obtain a copy of the // License at http://www.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either express or implied. See the License for the specific language governing rights // and limitations under the License. // // The Original Code is Vcl.Styles.InnoSetup.pas. // // The Initial Developer of the Original Code is Rodrigo Ruz V. // // Portions created by Rodrigo Ruz V. are Copyright (C) 2013-2021 Rodrigo Ruz V. // All Rights Reserved. // // ************************************************************************************************** unit Vcl.Styles.InnoSetup; interface Procedure Done; implementation { TODO: TNewEdit = class(TEdit) ok TEdit ok TPasswordEdit ok TNewMemo = class(TMemo) ok TNewComboBox = class(TComboBox) ok TNewListBox = class(TListBox) ok TListBox ok TNewButton = class(TButton) ok TNewCheckBox = class(TCheckBox) ok TNewRadioButton = class(TRadioButton) TSelectFolderForm ok TFolderTreeView ok TStartMenuFolderTreeView ok TRichEditViewer ok TNewStaticText ok TNewNotebook ok TNewNotebookPage ok TPanel ok } { .$DEFINE USEGENERICS } // -->Reduce the final exe/dll size uses DDetours, Winapi.Windows, Winapi.CommDlg, Winapi.Messages, {$IFDEF USEGENERICS} System.Generics.Collections, {$ENDIF} System.SysUtils, System.Classes, {$IFDEF DEBUG} System.IOUtils, {$ENDIF} Vcl.Themes, Vcl.Styles.InnoSetup.StyleHooks, Vcl.Styles.Utils.SysStyleHook, Vcl.Styles.Utils.Forms, Vcl.Styles.Utils.SysControls, Vcl.Styles.Utils.ComCtrls, Vcl.Styles.Utils.StdCtrls, uLogExcept; type TThemedInnoControls = class private class var FHook_WH_CALLWNDPROC: HHook; class var FHook_WH_CBT: HHook; protected class function HookActionCallBackWndProc(nCode: Integer; wParam: wParam; lParam: lParam): LRESULT; stdcall; static; class function HookActionCallBackCBT(nCode: Integer; wParam: wParam; lParam: lParam): LRESULT; stdcall; static; procedure InstallHook; procedure RemoveHook; procedure InstallHook_WH_CBT; procedure RemoveHook_WH_CBT; public constructor Create; overload; destructor Destroy; override; end; {$IFNDEF USEGENERICS} TDictionary = class private FKeys, FValues: TList; public procedure Add(hwnd: hwnd; StyleHook: TSysStyleHook); function ContainsKey(hwnd: Winapi.Windows.hwnd): Boolean; constructor Create; overload; destructor Destroy; override; end; {$ENDIF} var {$IFDEF USEGENERICS} InnoSetupControlsList: TObjectDictionary<hwnd, TSysStyleHook>; {$ELSE} InnoSetupControlsList: TDictionary; {$ENDIF} ClassesList: TStrings; // use a TStrings to avoid the use of generics ThemedInnoControls: TThemedInnoControls; {$IFNDEF USEGENERICS} { TDictionary } procedure TDictionary.Add(hwnd: hwnd; StyleHook: TSysStyleHook); begin FKeys.Add(Pointer(hwnd)); FValues.Add(StyleHook); end; function TDictionary.ContainsKey(hwnd: Winapi.Windows.hwnd): Boolean; var i: Integer; begin Result := False; for i := 0 to FKeys.Count - 1 do if Winapi.Windows.hwnd(FKeys[i]) = hwnd then Exit(True); end; constructor TDictionary.Create; begin FKeys := TList.Create; FValues := TList.Create; end; destructor TDictionary.Destroy; var i: Integer; begin FKeys.Free; for i := 0 to FValues.Count - 1 do TSysStyleHook(FValues[i]).Free; FValues.Free; inherited; end; {$ENDIF} { TThemedSysControls } constructor TThemedInnoControls.Create; begin inherited; FHook_WH_CALLWNDPROC := 0; InstallHook; InstallHook_WH_CBT; {$IFDEF USEGENERICS} InnoSetupControlsList := TObjectDictionary<hwnd, TSysStyleHook>.Create([doOwnsValues]); {$ELSE} InnoSetupControlsList := TDictionary.Create; {$ENDIF} ClassesList := TStringList.Create; end; destructor TThemedInnoControls.Destroy; begin RemoveHook; RemoveHook_WH_CBT; InnoSetupControlsList.Free; ClassesList.Free; inherited; end; class function TThemedInnoControls.HookActionCallBackCBT(nCode: Integer; wParam: wParam; lParam: lParam): LRESULT; var LHWND: hwnd; LClassName: string; begin if (StyleServices.Enabled) and not(StyleServices.IsSystemStyle) then case nCode of HCBT_ACTIVATE: begin //TLogFile.Add('HookActionCallBackCBT'); LHWND := hwnd(wParam); if (LHWND > 0) then begin LClassName := GetWindowClassName(LHWND); if (LClassName <> '') and (not TSysStyleManager.SysStyleHookList.ContainsKey(LHWND)) { and SameText(LClassName,'#32770') } then begin TSysStyleManager.AddControlDirectly(LHWND, LClassName); InvalidateRect(LHWND, nil, False); end; end; end; end; Result := CallNextHookEx(TThemedInnoControls.FHook_WH_CBT, nCode, wParam, lParam); end; class function TThemedInnoControls.HookActionCallBackWndProc(nCode: Integer; wParam: wParam; lParam: lParam): LRESULT; var C: array [0 .. 256] of Char; sClassName: string; begin Result := CallNextHookEx(FHook_WH_CALLWNDPROC, nCode, wParam, lParam); try if (nCode < 0) then Exit; if (StyleServices.Enabled) and not(StyleServices.IsSystemStyle) then begin if ClassesList.IndexOfName(IntToStr(PCWPStruct(lParam)^.hwnd)) = -1 then begin GetClassName(PCWPStruct(lParam)^.hwnd, C, 256); // Addlog('GetClassName ' + C); ClassesList.Add(Format('%d=%s', [PCWPStruct(lParam)^.hwnd, C])); end; if ClassesList.IndexOfName(IntToStr(PCWPStruct(lParam)^.hwnd)) >= 0 then begin sClassName := ClassesList.Values[IntToStr(PCWPStruct(lParam)^.hwnd)]; // ClassesList[PCWPStruct(lParam)^.hwnd]; {$IFDEF DEBUG} // if (SameText(sClassName,'LiteUI_Label')) then // Addlog(sClassName+' '+WM_To_String(PCWPStruct(lParam)^.message)+ // ' WParam '+IntToHex(PCWPStruct(lParam)^.wParam, 8) + // ' lParam '+IntToHex(PCWPStruct(lParam)^.lParam, 8) + // ' hwnd: '+ IntToHex(PCWPStruct(lParam)^.hwnd, 8) + // ' WNDPROC: ' + IntToHex(GetWindowLongPtr(PCWPStruct(lParam)^.hwnd, GWL_WNDPROC), 8 ) // ); {$ENDIF} if SameText(sClassName, 'TNewButton') then begin if (PCWPStruct(lParam)^.message = WM_CREATE) and not(InnoSetupControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then InnoSetupControlsList.Add(PCWPStruct(lParam)^.hwnd, TNewButtonStyleHook.Create(PCWPStruct(lParam)^.hwnd)); end else if SameText(sClassName, 'TWizardForm') or SameText(sClassName, 'TSetupForm') or SameText(sClassName, 'TSelectFolderForm') or SameText(sClassName, 'TSelectLanguageForm') or SameText(sClassName, 'TUninstallProgressForm') then begin if (PCWPStruct(lParam)^.message = WM_NCCALCSIZE) and not(InnoSetupControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then InnoSetupControlsList.Add(PCWPStruct(lParam)^.hwnd, TWizardFormStyleHook.Create(PCWPStruct(lParam)^.hwnd)); end else if SameText(sClassName, 'TNewComboBox') then begin if (PCWPStruct(lParam)^.message = WM_CREATE) and not(InnoSetupControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then InnoSetupControlsList.Add(PCWPStruct(lParam)^.hwnd, TSysComboBoxStyleHook.Create(PCWPStruct(lParam)^.hwnd)); end else if SameText(sClassName, 'TNewCheckBox') then begin if (PCWPStruct(lParam)^.message = WM_CREATE) and not(InnoSetupControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then InnoSetupControlsList.Add(PCWPStruct(lParam)^.hwnd, TSysCheckBoxStyleHook.Create(PCWPStruct(lParam)^.hwnd)); end else if SameText(sClassName, 'TNewRadioButton') then begin if (PCWPStruct(lParam)^.message = WM_CREATE) and not(InnoSetupControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then InnoSetupControlsList.Add(PCWPStruct(lParam)^.hwnd, TSysRadioButtonStyleHook.Create(PCWPStruct(lParam)^.hwnd)); end else if SameText(sClassName, 'TEdit') or SameText(sClassName, 'TNewEdit') or SameText(sClassName, 'TPasswordEdit') then begin if (PCWPStruct(lParam)^.message = WM_CREATE) and not(InnoSetupControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then InnoSetupControlsList.Add(PCWPStruct(lParam)^.hwnd, TSysEditStyleHook.Create(PCWPStruct(lParam)^.hwnd)); end else // TSysScrollingStyleHook.PaintNC<>TScrollingStyleHook.PaintNC if SameText(sClassName, 'TNewMemo') or SameText(sClassName, 'TMemo') then begin if (PCWPStruct(lParam)^.message = WM_NCCALCSIZE) and not(InnoSetupControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then begin InnoSetupControlsList.Add(PCWPStruct(lParam)^.hwnd, TNewMemoStyleHook.Create(PCWPStruct(lParam)^.hwnd)); end; end else if SameText(sClassName, 'TNewListBox') or SameText(sClassName, 'TListBox') then begin if (PCWPStruct(lParam)^.message = WM_NCCALCSIZE) and not(InnoSetupControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then InnoSetupControlsList.Add(PCWPStruct(lParam)^.hwnd, TNewListBoxStyleHook.Create(PCWPStruct(lParam)^.hwnd)); end else if SameText(sClassName, 'TNewCheckListBox') then begin if (PCWPStruct(lParam)^.message = WM_NCCALCSIZE) and not(InnoSetupControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then InnoSetupControlsList.Add(PCWPStruct(lParam)^.hwnd, TNewCheckListBoxStyleHook.Create(PCWPStruct(lParam)^.hwnd)); end else if SameText(sClassName, 'TRichEditViewer') then begin if (PCWPStruct(lParam)^.message = WM_NCCALCSIZE) and not(InnoSetupControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then InnoSetupControlsList.Add(PCWPStruct(lParam)^.hwnd, TRichEditViewerStyleHook.Create(PCWPStruct(lParam)^.hwnd)); end else // if SameText(sClassName,'TNewStaticText') then // begin // if (PCWPStruct(lParam)^.message=WM_CREATE) and not (InnoSetupControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then // InnoSetupControlsList.Add(PCWPStruct(lParam)^.hwnd, TStaticTextWnd.Create(PCWPStruct(lParam)^.hwnd)); // end // else // if (SameText(sClassName,'TNewProgressBar')) then The Vcl.Styles.Hooks unit is used to paint the progressbar. // begin // if (PCWPStruct(lParam)^.message=WM_CREATE) and not (InnoSetupControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then // InnoSetupControlsList.Add(PCWPStruct(lParam)^.hwnd, TSysProgressBarStyleHook.Create(PCWPStruct(lParam)^.hwnd)); // end // else if (SameText(sClassName, 'TStartMenuFolderTreeView')) or (SameText(sClassName, 'TFolderTreeView')) then begin if (PCWPStruct(lParam)^.message = WM_CREATE) and not(InnoSetupControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then InnoSetupControlsList.Add(PCWPStruct(lParam)^.hwnd, TFolderTreeViewStyleHook.Create(PCWPStruct(lParam)^.hwnd)); end else // if (SameText(sClassName,'LiteUI_Panel')) then // begin // if (PCWPStruct(lParam)^.message=WM_CREATE) and not (InnoSetupControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then // InnoSetupControlsList.Add(PCWPStruct(lParam)^.hwnd, TPanelComponentStyleHook.Create(PCWPStruct(lParam)^.hwnd)); // end // else // if (SameText(sClassName,'LiteUI_Label')) then // begin // if (PCWPStruct(lParam)^.message=WM_NCCREATE) and not (InnoSetupControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then // InnoSetupControlsList.Add(PCWPStruct(lParam)^.hwnd, TLabelComponentStyleHook.Create(PCWPStruct(lParam)^.hwnd)); // end // else // if (SameText(sClassName,'TNewNotebook')) then //TNewNotebook is handled by the Getsyscolors hook // begin // if (PCWPStruct(lParam)^.message=WM_CREATE) and not (InnoSetupControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then // InnoSetupControlsList.Add(PCWPStruct(lParam)^.hwnd, TNotebookWnd.Create(PCWPStruct(lParam)^.hwnd)); // end // else // if (SameText(sClassName,'TNewNotebookPage')) then //TNewNotebookPage is handled by the Getsyscolors hook // begin // if (PCWPStruct(lParam)^.message=WM_CREATE) and not (InnoSetupControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then // InnoSetupControlsList.Add(PCWPStruct(lParam)^.hwnd, TSysStyleHook.Create(PCWPStruct(lParam)^.hwnd)); // end // else // if (SameText(sClassName,'TPanel')) then //TPanel is handled by the Getsyscolors hook // begin // if (PCWPStruct(lParam)^.message=WM_CREATE) and not (InnoSetupControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then // InnoSetupControlsList.Add(PCWPStruct(lParam)^.hwnd, TPanelWnd.Create(PCWPStruct(lParam)^.hwnd)); // end; end; end; except on e: Exception do TLogFile.Add(e); end; end; procedure TThemedInnoControls.InstallHook; begin FHook_WH_CALLWNDPROC := SetWindowsHookEx(WH_CALLWNDPROC, @TThemedInnoControls.HookActionCallBackWndProc, 0, GetCurrentThreadId); end; procedure TThemedInnoControls.InstallHook_WH_CBT; begin FHook_WH_CBT := SetWindowsHookEx(WH_CBT, @TThemedInnoControls.HookActionCallBackCBT, 0, GetCurrentThreadId); end; procedure TThemedInnoControls.RemoveHook; begin if FHook_WH_CALLWNDPROC <> 0 then UnhookWindowsHookEx(FHook_WH_CALLWNDPROC); end; procedure TThemedInnoControls.RemoveHook_WH_CBT; begin if FHook_WH_CBT <> 0 then UnhookWindowsHookEx(FHook_WH_CBT); end; Procedure Done; begin if Assigned(ThemedInnoControls) then begin ThemedInnoControls.Free; ThemedInnoControls := nil; end; end; const commdlg32 = 'comdlg32.dll'; var TrampolineGetOpenFileNameW: function(var OpenFile: TOpenFilenameW): Bool; stdcall; TrampolineGetOpenFileNameA: function(var OpenFile: TOpenFilenameA): Bool; stdcall; function DialogHook(Wnd: hwnd; msg: UINT; wParam: wParam; lParam: lParam): UINT_PTR; stdcall; begin Exit(0); end; function DetourGetOpenFileNameW(var OpenFile: TOpenFilename): Bool; stdcall; begin OpenFile.lpfnHook := @DialogHook; OpenFile.Flags := OpenFile.Flags or OFN_ENABLEHOOK or OFN_EXPLORER; Exit(TrampolineGetOpenFileNameW(OpenFile)); end; function DetourGetOpenFileNameA(var OpenFile: TOpenFilenameA): Bool; stdcall; begin OpenFile.lpfnHook := @DialogHook; OpenFile.Flags := OpenFile.Flags or OFN_ENABLEHOOK or OFN_EXPLORER; Exit(TrampolineGetOpenFileNameA(OpenFile)); end; procedure HookFileDialogs; begin @TrampolineGetOpenFileNameW := InterceptCreate(commdlg32, 'GetOpenFileNameW', @DetourGetOpenFileNameW); @TrampolineGetOpenFileNameA := InterceptCreate(commdlg32, 'GetOpenFileNameA', @DetourGetOpenFileNameA); end; procedure UnHookFileDialogs; begin InterceptRemove(@TrampolineGetOpenFileNameW); InterceptRemove(@TrampolineGetOpenFileNameA); end; initialization ThemedInnoControls := nil; if StyleServices.Available then begin ThemedInnoControls := TThemedInnoControls.Create; TSysStyleManager.HookVclControls := True; HookFileDialogs; end; finalization Done; UnHookFileDialogs; end.
unit RTF_ListaKlientow; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, JvUIB, JvUIBLib, RT_Tools; type TFrmListaKlientow = class(TForm) LblQuickSearch: TLabel; LblListaKlientow: TLabel; EdtQuickSearch: TEdit; BtnZamknij: TButton; BtnNowy: TBitBtn; BtnPopraw: TBitBtn; BtnUsun: TBitBtn; LbxListaKlientow: TListBox; BtnAnuluj: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure LbxListaKlientowClick(Sender: TObject); procedure EdtQuickSearchKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EdtQuickSearchChange(Sender: TObject); procedure BtnNowyClick(Sender: TObject); procedure BtnPoprawClick(Sender: TObject); procedure BtnUsunClick(Sender: TObject); procedure LbxListaKlientowDblClick(Sender: TObject); procedure LbxListaKlientowDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); private { Private declarations } DialogKind: TDialogKind; Klienci: TJvUIBQuery; procedure DisplayKlienci; public { Public declarations } procedure SetupAsSelector; procedure SetupAsEditor; end; implementation uses RTF_EdytorKlienta, RT_SQL; {$R *.DFM} { TFrmListaKlientow } { Private declarations } procedure TFrmListaKlientow.DisplayKlienci; begin LbxListaKlientow.Items.BeginUpdate; LbxListaKlientow.Clear; Klienci.Close(etmRollback); Klienci.Open; while not Klienci.Eof do begin LbxListaKlientow.AddItem(Klienci.Fields.ByNameAsString['ULICA'], nil); Klienci.Next; end; LbxListaKlientow.ItemIndex := -1; LbxListaKlientow.Items.EndUpdate; end; { Public declarations } procedure TFrmListaKlientow.SetupAsEditor; begin DialogKind := dkEditor; Caption := 'Edytor klientów'; BtnZamknij.Caption := '&Zamknij'; BtnZamknij.Cancel := True; BtnAnuluj.Visible := False; BtnNowy.Visible := True; BtnPopraw.Visible := True; BtnPopraw.Default := True; BtnUsun.Visible := True; end; procedure TFrmListaKlientow.SetupAsSelector; begin DialogKind := dkSelector; Caption := 'Wybierz klienta'; BtnZamknij.Caption := '&OK'; BtnZamknij.Default := True; BtnAnuluj.Visible := True; BtnAnuluj.Cancel := True; BtnNowy.Visible := False; BtnPopraw.Visible := False; BtnUsun.Visible := False; end; { Event handlers } procedure TFrmListaKlientow.FormCreate(Sender: TObject); begin Klienci := TSQL.Instance.CreateQuery; Klienci.SQL.Text := 'SELECT * FROM KLIENT ORDER BY ULICA,DOM;'; end; procedure TFrmListaKlientow.FormDestroy(Sender: TObject); begin Klienci.Free; end; procedure TFrmListaKlientow.FormShow(Sender: TObject); begin DisplayKlienci; EdtQuickSearch.SetFocus; EdtQuickSearch.SelectAll; end; procedure TFrmListaKlientow.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if (DialogKind = dkSelector) and (LbxListaKlientow.ItemIndex = -1) and (ModalResult <> mrCancel) then begin CanClose := False; EdtQuickSearch.SetFocus; EdtQuickSearch.SelectAll; end; end; procedure TFrmListaKlientow.LbxListaKlientowClick(Sender: TObject); var Temp: TNotifyEvent; begin Temp := EdtQuickSearch.OnChange; EdtQuickSearch.OnChange := nil; if LbxListaKlientow.ItemIndex >= 0 then EdtQuickSearch.Text := LbxListaKlientow.Items[LbxListaKlientow.ItemIndex] else EdtQuickSearch.Text := ''; EdtQuickSearch.SetFocus; EdtQuickSearch.SelectAll; EdtQuickSearch.OnChange := Temp; end; procedure TFrmListaKlientow.EdtQuickSearchKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_DOWN) or (Key = VK_UP) or (Key = VK_PRIOR) or (Key = VK_NEXT) or (Key = VK_HOME) or (Key = VK_END) then begin SendMessage(LbxListaKlientow.Handle, WM_KEYDOWN, Key, 0); Key := 0; end; end; procedure TFrmListaKlientow.EdtQuickSearchChange(Sender: TObject); var I: Integer; S: String; begin for I := 0 to LbxListaKlientow.Items.Count - 1 do begin S := Copy(LbxListaKlientow.Items[I], 1, Length(EdtQuickSearch.Text)); if AnsiCompareText(EdtQuickSearch.Text, S) <= 0 then begin LbxListaKlientow.ItemIndex := I; Break; end; end; end; procedure TFrmListaKlientow.BtnNowyClick(Sender: TObject); begin with TFrmEdytorKlienta.Create(nil) do try if ShowModal = mrOk then DisplayKlienci; finally Free; end; EdtQuickSearch.SetFocus; EdtQuickSearch.SelectAll; end; procedure TFrmListaKlientow.BtnPoprawClick(Sender: TObject); begin if LbxListaKlientow.ItemIndex = -1 then Exit; with TFrmEdytorKlienta.Create(nil) do try Klienci.Fields.GetRecord(LbxListaKlientow.ItemIndex); SetData(Klienci.Fields); if ShowModal = mrOK then DisplayKlienci; finally Free; end; end; procedure TFrmListaKlientow.BtnUsunClick(Sender: TObject); begin if LbxListaKlientow.ItemIndex = -1 then Exit; if MessageDlg('Czy na pewno chcesz usun¹ę tego klienta ?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin Klienci.Fields.GetRecord(LbxListaKlientow.ItemIndex); with TSQL.Instance.CreateQuery do try SQL.Text := Format('EXECUTE PROCEDURE DELETE_KLIENT %d', [ Klienci.Fields.ByNameAsInteger['ID'] ]); Execute; Transaction.Commit; finally Free; end; DisplayKlienci; LbxListaKlientowClick(Sender); EdtQuickSearch.Text := ''; EdtQuickSearch.SetFocus; end; EdtQuickSearch.SetFocus; EdtQuickSearch.SelectAll; end; procedure TFrmListaKlientow.LbxListaKlientowDblClick(Sender: TObject); begin if DialogKind = dkEditor then BtnPopraw.Click else BtnZamknij.Click; end; procedure TFrmListaKlientow.LbxListaKlientowDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var Rest: Integer; begin TListBox(Control).Canvas.FillRect(Rect); Klienci.Fields.GetRecord(Index); Rest := Rect.Right - 220; Rect.Right := Rect.Left + 220; TListBox(Control).Canvas.TextRect(Rect, Rect.Left + 2, Rect.Top, TListBox(Control).Items[Index]); Rect.Right := 220 + Rest; Rect.Left := 220; TListBox(Control).Canvas.TextRect(Rect, Rect.Left + 2, Rect.Top, Klienci.Fields.ByNameAsString['TELEFON']); end; end.
{******************************************************************************* 作者: dmzn@163.com 2013-07-05 描述: 站点区域管理 *******************************************************************************} unit UFrameArea; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, UBusinessConst, UBusinessWorker, UBusinessPacker, IniFiles, UFormBase, UFrameNormal, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, dxSkinsCore, dxSkinsDefaultPainters, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxContainer, dxLayoutControl, dxorgchr, ADODB, cxLabel, UBitmapPanel, cxSplitter, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, ComCtrls, ToolWin; type TfFrameArea = class(TfFrameNormal) Chart1: TdxOrgChart; dxLayout1Item1: TdxLayoutItem; cxLevel2: TcxGridLevel; cxView2: TcxGridTableView; procedure BtnAddClick(Sender: TObject); procedure BtnEditClick(Sender: TObject); procedure BtnDelClick(Sender: TObject); procedure Chart1DblClick(Sender: TObject); private { Private declarations } FAreaItems: TList; FExpandList: TStrings; //展开节点 procedure ClearItemList(const nFree: Boolean); //清理资源 procedure LoadAreaItemsData; procedure BuildAreaItemsTree; procedure BuildSubTree(const nParent: TdxOcNode); procedure InitNodeStyle(const nNode: TdxOcNode); //区域结构 procedure EnumSubNodes(const nParent: TdxOcNode; const nList: TList); //枚举节点 protected procedure OnLoadGridConfig(const nIni: TIniFile); override; procedure OnSaveGridConfig(const nIni: TIniFile); override; procedure OnInitFormData(var nDefault: Boolean; const nWhere: string = ''; const nQuery: TADOQuery = nil); override; public { Public declarations } class function FrameID: integer; override; end; implementation {$R *.dfm} uses UMgrControl, ULibFun, UFormWait, USysDataDict, UDataModule, USysGrid, USysDB, USysBusiness, USysConst; type PAreaItem = ^TAreaItem; TAreaItem = record FID: string; FName: string; FMIT: string; FParent: string; end; var gTruckData: TTruckDataSource = nil; //全局使用 //------------------------------------------------------------------------------ class function TfFrameArea.FrameID: integer; begin Result := cFI_FrameArea; end; procedure TfFrameArea.OnLoadGridConfig(const nIni: TIniFile); var nInt: Integer; begin inherited; FAreaItems := TList.Create; FExpandList := TStringList.Create; nInt := nIni.ReadInteger(Name, 'GridHeight', 0); if nInt > 0 then cxGrid1.Height := nInt; if gSysParam.FSysDBType <> sFlag_DB_HQArea then begin for nInt:=ToolBar1.ButtonCount - 1 downto 0 do ToolBar1.Buttons[nInt].Enabled := False; ShowMsg('无效的区域数据库', sHint); end; cxGrid1.ActiveLevel := cxLevel2; gSysEntityManager.BuildViewColumn(cxView2, PopedomItem); InitTableView(Name, cxView2, nIni); if not Assigned(gTruckData) then gTruckData := TTruckDataSource.Create; cxView2.DataController.CustomDataSource := gTruckData; end; procedure TfFrameArea.OnSaveGridConfig(const nIni: TIniFile); begin ClearItemList(True); FreeAndNil(FExpandList); FreeAndNil(gTruckData); inherited; cxView2.DataController.CustomDataSource := nil; FreeAndNil(gTruckData); SaveUserDefineTableView(Name, cxView2, nIni); nIni.WriteInteger(Name, 'GridHeight', cxGrid1.Height); end; procedure TfFrameArea.OnInitFormData(var nDefault: Boolean; const nWhere: string; const nQuery: TADOQuery); begin nDefault := False; if gSysParam.FSysDBType = sFlag_DB_HQArea then BuildAreaItemsTree; //xxxxx end; //------------------------------------------------------------------------------ //Date: 2013-07-05 //Parm: 释放 //Desc: 释放区域列表 procedure TfFrameArea.ClearItemList(const nFree: Boolean); var nIdx: Integer; begin for nIdx:=FAreaItems.Count - 1 downto 0 do begin Dispose(PAreaItem(FAreaItems[nIdx])); FAreaItems.Delete(nIdx); end; if nFree then FreeAndNil(FAreaItems); //xxxxx end; //Date: 2013-07-06 //Parm: 父几点;列表 //Desc: 枚举nParent下的所有子节点 procedure TfFrameArea.EnumSubNodes(const nParent: TdxOcNode; const nList: TList); var nNode: TdxOcNode; begin nNode := nParent.GetFirstChild; while Assigned(nNode) do begin nList.Add(Pointer(nNode)); EnumSubNodes(nNode, nList); nNode := nParent.GetNextChild(nNode); end; end; //Date: 2013-07-05 //Desc: 读取区域数据 procedure TfFrameArea.LoadAreaItemsData; var nStr: string; nItem: PAreaItem; begin ClearItemList(False); nStr := 'Select * From %s Order By A_Index'; nStr := Format(nStr, [sTable_Area]); with FDM.QuerySQL(nStr) do begin if RecordCount < 1 then Exit; First; while not Eof do begin New(nItem); FAreaItems.Add(nItem); nItem.FID := FieldByName('A_ID').AsString; nItem.FName := FieldByName('A_Name').AsString; nItem.FMIT := FieldByName('A_MIT').AsString; nItem.FParent := FieldByName('A_Parent').AsString; Next; end; end; end; procedure TfFrameArea.InitNodeStyle(const nNode: TdxOcNode); begin if nNode.Level = 0 then begin nNode.Text := '华新商砼'; end; end; //Date: 2013-07-05 //Desc: 构建区域树 procedure TfFrameArea.BuildAreaItemsTree; var nIdx: Integer; nItem: PAreaItem; nNode,nTmp: TdxOcNode; begin Chart1.BeginUpdate; try FExpandList.Clear; nNode := Chart1.GetFirstNode; while Assigned(nNode) do begin if nNode.HasChildren and nNode.Expanded then begin nItem := nNode.Data; if Assigned(nItem) then FExpandList.Add(nItem.FID); //xxxxx end; nNode := nNode.GetNext; end; LoadAreaItemsData; //载入数据 Chart1.Clear; nNode := Chart1.Add(nil, nil); InitNodeStyle(nNode); for nIdx:=0 to FAreaItems.Count - 1 do begin nItem := FAreaItems[nIdx]; if nItem.FParent <> '' then Continue; nTmp := Chart1.AddChild(nNode, nItem); nTmp.Text := nItem.FName; InitNodeStyle(nTmp); BuildSubTree(nTmp); //构建子节点 end; nNode := Chart1.GetFirstNode; while Assigned(nNode) do begin if nNode.HasChildren then begin nItem := nNode.Data; if (not Assigned(nItem)) or (FExpandList.IndexOf(nItem.FID) >= 0) then nNode.Expand(False); //restore end; nNode := nNode.GetNext; end; finally Chart1.EndUpdate; end; end; procedure TfFrameArea.BuildSubTree(const nParent: TdxOcNode); var nIdx: Integer; nNode: TdxOcNode; nItem,nP: PAreaItem; begin nP := nParent.Data; //xxxxx for nIdx:=0 to FAreaItems.Count - 1 do begin nItem := FAreaItems[nIdx]; if nItem.FParent <> nP.FID then Continue; nNode := Chart1.AddChild(nParent, nItem); nNode.Text := nItem.FName; InitNodeStyle(nNode); BuildSubTree(nNode); //构建子节点 end; end; procedure TfFrameArea.BtnAddClick(Sender: TObject); var nStr: string; nParam: TFormCommandParam; begin if not Assigned(Chart1.Selected) then begin ShowMsg('请选择上级节点', sHint); Exit; end; if Chart1.Selected.Level = 0 then begin nStr := ''; end else begin if PAreaItem(Chart1.Selected.Data).FMIT = '' then nStr := PAreaItem(Chart1.Selected.Data).FID else nStr := PAreaItem(Chart1.Selected.Parent.Data).FID; end; nParam.FCommand := cCmd_AddData; nParam.FParamA := nStr; CreateBaseFormItem(cFI_FormArea, PopedomItem, @nParam); if (nParam.FCommand = cCmd_ModalResult) and (nParam.FParamA = mrOK) then begin InitFormData(); end; end; procedure TfFrameArea.BtnEditClick(Sender: TObject); var nParam: TFormCommandParam; begin if (not Assigned(Chart1.Selected)) or (Chart1.Selected.Level < 1) then begin ShowMsg('请选择要编辑的节点', sHint); Exit; end; nParam.FCommand := cCmd_EditData; nParam.FParamA := PAreaItem(Chart1.Selected.Data).FID; CreateBaseFormItem(cFI_FormArea, PopedomItem, @nParam); if (nParam.FCommand = cCmd_ModalResult) and (nParam.FParamA = mrOK) then begin InitFormData(); end; end; procedure TfFrameArea.BtnDelClick(Sender: TObject); var nStr: string; nIdx: Integer; nList: TList; nNode: TdxOcNode; begin if (not Assigned(Chart1.Selected)) or (Chart1.Selected.Level < 1) then begin ShowMsg('请选择要删除的节点', sHint); Exit; end; nStr := '确定要删除【%s】节点吗?'; nStr := Format(nStr, [PAreaItem(Chart1.Selected.Data).FName]); if not QueryDlg(nStr, sAsk) then Exit; nStr := ''; nList := TList.Create; try nList.Add(Chart1.Selected); EnumSubNodes(Chart1.Selected, nList); for nIdx:=0 to nList.Count - 1 do begin nNode := TdxOcNode(nList[nIdx]); if nIdx = 0 then nStr := Format('''%s''', [PAreaItem(nNode.Data).FID]) else nStr := nStr + Format(',''%s''', [PAreaItem(nNode.Data).FID]); end; finally nList.Free; end; nStr := Format('Delete From %s Where A_ID In (%s)', [sTable_Area, nStr]); FDM.ExecuteSQL(nStr); InitFormData(); end; //Desc: 刷新 procedure TfFrameArea.Chart1DblClick(Sender: TObject); var nStr: String; begin if Assigned(Chart1.Selected) and Assigned(Chart1.Selected.Data) and (not Chart1.Selected.HasChildren) then try nStr := PAreaItem(Chart1.Selected.Data).FMIT; if nStr <> '' then begin ShowWaitForm(ParentForm, '读取队列'); gTruckData.LoadTrucks(nStr); end; finally CloseWaitForm; end; end; initialization gControlManager.RegCtrl(TfFrameArea, TfFrameArea.FrameID); end.
unit ucDADOS; interface uses SysUtils, Classes, DBXpress, FMTBcd, DB, Provider, DBClient, SqlExpr, ImgList, Controls, Forms, MidasLib, ucCOMP, Dialogs; type TdDADOS = class(TDataModule) _Conexao: TSqlConnection; _ImageList: TImageList; procedure DataModuleCreate(Sender: TObject); procedure _ConexaoBeforeConnect(Sender: TObject); procedure _QueryAfterOpen(DataSet: TDataSet); private protected vBanSis, vTipBan, vUsuBan, vSenBan : String; FTD : TTransactionDesc; public gNmUsuario, gDtSistema, gTpPrivilegio, gIpComputador, gNmComputador : String; function getQuery(pSql : String = ''; pOpen : Boolean = False) : TSqlQuery; procedure _ConexaoSetParam(Sender: TObject); procedure StartTransaction(pParams : String = ''); procedure Commit(); procedure Rollback(); function GetMetadataEnt(pEnt : String) : String; function f_RunSql(pSql : String; pMessage : Boolean = True) : Boolean; function f_TotalRegSql(pSql : String) : Integer; function f_ExistSql(pSql : String) : Boolean; function f_ConsultaStrSql(pSql : String; pCpo : String = '*') : String; function f_LerParametro(pCdParametro : String; pAvisa : Boolean = False) : String; function f_BuscarDescricao(pParams : String; pDsValue : String = '') : String; function f_IncrementoCodigo(pTabela, pCampo : String; pWhere : String = '') : Integer; procedure p_IncrementoCodigo(pClientDataSet : TClientDataSet; pTabela, pCampo : String; pWhere : String = ''); function f_VerPrivilegio(pTabela, pTpPrivilegio : String) : boolean; procedure p_GeraListaTabela(pStrings : TStrings; pParams : String); function f_GeraListaTabela(pParams : String) : String; end; var dDADOS: TdDADOS; implementation {$R *.dfm} uses ucCADASTROFUNC, ucFUNCAO, ucITEM, ucXML, ucCONST, ucCLIENT, ucMETADATA, ucVERSAO, StrUtils; function TdDADOS.getQuery(pSql : String; pOpen : Boolean) : TSqlQuery; begin Result := TSqlQuery.Create(Self); Result.SqlConnection := _Conexao; Result.Sql.Text := pSql; if pOpen then Result.Open; end; procedure TdDADOS.DataModuleCreate(Sender: TObject); begin dDADOS := Self; gIpComputador := GetIpComputador(); gNmComputador := GetNmComputador(); TcCLIENT.validaPathBan(); vBanSis := LerIni(BAN_SIS); vTipBan := IfNullS(LerIni(TIP_BAN), 'FIREBIRD'); vUsuBan := IfNullS(LerIni(USU_BAN), 'sysdba'); vSenBan := IfNullS(LerIni(SEN_BAN), 'masterkey'); TcVERSAO.verificar(); end; procedure TdDADOS._ConexaoSetParam(Sender: TObject); begin with TSqlConnection(Sender) do begin Params.Clear; if Pos(vTipBan, 'INTERBASE|FIREBIRD') > 0 then begin DriverName := 'Interbase'; GetDriverFunc := 'getSQLDriverINTERBASE'; LibraryName := 'dbexpint.dll'; VendorLib := IfThen(vTipBan = 'INTERBASE', 'gds32.dll', 'fbclient.dll'); Params.Values['DriverName'] := 'Interbase'; Params.Values['BlobSize'] := '-1'; Params.Values['CommitRetain'] := 'False'; Params.Values['ErrorResourceFile'] := ''; Params.Values['LocaleCode'] := '0000'; Params.Values['RoleName'] := 'RoleName'; Params.Values['ServerCharSet'] := 'win1252'; Params.Values['SqlDialect'] := '3'; Params.Values['Interbase TransIsolation'] := 'ReadCommited'; Params.Values['WaitOnLocks'] := 'True'; end else if Pos(vTipBan, 'ORACLE') > 0 then begin DriverName := 'Oracle'; GetDriverFunc := 'getSQLDriverORACLE'; LibraryName := 'dbexpora.dll'; VendorLib := 'oci.dll'; Params.Values['BlobSize'] := '-1'; Params.Values['ErrorResourceFile'] := ''; Params.Values['LocaleCode'] := '0000'; Params.Values['Oracle TransIsolation'] := 'ReadCommited'; end; Params.Values['Database'] := vBanSis; Params.Values['User_Name'] := vUsuBan; Params.Values['Password'] := vSenBan; end; end; procedure TdDADOS._ConexaoBeforeConnect(Sender: TObject); begin try if (vBanSis = '') then raise Exception.Create('Caminho banco de dados não informado!'); if (vTipBan = '') then raise Exception.Create('Tipo banco de dados não informado!'); if (vUsuBan = '') then raise Exception.Create('Usuário banco de dados não informado!'); if (vSenBan = '') then raise Exception.Create('Senha banco de dados não informado!'); except Application.Terminate; raise; end; _ConexaoSetParam(_Conexao); end; function TdDADOS.f_RunSql(pSql : String; pMessage : Boolean) : Boolean; begin try _Conexao.ExecuteDirect(pSql); Result := True; except on E: Exception do begin if pMessage then Mensagem('Erro ao executar sql! / Erro: ' + E.Message + ' / Sql: ' + pSql); Result := False; end; end; end; function TdDADOS.f_TotalRegSql(pSql : String) : Integer; begin with getQuery() do begin try Close; Sql.Text := 'select count(*) as TOTAL from (' + pSql + ')'; Open; Result := FieldByName('TOTAL').AsInteger; except on E: Exception do begin Mensagem('Erro ao totalizar sql! / Erro: ' + E.Message + ' / Sql: ' + pSql); Result := -1; end; end; Free; end; end; function TdDADOS.f_ExistSql(pSql : String) : Boolean; // f_ConsultaSql begin Result := f_TotalRegSql(pSql) > 0; end; function TdDADOS.f_ConsultaStrSql(pSql, pCpo : String) : String; // f_ConsultaSqlRetorna var vSqlQuery : TSqlQuery; vResult : String; begin vResult := ''; vSqlQuery := getQuery(); with vSqlQuery do begin try Close; Sql.Text := pSql; Open; if (pCpo = '*') then begin putlistitensocc(vResult, vSqlQuery); end else if (pCpo = 'X') then begin putlistitensoccX(vResult, vSqlQuery); end else begin vResult := FieldByName(pCpo).asString; end; except on E: Exception do begin Mensagem('Erro ao consultar (ret) sql! / Erro: ' + E.Message + ' / Sql: ' + pSql); vResult := ''; end; end; Free; end; Result := vResult; end; function TdDADOS.f_LerParametro(pCdParametro : String; pAvisa : Boolean) : String; var vResult : String; begin vResult := dDADOS.f_ConsultaStrSql('select VL_PARAMETRO from ADM_PARAM where CD_PARAMETRO = ''' + pCdParametro + ''' ','VL_PARAMETRO'); if (vResult = '') and (pAvisa) then raise Exception.Create('Paramêtro ' + pCdParametro + ' deve ser informado!'); Result := vResult; end; function TdDADOS.f_BuscarDescricao(pParams : String; pDsValue : String = '') : String; var vDsTabela, vCdCampo, vDsCampo, vCdValue, vDsValue : String; begin vDsTabela := item('DS_TABELA', pParams); vCdCampo := item('CD_CAMPO', pParams); vDsCampo := item('DS_CAMPO', pParams); vCdValue := item('CD_VALUE', pParams); vDsValue := pDsValue; if (vCdValue <> '') then begin with getQuery() do begin Close; Sql.Text := 'select ' + vDsCampo + ' from ' + vDsTabela + ' where ' + vCdCampo + '=''' + vCdValue + ''''; Open; if not IsEmpty then vDsValue := FieldByName(vDsCampo).AsString; Free; end; end; Result := vDsValue; end; function TdDADOS.f_IncrementoCodigo(pTabela, pCampo, pwhere : String) : Integer; begin Result := 0; if (pTabela = '') or (pCampo = '') then Exit; Result := StrToIntDef(f_ConsultaStrSql('select max(' + pCampo + ') as CODIGO from ' + pTabela + IfThen(pwhere<>'',' where ' + pwhere,''),'CODIGO'), 0) + 1; end; procedure TdDADOS.p_IncrementoCodigo(pClientDataSet : TClientDataSet; pTabela, pCampo, pWhere : String); begin if pCampo = '' then Exit; with pClientDataSet do begin if not (State in [dsInsert]) then Exit; if (FieldByName(pCampo).asString <> '') then Exit; FieldByName(pCampo).asInteger := f_IncrementoCodigo(pTabela, pCampo, pWhere); end; end; function TdDADOS.f_VerPrivilegio(pTabela, pTpPrivilegio : String) : boolean; const cLST_PERMISSAO = 'IN_INCLUIR=Usuário sem permissão para incluir!;' + 'IN_ALTERAR=Usuário sem permissão para alterar!;' + 'IN_EXCLUIR=Usuário sem permissão para excluir!;' + 'IN_IMPRIMIR=Usuário sem permissão para imprimir!;' ; begin Result := False; if Pos(gTpPrivilegio, '1,2') > 0 then begin //Suporte / Administrador Result := True; Exit; end; if (gTpPrivilegio = '3') then begin //Operador Result := (f_ExistSql('select * from ADM_NIVEL where CD_ENTIDADE=''' + pTabela + ''' '+ 'and NM_LOGIN=''' + gNmUsuario + ''' '+ 'and ' + pTpPrivilegio + '=''T'' ')); end; if (Result = False) or (gTpPrivilegio = '4') then begin //Consulta raise Exception.Create(item(pTpPrivilegio, cLST_PERMISSAO)); end; end; procedure TdDADOS.p_GeraListaTabela(pStrings : TStrings; pParams : String); begin TcStringList(pStrings).p_AddLista(f_GeraListaTabela(pParams)); end; function TdDADOS.f_GeraListaTabela(pParams : String) : String; var vTabela, vCdKey, vDsKey, vDsWhr : String; begin Result := ''; vTabela:= item('DS_TABELA', pParams); vCdKey := item('CD_KEY', pParams); vDsKey := item('DS_KEY', pParams); vDsWhr := item('DS_WHR', pParams); if (vTabela = '') or (vCdKey = '') or (vDsKey = '') then Exit; with getQuery() do begin Close; Sql.Text := 'select ' + vCdKey + ',' + vDsKey + ' ' + 'from ' + vTabela + ' ' + IfThen(vDsWhr<>'', 'where ' + vDsWhr + ' ', '') + 'order by ' + vDsKey; Open; while not EOF do begin putitem(Result, FieldByName(vCdKey).asString, FieldByName(vDsKey).asString); Next; end; Free; end; end; procedure TdDADOS._QueryAfterOpen(DataSet: TDataSet); begin TcCADASTROFUNC.CorrigeDisplayLabel(DataSet); end; //-- procedure TdDADOS.StartTransaction(pParams : String); const cMETHOD = 'TdDADOS.StartTransaction()'; begin if _Conexao.InTransaction then raise Exception.Create('Conexao ja contem transacao em andamento / ' + cMETHOD); FTD.TransactionID := IfNullI(itemX('ID_TRANSACAO', pParams), 1); FTD.IsolationLevel := xilREADCOMMITTED; _Conexao.StartTransaction(FTD); end; procedure TdDADOS.Commit(); const cMETHOD = 'TdDADOS.Commit()'; begin if not _Conexao.InTransaction then raise Exception.Create('Conexao ja nao contem transacao em andamento / ' + cMETHOD); _Conexao.Commit(FTD); end; procedure TdDADOS.Rollback(); const cMETHOD = 'TdDADOS.Rollback()'; begin if not _Conexao.InTransaction then raise Exception.Create('Conexao ja nao contem transacao em andamento / ' + cMETHOD); _Conexao.Rollback(FTD); end; //-- function TdDADOS.GetMetadataEnt(pEnt: String): String; var vSqlQuery : TSqlQuery; vSql : String; begin vSql := 'select * from ' + pEnt + ' where 1<>1 '; vSqlQuery := getQuery(vSql); vSqlQuery.Open; Result := TcMETADATA.GetMetadataEnt(vSqlQuery); vSqlQuery.Free; end; //-- initialization dDADOS := TdDADOS.Create(nil); finalization dDADOS.Free; end.
unit HttpClient; interface uses Classes, uLkJSON, SysUtils, IURL, IdHTTP, Response; type TMethod = ( mtGet, mtPost, mtPut, mtDelete ); type THttpClient = class(TObject) private Furl :IUrls; Fmethod :TMethod; Frequest :TStringStream; Fresponse :TStringStream; Fhttp :TIdHTTP; Ftoken :String; function Get :TResponse; function Delete :TResponse; function Post :TResponse; function Put :TResponse; procedure GravaLog(log :String); protected public function Execute :Tresponse; function ToString :String; constructor Create( Url :IUrls; method :TMethod; token :String; request :TStringStream); destructor Destroy; override; published end; implementation uses Math; { THttpClient } constructor THttpClient.Create(Url: IUrls; method :TMethod; token: String; request: TStringStream); begin Furl := Url; Fmethod := method; Ftoken := token; Frequest := request; Fresponse := TStringStream.Create(''); Fhttp := TIdHTTP.Create(nil); Fhttp.Request.ContentType := 'application/json'; Fhttp.Request.CustomHeaders.Values['Authorization'] := Ftoken; end; function THttpClient.Delete: TResponse; var url :String; ljson :TlkJSONobject; begin ljson := TlkJSONobject.Create; url := Furl.getURL; try Fhttp.Delete(url,Fresponse); ljson := TlkJSON.ParseText( Fresponse.DataString ) as TlkJSONobject; Result := TResponse.Create( Fhttp.ResponseCode, ljson ); except on E :Exception do begin ljson.Add('code', 500); ljson.Add('Exception', E.Message); Fresponse := TStringStream.Create( TlkJSON.GenerateText(ljson) ); Result := TResponse.Create( 500, ljson ); end; end; end; destructor THttpClient.Destroy; begin Fhttp.Free; Frequest.Free; Fresponse.Free; //Furl.Free; inherited; end; function THttpClient.Execute: Tresponse; begin case Fmethod of mtGet : Result := Get; mtPost : Result := Post; mtPut : Result := Put; mtDelete : Result := Delete; end; GravaLog( ToString ); end; function THttpClient.Get: TResponse; var url :String; ljson :TlkJSONobject; begin ljson := TlkJSONobject.Create; url := Furl.getURL; try Fhttp.Get(url,Fresponse); ljson := TlkJSON.ParseText( Fresponse.DataString ) as TlkJSONobject; Result := TResponse.Create( Fhttp.ResponseCode, ljson ); except on E :Exception do begin ljson.Add('code', 500); ljson.Add('message', 'Exception: ' + E.Message); Result := TResponse.Create( 500, ljson ); end; end; end; procedure THttpClient.GravaLog(log: String); var NomeDoLog: string; Arquivo: TextFile; begin NomeDoLog := ExtractFileDir(ParamStr(0)) +'\HTTPCLIENT' + '.txt'; AssignFile(Arquivo, NomeDoLog); if FileExists(NomeDoLog) then Append(Arquivo) else ReWrite(Arquivo); try Writeln( arquivo, DateTimeToStr(Now) + ' - ' + log ); finally CloseFile(arquivo) end; end; function THttpClient.Post( ) : TResponse; var url :String; lresponse :TStringStream; ljson :TlkJSONobject; begin ljson := TlkJSONobject.Create; lresponse := TStringStream.Create(''); url := Furl.getURL; try //Frequest.Create( TlkJSON.GenerateText(Frequest) ); Fhttp.Post(url, Frequest, Fresponse); ljson := TlkJSON.ParseText( '{"Lista": '+ lresponse.DataString + '}' ) as TlkJSONobject; Result := TResponse.Create( Fhttp.ResponseCode, ljson ); except on E :Exception do begin ljson.Add('Exception', E.Message); Result := TResponse.Create( 500, ljson ); end; end; end; function THttpClient.Put : TResponse; var url :String; lresponse :TStringStream; ljson :TlkJSONObject; begin ljson := TlkJSONObject.Create; lresponse := TStringStream.Create(''); url := Furl.getURL; try Fhttp.Post(url, Frequest, lresponse); ljson := TlkJSON.ParseText( '{"Lista": '+ lresponse.DataString + '}' ) as TlkJSONobject; Result := TResponse.Create( Fhttp.ResponseCode, ljson ); except on E :Exception do begin ljson.Add('Exception', E.Message); Result := TResponse.Create( 500, ljson ); end; end; end; function THttpClient.ToString: String; var metodo :String; begin case Fmethod of mtGet : metodo := 'GET'; mtPost : metodo := 'POST'; mtPut : metodo := 'PUT'; mtDelete : metodo := 'DELETE'; end; Result := #13#10 + 'Method: ' + metodo + #13#10 + 'URL: ' + Furl.getURL + #13#10 + 'Authorization: ' + Ftoken + #13#10 + 'ContentType: ' + Fhttp.Request.ContentType + #13#10 + 'Request: ' + Frequest.DataString + 'Resposta:' + Fresponse.DataString + #13#10; end; end.
unit uDictionaryDemo; interface uses Generics.Collections ; type TStudentGPADictionary = TDictionary<string, double>; procedure ProcessStudents; implementation uses System.SysUtils ; procedure ReportOnStudents(aStudents: TStudentGPADictionary); var Student: string; begin for Student in aStudents.Keys do begin WriteLn(Student, ' has a ', Format('%.2f', [aStudents[Student]]), ' GPA.'); end; end; procedure ProcessStudents; var StudentGPADictionary: TStudentGPADictionary; begin StudentGPADictionary := TStudentGPADictionary.Create; try // Add some students StudentGPADictionary.Add('Sally Superstar', 4.0); StudentGPADictionary.Add('Harry Hardworker', 3.73); StudentGPADictionary.Add('Andy Average', 2.55); StudentGPADictionary.Add('Freddy Failure', 1.01); // Report out on students ReportOnStudents(StudentGPADictionary); WriteLn; WriteLn('Oops, we missed a few classes....'); StudentGPADictionary['Andy Average'] := 2.62; StudentGPADictionary['Harry Hardworker'] := 3.70; // Report out on students ReportOnStudents(StudentGPADictionary ); WriteLn; finally StudentGPADictionary.Free; end; end; end.
unit Work.Table.Customers; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Generics.Collections, Vcl.Grids, HGM.Controls.VirtualTable, SQLLang, SQLiteTable3, Work.DB; type TTableCustomers = class; TItemCustomer = class private FModifed:Boolean; FOwner:TTableCustomers; FEmpty:Boolean; function GetFullFIO: string; function GetShortFIO: string; public ID:Integer; F, I, O:string; Phone, Telegram:string; DateCreate:TDateTime; property FullFIO:string read GetFullFIO; property ShortFIO:string read GetShortFIO; property Modifed:Boolean read FModifed write FModifed; property Empty:Boolean read FEmpty write FEmpty; procedure OpenTelegramChat; procedure Update; procedure Delete; procedure GetBack; constructor Create(AOwner:TTableCustomers); end; TTableCustomers = class(TTableData<TItemCustomer>) const TableName = 'Customers'; const fnID = 'cuID'; const fnF = 'cuF'; const fnI = 'cuI'; const fnO = 'cuO'; const fnPhone = 'cuPhone'; const fnTelegram = 'cuTelegram'; const fnDateCreate = 'cuDateCreate'; private FDB:TDatabaseCore; public function Find(ID:Integer):Integer; procedure Load; procedure Save; procedure GetBack(Index:Integer); overload; procedure GetBack(Item:TItemCustomer); overload; procedure Update(Index:Integer); overload; procedure Update(Item:TItemCustomer); overload; procedure Delete(Item:TItemCustomer); overload; procedure Delete(Index:Integer); overload; procedure FillList(List:TStrings; var SelID:Integer); procedure Clear; override; constructor Create(ADB:TDatabaseCore); overload; property DatabaseCore:TDatabaseCore read FDB write FDB; end; implementation uses ShellAPI; { TTableCustomers } procedure TTableCustomers.Clear; var i:Integer; begin for i:= 0 to Count-1 do Items[i].Free; inherited; end; constructor TTableCustomers.Create(ADB:TDatabaseCore); begin inherited Create; FDB:=ADB; if not FDB.SQL.TableExists(TableName) then with SQL.CreateTable(TableName) do begin AddField(fnID, ftInteger, True, True); AddField(fnF, ftString); AddField(fnI, ftString); AddField(fnO, ftString); AddField(fnPhone, ftString); AddField(fnTelegram, ftString); AddField(fnDateCreate, ftDateTime); FDB.SQL.ExecSQL(GetSQL); EndCreate; end; end; procedure TTableCustomers.Delete(Item: TItemCustomer); begin with SQL.Delete(TableName) do begin WhereFieldEqual(fnID, Item.ID); FDB.SQL.ExecSQL(GetSQL); EndCreate; end; end; procedure TTableCustomers.Delete(Index: Integer); begin Delete(Items[Index]); inherited; end; procedure TTableCustomers.FillList(List:TStrings; var SelID:Integer); var i, s:Integer; begin s:=-1; List.BeginUpdate; List.Clear; try for i:= 0 to Count-1 do begin List.Add(Items[i].FullFIO); if Items[i].ID = SelID then s:=i; end; finally List.EndUpdate; end; SelID:=s; end; function TTableCustomers.Find(ID: Integer): Integer; var i:Integer; begin Result:=-1; for i:= 0 to Count-1 do if Items[i].ID = ID then Exit(i); end; procedure TTableCustomers.GetBack(Item: TItemCustomer); var RTable:TSQLiteTable; begin with SQL.Select(TableName) do begin AddField(fnF); AddField(fnI); AddField(fnO); AddField(fnPhone); AddField(fnTelegram); AddField(fnDateCreate); WhereFieldEqual(fnID, Item.ID); RTable:=FDB.SQL.GetTable(GetSQL); if RTable.Count > 0 then begin Item.F:=RTable.FieldAsString(0); Item.I:=RTable.FieldAsString(1); Item.O:=RTable.FieldAsString(2); Item.Phone:=RTable.FieldAsString(3); Item.Telegram:=RTable.FieldAsString(4); Item.DateCreate:=RTable.FieldAsDateTime(5); Item.Modifed:=False; Item.Empty:=False; end; RTable.Free; EndCreate; end; end; procedure TTableCustomers.Load; var RTable:TSQLiteTable; Item:TItemCustomer; begin BeginUpdate; Clear; try with SQL.Select(TableName) do begin AddField(fnID); AddField(fnF); AddField(fnI); AddField(fnO); AddField(fnPhone); AddField(fnTelegram); AddField(fnDateCreate); RTable:=FDB.SQL.GetTable(GetSQL); while not RTable.EOF do begin Item:=TItemCustomer.Create(Self); Item.ID:=RTable.FieldAsInteger(0); Item.F:=RTable.FieldAsString(1); Item.I:=RTable.FieldAsString(2); Item.O:=RTable.FieldAsString(3); Item.Phone:=RTable.FieldAsString(4); Item.Telegram:=RTable.FieldAsString(5); Item.DateCreate:=RTable.FieldAsDateTime(6); Item.Modifed:=False; Item.Empty:=False; Add(Item); RTable.Next; end; RTable.Free; EndCreate; end; finally EndUpdate; end; end; procedure TTableCustomers.GetBack(Index: Integer); begin GetBack(Items[Index]); end; procedure TTableCustomers.Save; var i:Integer; begin for i:= 0 to Count-1 do if Items[i].Modifed then Update(i); end; procedure TTableCustomers.Update(Item: TItemCustomer); var Res:Integer; begin with SQL.Select(TableName) do begin AddField(fnID); WhereFieldEqual(fnID, Item.ID); Res:=FDB.SQL.GetTableValue(GetSQL); EndCreate; end; if Res < 0 then begin with SQL.InsertInto(TableName) do begin AddValue(fnF, Item.F); AddValue(fnI, Item.I); AddValue(fnO, Item.O); AddValue(fnPhone, Item.Phone); AddValue(fnTelegram, Item.Telegram); AddValue(fnDateCreate, Now); FDB.SQL.ExecSQL(GetSQL); Item.ID:=FDB.SQL.GetLastInsertRowID; EndCreate; end; end else begin with SQL.Update(TableName) do begin AddValue(fnF, Item.F); AddValue(fnI, Item.I); AddValue(fnO, Item.O); AddValue(fnPhone, Item.Phone); AddValue(fnTelegram, Item.Telegram); WhereFieldEqual(fnID, Item.ID); FDB.SQL.ExecSQL(GetSQL); EndCreate; end; end; Item.Modifed:=False; Item.Empty:=False; end; procedure TTableCustomers.Update(Index: Integer); begin Update(Items[Index]); end; { TItemCustomer } constructor TItemCustomer.Create(AOwner:TTableCustomers); begin inherited Create; FModifed:=True; FEmpty:=True; FOwner:=AOwner; end; procedure TItemCustomer.Delete; begin FOwner.Delete(Self); end; procedure TItemCustomer.GetBack; begin FOwner.GetBack(Self); end; function TItemCustomer.GetFullFIO: string; begin Result:=CreateFullFIO(F, I, O); end; function TItemCustomer.GetShortFIO: string; begin Result:=CreateFIO(F, I, O); end; procedure TItemCustomer.OpenTelegramChat; begin ShellExecute(Application.Handle, 'open', PChar('tg://resolve?domain='+Telegram), nil, nil, SW_NORMAL); end; procedure TItemCustomer.Update; begin FOwner.Update(Self); end; end.
//////////////////////////////////////////////////////////////////////////// // TMsg.pas //========================================================================== // 功能 : 定义Timeline向外部发送的消息 和Timeline接收的命令消息 // 创建时间: 2005-08-12 // 创建者 : 杨长元 // 修订 : //========================================================================== unit TMsg; interface uses Windows; // Timeline消息(命令)定义 const //========================================================================== // 主要Callback消息ID // 文档Message TCM_UPDATE = 1; // 时间线数据已经更改 TCM_CLIP_PARAM = 2; // Clip参数发生改变 TCM_ADD_CLIPS = 3; // 加入了新的Clip TCM_DELETE_CLIPS = 4; // 有Clip被删除 wParam - 删除的元素个数 lParam为指向HCLIP的数组指针 可能包含转场Clip TCM_CLIP_SELCET_CHANGE = 5; // Clip选择状态发生改变, wParam - 选中状态的Clip数量, lParam - 选择集是否连续 TCM_DELETE_ALL_CLIPS = 6; // 所有Clip被删除 TCM_CLIP_STATE = 100; // Clip状态发生改变 lParam - clip指针 HCLIP TCM_SELECT_ALL = 101; // 选中了所有clip TCM_SELECT_CLEAR_ALL = 102; // 清除所有clip的选中状态 TCM_MOVE_CLIPS = 103; // 有Clip被移动 TCM_DOC_MSG_MAX = 299; // 文档更改消息通知最大值 //--------------------------------------------------------------------------- // 视图Message TCM_TIMELINE_MOVING = 302; // 时间线移动消息(正在移动),lParam为指向double时间数据的指针 TCM_TIMELINE_MOVED = 303; // 时间线移动消息(移动完毕),lParam为指向double时间数据的指针 TCM_ZOOM_IN = 304; // 视图放大,wParam为0-9之间的整数,表示显示比例等级,一共10级;lParam为指向视图double起始时间数据的指针 TCM_ZOOM_OUT = 305; // 视图缩小,参数同TMI_ZOOM_IN TCM_PAN = 306; // 视图平移,lParam为指向视图double起始时间数据的指针 //--------------------------------------------------------------------------- // 其他Message TCM_CLIPS_LOAD_PROGRESS = 500; // 正在加载照片文件 lParam - 进度百分比 (0, 100) TCM_CLIP_CLICK = 510; // Clip被单击 lParam为被单击的HCLIP句柄 TCM_CLIP_DOUBLECLK = 511; // Clip被双击 lParam为被双击的HCLIP句柄 TCM_CONTEXT_MENU = 512; // 上下文菜单,RButtonClick wParam - MAKEWPARAM(x, y) lParam - 为被点击的HCLIP句柄 TCM_OVER_CLIP_COUNT = 520; // Timeline中的非转场Clip数量已经达到最大值 //TCM_PRE_DELETE_CLIPS = 521; // Clip将被删除 lParam为指向用户数据的数组指针,内容为0则结束 //========================================================================== // Timeline接收的主要命令消息ID //TCC_DELETE_SELECTED_CLIPS = 5001; // 删除所有选中的Clips //TCC_DELETE_ALL_CLIPS = 5002; // 删除所有Clips TCC_SWITCH_VIEWMODE = 5003; // TCC_SET_VIEWMODE = 5004; // wParam: 0 - Timeline Mode 1 - Storyboard View Mode TCC_GET_VIEWMODE = 5005; // return: 0 - Timeline Mode 1 - Storyboard View Mode TCC_STORYBOARD_ONLY = 5006; // 仅使用故事板模式 //TCC_APPLY_EFFECT_TO_SELECTED = 5007; // 应用特效到选中的Clip wParam - 特效长度(毫秒) lParam - 特效ID(字符串指针) TCC_ENSURE_VISIBLE_CLIP = 5008; // 让指定Clip处于可见状态 wParam - 照片元素索引号 TCC_ON_HOME = 5009; // 视图滚动到头部 TCC_ON_END = 5010; // 视图滚动到尾部 //TCC_CAN_APPLY_EFFECT_TO_SELECTED = 5011; // 是否可以应用特效到选择集 返回 0 - 不能, 1 - 能 //TCC_SELECTED_CLIP_COUNT = 5012; // 返回选中的Clip个数 包括媒体和转场Clip //TCC_SELECTED_CAN_PREVIEW = 5013; // 返回 1 - 照片选择集连续可以预览 0 - 不可以预览 //TCC_ADD_CLIPS = 5014; // 添加Clip wParam = MAKEWPARAM(nCount, nDefultLength) lParam - const wchar_t*szFileNameArray[] //TCC_APPLY_EFFECT_TO_ALL = 5015; // 应用特效到所有Clip wParam - 特效长度(毫秒) lParam - 特效ID(字符串指针) //TCC_RANDOM_EFFECT_TO_ALL = 5016; // 应用随机特效到所有Clip wParam - 特效长度(毫秒) TCC_SET_TIME = 5020; // 设置时间线位置 lParam - double类型时间数据地址指针 TCC_SHOW_TRANSCLIP = 8000; // wParam: 1 - 显示转场 0 - 隐藏转场 TCC_ENSURE_CLIP = 8001; // 滚动视图,使索引为wParam的Clip可见 //TCC_STORYBOARD_THUMBNAIL_SIZE = 8002; // 故事板缩略图尺寸控制 lParam //TCC_STORYBOARD_TIMEMODE = 8003; // 故事板时间显示方式,0 - 秒 1 - 时:分:秒 TCC_STORYBOARD_GETPARAM = 8004; // 设置取得故事板参数,lParam - 指向StoryboardOptions结构的指针 TCC_STORYBOARD_SETPARAM = 8005; // 设置故事板参数,lParam - 指向StoryboardOptions结构的指针 // 故事板参数结构 type StoryboardOptions = record nImageAreaWidth : Integer; // 图像区宽度 nTransAreaWidth : Integer; // 转场区宽度 nTransWidth : Integer; // 转场缩略图宽度 nTransHeight : Integer; // 转场缩略图高度 nImageBorderLeft : Integer; // 图像左边框宽度 nImageBorderTop : Integer; // 图像上边框高度 nImageBorderRight : Integer;// 图像右边框宽度 nImageBorderBottom : Integer;// 图像下边框高度 nBottomAreaHeight : Integer;// 底部预留高度 nImageEditWidth : Integer; // 图像编辑框长度 nEditHeight : Integer; // 编辑框高度 bTransVisible : BOOL; // 转场是否可见 uImageLengthFlag : UINT; // Image片段长度区 0 - 不可见 1 - 可见 不能编辑 3 - 可见 可以编辑 uTransLengthFlag : UINT; // Trans片段长度区 0 - 不可见 1 - 可见 不能编辑 3 - 可见 可以编辑 uTimeMode : UINT; // 0 - 秒(只允许输入整数) // 1 - 秒(允许输入小数) (目前不支持) // 2 - 时:分:秒:帧 (目前不支持) // 3 - 时:分:秒.秒/100 (目前不支持) nMaxClips : Integer; // 最大clip数量 不计转场 0 为不限制 uEditCtrlFlag : UINT; // 0 - 可以接受外部拖入数据、clip可以交换顺序、可以删除 // 1 - 不可以接受外部拖入数据、clip不可以交换顺序、不可以删除 end; // ... implementation end.
(*======================================================================* | cmpSpellChecker | | | | ISpell spell checker component. | | | | The contents of this file are subject to the Mozilla Public License | | Version 1.1 (the "License"); you may not use this file except in | | compliance with the License. You may obtain a copy of the License | | at http://www.mozilla.org/MPL/ | | | | Software distributed under the License is distributed on an "AS IS" | | basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See | | the License for the specific language governing rights and | | limitations under the License. | | | | Copyright © Colin Wilson 2003 All Rights Reserved | | | | Version Date By Description | | ------- ---------- ---- ------------------------------------------| | 1.0 13/02/2003 CPWW Original | *======================================================================*) unit cmpSpellChecker; interface uses Windows, SysUtils, Classes, ConTnrs, StrUtils; type //============================================================== // TSpeller class // // Class for controlling ISpell.exe TSpeller = class private fCodePage : Integer; pi : TProcessInformation; fHInputWrite, fHErrorRead, fHOutputRead : THandle; public constructor Create (const APath, ACmd : string; ACodePage : Integer); destructor Destroy; override; procedure SpellCommand (const cmd : string); function GetResponse : string; function GetCheckResponse : string; property CodePage : Integer read fCodePage; end; //============================================================== // TISpellLanguage class // // Class used in fISpellLanguages object list. Contains the details // of the supported language variants TISpellLanguage = class private fCmd: string; fPath : string; fCodePage: Integer; fLang: Integer; fName: string; public constructor Create (const APath, AName : string; ACodePage, ALang : Integer; const ACmd : string); property CodePage : Integer read fCodePage; property Cmd : string read fCmd; // Cmd to send to ISpell.exe property Lang : Integer read fLang; // Language ID property Name : string read fName; property Path : string read fPath; end; //============================================================== // TSpellChecker class // // Class for checking words or strings against the ISpell // dictionary TSpellChecker = class(TComponent) private fLanguageIdx: Integer; fSpeller : TSpeller; fQuoteChars: string; procedure SetLanguageIdx(const Value: Integer); procedure Initialize; protected public constructor Create (AOwner : TComponent); override; destructor Destroy; override; class function LanguageCount : Integer; class function Language (idx : Integer) : TISpellLanguage; function CheckWord (const ws : WideString; suggestions : TStrings = Nil) : boolean; function Check (const ws : WideString; startPos : Integer; var selStart, selEnd : Integer; suggestions : TStrings = Nil; SkipFirstLine : boolean = False) : boolean; procedure Add (const word : WideString); property LanguageIdx : Integer read fLanguageIdx write SetLanguageIdx default -1; property QuoteChars : string read fQuoteChars write fQuoteChars; end; EISpell = class (Exception) end; var gDefaultISpellLanguage : Integer = -1; implementation uses ActiveX, unitDefRegistry, iniFiles, unitCharsetMap, unitSearchString; var gISpellLanguages : TObjectList = Nil; gCoInitialize : boolean = False; { TSpellChecker } (*----------------------------------------------------------------------* | procedure TSpellChecker.Add | | | | Add a word to the ISpell dictionary | | | | Parameters: | | const word: WideString The word to add | *----------------------------------------------------------------------*) procedure TSpellChecker.Add(const word: WideString); begin if not Assigned (fSpeller) then Initialize; if Assigned (fSpeller) then fSpeller.SpellCommand('*' + WideStringToString (word, fSpeller.CodePage)); end; (*----------------------------------------------------------------------* | function TSpellChecker.Check | | | | Check the words in a string. Return false on the first misspelt | | word, or True if there aren't any misspelt words. | | | | If it returns false, also fill in the selStart and selEnd variables | | to indicate the (1-based) position and length of the misspelt | | word, and fil in the optional list of suggestions. | | | | Parameters: | | const ws: WideString; The string of words to check | | var startPos: Integer; The starting position for the search | | var selStart : Integer Returns position of first misspelling | | var selEnd : Integer; Returns the end position of the " | | suggestions : TStrings Optional list of suggestions filled in | | when there is a misspelling. | *----------------------------------------------------------------------*) function TSpellChecker.Check(const ws: WideString; startPos: Integer; var selStart, selEnd: Integer; suggestions: TStrings; SkipFirstLine : boolean): boolean; var l, p, lp : Integer; sw, ew : Integer; ch : WideChar; InQuoteLine : boolean; //-------------------------------------------------------------- // Check the individual word at sw..ew function DoCheck : boolean; begin if sw <> -1 then begin result := CheckWord (Copy (ws, sw, ew - sw + 1), suggestions); if not result then begin selStart := sw; selEnd := ew end; sw := -1 end else result := True; end; begin l := Length (ws); if l = 0 then begin result := True; exit end; sw := -1; ew := -1; p := StartPos; // Skip first line if requested - eg. to climb over // quote header, etc. if SkipFirstLine then begin ch := ' '; while (p <= l) do begin ch := ws [p]; if (ch = #$a) or (ch = #$d) then break else Inc (p) end; while (p <= l) and ((ch = #$a)or (ch = #$d)) do begin Inc (p); ch := ws [p] end; end; result := True; InQuoteLine := False; lp := p; // If the StartPos wasn't at the beginning, detect // whether we're in the middle of a quote line. while (lp > 1) do begin ch := ws [lp - 1]; if (ch = #$d) or (ch = #$a) then begin InQuoteLine := Pos (ws [lp], QuoteChars) > 0; break end else Dec (lp) end; // Find each word while result and (p <= l) do begin ch := ws [p]; // Keep track of 'start of line' so we can // detect quoted lines. if (ch = #$d) or (ch = #$a) then lp := 0 else if lp = 1 then InQuoteLine := Pos (ch, QuoteChars) > 0; if IsWideCharAlNum (ch) or (word (ch) = Word ('''')) then begin if sw = -1 then sw := p; ew := p end else if sw <> -1 then if not InQuoteLine then result := DoCheck // End of word found. Check it. else sw := -1; Inc (p); Inc (lp); end; if result and (sw <> -1) and not InQuoteLine then result := DoCheck; // Check final word end; (*----------------------------------------------------------------------* | function TSpellChecker.CheckWord | | | | Check an individual word | | | | Parameters: | | const ws: WideString The word to check | | suggestions: TStrings Optional suggestions returned | | if the word was misspelt | | | | The function returns False if the word was misspelt | *----------------------------------------------------------------------*) function TSpellChecker.CheckWord(const ws: WideString; suggestions: TStrings): boolean; var resp : string; begin if not Assigned (fSpeller) then Initialize; if Assigned (fSpeller) then begin // Send word to ispell.exe fSpeller.SpellCommand(WideStringToString (ws, fSpeller.CodePage)); resp := fSpeller.GetResponse; result := resp = ''; // If blank line received the word was // spelt OK. if Assigned (suggestions) then begin Suggestions.BeginUpdate; Suggestions.Clear; try if (not result) then begin // Misspelt word. Parse the suggestions SplitString (':', resp); while resp <> '' do Suggestions.Add(SplitString (',', resp)) end finally Suggestions.EndUpdate end end end else result := True; end; (*----------------------------------------------------------------------* | constructor TSpellChecker.Create | | | | Constructor for TSpellChecker | *----------------------------------------------------------------------*) constructor TSpellChecker.Create(AOwner: TComponent); begin inherited; fLanguageIdx := -1; end; (*----------------------------------------------------------------------* | destructor TSpellChecker.Destroy | | | | Destructor for TSpellChecker | *----------------------------------------------------------------------*) destructor TSpellChecker.Destroy; begin fSpeller.Free; inherited; end; (*----------------------------------------------------------------------* | Initialize the speller with the appropriate language | *----------------------------------------------------------------------*) procedure TSpellChecker.Initialize; begin if fLanguageIdx = -1 then // If not language was specified... fLanguageIdx := gDefaultISpellLanguage; FreeAndNil (fSpeller); if (fLanguageIdx >= 0) and Assigned (gISpellLanguages) and (fLanguageIdx < gISpellLanguages.Count) then with TISpellLanguage (gISpellLanguages [fLanguageIdx]) do fSpeller := TSpeller.Create(Path, Cmd, CodePage); end; (*----------------------------------------------------------------------* | procedure TSpellChecker.SetLanguage | | | | 'Set' method for the Language property | *----------------------------------------------------------------------*) class function TSpellChecker.Language(idx: Integer): TISpellLanguage; begin if (idx >= 0) and (idx < gISpellLanguages.Count) then result := TISpellLanguage (gISpellLanguages [idx]) else result := nil end; class function TSpellChecker.LanguageCount: Integer; begin if Assigned (gISpellLanguages) then result := gISpellLanguages.Count else result := 0 end; procedure TSpellChecker.SetLanguageIDx(const Value: Integer); begin if fLanguageIdx <> Value then begin fLanguageIdx := Value; if not (csDesigning in ComponentState) then Initialize end end; { TISpellLanguage } (*----------------------------------------------------------------------* | constructor TISpellLanguage.Create | | | | Constructor for TISpellLanguage | | | | Parameters: | | const APath, // Initial values of fields | | const AName: string; | | ACodePage, | | ALang: Integer; | | const ACmd: string | *----------------------------------------------------------------------*) constructor TISpellLanguage.Create(const APath, AName: string; ACodePage, ALang: Integer; const ACmd: string); begin fPath := APath; fName := AName; fCodePage := ACodePage; fLang := ALang; fCmd := ACmd; end; procedure CreateSTDHandles (const sa : TSecurityAttributes; var hInputRead, hInputWrite, hOutputRead, hOutputWrite, hErrorRead, hErrorWrite : THandle); var hOutputReadTmp : THandle; hInputWriteTmp : THandle; hErrorReadTmp : THandle; begin hOutputReadTmp := 0; hInputWriteTmp := 0; hErrorReadTmp := 0; hInputRead := 0; hInputWrite := 0; hOutputRead := 0; hOutputWrite := 0; hErrorRead := 0; hErrorWrite := 0; try if not CreatePipe (hOutputReadTmp, hOutputWrite, @sa, 0) then RaiseLastOSError; if not CreatePipe (hErrorReadTmp, hErrorWrite, @sa, 0) then RaiseLastOSError; if not CreatePipe (hInputRead, hInputWriteTmp, @sa, 0) then RaiseLastOSError; if not DuplicateHandle (GetCurrentProcess, hOutputReadTmp, GetCurrentProcess, @hOutputRead, 0, FALSE, DUPLICATE_SAME_ACCESS) then RaiseLastOSError; if not DuplicateHandle (GetCurrentProcess, hErrorReadTmp, GetCurrentProcess, @hErrorRead, 0, FALSE, DUPLICATE_SAME_ACCESS) then RaiseLastOSError; if not DuplicateHandle (GetCurrentProcess, hInputWriteTmp, GetCurrentProcess, @hInputWrite, 0, FALSE, DUPLICATE_SAME_ACCESS) then RaiseLastOSError; CloseHandle (hOutputReadTmp); hOutputReadTmp := 0; CloseHandle (hInputWriteTmp); hInputWriteTmp := 0; CloseHandle (hErrorReadTmp); hErrorReadTmp := 0; except if hOutputReadTmp <> 0 then CloseHandle (hOutputReadTmp); if hInputWriteTmp <> 0 then CloseHandle (hInputWriteTmp); if hErrorReadTmp <> 0 then CloseHandle (hErrorReadTmp); if hInputRead <> 0 then CloseHandle (hInputRead); hInputRead := 0; if hInputWrite <> 0 then CloseHandle (hInputWrite); hInputWrite := 0; if hOutputRead <> 0 then CloseHandle (hOutputRead); hOutputRead := 0; if hOutputWrite <> 0 then CloseHandle (hOutputWrite); hOutputWrite := 0; if hErrorRead <> 0 then CloseHandle (hErrorRead); hErrorRead := 0; if hErrorWrite <> 0 then CloseHandle (hErrorWrite); hErrorWrite := 0; raise end end; { TSpeller } (*----------------------------------------------------------------------* | constructor TSpeller.Create | | | | Create the ISpell.exe controller class. Run ISpell with input | | output and error pipes. | | | | Parameters: | | const APath, | | ACmd: string; | | ACodePage : Integer | *----------------------------------------------------------------------*) constructor TSpeller.Create(const APath, ACmd: string; ACodePage : Integer); var si : TStartupInfo; buf : string; hInputRead, hOutputWrite, hErrorWrite : THandle; sa : TSecurityAttributes; begin fCodePage := ACodePage; SetEnvironmentVariable ('HOME', PChar (APath)); sa.nLength := sizeof (TSecurityAttributes); sa.lpSecurityDescriptor := Nil; sa.bInheritHandle := True; FillChar (pi, SizeOf (pi), 0); FillChar (si, SizeOf (si), 0); CreateStdHandles (sa, hInputRead, fHInputWrite, fHOutputRead, hOutputWrite, fHErrorRead, hErrorWrite); try si.cb := SizeOf (si); si.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW; si.hStdOutput := hOutputWrite; si.hStdInput := hInputRead; si.hStdError := hErrorWrite; si.wShowWindow := SW_HIDE; if not CreateProcess (nil, PChar (ACmd), @sa, @sa, True, 0, nil, nil, si, pi) then RaiseLastOSError; finally CloseHandle (hOutputWrite); CloseHandle (hInputRead); CloseHandle (hErrorWrite); end; buf := GetCheckResponse; SpellCommand('!') end; (*----------------------------------------------------------------------* | destructor TSpeller.Destroy | | | | Destructor for ISpell.exe controller class | *----------------------------------------------------------------------*) destructor TSpeller.Destroy; begin if PI.hProcess <> 0 then begin SpellCommand(^Z); // Send Ctrl-Z to ISpell to terminate it WaitForSingleObject (PI.hProcess, 1000); // Wait for it to finish end; try if pi.hThread <> 0 then CloseHandle (PI.hThread); if pi.hProcess <> 0 then CloseHandle (PI.hProcess); if fHInputWrite <> 0 then CloseHandle (fHInputWrite); if fHErrorRead <> 0 then CloseHandle (fHErrorRead); if fHOutputRead <> 0 then CloseHandle (fHOutputRead); except on E: Exception do TerminateProcess(PI.hProcess,0); end; inherited; end; (*----------------------------------------------------------------------* | function TSpeller.GetCheckResponse | | | | Get a response. If the response was on stderr, raise an exception | *----------------------------------------------------------------------*) function TSpeller.GetCheckResponse: string; var l : DWORD; // ReadPipe // // Read from a pipe. If there's nothing in the pipe return an empty string function ReadPipe (pipeHandle : THandle; var s : string) : boolean; var avail : DWORD; begin if not PeekNamedPipe (pipeHandle, nil, 0, nil, @avail, nil) then RaiseLastOSError; if avail > 0 then begin SetLength (s, avail + 512); if not ReadFile (pipeHandle, s [1], avail + 512, avail, nil) then RaiseLastOSError; SetLength (s, avail); result := True end else result := False end; begin { GetCheckResponse } l := 20; Sleep (100); repeat { Try stdout first } if ReadPipe (fHOutputRead, result) then break; { Try stderr} if ReadPipe (fHErrorRead, result) then raise EISpell.Create (result); Sleep (100); Dec (l) until l = 0; if l = 0 then result := ''; // raise EISpell.Create ('Timeout in ISpell'); result := Trim (result); end; (*----------------------------------------------------------------------* | function TSpeller.GetResponse | | | | Blocking call to get response from ISpell | *----------------------------------------------------------------------*) function TSpeller.GetResponse: string; var avail : DWORD; begin SetLength (result, 2048); if ReadFile (fHOutputRead, result [1], 2048, avail, nil) then begin SetLength (result, avail); result := Trim (result) end else raiseLastOSError; end; (*----------------------------------------------------------------------* | procedure TSpeller.SpellCommand | | | | Send a command to ISpell | *----------------------------------------------------------------------*) procedure TSpeller.SpellCommand(const cmd: string); var n : DWORD; begin WriteFile (fHInputWrite, (cmd + #13#10) [1], Length (cmd) + 2, n, Nil); end; procedure InitISpell; var reg : TDefRegistry; ISpellPath, path, s, name, cmd : string; f : TSearchRec; sections : TStrings; i : Integer; sectionLanguage : Integer; function SpellerForLocale (locale : Integer) : Integer; var i : Integer; begin result := -1; for i := 0 to gISpellLanguages.Count - 1 do if TISpellLanguage (gISpellLanguages [i]).Lang = locale then begin result := i; break end end; begin if CoInitialize (nil) = S_OK then gCoInitialize := True; sections := Nil; reg := TDefRegistry.Create (KEY_READ); try reg.RootKey := HKEY_LOCAL_MACHINE; if reg.OpenKey('\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\ispell.exe', False) then begin // Get the ISpell.exe path from the registry ISpellPath := IncludeTrailingPathDelimiter (reg.ReadString ('Path')); path := ExtractFilePath (ExcludeTrailingPathDelimiter (ISpellPath)); if FindFirst (ISpellPath + '*.*', faDirectory, f) = 0 then try sections := TStringList.Create; // Enumerate the subdirectories of the ISpell // directory. Each one will containe a language repeat if ((f.Attr and faDirectory) <> 0) and (Copy (f.Name, 1, 1) <> '.') then with TInIFile.Create(ISpellPath + f.Name + '\ISpell.ini') do try ReadSections (sections); sectionLanguage := 1033; for i := 0 to sections.Count - 1 do begin // Read the language settings from the .INI file // in the language directory s := sections [i]; if s = '' then name := f.Name else name := s; cmd := ReadString (s, 'Cmd', ''); cmd := StringReplace (cmd, '%UniRed%',path, [rfReplaceAll, rfIgnoreCase]); if not Assigned (gISpellLanguages) then gISpellLanguages := TObjectList.Create; sectionLanguage := ReadInteger (s, 'LangNo', sectionLanguage); gISpellLanguages.Add(TISpellLanguage.Create( ExcludeTrailingPathDelimiter (ISpellPath), name, MIMECharsetNameToCodePage (ReadString (s, 'Charset', 'us-ascii')), sectionLanguage, cmd)) end; finally Free end until FindNext (f) <> 0 finally FindClose (f) end; gDefaultISpellLanguage := SpellerForLocale (GetThreadLocale); if gDefaultISpellLanguage = -1 then gDefaultISpellLanguage := SpellerForLocale (GetUserDefaultLCID); if gDefaultISpellLanguage = -1 then gDefaultISpellLanguage := SpellerForLocale (GetSystemDefaultLCID); if gDefaultISpellLanguage = -1 then gDefaultISpellLanguage := SpellerForLocale (1033); // US English if (gDefaultISpellLanguage = -1) and (gISpellLanguages.Count > 0) then gDefaultISpellLanguage := 0 end finally sections.Free; reg.Free end end; initialization InitISpell; finalization gISpellLanguages.Free; if gCoInitialize then CoUninitialize end.
// shallow way to recognize item as Shield function isShield(item: IInterface): boolean; var tmp: IInterface; begin Result := false; if (Signature(item) = 'ARMO') then begin tmp := GetElementEditValues(item, 'ETYP'); if (Assigned(tmp) and (tmp = 'Shield [EQUP:000141E8]')) then begin Result := true; end else if hasKeyword(item, 'ArmorShield') then begin Result := true; end; end; end;
(* @abstract(Prise en charge des Images au format X PixMap.) Spécifications : @br @unorderedList( @item(Méthode de compression : Aucune) @item(Nombre de couleurs : Format RGB, 24 bits ou 32 bits RGB(A)) + Format HSL(A) @item(Supporte plusieurs images : Non, une seule image dans un même fichier) @item(Format des nombres : Texte) @item(Auteur : Colas Nahaboo et Daniel Dardailler.) @item(Extensions : *.xpm ( *.xbm)) ) ------------------------------------------------------------------------------------------------------------- @created(2017-05-11) @author(J.Delauney (BeanzMaster)) Historique : @br @unorderedList( @item(11/05/2017 : Creation ) ) ------------------------------------------------------------------------------------------------------------- @bold(Notes) : @br Informations sur le format XPM : @unorderedList( @item(https://en.wikipedia.org/wiki/X_PixMap) @item(http://www.fileformat.info/format/xpm/egff.htm) @item(https://www.w3.org/People/danield/xpm_story.html) @item(http://www.linux-france.org/article/memo/node60.html) @item(https://www.x.org/docs/XPM/xpm.pdf) ) Autres informations utiles : @br @unorderedList( @item(https://en.wikipedia.org/wiki/X_BitMap) ) Fichiers test :@br @unorderedList( @item(http://www.fileformat.info/format/xpm/sample/index.htm) @item(Lazarus) ) ------------------------------------------------------------------------------------------------------------- @bold(Dépendances) : BZClasses, BZColors, BZGraphic, BZBitmap, BZImageFileIO, BZImageStrConsts, BZUtils ------------------------------------------------------------------------------------------------------------- @bold(Credits :) @unorderedList( @item(FPC/Lazarus) ) ------------------------------------------------------------------------------------------------------------- @bold(Licence) : MPL / GPL ------------------------------------------------------------------------------------------------------------- *) unit BZImageFileXPM; { TODO 0 -oBZBitmap -cSupport_Images_XPM : Ecriture Format XPM TODO 0 -oBZBitmap -cSupport_Images_XPM : Lecture des couleurs en HSV(A) (nb : la couleur est précédée de "%" au lieu "#" pour valeur RGB) TODO 0 -oBZBitmap -cSupport_Images_XPM : Lecture des extensions. Placées juste après les données de l'image TODO 0 -oBZBitmap -cSupport_Images_XPM : Gestion des différent mode de couleurs : "c", "m", "g", "g4" et "s" } //============================================================================== {$mode objfpc}{$H+} {$i ..\..\bzscene_options.inc} //============================================================================== interface uses Classes, SysUtils, BZClasses, BZColors, BZGraphic, BZBitmap, BZImageFileIO; Const cXPM2_MagicID = '! XPM2'; cXPM3_MagicID = '/* XPM */'; // Caractères autorisés par defaut. Gimp ajoute d'autres comme "/" DefCharsCount = 78; DefPalChars = '.,-*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#;:=+%$()[]'; ExtPalCharsCount = 92; ExtPalChars = ' .XoO+@#$%&*=-;:>,<1234567890qwertyuipasdfghjklzxcvbnmMNBVCZASDFGHJKLPIUYTREWQ!~^/()_`''][{}|'; type TBZColorHolder = class public Color: TBZColor; end; Type { TBZBitmapXPMImage : Classe de lecture et d"ecriture des images au format XPM } TBZBitmapXPMImage = class(TBZCustomImageFileIO) private procedure SkipComments; protected W,H,nbCols, cpp, xhot, yhot : integer; xpmext : boolean; PalLookUp : TBZStringList; procedure LoadFromMemory();override; function CheckFormat(): Boolean; override; function ReadImageProperties:Boolean;override; public Constructor Create(AOwner: TPersistent; AWidth, AHeight: integer); override; Destructor Destroy;override; class function Capabilities: TBZDataFileCapabilities;override; property FullFileName; end; implementation // Uses BZStringUtils, BZLogger, Dialogs; uses BZImageStrConsts, BZUtils; const WhiteSpaces = [#8, #9, #13, #10, #32]; procedure SkipWhiteSpace(var Line: string); begin while (Length(Line) > 0) and (Line[1] in WhiteSpaces) do Delete(Line, 1, 1); end; function ReadString(var Line: string): string; begin Result := ''; SkipWhiteSpace(Line); while (Length(Line) > 0) and not(Line[1] in WhiteSpaces) do begin SetLength(Result, Length(Result) + 1); Result[Length(Result)] := Line[1]; Delete(Line, 1, 1); end; end; function ReadInt(var Line: string): Integer; begin Result := StrToInt(ReadString(Line)); end; {%region%=====[ TBZBitmapXPMImage ]===========================================} Constructor TBZBitmapXPMImage.Create(AOwner: TPersistent; AWidth, AHeight: integer); begin inherited create(AOwner,AWidth,AHeight); With DataFormatDesc do begin Name:='XPM'; Desc:='X Window Pixmap'; FileMask:='*.xpm'; end; xpmext:=False; // Table de correspondance pour les couleur dans la palette (Basée sur le "Haschage")) PalLookup := TBZStringList.Create(nil); PalLookup.CaseSensitive := True; end; destructor TBZBitmapXPMImage.Destroy; begin FreeAndNil(PalLookup); inherited destroy; end; class function TBZBitmapXPMImage.Capabilities: TBZDataFileCapabilities; begin result:=[dfcRead]; //[dfcRead, dfcWrite] end; procedure TBZBitmapXPMImage.SkipComments; Var NextC, C2, NextC2 : Char; begin Memory.SkipNextByte; NextC:=Memory.ReadChar; if (Memory.Position<Memory.Size) and (NextC='*') then begin // C'est un tag ou commentaire // On cherche la fin while (Memory.Position<Memory.Size) do begin C2:=Memory.ReadChar; NextC2:=Memory.ReadNextChar; if (C2='*') and (NextC2='/') then begin // Fin du tag ou commentaire Memory.GotoNextStringLine; // On passe à la ligne suivante break; // On sort de la boucle end; end; End; End; function TBZBitmapXPMImage.ReadImageProperties:Boolean; Var xpmexts : String; C:Char; ok:Boolean; begin Result:=false; C:=Memory.ReadNextChar; // On verifie si il y a commentaire if C='/' then SkipComments; Memory.SkipNextByte; // On saute le 1er '"' with Memory Do begin SkipChar; // On saute les caractères vide si ils existent (valeur par defaut DefaultCharsDelims = #8#9#10#13#32 ); . W:=ReadStrIntToken; // On lit la largeur SkipChar; H:=ReadStrIntToken; // On Lit la hauteur SkipChar; nbCols:=ReadStrIntToken; // Le Nombre de couleur dans la palette SkipChar; cpp:=ReadStrIntToken; // Nombre de caractères décrivant 1 pixel SkipChar; C:=ReadNextChar; // Fin de la ligne atteinte if (C='"') or (C=',') then begin GotoNextStringLine; Ok:=True; end else // Il y a des informations pour les curseurs begin xHot:=ReadStrIntToken; // Lecture du point chaud X yHot:=ReadStrIntToken; // Lecture du point chaud Y xpmExts:=ReadStrToken; // Lecture de l'extension // L'extension est elle valide ? // NB : Des extensions peuvent se trouver après les données de l'image Ok := (comparetext(xpmExts, 'XPMEXT') = 0); if (xpmExts <> '') and xpmext and not(ok) then begin Ok:=false; RaiseInvalidImageFile(rsInvalidTagXPMExt); end; end; end; Result:=Ok; if Not(Ok) then RaiseInvalidImageHeader end; function TBZBitmapXPMImage.CheckFormat(): Boolean; Var MagicID : String; begin Result := False; DataFormatDesc.Version := '1.0'; // On vérifie que l'on a bien à faire à un fichier XPM correct MagicID:=Memory.ReadLnString; // v2 ou v3 ? if (MagicID = cXPM3_MagicID) or (MagicID = cXPM2_MagicID) then begin //Version 3. On saute la ligne de description du nom de fichier (y'en n'a pas dans la 2) DataFormatDesc.Version := '2.0'; if MagicID = cXPM3_MagicID then begin Memory.ReadLnString; if (MagicID = cXPM3_MagicID) then DataFormatDesc.Version := '3.0'; End; // On Lit les propriétes de l'image Result:= ReadImageProperties; end; end; procedure TBZBitmapXPMImage.LoadFromMemory(); Var SectionSize : Integer; function NameToColor(const ColStr: string): TBZColor; var S: string; begin S := LowerCase(ColStr); if (S = 'transparent') or (S = 'none') then Result := clrTransparent else if S = 'black' then Result := clrBlack else if S = 'blue' then Result := clrBlue else if S = 'green' then Result := clrGreen else if S = 'cyan' then Result := clrAqua else if S = 'red' then Result := clrRed else if S = 'magenta' then Result := clrFuchsia else if S = 'yellow' then Result := clrYellow else if S = 'white' then Result := clrWhite else if S = 'gray' then Result := clrLtGray else if S = 'dkblue' then Result := clrNavy else if S = 'dkgreen' then Result := clrGreen else if S = 'dkcyan' then Result := clrTeal else if S = 'dkred' then Result := clrMaroon else if S = 'dkmagenta' then Result := clrPurple else if S = 'dkyellow' then Result := clrOlive else if S = 'maroon' then Result := clrMaroon else if S = 'olive' then Result := clrOlive else if S = 'navy' then Result := clrNavy else if S = 'purple' then Result := clrPurple else if S = 'teal' then Result := clrTeal else if S = 'silver' then Result := clrSilver else if S = 'lime' then Result := clrLime else if S = 'fuchsia' then Result := clrFuchsia else if S = 'aqua' then Result := clrAqua else Result := clrTransparent; end; procedure ReadPalette; var I: Integer; S, ColType,ColStr, Code: string; Color: TBZColor; C, C3:Char; Delta : Single; begin Delta:= 100/nbCols; StartProgressSection((nbCols*100) / SectionSize ,'Chargement de la palette'); C:=Memory.ReadNextChar; // On verifie si il y a commentaire if C='/' then SkipComments; // On Charge la palette S:=''; I:=0; // On extrait ligne par ligne repeat C:=Memory.ReadChar; case C of '/': // Tags ou commentaires, on les ignores, on passe juste par dessus begin Memory.GotoPreviousByte; SkipComments; end; '"': // Lecture d'une ligne begin // Constante de type chaine de caractères C3:=Memory.ReadNextChar; while (Memory.Position<Memory.Size) and (C3<>'"') do begin C3:=Memory.ReadChar; if (C3='"') then begin // Fin de la chaine de caractères break; // On stoppe la boucle end else S:=S+C3 end; end; ',': // fin de la ligne (intervient normalement toujours apres le 2eme " begin { Evaluation de la ligne pour extraire les paramètres NOTE : On ne lit que le 1er paramètre. Mais il faudrait également traiter les autres si ils sont présent. Afin de gérér à 100% le format XPM. } Code := Copy(S, 1, cpp); Delete(S, 1, cpp); ColType := LowerCase(ReadString(S)); ColStr := ReadString(S); // Conversion des couleurs par leur nom ou leur valeur hexa vers TBZColor Case Coltype of 'c', 'm', 'g' : // "C"ouleur, "M"onochrome, "G"ris begin if ColStr[1] = '#' then // Format RGB(A) begin Delete(ColStr, 1, 1); Color.Create(ColStr); S:=''; inc(i); end else if ColStr[1]='%' then // Format HSV(A) (aussi en Hexa) begin { TODO 5 -oBZBitmap -cSupport_Images_XPM : Prise en charge format couleur HSV } end else begin Color:=NameToColor(ColStr); S:=''; Inc(I); end; end; 's' : begin Color:=NameToColor(ColStr); S:=''; Inc(I); end; else begin RaiseInvalidImageFile('Fichier au format XPM invalide'); end; end; // On ajoute la couleur à la palette PalLookup.AddInt(Code,Color.AsInteger); // On avance AdvanceProgress(Delta,0,0,False); // On sa place à la ligne suivante Memory.GotoNextStringLine; end; end; until (I=nbCols); FinishProgressSection(False); end; procedure ReadPixelData; var C, X, Y, Idx: Integer; Code: string; DstLine : PBZColor; AColor : TBZColor; Cr:Char; Delta : Single; begin // On Charge le bitmap idx:=0; X:=0; Y:=0; Delta := 100 / (Height); StartProgressSection((Height*100) / SectionSize ,'Chargement de l''image'); Cr:=Memory.ReadNextChar; // On verifie si il y a commentaire sinon, On saute le 1er '"' if Cr='/' then begin SkipComments; End; // On se place sur la 1ere de notre bitmap DstLine:=GetScanLine(0); C:=0; Y:=0; repeat Memory.SkipNextByte; // On saute le '"' de debut Code:=''; Code:=Memory.ReadString(cpp); // On lit le code idx:=PalLookUp.IndexOf(Code); // On va chercher couleur correspondante au code dans la palette AColor.AsInteger := PalLookUp.Items[Idx].Tag; DstLine^ := AColor; // On ecrit le pixel //DstLine^.AsInteger := PalLookUp.Items[Idx].Tag; Inc(X); if X>MaxWidth then begin X:=0; Inc(Y); AdvanceProgress(Delta,0,1,False); Memory.GotoNextStringLine; // On saute le '"' de fin , le ',' et les caractères de fin de ligne (#13#10) end; Inc(DstLine); Inc(C); until (C>MaxSize); FinishProgressSection(False); end; begin // On à passé tous les tests de vérification, on peux lire les données // On Initialise le system de notification de la progression SectionSize := nbCols + H; InitProgress(W,H); StartProgressSection(0, ''); // On debute une nouvelle section globale SetSize(W,H); // On itialise notre bitmap aux bonnes dimensions // Lecture de la palette de couleurs ReadPalette; // Remplissage de notre bitmap avec les données ReadPixelData; FinishProgressSection(True); //ConvertRawDataToBitmapData; end; //--- Ecriture (* procedure SaveToStream(aStream) *) {%endregion%} initialization RegisterRasterFormat('xpm', 'X Window Pixmap', TBZBitmapXPMImage); end.